project sekai 2023

This commit is contained in:
Simon Hünecke
2023-08-27 15:42:44 +02:00
commit 62ab804867
23 changed files with 539 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
C++20 introduced coroutines, I cant wait to abuse them!
1. To get a leak, look into c++ Small String Optimization.
2. Lambda capture variable is stored in the stack, you can overwrite it somehow. if you figure out what its overwritten with, solving this is straightforward.

View File

@@ -0,0 +1,13 @@
Just text chatting is boring, so we made a plugin to introduce sticker communication to GoldSrc. Server owners can put their .bmp files in svencoop/headicons directory, and the plugin will automatically convert it to in-game format. When the game detects a chat message that corresponds to a sticker, it will be visible above that player's head. Our test server has a yay.bmp file, which will show up when a player types yay in chat.
This plugin can also run on Counter-Strike 1.6 and Half-Life, but to avoid copyright issues, we decided to use a free-to-play game. You can download the game client here. Please make sure that your exploit works locally with the provided setup, as remote server access may be slow for distant users. If you cannot move your character around when connecting to remote, try lowering your fps_max value to 100.
Note: If you are running the challenge using WSL, make sure that the files are in your WSL disk, not under mounted Windows folders. The server is using Intel CPU, so some of you who use AMD CPU would run another executable in the container, which will prevent you from solving the challenge. To overcome this, you can try replacing svends_amd binary with svends_i686 binary in the game folder. If this doesn't work, you should try build a VM or use an Intel CPU machine.
1. Why is engine_i686.so provided seperately?
2. The server turned off anti-cheat, so I think maybe can remove some client-side obstacles. Maybe can even call something normally not accessible from console?
3. The file transfer code of client and server are the same.
4. Try to understand GoldSrc filesystem a bit. Observe where the downloaded files are stored to. Also it doesn't use any pack file like .vpk, every file is stored directly on disk.

Binary file not shown.

View File

@@ -0,0 +1,149 @@
use std::io::{self, Write, Read};
use dns_lookup::{lookup_host, lookup_addr};
use std::net::Ipv4Addr;
use std::process::Command;
use std::str;
use std::string::String;
static mut CHOICE: i32 = 0;
fn read(arr: &mut[u8], size: isize) -> isize{
let arr_ptr = &mut arr[0] as *mut u8;
let mut count = 0;
unsafe{
let mut input: [u8;1] = [0;1];
for i in 0..size {
io::stdin().read_exact(&mut input).expect("msg");
if input[0] == 0xa {
break;
}
*arr_ptr.offset(i) = input[0];
}
while *arr_ptr.offset(count) != 0{
count+=1;
}
}
count
}
fn menu(){
println!("1. ping");
println!("2. traceroute");
println!("3. IP lookup");
println!("4. Reverse IP lookup");
println!("5. Exit");
print!("> ");
io::stdout().flush().unwrap();
}
fn ping(){
let mut input: String = String::new();
print!("IPv4: ");
io::stdout().flush().unwrap();
io::stdin().read_line(&mut input).expect("Failed to read IP");
match input.trim().parse::<Ipv4Addr>() {
Ok(ip) => {
let cmd = format!("ping {} -w 4", ip.to_string());
let process = Command::new("/bin/sh")
.arg("-c")
.arg(cmd)
.output()
.expect("Failed");
println!("{}", String::from_utf8_lossy(&process.stdout));
}
_ => {
println!("Invalid IPv4 format!");
return;
},
};
}
fn traceroute(){
let mut input: String = String::new();
print!("IPv4: ");
io::stdout().flush().unwrap();
io::stdin().read_line(&mut input).expect("Failed to read IP");
match input.trim().parse::<Ipv4Addr>() {
Ok(ip) => {
let cmd = format!("traceroute {}", ip.to_string());
let process = Command::new("/bin/sh")
.arg("-c")
.arg(cmd)
.output()
.expect("Failed");
println!("{}", String::from_utf8_lossy(&process.stdout));
}
_ => {
println!("Invalid IPv4 format!");
return;
},
};
}
fn ip_lookup(){
let mut input: [u8; 400] = [0; 400];
print!("Hostname: ");
io::stdout().flush().unwrap();
let size = read(&mut input, 0x400);
let (hostname, _) = input.split_at(size as usize);
let hostname = str::from_utf8(hostname).expect("msg").to_string();
// println!("{:?}", hostname.trim());
match lookup_host(hostname.trim()) {
Ok(ip) => println!("{:?}", ip),
_ => println!("Invalid domain name!")
}
}
fn reverse_ip_lookup(){
let mut ip_str: String = String::new();
print!("IP: ");
io::stdout().flush().unwrap();
io::stdin().read_line(&mut ip_str).expect("Failed to read IP");
match ip_str.trim().parse::<std::net::IpAddr>() {
Ok(ip) => {
match lookup_addr(&ip) {
Ok(hostname) => println!("{}", hostname),
_ => println!("Invalid IP!")
}
},
_ => {
println!("Invalid IP format!");
return;
}
}
}
fn main(){
unsafe {
let mut input = String::new();
println!("**************************");
println!("* *");
println!("* Network Tools *");
println!("* *");
println!("**************************");
println!("Opss! Something is leaked: {:p}", &CHOICE);
loop {
menu();
input.clear();
io::stdin().read_line(&mut input).expect("Failed to readline!");
CHOICE = match input.trim().parse() {
Ok(num) => num,
_ => 0
};
match CHOICE {
1 => ping(),
2 => traceroute(),
3 => ip_lookup(),
4 => reverse_ip_lookup(),
5 => break,
_ => println!("Invalid choice!")
}
}
}
}

View File

@@ -0,0 +1,3 @@
Terrible programmer like me cannot avoid making bugs using language without memory-safety. So to avoid making my program insecure I shall use a different heap implementation making heap-related bug unexploitable. Or is it exploitable?
libzone_source: https://github.com/peternguyen93/libzone

View File

@@ -0,0 +1,45 @@
import secrets
from Crypto.Util.number import *
from Crypto.Cipher import AES
from hashlib import sha256
from flag import FLAG
def getCRC16(msg, gen_poly):
assert (1 << 16) <= gen_poly < (1 << 17) # check if deg = 16
msglen = msg.bit_length()
msg <<= 16
for i in range(msglen - 1, -1, -1):
if (msg >> (i + 16)) & 1:
msg ^= (gen_poly << i)
return msg
def oracle(secret, gen_poly):
res = [secrets.randbits(16) for _ in range(3)]
res[secrets.randbelow(3)] = getCRC16(secret, gen_poly)
return res
def main():
key = secrets.randbits(512)
cipher = AES.new(sha256(long_to_bytes(key)).digest()[:16], AES.MODE_CTR, nonce=b"12345678")
enc_flag = cipher.encrypt(FLAG)
print(f"Encrypted flag: {enc_flag.hex()}")
used = set({})
while True:
gen_poly = int(input("Give me your generator polynomial: "))
assert (1 << 16) <= gen_poly < (1 << 17) # check if deg = 16
if gen_poly in used:
print("No cheating")
exit(1)
used.add(gen_poly)
print(oracle(key, gen_poly))
main()

View File

@@ -0,0 +1,272 @@
from math import log2
import random
import secrets
import signal
def gen_pbox(s, n):
"""
Generate a balanced permutation box for an SPN
:param s: Integer, number of bits per S-box.
:param n: Integer, number of S-boxes.
:return: List of integers, representing the generated P-box.
"""
return [(s * i + j) % (n * s) for j in range(s) for i in range(n)]
def gen_sbox(n):
"""
Gen SBox for a given non negative integer n using a random permutation.
Parameters:
:param n: Integer, the bit size of sbox
:return: List of integers, representing 2^n elements corresponding to the
SBox permutation generated for the input.
"""
a, b = 2**((n + 1) // 2), 2**(n // 2)
x = list(range(a))
random.shuffle(x)
res = x[:]
for i in range(b - 1):
for j in range(len(x)):
res.insert((i + 2) * j - 1, a * (i + 1) + x[j])
res = [res[i] for i in res]
return res
def rotate_left(val, shift, mod):
"""
Rotate the bits of the value to the left by the shift amount.
The function rotates the bits of the value to the left by the shift amount,
wrapping the bits that overflow. The result is then masked by (1<<mod)-1
to only keep the mod number of least significant bits.
:param val: Integer, the value to be rotated.
:param shift: Integer, the number of places to shift the value to the left.
:param mod: Integer, the modulo to be applied on the result.
:return: Integer, the rotated value.
"""
shift = shift % mod
return (val << shift | val >> (mod - shift)) & ((1 << mod) - 1)
class SPN:
def __init__(self, SBOX, PBOX, key, rounds):
"""
Initialize the SPN class with the provided parameters.
:param SBOX: List of integers representing the S-box.
:param PBOX: List of integers representing the P-box.
:param key: List of integers, bytes or bytearray representing the key.
LSB BLOCK_SIZE bits will be used
:param rounds: Integer, number of rounds for the SPN.
"""
self.SBOX = SBOX
self.PBOX = PBOX
self.SINV = [SBOX.index(i) for i in range(len(SBOX))]
self.PINV = [PBOX.index(i) for i in range(len(PBOX))]
self.BLOCK_SIZE = len(PBOX)
self.BOX_SIZE = int(log2(len(SBOX)))
self.NUM_SBOX = len(PBOX) // self.BOX_SIZE
self.rounds = rounds
self.round_keys = self.expand_key(key, rounds)
def perm(self, inp):
"""
Apply the P-box permutation on the input.
:param inp: Integer, the input value to apply the P-box permutation on.
:return: Integer, the permuted value after applying the P-box.
"""
ct = 0
for i, v in enumerate(self.PBOX):
ct |= (inp >> (self.BLOCK_SIZE - 1 - i) & 1) << (self.BLOCK_SIZE - 1 - v)
return ct
def inv_perm(self, inp):
"""
Apply the inverse P-box permutation on the input.
:param inp: Integer, the input value to apply the inverse P-box
permutation on.
:return: Integer, the permuted value after applying the inverse P-box.
"""
ct = 0
for i, v in enumerate(self.PINV):
ct |= (inp >> (self.BLOCK_SIZE - 1 - i) & 1) << (self.BLOCK_SIZE - 1 - v)
return ct
def sbox(self, inp):
"""
Apply the S-box substitution on the input.
:param inp: Integer, the input value to apply the S-box substitution on.
:return: Integer, the substituted value after applying the S-box.
"""
ct, BS = 0, self.BOX_SIZE
for i in range(self.NUM_SBOX):
ct |= self.SBOX[(inp >> (i * BS)) & ((1 << BS) - 1)] << (BS * i)
return ct
def inv_sbox(self, inp: int) -> int:
"""
Apply the inverse S-box substitution on the input.
:param inp: Integer, the input value to apply the inverse S-box
substitution on.
:return: Integer, the substituted value after applying the inverse S-box.
"""
ct, BS = 0, self.BOX_SIZE
for i in range(self.NUM_SBOX):
ct |= self.SINV[(inp >> (i * BS)) & ((1 << BS) - 1)] << (BS * i)
return ct
def int_to_list(self, inp):
"""
Convert a len(PBOX)-sized integer to a list of S-box sized integers.
:param inp: Integer, representing a len(PBOX)-sized input.
:return: List of integers, each representing an S-box sized input.
"""
BS = self.BOX_SIZE
return [(inp >> (i * BS)) & ((1 << BS) - 1)
for i in range(self.NUM_SBOX - 1, -1, -1)]
def list_to_int(self, lst):
"""
Convert a list of S-box sized integers to a len(PBOX)-sized integer.
:param lst: List of integers, each representing an S-box sized input.
:return: Integer, representing the combined input as a
len(PBOX)-sized integer.
"""
res = 0
for i, v in enumerate(lst[::-1]):
res |= v << (i * self.BOX_SIZE)
return res
def expand_key(self, key, rounds):
"""
Derive round keys deterministically from the given key.
:param key: List of integers, bytes, or bytearray representing the key.
:param rounds: Integer, number of rounds for the SPN.
:return: List of integers, representing the derived round keys.
"""
if isinstance(key, list):
key = self.list_to_int(key)
elif isinstance(key, (bytes, bytearray)):
key = int.from_bytes(key, 'big')
block_mask = (1 << self.BLOCK_SIZE) - 1
key = key & block_mask
keys = [key]
for _ in range(rounds):
keys.append(self.sbox(rotate_left(
keys[-1], self.BOX_SIZE + 1, self.BLOCK_SIZE)))
return keys
def encrypt(self, pt):
"""
Encrypt plaintext using the SPN, where the last round doesn't
contain the permute operation.
:param pt: Integer, plaintext input to be encrypted.
:return: Integer, ciphertext after encryption.
"""
ct = pt ^ self.round_keys[0]
for round_key in self.round_keys[1:-1]:
ct = self.sbox(ct)
ct = self.perm(ct)
ct ^= round_key
ct = self.sbox(ct)
return ct ^ self.round_keys[-1]
def decrypt(self, ct):
"""
Decrypt ciphertext using the SPN, where the last round doesn't
contain the permute operation.
:param ct: Integer, ciphertext input to be decrypted.
:return: Integer, plaintext after decryption.
"""
ct = ct ^ self.round_keys[-1]
ct = self.inv_sbox(ct)
for rk in self.round_keys[-2:0:-1]:
ct ^= rk
ct = self.inv_perm(ct)
ct = self.inv_sbox(ct)
return ct ^ self.round_keys[0]
def encrypt_bytes(self, pt):
"""
Encrypt bytes using the SPN, in ECB on encrypt
:param pt: bytes, should be multiple of BLOCK_SIZE//8
:return: bytes, ciphertext after block-by-block encryption
"""
block_len = self.BLOCK_SIZE // 8
assert len(pt) % block_len == 0
int_blocks = [int.from_bytes(pt[i:i + block_len], 'big')
for i in range(0, len(pt), block_len)]
return b''.join(self.encrypt(i).to_bytes(block_len, 'big')
for i in int_blocks)
class Challenge:
def __init__(self, box_size, num_box, num_rounds, max_mess):
pbox = gen_pbox(box_size, num_box)
sbox = gen_sbox(box_size)
key = secrets.randbits(box_size * num_box)
self.spn = SPN(sbox, pbox, key, num_rounds)
self.quota = max_mess
def query(self, text_hex):
block_len = self.spn.BLOCK_SIZE // 8
if len(text_hex) & 1:
text_hex += "0"
text = bytes.fromhex(text_hex)
text += bytes((block_len - len(text)) % block_len)
if self.quota <= 0:
raise Exception(
"Encryption quota exceeded, buy pro subscription for $69/month")
self.quota -= len(text) // block_len
print("Quota remaining:", self.quota)
return self.spn.encrypt_bytes(text).hex()
def get_flag(self, key_guess):
if key_guess == self.spn.round_keys[0]:
from flag import flag
print(flag)
else:
raise Exception("There is no free lunch")
if __name__ == "__main__":
BOX_SIZE = 6
NUM_BOX = 16
QUOTA = 50000
ROUNDS = 5
PROMPT = ("Choose API option\n"
"1. Test encryption\n"
"2. Get Flag\n")
challenge = Challenge(BOX_SIZE, NUM_BOX, ROUNDS, QUOTA)
print("sbox:", "".join(hex(i)[2:].zfill(2) for i in challenge.spn.SBOX))
signal.alarm(500)
while True:
try:
option = int(input(PROMPT))
if option == 1:
pt = input("(hex) text: ")
print(challenge.query(pt))
elif option == 2:
key = int(input("(int) key: "))
challenge.get_flag(key)
exit(0)
except Exception as e:
print(e)
exit(1)

Binary file not shown.

View File

@@ -0,0 +1,50 @@
from lib import GES, utils
import networkx as nx
import random
from SECRET import flag, decrypt
NODE_COUNT = 130
EDGE_COUNT = 260
SECURITY_PARAMETER = 16
def gen_random_graph(node_count: int, edge_count: int) -> nx.Graph:
nodes = [i for i in range(1, node_count + 1)]
edges = []
while len(edges) < edge_count:
u, v = random.choices(nodes, k=2)
if u != v and (u, v) not in edges and (v, u) not in edges:
edges.append([u, v])
return utils.generate_graph(edges)
if __name__ == '__main__':
try:
print("[+] Generating random graph...")
G = gen_random_graph(NODE_COUNT, EDGE_COUNT)
myGES = GES.GESClass(cores=4, encrypted_db={})
key = myGES.keyGen(SECURITY_PARAMETER)
print(f"[*] Key: {key.hex()}")
print("[+] Encrypting graph...")
enc_db = myGES.encryptGraph(key, G)
print("[!] Answer 50 queries to get the flag. In each query, input the shortest path \
decrypted from response. It will be a string of space-separated nodes from \
source to destination, e.g. '1 2 3 4'.")
for q in range(50):
while True:
u, v = random.choices(list(G.nodes), k=2)
if nx.has_path(G, u, v):
break
print(f"[+] Query {q+1}/50: {u} {v}")
token = myGES.tokenGen(key, (u, v))
_, resp = myGES.search(token, enc_db)
print(f"[*] Response: {resp.hex()}")
ans = input("> Original query: ").strip()
if ans != decrypt(u, v, resp, key):
print("[!] Wrong answer!")
exit()
print(f"[+] Flag: {flag}")
except:
exit()

Binary file not shown.

Binary file not shown.

Binary file not shown.