Dev.to Security 🔐 Cybersecurity 👁 0 📖 12 min read

Never IP:port — per-team CTF instances with frp, WireGuard and HMAC flags

Picture a CTF where every web or pwn challenge is published as public-ip:port. Two teammates launch the same challenge and step on each other's box. A player runs a port scan against the platform and lands on another tea

Picture a CTF where every web or pwn challenge is published as public-ip:port. Two teammates launch the same challenge and step on each other's box. A player runs a port scan against the platform and lands on another team's instance. And on boot2root machines, where finding the services is the challenge, you have just handed out the answer in the connection string.

That was the model we started from. This article is about the one we ended up running instead: one container per player, one flag per team, and a rule that no instance is ever reachable as IP:port.

Context: NCTF26

NCTF26 is the 4th National CTF of Togo, organized by CERT.tg: an online qualifier (6 November 19:00 to 7 November 23:59 UTC), then a 24-hour on-site final in Lomé (19 November 11:40 to 20 November 11:40 UTC) for 10 teams and 47 players. 609 challenges were played over the two phases. I was the technical lead. The public site is still up at https://ctf.tg; the cloud infrastructure was deleted on 21 November 2026.

The architecture in one picture

Two machines did all the work:

  • a front running CTFd, nginx, the frp server and a small SNI router;
  • an arena running Docker, where every player box lives, plus the frp client.

The arena never exposes a challenge port to the internet. Each container publishes its port on the arena's loopback only, and the frp client opens an outbound tunnel to the front. Players only ever talk to the front.

                         FRONT
 Player --https://<label>.<instance-domain>-------> nginx (wildcard cert) --+
 Player --ncat --ssl <label>.<instance-domain> ---> SNI router (TLS) -------+--> frps
 Player --WireGuard (UDP) ------------------------> frps UDP proxy ---------+
                         CTFd + instancer plugin --(filtered Docker API)--> arena
                                    ^
                                    | frp tunnel, opened outbound by the arena
                         ARENA      |
                                  frpc --> player boxes (ports on loopback only)
                                       --> team WireGuard gateway --> VPN boxes (fixed private IPs)

CTFd reaches the arena's Docker daemon through a filtering proxy, not a raw socket. That proxy only lets through the operations the instancer needs, keeps published ports on loopback, and refuses extra capabilities, sysctls and devices, with one narrow exception for the WireGuard gateway image. A web app that can create containers is a web app that can own the host; we treated that channel as the most sensitive part of the design.

Lifecycle of an instance

The instancer is a CTFd plugin (about 2,400 lines of Python). From the player's side it comes down to four actions: launch, check status, renew, destroy.

Spawn. The plugin checks that the challenge is visible and its prerequisites are met, that the player is in a team, and that the per-team and global caps are not exceeded. It re-checks the caps after inserting the instance row, so two teammates clicking at the same time settle it without an SQL lock. Then it:

  1. picks the access mode of the challenge (more on that below), frozen for the life of the instance;
  2. draws a random public label: 16 base32 characters, 80 bits;
  3. creates the container on the arena with labels (team, user, challenge) and hard limits;
  4. adds an frp proxy for that container through the frp client's admin API (read config, write config, reload), under a lock.

Each box got 128 MiB of RAM, half a CPU and a 256-process limit by default, overridable per challenge up to a ceiling. An instance lived one hour and could be renewed five times. The global cap was 480 instances.

One instance per (player, challenge), flag per team. In the first version, teammates shared one instance and kept getting in each other's way. On 29 October we switched to one box per player and kept the flag and the quota at team level. The per-team cap went from 4 to 6 between the qualifier and the final, because the Defense challenges keep a "production box" alive per team.

Reaper. A background thread, run by a single worker thanks to a file lock, passes every 30 seconds. It deletes expired instances, rows whose container vanished, labelled containers with no row, and stops a team's VPN gateway when the team has no VPN instance left.

A generic sketch of the spawn path, stripped of everything specific:

import base64
import os

def spawn(player, challenge):
    check_visible_and_unlocked(challenge, player)
    row = insert_instance_row(player, challenge, state="spawning")
    if over_team_cap(player.team) or over_global_cap():
        delete_row(row)
        raise TooMany()

    mode = challenge.access_mode            # "https" | "tls" | "vpn"
    label = base64.b32encode(os.urandom(10)).decode().lower()  # 16 chars, 80 bits

    env = {"FLAG": team_flag(player.team.id, challenge.slug)}
    container = docker.containers.run(
        challenge.image, detach=True, environment=env,
        mem_limit="128m", nano_cpus=500_000_000, pids_limit=256,
        labels={"instancer": "1", "team": str(player.team.id)},
        ports={f"{challenge.port}/tcp": ("127.0.0.1", allocate_port())},
    )
    with frpc_lock(timeout=60):
        add_frp_proxy(label, mode, container)
    mark_running(row, label)

Three ways in, none of them IP:port

On 30 October, a week before the qualifier, we decided that instances would no longer be exposed as public IP:port. Three modes replaced it, chosen per challenge.

Mode For What the player sees Path
https web https://<random-label>.<instance-domain>/ nginx (wildcard certificate) → frp HTTP vhost, subdomain = label
tls raw TCP (pwn, nc), HTTP that must stay raw ncat --ssl <random-label>.<instance-domain> <port> SNI router terminates TLS, reads the SNI, relays to the private frp port
vpn boot2root, multi-port, UDP a private IP + a WireGuard config per-team gateway

https. The simplest one. A wildcard certificate in front of nginx, and frp's HTTP vhost routes on the subdomain. With 80 random bits per label, you do not guess another team's instance.

tls. For services that speak raw TCP, there is no Host header to route on. The SNI of the TLS handshake plays that role. The router terminates TLS with the same wildcard certificate, asks CTFd which private port the label maps to (an internal endpoint protected by a shared key, which answers an empty 404 on any failure), and pipes bytes. For the player:

ncat --ssl <random-label>.<instance-domain> <port>
# or, from a pwntools script:
# remote(host, port, ssl=True, sni=host)

vpn. For machines where discovering services is part of the game, a subdomain does not help: it hides nothing about the ports. Each team gets its own WireGuard gateway container on the arena, its own Docker network and its own private /24. Instances in VPN mode get a fixed private IP; the player scans them like a lab.

The per-team WireGuard VPN

The design goals were: no state to leak, nothing else reachable, and no per-player setup by an organizer.

  • Gateway on demand. A team's gateway starts with its first VPN instance and stops with its last one.
  • A stable slot per team for the whole event, which fixes its subnets and its UDP port. frp publishes that UDP port on the front.
  • Derived server key. The gateway's private key is derived from a master secret with HMAC and a domain separator. Nothing is stored.
  • Player keys generated on click. "Generate my config" creates a key pair; only the public key is kept. Generating again replaces the key, which revokes the previous file and restarts the team's gateway for a few seconds.
  • A tight firewall in the gateway, set before the interface comes up: forwarding only from the tunnel to the team's subnet, return traffic limited to established connections, NAT into the team network. No internet, no cloud network, no metadata endpoint, no access to other teams.

The client file is deliberately minimal: no DNS line, no default route. Only challenge traffic goes through the tunnel.

[Interface]
PrivateKey = <generated for this player, stored nowhere>
Address    = <team client range>/32
MTU        = 1380

[Peer]
PublicKey           = <team gateway public key>
Endpoint            = <vpn-host>:<team port>
AllowedIPs          = <team instance range>/24
PersistentKeepalive = 25

Because ping does not always cross the tunnel, the advice we drafted for players was a TCP scan without host discovery:

nmap -Pn -sT -p- --min-rate 2000 <instance-ip>

Flags derived per team, stored nowhere

Every instance challenge has a flag of type "team HMAC". Its content is just the challenge's slug. The flag is computed, never stored:

import hmac, hashlib

def h(key: str, msg: str) -> str:
    return hmac.new(key.encode(), msg.encode(), hashlib.sha256).hexdigest()

def team_flag(master: str, team_id: int, slug: str) -> str:
    team_secret = h(master, str(team_id))
    challenge_secret = h(team_secret, slug)
    return "NCTF{" + challenge_secret[:24] + "}"

At submission, CTFd recomputes the expected flag for the submitting team and compares in constant time. Consequences we relied on:

  • The box never sees the master secret. It only receives values derived for its own team and challenge, so a player who gets root on their box cannot compute any other flag.
  • The whole team shares the flag, even though each player has their own box.
  • A flag that shows up in the wrong team is visible: it is, by construction, another team's correct answer.
  • Replaying challenges is cheap. For the final, we renamed the slug of the 69 qualifier challenges we kept. Every team got new flags, and since the flag is injected at launch, the images themselves did not have to change for that.

199 challenges used per-team flags during the qualifier.

What went wrong, and why

The unsafe default was still the default. The code fell back to port mode when a challenge had no mode, or when the infrastructure for its mode was not configured, and it did so silently. Our import tool for creators' challenges never wrote the access mode. A dry run on 14 November, five days before the final, found the gap in the release plan. On 15 November we classified the 46 challenges that still had no mode: 18 VPN, 10 HTTPS, 18 TLS. We fixed the data; the default itself was never changed. That is the first thing I would fix.

A proxy chain is not transparent. In https mode, nginx and frp route on Host, set their own X-Forwarded-* headers and normalize requests. Any challenge whose intended solve spoofs those headers, or relies on HTTP request smuggling, breaks. Four challenges had to move to tls between 15 and 17 November. We searched solvers and writeups for those headers, but a challenge without a text solver escapes that search; only replaying the solver through the player's URL catches it.

A blocking lock under gevent. The frp configuration is edited under a file lock. The first version used a blocking flock. Under gevent, a second greenlet waiting on that lock froze its whole worker, and the holder could never release it. On 7 November that turned into 502s with the CPU at 0%. The fix was a non-blocking lock in a cooperative retry loop:

import fcntl, time

def acquire(fd, timeout=60):
    deadline = time.monotonic() + timeout
    while True:
        try:
            fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
            return
        except BlockingIOError:
            if time.monotonic() > deadline:
                raise TimeoutError("lock busy")
            time.sleep(0.05)   # monkey-patched by gevent: yields to other greenlets

That incident gets its own article in this series.

frpc stopped answering reloads. The same day, the frp client, running for eight days, still answered "read config" but no longer "reload". Every spawn held the lock during a reload that never returned. A restart fixed it; from then on, a watcher probed reload latency every 3 minutes and alerted after two slow or failed probes in a row.

Orphan proxies. When removing a proxy failed, its block stayed in the config while the container was gone. The port went back to the pool, got reassigned, and the frp server refused the duplicate. We cleaned 33 orphans by hand. The reaper never learned to sweep proxies without a container.

Volumes leak. Containers were removed without their anonymous volumes. By 15 November the arena held 801 orphan volumes, 25.65 GB.

Entrypoints that ignore FLAG. Every "correct flag rejected" of the event had the same root cause: a creator's entrypoint that generated its own random flag, or a Dockerfile ENV that took precedence. Our pre-flight check confirmed that FLAG was in the environment, not that the file the player reads contained it. One of these surfaced mid-final. We fixed the image, but a flag read from the broken image could never be accepted: the team had to relaunch the instance and solve again. A related shell trap worth knowing:

# Broken: the first "}" ends the expansion, so when FLAG is set
# the value ends with "}}"
FLAG="${FLAG:-NCTF{local_test}}"

# Safe
f="${FLAG:-}"
[ -n "$f" ] || f='NCTF{local_test}'
printf '%s\n' "$f" > /flag

The VPN lifecycle surprised players. The tunnel of a team only exists while it has at least one VPN instance. A player who connects WireGuard before launching anything has nothing in front of them. During the final, gateways were recreated several times an hour as teams launched and destroyed boxes. The fix was an instruction to players, not code: launch first, then connect, and reconnect if the gateway was just recreated. And I only ran the complete player path (real client, handshake, HTTP 200, flag accepted) for the first time the night before the final. It worked, but that was luck, not process.

What I would do again, and what I would change

Again: loopback-only ports plus an outbound tunnel; random labels; a per-team VPN with derived keys and a firewall set before the interface; flags derived instead of stored; a filtering proxy in front of the Docker API; hard resource limits on every box.

Change:

  1. Make the safe mode the default, and make the importer write the access mode. An import without a mode must fail, not fall back to IP:port.
  2. Fail the pre-flight on the real criterion: the flag the player reads, at production memory limits, through the player URL, in the challenge's real access mode.
  3. Teach the reaper to sweep orphan frp proxies and to delete volumes with containers.
  4. Test the VPN end to end with a real client weeks before, not the night before, and show the date of the active key on the VPN page.
  5. Publish a contract for creators: read FLAG, never generate it; declare the access mode and ports; ship a solver that takes a URL.

Key takeaways

  • Never publish an instance as IP:port. A random subdomain for web, TLS with SNI routing for raw TCP, a per-team VPN for multi-port boxes.
  • Your default is your real policy. If the fallback is the unsafe mode, some challenge will reach production in that mode.
  • Derive flags, do not store them. HMAC of team and challenge gives you per-team flags, cheap replays and a box that knows only its own secret.
  • Proxies rewrite requests. Any challenge whose solution plays with HTTP headers needs a raw transport.
  • Under cooperative workers, never block. A blocking lock freezes the whole worker, not one request.

Next in the series

This is part of NCTF26: running a national CTF. The next article is the post-mortem of the day the platform froze at 0% CPU. Results are on ctf.tg, the credits of every challenge author at ctf.tg/merci, community writeups at ctf.tg/writeups and ideas for NCTF27 at ctf.tg/idees.

Next in the series: CPU at 0% and 502s in a loop: how one blocking lock froze our national CTF platform

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.