#!/usr/local/bin/python import os import base64 import hashlib import secrets import…
- User
#!/usr/local/bin/python
import os import base64 import hashlib import secrets
import datetime
b64 = "off" # Base64 encoding mode SECURE_PREFIX = secrets.token_hex(16).encode()
def generate_safe_file_access_key(filename: str) -> str: return hashlib.sha256(SECURE_PREFIX + filename.encode("latin")).hexdigest()
if name == "main": print("Welcome to the CNS3 server!") print("Type 'help' for a list of commands")
while True: line = input("> ") if line == "exit": break elif line == "help" or line.startswith("help "): if len(line.split(" ")) == 1: print("""Commands: help [<sub-command>] - show help message ls - list files in the bucket b64 {on | off} - enable or disable base64 encoding get <file> <key> - get the file from the bucket put* <file> - put the file to the bucket (* Not implemented) exit - exit the program""") else: subcommand = line.split(" ")[1] if subcommand == "b64": print("""b64 {on | off} - enable or disable base64 encoding on - enable base64 encoding for filename and content off - disable base64 encoding for filename and content""") elif subcommand == "get": print(f"""get <file> <key> - get the file from the bucket file - the file to get key - the key to decrypt the file Example: get README.md {generate_safe_file_access_key("README.md")}""") elif line == "ls": for file in os.listdir("bucket"): path = os.path.abspath(os.path.join("bucket", file)) fsize = os.path.getsize(path) if fsize < 1024: fsize = f"{fsize}B" elif fsize < 1024 * 1024: fsize = f"{fsize / 1024:.1f}K" else: fsize = f"{fsize / 1024 / 1024:.1f}M" fctime = datetime.datetime.fromtimestamp(os.path.getctime(path)) if fctime.year != datetime.datetime.now().year: fctime = fctime.strftime("%b %d %Y") else: fctime = fctime.strftime("%b %d %H:%M") print(f"-r--r--r-- 1 CNS3 CNS3 {fsize} {fctime} {file}") elif line.startswith("b64 "): b64 = line.split(" ")[1] if b64 == "on": print("Base64 encoding enabled") elif b64 == "off": print("Base64 encoding disabled") else: print("Unknown option") elif line == "get" or line.startswith("get "): parts = line.split(" ") if len(parts) != 3: print("Invalid number of arguments") continue file = parts[1] if b64 == "on": file = base64.b64decode(file.encode()).decode('latin') key = parts[2] try: assert key == generate_safe_file_access_key(file) path = os.path.abspath(os.path.join("bucket", file)) with open(path, "r") as f: data = f.read() if b64 == "on": data = base64.b64encode(data.encode()).decode() print(data) except AssertionError: print("Invalid key") except: print("File not found") elif line == "put" or line.startswith("put "): parts = line.split(" ") if len(parts) != 2: print("Invalid number of arguments") continue file = parts[1] print("Not implemented :P") else: print("Unknown command") - Assistant
- User
from pwn import *
def getLineMSG(r): txt = r.recvline() print('server : ', txt) return txt
def getLinesTimeout(r, timeout): while True: txt = r.recvline(timeout=timeout) if not txt: break print('server : ', txt)
r = remote('cns.csie.org', 13333) getLinesTimeout(r, 0.5) r.sendline('help') getLinesTimeout(r, 0.5) r.sendline('b64 off') getLinesTimeout(r, 0.5) r.sendline('ls') getLinesTimeout(r, 0.5) r.sendline('b64 on') getLinesTimeout(r, 0.5) r.sendline('ls') getLinesTimeout(r, 0.5)
This is a code that can request to the server(via r.sendline(command)). How to implement a attacking scheme on it? You can also import other packages.
- Assistant
Attack Plan: Bypass Key Verification to Download FLAG The goal is to retrieve FLAG without knowing the correct key. Based on the weaknesses identified earlier, we will attempt the following attacks:
Exploit Base64 Mode (b64 on)
List files in Base64 mode and check if FLAG changes.
If filenames change, try to infer the Base64 encoding pattern.
- User
I miss an information that the key of README.md is given, in that case, how to design the attack to get 'FLAG'?
- Assistant
- User
Ok, first, tell me how many bits of the two have:
-
SECURE_PREFIX = secrets.token_hex(16).encode()
-
def generate_safe_file_access_key(filename: str) -> str: return hashlib.sha256(SECURE_PREFIX + filename.encode("latin")).hexdigest()1
-
- Assistant
Let's analyze the bit lengths of both SECURE_PREFIX and generate_safe_file_access_key():
- SECURE_PREFIX Bit Length python複製編輯SECURE_PREFIX = secrets.token_hex(16).encode()
secrets.token_hex(16) generates 16 bytes (128 bits) of random data and converts it to a hex string.
Each byte is represented as two hex characters, so token_hex(16) produces 32 hex characters.
Encoding it (.encode()) does not change its size in bytes.
Result:
SECURE_PREFIX has 128 bits (16 bytes) of entropy.
- Bit Length of generate_safe_file_access_key() python複製編輯def generate_safe_file_access_key(filename: str) -> str: return hashlib.sha256(SECURE_PREFIX + filename.encode("latin")).hexdigest()
hashlib.sha256(...) produces a 256-bit hash (32 bytes).
.hexdigest() converts it into a 64-character hex string (each hex character = 4 bits).
Result:
The output of generate_safe_file_access_key() is 256 bits (64 hex characters).
Final Answer Variable / FunctionBitsBytesSECURE_PREFIX128 bits16 bytesgenerate_safe_file_access_key()256 bits32 bytes (64 hex characters) Would you like to discuss how feasible it is to brute-force SECURE_PREFIX? 🚀
- User
The only attack i know is to use a valid hash(PREFIX+README and its key) to generate other valid result that are pairs of PREFIX+README+M_new and KEY_new by ength extension attacks. Will this make bruteforcing more feasible in some way?
- Assistant
- User
The file access key is genenrated by sha256, so it is prone to length extension attack. The SECURE_PREFIX is in front of the filename, so we can use length extension attack to do directory traversal. The block size of sha256 is 512, so we need to fill padding to make the last block same as before, then we put append message in a totally new block. "README.md" + padding + "/../FLAG"
Where the append_data is /../FLAG, original_data and original_key is from help get, and the secret key length is 16 bytes represented in hex 24, so is 32. And since the padding contains special character, to ensure the message is correct, we should turn b64 on before getting the flag.
I finally figure out something ans write it down. Do you agree with my idea?
- Assistant
- User
Yes, write a python version and assume that I know the key of "README.md", which is "XXX"
- Assistant