writeups / crypto / server-rouletteNo.01

Server Roulette

EventBreak the Syntax CTF 2025Date2025.05.13

Category: crypto. Tags: none.

Source Code

The server runs the following script; we interact with it over a socket.

from hashlib import sha256
import secrets


def get_color(number):
    """Determine roulette color for a given number"""
    if number == 0:
        return 'green'
    return 'red' if number % 2 == 1 else 'black'


def main():
    print("Welcome to Provably Fair Roulette!")

    with open('flag', 'rt') as f:
        FLAG = f.read()

    streak_13 = 0
    while True:
        # Generate server seed and its hash
        server_seed = sha256(bytes(secrets.randbits(17))).hexdigest()
        server_seed_hash = sha256(server_seed.encode()).hexdigest()

        print(f"Server seed hash (verify later): {server_seed_hash}")

        # Get client seed
        print("Enter your client seed (press enter to generate): ", end="")
        client_seed = input().strip()
        if not client_seed:
            client_seed = secrets.token_bytes(8).hex()
            print(f"Generated client seed: {client_seed}")

        # Generate game hash
        combined = f"{server_seed}:{client_seed}"
        game_hash = sha256(combined.encode()).hexdigest()
        hash_int = int(game_hash, 16)

        # Calculate roulette result
        roulette_number = hash_int % 37  # 0-36
        roulette_color = get_color(roulette_number)

        # Get user's bet
        while True:
            print("Place your bet (number 0-36 or color red/black/green): ", end="")
            bet = input().strip().lower()
            if bet in ['green', 'red', 'black']:
                break
            try:
                num = int(bet)
                if 0 <= num <= 36:
                    bet = str(num)  # Standardize to string for comparison
                    break
                print("Number must be between 0-36")
            except ValueError:
                print("Invalid bet. Enter number (0-36) or color (red/black/green)")

        # Determine result
        result_str = f"{roulette_number} ({roulette_color})"
        print(f"\nThe wheel lands on: {result_str}")

        # Check win conditions
        win = False
        if bet.isdigit():
            win = int(bet) == roulette_number
        else:
            win = bet == roulette_color

        if win:
            print("Congratulations! You win! ")
            if roulette_number == 13:
                print("...and you got 13, double congratulations!")
                streak_13 += 1
            else:
                print("But it's not 13, no streak for you")
                streak_13 = 0
        else:
            print("Sorry, you lose!")
            streak_13 = 0

        # Verification information
        print()
        print("Verification Details:")
        print(f"Server seed: {server_seed}")
        print(f"Client seed: {client_seed}")
        print(f"Combined string: {combined}")
        print(f"Game hash: {game_hash}")
        print(f"Calculated number: {roulette_number}")
        print(f"Resulting color: {roulette_color}")

        if streak_13 == 37:
            print("How? How is it possible? What was the chance?! "
                  f"Anyway, here's your flag, congratulations... {FLAG}")
            exit()


if __name__ == "__main__":
    main()

Code Analysis

Each round works like this:

  1. The server picks server_seed = sha256(bytes(secrets.randbits(17))).hexdigest(). Calling bytes(k) with an integer k produces k zero bytes, so the seed is the hash of a run of between 00 and 217−12^{17}-1 null bytes. There are only 217=131,0722^{17} = 131{,}072 possible seeds.
  2. It prints sha256(server_seed) as a commitment.
  3. We choose a client seed. The result is int(sha256(f"{server_seed}:{client_seed}"), 16) % 37.
  4. The streak increases only when we bet 13 and the wheel lands on 13. Any other outcome, including a correct bet on another number or color, resets it to 00.

The flag requires a streak of 3737, which by chance has probability (1/37)37(1/37)^{37}.

Approach

The commitment hides much less than it should. With only 2172^{17} server seeds, we can precompute every seed’s hash, so the printed hash tells us the exact server seed. We also control the client seed, so for each server seed we can search for a client seed that makes the result 1313. Every round then becomes deterministic: look up the printed hash, send the matching client seed, and bet 1313.

Precomputing Client Seeds

from hashlib import sha256
import json

server_hash_db = {}

# Generate server seed and hash
for i in range(2 ** 17):
    server_seed = sha256(bytes(i)).hexdigest()
    server_seed_hash = sha256(server_seed.encode()).hexdigest()

    # Find corresponding client seed
    for j in range(1000):
        combined = f"{server_seed}:{j}"
        game_hash = sha256(combined.encode()).hexdigest()
        hash_int = int(game_hash, 16)
        if hash_int % 37 == 13:
            server_hash_db[server_seed_hash] = j
            break

with open("sol-server_seeds.json", "w") as f:
    json.dump(server_hash_db, f, indent=2)

For each possible server seed, the script tries client seeds 0, 1, 2, … until the result is 1313, and maps the seed’s hash to that client seed. Each attempt succeeds with probability 1/371/37, so about 3737 tries are expected; none needed more than 200200, well under the cap of 10001000.

The result is a JSON lookup table:

{
  "cd372fb85148700fa88095e3492d3f9f5beb43e555e5ff26d95f5a6adc36f8e6": 8,
  "bb7c53d34f6384244da5d41af9523beb234190b8209ec56dec7b7ecee341c300": 5,
  "d3181ef76c9daf05afba3c94ff4e341a834ee2854e36fbeb8388352d2fd23b35": 3,
  ...
}

Playing 37 Rounds

The 37 rounds could be played by hand with the table, but pwntools automates them.

from pwn import *
import json

# server seeds database
with open("sol-server_seeds.json", "r") as f:
    winning_seeds = json.load(f)

HOST = "localhost"
PORT = 1337

r = remote(HOST, PORT)

streak = 0

while True:
    try:
        # Read server seed hash
        r.recvuntil(b"Server seed hash (verify later): ")
        server_seed_hash = r.recvline().strip().decode()
        print(f"Server seed hash: {server_seed_hash}")

        # Send number from database
        client_seed = winning_seeds[server_seed_hash]
        print(f"Sending: {client_seed}")
        r.recvuntil(b"Enter your client seed (press enter to generate): ")
        r.sendline(str(client_seed).encode())

        # Send 13
        print(f"Sending: 13")
        r.recvuntil(b"Place your bet (number 0-36 or color red/black/green): ")
        r.sendline(b"13")
        
        # Check response
        response = r.recvuntil(b"Verification Details:").decode()
        streak += 1
        print(f"Win #{streak}")
        
        if streak == 37:
                print("Receiving final message:")
                final_output = r.recv().decode()
                print(final_output)
                r.close()
                break
    except EOFError:
        print("Connection closed early")
        break

Each round, the script reads the server seed hash, sends the matching client seed from the table, bets 13, and waits for the verification block before moving on. After the 37th win, it prints the final message.

Final Result

[+] Opening connection to localhost on port 1337: Done
Server seed hash: fbee1b5973470403ba6505796e20d518c26576396433a7931f040aec0f00949e
Sending: 6
Sending: 13
Win #1
Server seed hash: 8b355c227c3eef280dadc4d7f3315bce32dc9a56e55f93d811f1b5786edfc84a
Sending: 29
Sending: 13
Win #2
...
Server seed hash: 189390e66b472d3cc900563f73e3052fb2616eeca69c0226d8d68c69b7e2c73c
Sending: 28
Sending: 13
Win #37
Receiving final message:

Server seed: ece3072155b4392939a7739c57cc307aac2dccef70eae1927b098a7a8c5fb81f
Client seed: 28
Combined string: ece3072155b4392939a7739c57cc307aac2dccef70eae1927b098a7a8c5fb81f:28
Game hash: abfc04810ff67c47736d18c2cf1d76f3f0842df4ee61fcbf01e256a6e10f5b31
Calculated number: 13
Resulting color: red
How? How is it possible? What was the chance?! Anyway, here's your flag, congratulations... FLAG

[*] Closed connection to localhost port 1337
912 words↑ Top