The Missing Link: Draytek’s New RCEs Complete the Chain

O. Gianatiempo (Security Researcher · Faraday), G. Aznarez (Security Researcher · Faraday)

DEF CON 33 · Day 1 · Main Stage

Overview

This talk, presented by Gastonas Narees and Octavio Gianatiempo, security researchers at Faraday, unveils new pre-authentication remote code execution (RCE) vulnerabilities in Draytek routers. Building upon their previous research at DEF CON, which focused on achieving kernel-level persistence on these devices, the speakers demonstrate how these latest discoveries can be chained with older vulnerabilities to achieve a full exploit chain: from an unauthenticated internet-facing attack to deep, persistent compromise of the router's operating system. The presentation meticulously details the technical intricacies of these vulnerabilities, their exploitation, and their potential connection to widespread router reboots observed in early 2024.

Watch on YouTube

Visual summary for The Missing Link: Draytek’s New RCEs Complete the Chain by O. Gianatiempo, G. Aznarez
Visual summary for The Missing Link: Draytek’s New RCEs Complete the Chain by O. Gianatiempo, G. Aznarez

Key moments

  1. 0:00 Introduction and talk goal: complete RCE chain
  2. 1:00 Recap: Draytek routers and previous findings
  3. 3:50 The missing link: achieving pre-authentication RCE
  4. 4:15 Drybreak research inspired new vulnerability discovery
  5. 5:25 First new vulnerability: TR69 buffer overflow explained
  6. 7:10 Visualizing getCGI buffer overflow via parameter count
  7. 9:25 TR69 allows unauthenticated queries to the router
  8. 10:30 Introducing the second bug: integer overflow in CGI

The Missing Link: Draytek’s New RCEs Complete the Chain

Speakers: O. Gianatiempo (Security Researcher, Faraday), G. Aznarez (Security Researcher, Faraday)

Conference: DEF CON

YouTube: https://www.youtube.com/watch?v=CUZhORHp27U

Overview

This talk, presented by Gastonas Narees and Octavio Gianatiempo, security researchers at Faraday, unveils new pre-authentication remote code execution (RCE) vulnerabilities in Draytek routers. Building upon their previous research at DEF CON, which focused on achieving kernel-level persistence on these devices, the speakers demonstrate how these latest discoveries can be chained with older vulnerabilities to achieve a full exploit chain: from an unauthenticated internet-facing attack to deep, persistent compromise of the router's operating system. The presentation meticulously details the technical intricacies of these vulnerabilities, their exploitation, and their potential connection to widespread router reboots observed in early 2024.

The research highlights the complex attack surface presented by embedded systems, particularly those running custom real-time operating systems (RTOS) or emulating them. By dissecting the internal workings of Draytek’s firmware, Narees and Gianatiempo expose critical flaws in common parsing functions, transforming seemingly innocuous bugs into powerful primitives for arbitrary code execution. Their work not only provides a comprehensive understanding of the exploitability of Draytek devices but also offers critical insights into defensive strategies for mitigating such advanced threats in the realm of small business and enterprise networking equipment.

The significance of this research extends beyond Draytek routers, serving as a stark reminder of the persistent security challenges in embedded and IoT devices. The ability to achieve pre-authentication RCE followed by kernel-level persistence represents a worst-case scenario for device owners, allowing attackers to maintain control even across reboots, factory resets, and firmware updates. This talk is crucial for network administrators, security professionals, and anyone involved in securing critical infrastructure or managing internet-connected devices.

Background

▶ Watch: Introduction and talk goal: complete RCE chain (0:00)

Faraday's engagement with Draytek router security is not new; Gastonas Narees and Octavio Gianatiempo previously presented at DEF CON, focusing on methods for detecting and achieving persistence on these devices. Their earlier work established a foundational understanding of Draytek's diverse product lines. Small business routers typically utilize a MIPS32 CPU running a proprietary DryOS (Real-Time Operating System). Interestingly, Draytek's medium-sized enterprise routers, despite featuring an ARM CPU and Linux, emulate the same DryOS environment using QEMU. This emulation is a critical detail, as vulnerabilities found in the DryOS on smaller devices are often transferable to the more powerful enterprise models.

The attack surface for Draytek routers is substantial, with over 500,000 devices found to be exposed online, many concentrated in the UK. Prior research, including the speakers' own, had uncovered a range of vulnerabilities, from information disclosure to authenticated remote code execution. These included issues like missing SSL certificate validation, non-constant-time password comparisons susceptible to side-channel attacks, insecure password storage practices, predictable two-factor authentication (2FA) code generation, and a DHCP server null reference vulnerability that could trigger device reboots or denial of service (DoS). Crucially, their previous work also demonstrated methods to upload arbitrary kernel modules to the devices, enabling kernel-level persistence.

At the time of their previous talk, the full exploit chain required an initial foothold, typically through password reuse, default credentials, or a 2FA bypass, leading to authenticated code execution, which then allowed for kernel-level persistence. However, the ultimate goal remained elusive: a pre-authentication vulnerability that could grant code execution directly from the internet, thus completing the "missing link" in the attack chain. To assist the community in further research, the team released Draytek Arsenal, a tool available on GitHub designed to aid in reverse engineering and vulnerability discovery for these routers, which has since been updated to support newer firmware versions.

The impetus for revisiting Draytek routers came from external research: "DryBreak," presented by Forescout at Black Hat Europe 2024. This research specifically highlighted a buffer overflow in a function named get_cgi. This discovery was a "wake-up call" for the Faraday team, as their extensive prior reverse engineering and malware development had not focused on the CGI request parser — a critical omission that revealed a new, vulnerable pattern and a significant untapped attack surface. Recognizing this gap, Narees and Gianatiempo redirected their efforts to this overlooked component, leading to the discovery of the two new pre-authentication vulnerabilities that form the core of this talk and ultimately complete the desired exploit chain.

Key Findings

▶ Watch: The missing link: achieving pre-authentication RCE (3:50)

The core contribution of this research lies in the discovery and exploitation of two new pre-authentication vulnerabilities in Draytek routers, which, when combined with existing knowledge, forge a complete exploit chain from the internet to deep, persistent kernel compromise.

  1. Buffer Overflow in TR-069 STUN Parsing: The first major finding is a buffer overflow within the function responsible for parsing TR-069 STUN requests. This vulnerability bears a striking resemblance to the get_cgi buffer overflow identified by Forescout, suggesting a common underlying vulnerable pattern in Draytek's codebase. While the Forescout vulnerability targeted stack overflows in query string parameters processed by get_cgi, Faraday's discovery extends this pattern to the TR-069 handler, which they hypothesize may have inlined the vulnerable get_cgi logic. This flaw allows an attacker to overwrite critical stack data, including the function's return address, leading to remote code execution.
  1. Integer Overflow Leading to Heap Overflow in get_cgi (POST Requests): The second, and arguably more potent, finding is an integer overflow within the get_cgi function itself, specifically when handling POST requests. By manipulating the Content-Length header in an HTTP request, an attacker can trigger a signed integer overflow. This overflow causes the router's malloc function to allocate an extremely small, negative-sized buffer, leading to a heap overflow. This heap overflow corrupts the slab allocator's metadata, transforming it into a powerful arbitrary write primitive. This primitive is then leveraged to overwrite MIPS exception handler pointers, redirecting the execution flow to attacker-controlled shellcode.

These two vulnerabilities provide the crucial pre-authentication RCE capabilities that were previously missing. By chaining the integer/heap overflow with the speakers' existing knowledge of Dynamically Loadable Modules (DLMs) for persistence and their prior null reference vulnerability for exception triggering, they established a full, end-to-end exploit chain. This chain allows an attacker to gain unauthenticated RCE, change administrative passwords, upload malicious kernel modules, and establish persistent backdoors that survive reboots, factory resets, and even firmware updates.

Finally, the research offers a compelling hypothesis regarding the widespread Draytek router reboots observed in March 2024. The speakers suggest that these reboots were likely caused by failed exploitation attempts of these very vulnerabilities, where attackers were unable to correctly calculate payload landing addresses across diverse firmware versions and router models. This implies that if there were failed attempts, there were almost certainly successful, albeit silent, compromises, underscoring the real-world impact and active exploitation of these critical security flaws.

Technical Deep Dive

▶ Watch: First new vulnerability: TR69 buffer overflow explained (5:25)

The technical core of this talk revolves around two distinct, yet related, pre-authentication vulnerabilities and the sophisticated techniques used to chain them for remote code execution and persistence.

Vulnerability 1: Buffer Overflow in TR-069 STUN Parsing

The first vulnerability identified is a classic buffer overflow affecting the function responsible for handling TR-069 STUN (Session Traversal Utilities for NAT) connections. This discovery was spurred by Forescout's prior research, which highlighted a stack buffer overflow in the get_cgi function when processing query string parameters. Faraday's team found a similar vulnerable pattern within the TR-069 handler, suggesting that the compiler might have inlined the get_cgi function or a similar parsing logic into the STUN handler.

Let's dissect the get_cgi function's behavior, as it serves as the blueprint for this vulnerability. The function typically takes two main arguments: a buffer (often located on the stack) and the query string itself. It then iterates through the query string, parsing arguments separated by an ampersand (&). For each argument, a helper function, make_word, is called. This function first copies the current argument to the heap, then cleans it up by replacing plus signs (+) with spaces and performing URL decoding. Next, it locates the equal sign (=) separating the key from its value, replacing it with a null character. Finally, it stores the memory addresses of both the key and the value into the provided buffer.

The critical flaw here is the lack of bounds checking on the number of parameters being parsed. As the function iteratively stores key and value pointers into the stack-allocated buffer, supplying a sufficiently large number of arguments will eventually cause these pointers to overwrite data beyond the buffer's intended boundaries. Critically, this includes the return address of the current function on the stack. By controlling the return address, an attacker can redirect program execution to an arbitrary location, achieving remote code execution (RCE).

To exploit this specific TR-069 STUN vulnerability, the TR-069 service must be enabled on the router. When active, the router listens on a UDP port (a non-default STUN port) for incoming connections. An attacker can send specially crafted STUN queries to this port without requiring any prior binding requests or responses. While the speakers developed a proof-of-concept that crashed the router, indicating the buffer overflow, they did not pursue full RCE through this vector due to perceived interface restrictions. Instead, they focused on a more versatile bug.

Vulnerability 2: Integer Overflow Leading to Heap Overflow in get_cgi (POST Requests)

The second and more impactful vulnerability is an integer overflow within the get_cgi function itself, specifically when processing HTTP POST requests. This vulnerability resides in the same ubiquitous get_cgi function, which is called by virtually every CGI handler on the router.

When a POST request arrives, the get_cgi function first extracts the Content-Length header from the HTTP request. This value, representing the size of the request body, is then used to allocate memory on the heap to store the POST data. The crucial detail here is that the Content-Length is processed as a signed 32-bit integer.

The exploit works as follows: if an attacker sets the Content-Length header to the maximum positive value for a 32-bit signed integer (e.g., 0x7FFFFFFF), the router's internal malloc call attempts to allocate Content-Length + 1 bytes (the +1 is for a null terminator). This addition causes a signed integer overflow, resulting in a negative integer value (e.g., 0x80000000).

The router's malloc implementation, similar to the Content-Length processing, also uses signed comparisons for allocation sizes. When presented with a negative size, it incorrectly allocates memory from the smallest available slab cache, which on these Draytek routers is typically designed for objects of 24 bytes. However, the internal representation of these objects by the slab allocator is 32 bytes, comprising 24 bytes of user data and 8 bytes of metadata. This metadata includes information like the line of code that made the allocation, timestamp, offset, and critically, a checksum.

By sending a POST request with the crafted Content-Length and a body larger than 24 bytes, the attacker effectively triggers a heap overflow. The data written past the 24-byte user data boundary will overwrite the slab allocator's internal metadata, including the checksum. This corruption manifests as "slab panic" messages in the router's logs, indicating an integrity check failure.

More importantly, when objects in the slab allocator are not in use, the first part of their user data area is repurposed to store a pointer to the next free object, forming a linked list of available memory chunks. By overflowing a chunk and overwriting this "next free object" pointer, an attacker gains an arbitrary write primitive. If the attacker then triggers two subsequent memory allocations, the second allocation will return an address controlled by the attacker, allowing them to write arbitrary data to that location. While this process breaks the allocator's internal consistency, it does not prevent exploitation.

Code Execution Strategy (MIPS)

With the arbitrary write primitive established, the next step is to achieve code execution. Draytek routers, particularly the DryOS-based ones, run on MIPS architectures. In MIPS, all exceptions (e.g., illegal memory access, division by zero) trigger a jump to a general exception handler. This handler consults the cause coprocessor register to determine the specific exception type. It then uses this value as an index into a table of exception handler pointers, jumping to the corresponding specific handler.

The exploitation strategy leverages this mechanism:

  1. Shellcode Injection: The attacker sends their shellcode as part of a request. Due to the router's low-level network processing, this shellcode is typically stored in a fixed-offset low-level network reception buffer in memory.
  2. Arbitrary Write to Exception Table: Using the heap overflow's arbitrary write primitive, the attacker overwrites an entry in the MIPS exception handler table. Specifically, they target the pointer for the illegal address load exception handler, redirecting it to the memory address where the shellcode resides.
  3. Exception Trigger: To force the execution flow to the shellcode, an exception must be triggered. The speakers reuse a null reference bug from their previous research (the DHCP server null reference) to reliably trigger an illegal address load exception.
  4. Shellcode Execution: When the null reference exception occurs, the MIPS exception handler, now corrupted, jumps directly to the attacker's shellcode, granting arbitrary code execution in the context of the router's kernel.

This sophisticated chain demonstrates a deep understanding of MIPS architecture, embedded operating system internals, and memory management techniques, effectively turning a seemingly minor integer overflow into a full-fledged RCE.

Demo / Proof of Concept

▶ Watch: Visualizing getCGI buffer overflow via parameter count (7:10)

The talk includes compelling demonstrations that illustrate the impact of the discovered vulnerabilities, from a basic crash proof-of-concept to a full exploit chain achieving persistent access.

The first demonstration showcases the heap overflow resulting from the integer overflow. By sending a crafted POST request with the oversized Content-Length header, the router doesn't immediately crash. Instead, the console output is flooded with "slab panic" messages. These logs are direct evidence of the slab allocator's checksums being corrupted due to the overflow, confirming that the arbitrary write primitive is successfully triggered. The proof-of-concept then executes a simple payload that repeatedly prints "success" to the console, demonstrating code execution within the router's environment.

The main highlight is the full chain exploit demo, which seamlessly integrates all the discovered and previously known vulnerabilities to achieve complete control and persistence:

  1. Initial Access Check: The demo begins by attempting to log into the router via SSH using known credentials (e.g., default or a previously set password). This attempt fails, establishing the pre-authentication nature of the attack.
  2. Password Change and RCE Trigger: The attacker then sends a specially crafted HTTP POST request. This request contains two critical components:
  • A shellcode payload designed to change the router's administrative password to a known value.
  • The manipulated Content-Length header that triggers the integer overflow and subsequent heap overflow.

This action overwrites the MIPS illegal address load exception handler pointer with the address of the shellcode.

  1. Exception and Shellcode Execution: Immediately following the POST request, the attacker triggers the null reference vulnerability (from their previous research). This reliably causes an illegal address load exception. Because the exception handler pointer has been redirected, the router's execution flow is hijacked, and the shellcode to change the admin password is executed. The demo confirms the password change, indicating successful pre-authentication RCE.
  2. Malicious DLM Upload: With the new administrative password, the attacker now has authenticated access. They proceed to upload a malicious Dynamically Loadable Module (DLM). DLMs are kernel modules that extend the router's functionality (e.g., SSH daemon) and are dynamically loaded at boot. The speakers previously reverse-engineered the custom XDA encryption and LC4 compression algorithms used for DLMs, allowing them to create backdoored versions.
  3. Router Reboot and Persistence: After the malicious DLM is uploaded, the router is rebooted. This step is crucial for the DLM to be loaded by the operating system.
  4. Persistent Backdoor: Upon reboot, the malicious DLM executes. In this demonstration, the DLM creates a new user account with attacker-defined credentials. This new user coexists with existing accounts and remains undetected by legitimate users.
  5. SSH Access with Backdoor: Finally, the attacker successfully logs into the router via SSH using the credentials of the newly created backdoor user, demonstrating persistent, kernel-level access. This access persists even after reboots, factory resets, and firmware updates because DLMs are stored in a separate flash partition and given priority during boot.

The demo vividly illustrates the devastating impact of these vulnerabilities, transforming unauthenticated internet access into stealthy, persistent control over network infrastructure.

Defensive Implications

▶ Watch: Introducing the second bug: integer overflow in CGI (10:30)

The detailed findings from this research provide critical insights for Draytek router users and network defenders. The existence of pre-authentication remote code execution vulnerabilities, especially those leading to kernel-level persistence, demands immediate and decisive action.

  1. Immediate Firmware Updates: The most crucial defensive measure is to update Draytek router firmware immediately. The speakers explicitly state that the first set of bugs (likely including the TR-069 overflow) were fixed between August and October of 2023, and the last two vulnerabilities (including the get_cgi integer/heap overflow) were patched very quickly in November 2023. Ensuring all devices are running the latest available firmware is paramount to mitigate these specific threats. Users should regularly check Draytek's official security advisories and download updates.
  1. Reduce Attack Surface: Many vulnerabilities arise from exposing unnecessary services to the internet. Defenders should review their router configurations and disable any services that are not strictly required. For instance, if TR-069 is not actively used by an Internet Service Provider (ISP) or for remote management, it should be disabled to remove that attack vector. Similarly, other administrative interfaces should not be exposed directly to the public internet unless absolutely necessary, and if so, protected by strong access controls, VPNs, or IP whitelisting.
  1. Monitor for Anomalies and Reboot Patterns: The hypothesis regarding router reboots in the wild suggests that failed exploitation attempts can cause crashes. Defenders should monitor router logs for unexpected reboots or "slab panic" messages, which are direct indicators of the heap overflow vulnerability being triggered. Additionally, monitoring for unusual login attempts, newly created user accounts, or unexpected SSH activity (especially after reboots or factory resets) can help detect successful compromises through malicious DLMs.
  1. Strong Password Policies and 2FA: While the current exploits bypass authentication, robust password policies and the use of two-factor authentication (2FA) for administrative interfaces remain essential layers of defense. These measures protect against other attack vectors and limit the impact if an authenticated vulnerability were to be discovered or if an attacker gains initial access through non-technical means.
  1. Network Segmentation and Intrusion Detection: For larger organizations, network segmentation can limit the lateral movement of attackers even if a router is compromised. Intrusion Detection/Prevention Systems (IDPS) can be configured to detect suspicious network traffic patterns, such as malformed HTTP POST requests with anomalous Content-Length headers or unusual UDP traffic targeting STUN ports, potentially blocking exploitation attempts before they succeed.
  1. Supply Chain Security Awareness: This research also underscores the broader challenge of embedded system security. Organizations reliant on such devices should engage with vendors about their security practices, vulnerability disclosure programs, and commitment to timely patching. Users should assume that complex embedded systems will continue to harbor vulnerabilities ("bugs are like cockroaches," as Ivan Arce states), necessitating continuous vigilance and a layered security approach.

By implementing these defensive strategies, organizations can significantly reduce their exposure to these and similar advanced threats targeting critical network infrastructure.

Key Takeaways

  • Pre-authentication RCEs Discovered: Two critical pre-authentication vulnerabilities were found in Draytek routers: a buffer overflow in the TR-069 STUN parsing function and an integer overflow in the get_cgi function (POST requests) leading to a heap overflow.
  • Full Exploit Chain Achieved: These new vulnerabilities complete a full exploit chain, enabling an unauthenticated attacker to gain remote code execution from the internet, change administrative passwords, and establish persistent kernel-level access.
  • MIPS and Slab Allocator Exploitation: The exploitation leverages MIPS-specific exception handling mechanisms and sophisticated manipulation of the slab allocator's metadata to achieve an arbitrary write primitive and redirect execution flow to attacker-controlled shellcode.
  • Persistent Backdoors via DLMs: Malicious Dynamically Loadable Modules (DLMs) provide a robust persistence mechanism, allowing attackers to maintain control across reboots, factory resets, and even firmware updates, by creating backdoored user accounts or other system modifications.
  • Real-World Impact and Observed Reboots: The widespread Draytek router reboots observed in March 2024 are hypothesized to be failed exploitation attempts of these very vulnerabilities, implying that successful, silent compromises likely also occurred.
  • Urgent Call for Firmware Updates and Attack Surface Reduction: All Draytek router users must update their firmware immediately to patch these vulnerabilities. Additionally, disabling unnecessary services (e.g., TR-069) and limiting internet exposure of administrative interfaces are crucial defensive measures.

About the Speaker(s)

Gastonas Narees and Octavio Gianatiempo are security researchers at Faraday, a company specializing in cybersecurity. Their primary focus areas include firmware, embedded systems, and low-level security. They have a history of presenting their significant research at major security conferences, including DEF CON, where they previously discussed vulnerabilities and persistence mechanisms in Draytek routers. Building on this expertise, their current work extends to other embedded domains, as they are actively developing evil doggy, an open-source, modular tool designed for CAN bus research and penetration testing in the automotive hacking space. Their work consistently highlights the critical security challenges present in the foundational layers of connected devices.

Reviews

Dr. Zero (Offensive Security Researcher) — STRONG ACCEPT

Solid embedded security research that delivers on its title — Gianatiempo and Narees actually complete the chain they promised, with two original pre-auth RCEs, a credible hypothesis tied to observed real-world events, and a live demo that goes all the way to persistent kernel access. Not quite five stars because the TR-069 vector gets abandoned mid-exploit and the slab allocator abuse, while well-executed, isn't a technique that'll make allocator experts gasp — but the end-to-end rigor and real-world relevance keep this firmly in 'strong accept' territory.

Heather Calloway (CISO) — WEAK

Technically rigorous work with real-world signal — the March 2024 reboot event alone confirms active exploitation at scale. But this talk is built for researchers, not defenders or decision-makers, and the gap between 'here's how we built the chain' and 'here's what you own and what you do about it' is never crossed.

→ Top-rated talks at DEF CON 33

All talks from DEF CON 33