Iconv, set the charset to RCE exploiting glibc to hack the PHP engine
Charles Fox
DEF CON 32 Main Stage · Day 1 · Main Stage
Overview
In this DEF CON 32 talk, Charles Fox unveils a critical buffer overflow vulnerability discovered within the glibc iconv library, a fundamental component for character set conversion in most Linux systems. While initially found during an audit of the PHP engine, the bug itself resides not in PHP, but in its underlying dependency, making its implications far-reaching across various applications that rely on iconv. Fox demonstrates how this seemingly innocuous character conversion flaw can be leveraged to achieve Remote Code Execution (RCE) within PHP applications, presenting two distinct attack vectors: via PHP's powerful php://filter stream wrappers and through direct calls to the iconv function.
Key moments
- 0:00 Talk introduction: Glibc Iconv bug exploiting PHP
- 1:00 PHP file read primitives and phar:// deserialization
- 2:50 Introducing php://filter for stream manipulation
- 4:05 Using convert.iconv for character set conversion
- 5:00 Context: Arbitrary prefix/suffix research with filters
- 6:10 Accidental discovery of Glibc Iconv crash
- 7:00 Core vulnerability: Iconv buffer boundary failure
Iconv, set the charset to RCE exploiting glibc to hack the PHP engine
Speakers: Charles Fox, Researcher, Ambionics
Conference: DEF CON 32
YouTube: https://www.youtube.com/watch?v=11Yv2Ru7gF8
Overview
In this DEF CON 32 talk, Charles Fox unveils a critical buffer overflow vulnerability discovered within the glibc iconv library, a fundamental component for character set conversion in most Linux systems. While initially found during an audit of the PHP engine, the bug itself resides not in PHP, but in its underlying dependency, making its implications far-reaching across various applications that rely on iconv. Fox demonstrates how this seemingly innocuous character conversion flaw can be leveraged to achieve Remote Code Execution (RCE) within PHP applications, presenting two distinct attack vectors: via PHP's powerful php://filter stream wrappers and through direct calls to the iconv function.
The discovery highlights a significant oversight in a widely used system library, demonstrating that even low-level, foundational components can harbor critical security flaws. Fox's research began with an exploration of advanced PHP filter chain techniques for arbitrary file manipulation, a path that unexpectedly led to the glibc crash. The talk delves into the technical specifics of the iconv bug, particularly its trigger condition involving the obscure ISO-2022-CN-EXT character set, and outlines the precise nature of the resulting byte overflow.
This presentation is crucial for developers, system administrators, and security researchers aiming to understand the intricate dependencies of modern software stacks and the subtle ways vulnerabilities can manifest. It underscores the importance of continuous auditing, even in well-established libraries, and provides actionable insights into protecting PHP applications and broader Linux systems from this specific class of attack.
Background
▶ Watch: Talk introduction: Glibc Iconv bug exploiting PHP (0:00)
The journey to discovering the iconv vulnerability began with Charles Fox's deep dive into PHP file read primitives and their exploitation potential. In PHP, functions like file_get_contents() or fopen() followed by fread() allow an application to read the content of local files, but also support various protocols to access remote resources (e.g., http://, ftp://) or PHP-specific stream wrappers.
One historically significant PHP-specific protocol is phar://. A PHAR archive (.phar file) is similar to a Java JAR, bundling source files and resources. Critically, PHAR archives can contain serialized metadata. For a long time, attackers could upload any file (e.g., an image), then use a file read primitive to interpret it as a phar:// archive. Accessing this archive would trigger deserialization of its metadata, often leading to arbitrary deserialization and, consequently, Remote Code Execution (RCE). This attack vector was particularly potent, with frameworks like Magento reportedly experiencing hundreds of related bugs. However, this attack has become less viable over time. PHP 8 and later versions have disabled metadata deserialization for PHAR archives, as it was deemed useless. Furthermore, major frameworks have proactively removed support for the phar:// protocol due to its inherent dangers, and the general hardening of PHP's deserialization mechanisms makes exploitation increasingly challenging.
With phar:// becoming less effective, security researchers shifted their focus to another powerful PHP-specific protocol: php://filter. This protocol allows developers to apply various filters to a stream before its contents are read. The syntax is php://filter/filter_name_1|filter_name_2/.../resource=target_file. For example, php://filter/convert.base64-encode/resource=/etc/passwd would return the base64-encoded content of /etc/passwd. Filters can be stacked, allowing for complex transformations. Common filters include convert.base64-encode, string.upper, string.lower, and rot13. Less documented but useful for attackers are filters like dechunk, which can remove HTTP chunked encoding.
Fox's specific interest lay in the convert.iconv.x.y filter. This filter leverages the system's iconv library (part of glibc on Linux systems) to convert a stream from an input character set x to an output character set y. For instance, php://filter/convert.iconv.UTF8.UTF16/resource=/etc/passwd converts the password file from UTF-8 to UTF-16.
Fox's prior research in 2023, which he dubbed wrap_wrap, focused on achieving arbitrary prefixes and suffixes for file contents using chained PHP filters. The goal was to overcome scenarios where a file read primitive was available, but the application expected the file content to conform to a specific format, such as JSON. By crafting a suitable filter chain, an attacker could make /etc/passwd appear as valid JSON, allowing it to be parsed and its contents extracted. It was during the development and testing of scripts for this wrap_wrap research, experimenting with various convert.iconv character set conversions, that Fox unexpectedly encountered a system crash. This crash, initially suspected to be a PHP bug given his 20 years of experience with the language, turned out to be a deeper vulnerability in glibc's iconv library itself.
Key Findings
▶ Watch: Introducing php://filter for stream manipulation (2:50)
The central discovery presented by Charles Fox is a buffer overflow vulnerability within the glibc iconv library. This vulnerability is triggered under a very specific condition: when performing a character set conversion to the obscure ISO-2022-CN-EXT encoding.
The iconv function is designed to convert data from an input buffer (with a specified size) to an output buffer (also with a specified size), strictly adhering to buffer boundaries to prevent overflows. However, Fox's research revealed a critical flaw: in certain scenarios, when converting data to ISO-2022-CN-EXT, iconv fails to adequately check the bounds of the output buffer before writing specific escape sequences.
This oversight results in a small but exploitable buffer overflow, ranging from one to three bytes. Crucially, the values of these overflow bytes are not arbitrary but are limited to a set of six very specific escape sequences:
$*H$+I$+J$*h$*i$*j
These specific byte sequences are part of the ISO-2022-CN-EXT standard for switching between different character sets (e.g., activating a specific Chinese character set). The bug is triggered by input containing certain Chinese characters which, when converted, necessitate these escape sequences.
The immediate impact of this glibc iconv buffer overflow is a system crash, as observed by Fox during his initial testing. However, the talk demonstrates that this primitive can be escalated to Remote Code Execution (RCE) within the context of the PHP engine. Fox outlines two primary attack vectors:
- Exploitation via PHP filters: By chaining
convert.iconv.x.ISO-2022-CN-EXTwithin aphp://filterstream wrapper, an attacker can remotely trigger the glibc bug if they can control thephp://filterstring. - Exploitation via direct
iconvcalls: Applications that directly invoke PHP'siconv()function with attacker-controlled input and output character sets, or attacker-controlled data to be converted, can also be vulnerable.
This vulnerability is significant because it targets a foundational library used by countless applications on Linux systems, demonstrating how a subtle bug in a low-level component can have high-impact consequences when exposed through higher-level application logic.
Technical Deep Dive
▶ Watch: Using convert.iconv for character set conversion (4:05)
The iconv library, part of the GNU C Library (glibc), is a critical component for handling character set conversions in Unix-like operating systems. Its primary function, iconv(), takes an input buffer, its size, an output buffer, and its size, then converts the data from a specified input character set to a specified output character set. A fundamental guarantee of iconv is that it should never write beyond the bounds of the provided output buffer or read beyond the input buffer. Fox's research, however, revealed a violation of this guarantee under specific conditions.
The vulnerability manifests when iconv is instructed to convert a stream of bytes into the ISO-2022-CN-EXT character set. ISO-2022-CN-EXT is an extension of ISO-2022-CN, a multi-byte character encoding that supports various Chinese character sets (GB2312, CNS 11643-1, CNS 11643-2, etc.) by using escape sequences to switch between them. For instance, ESC $ * H might switch to a specific GB character set, while ESC $ + I might switch to a CNS character set.
The core of the bug lies in how iconv handles these escape sequences during the conversion process. When certain input characters are encountered that require iconv to emit one of these multi-byte escape sequences to switch character sets, the library's internal bounds checking for the output buffer becomes insufficient. Specifically, it fails to verify if there is enough space remaining in the output buffer before writing the entire escape sequence.
The vulnerable code path involves the _iconv_internal_ function within glibc. When iconv processes characters that map to these specific ISO-2022-CN-EXT escape sequences, it attempts to write them to the output buffer. For example, if the conversion requires writing ESC $ * H (which is four bytes), and only three or fewer bytes remain in the output buffer, iconv may proceed to write all four bytes, resulting in a buffer overflow of 1 to 3 bytes.
The specific overflow values are tightly coupled to the escape sequences themselves:
$*H(hex:24 2A 48)$+I(hex:24 2B 49)$+J(hex:24 2B 4A)$*h(hex:24 2A 68)$*i(hex:24 2A 69)$*j(hex:24 2A 6A)
These are the byte sequences that represent the character set switching commands within ISO-2022-CN-EXT. An attacker can control which of these sequences are written by providing specific Chinese characters as input that, when converted, trigger the emission of these particular escape sequences. Fox notes that he used "Chinese characters, I have no idea what they mean, but they give you a buffer overflow." This implies that the specific input characters themselves are less important than their effect of forcing iconv to produce these vulnerable escape sequences.
The critical vector for exploiting this within PHP applications, as demonstrated by Fox, is through the php://filter stream wrapper. If an application allows user-controlled input to dictate the character sets used in a convert.iconv filter (e.g., php://filter/convert.iconv.UTF8.ISO-2022-CN-EXT/resource=...), an attacker can craft a malicious URL or input string. This string would specify ISO-2022-CN-EXT as the output character set and include specially crafted input data that, when processed by iconv, triggers the buffer overflow.
The outcome of this overflow, initially, is a crash of the PHP process. However, a controlled, small-byte overflow like this can be a powerful primitive in memory exploitation. By carefully manipulating heap metadata or adjacent data structures, an attacker could potentially achieve arbitrary write capabilities, leading to full Remote Code Execution. While the talk describes that RCE is possible, the detailed steps of escalating the 1-3 byte overflow to a full RCE chain (e.g., overwriting function pointers, corrupting object headers) are beyond the scope of this specific transcript, focusing instead on the discovery and nature of the glibc bug itself.
Beyond php://filter, any PHP application that directly calls the iconv() function (or its object-oriented equivalent iconv_stream_wrapper) with attacker-controlled parameters (either the input/output character sets or the data to be converted) would also be susceptible. This extends the attack surface to a broader range of PHP applications that might not explicitly use php://filter but still interact with iconv for character encoding tasks.
Demo / Proof of Concept
▶ Watch: Accidental discovery of Glibc Iconv crash (6:10)
While Charles Fox's presentation clearly articulates the discovery of the iconv vulnerability and its potential for Remote Code Execution within the PHP engine, the provided transcript focuses primarily on the technical details of the bug and its accidental discovery during his wrap_wrap research. The talk mentions experiencing a "crash" when experimenting with various convert.iconv filter chains, which subsequently led to the identification of the glibc bug. However, the transcript does not detail a live demonstration or a step-by-step Proof of Concept (PoC) for achieving RCE during the presentation itself. The speaker describes the conditions under which the buffer overflow occurs and the specific bytes that can be overwritten, laying the groundwork for exploitation.
Defensive Implications
▶ Watch: Core vulnerability: Iconv buffer boundary failure (7:00)
The discovery of a buffer overflow in a fundamental library like glibc's iconv carries significant defensive implications for systems administrators, developers, and security teams.
- Prioritize glibc Updates: The most direct defensive measure is to ensure that the underlying operating system's glibc library is promptly updated to a patched version. This vulnerability resides in a core system component, meaning that patching glibc will protect all applications that rely on it, regardless of their specific implementation details. System administrators should subscribe to security advisories from their Linux distribution vendors (e.g., Debian, Ubuntu, Red Hat) and apply patches for glibc without delay.
- Input Sanitization for Character Set Conversions: For PHP applications, developers must rigorously sanitize all user-supplied input that could influence
php://filterchains or directiconv()function calls.
php://filter: Never allow arbitrary user input to directly constructphp://filterstrings, especially theconvert.iconvfilter's character set parameters. Implement a strict allowlist of permitted filters and character sets.iconv()function: If an application uses theiconv()function, ensure that both the input string to be converted and the source/destination character set names are validated and sanitized. Avoid using obscure or less common character sets likeISO-2022-CN-EXTunless absolutely necessary and with extreme caution.
- Principle of Least Privilege for Character Sets: Review application requirements for character set conversions. Many applications only need to support a limited set of common encodings (e.g., UTF-8, ISO-8859-1). If
ISO-2022-CN-EXTor other complex multi-byte encodings are not explicitly required, consider restricting their use at the application level.
- Runtime Protection (e.g., ASLR, DEP): While the glibc bug itself is a buffer overflow, modern exploit mitigations like Address Space Layout Randomization (ASLR) and Data Execution Prevention (DEP)/NX bit make exploitation more challenging. However, a 1-3 byte overflow can sometimes be used to bypass these protections or corrupt adjacent data structures in ways that lead to RCE. It's crucial not to rely solely on these mitigations but to combine them with patching and secure coding practices.
- Security Audits and Fuzzing: The accidental discovery of this bug during routine testing of PHP filters underscores the importance of continuous security auditing and fuzzing, even for widely used and seemingly stable libraries. Organizations should invest in automated security testing tools and encourage manual code reviews of critical dependencies.
- Monitoring and Logging: Implement robust monitoring and logging for application crashes or unexpected behavior. A sudden termination of a PHP process, especially when processing user-controlled input related to character conversions, could be an indicator of an attempted exploit.
By addressing the underlying glibc vulnerability and implementing defensive coding practices within PHP applications, organizations can significantly reduce their exposure to this and similar character set conversion-related attacks.
Key Takeaways
- Glibc
iconvVulnerability: A critical buffer overflow exists in glibc'siconvlibrary, impacting a foundational component for character set conversions in Linux systems. - Specific Trigger: The vulnerability is activated when converting data to the ISO-2022-CN-EXT character set, where
iconvfails to bounds-check output buffers for specific escape sequences. - Controlled Overflow: The bug results in a small, controlled buffer overflow of 1-3 bytes, using specific values like
$*H,$+I, or$+J(and their lowercase variants). - RCE in PHP: This glibc primitive can be leveraged to achieve Remote Code Execution (RCE) in PHP applications, primarily through the
php://filterstream wrapper (viaconvert.iconv.x.y) or directiconv()function calls. - Beyond PHP: While demonstrated in PHP, the glibc nature of the bug implies that other applications and programming languages using
iconvon Linux systems could also be vulnerable. - Accidental Discovery: The vulnerability was discovered by chance during research into PHP filter chains, highlighting the value of extensive testing and fuzzing in uncovering deep-seated bugs in critical software.
About the Speaker(s)
Charles Fox is a security researcher whose work focuses on uncovering vulnerabilities in widely used software. With approximately 20 years of experience working with PHP, he possesses a deep understanding of the language's internals and its ecosystem. His research often involves exploring advanced exploitation techniques, as evidenced by his work on PHP filters and the wrap_wrap tool. He is associated with Ambionics, a security company, and has published his research on their blog, ambionics.io.
Reviews
Dr. Zero (Offensive Security Researcher) — MUST SEE
This talk presents a critical buffer overflow in glibc's iconv library, a foundational component, triggered by a highly specific character set conversion. The discovery of this low-level bug, and its clear path to Remote Code Execution within PHP applications via common attack vectors like php://filter, demonstrates exceptional technical depth and novelty. It's a prime example of impactful research that exposes vulnerabilities in layers of the stack most people take for granted, providing immediate, actionable intelligence for defenders.
Heather Calloway (CISO) — STRONG ACCEPT
Charles Fox's work on the glibc iconv buffer overflow is a critical finding, exposing a fundamental vulnerability in a core system library that enables Remote Code Execution in PHP applications. This isn't just a technical curiosity; it's a stark reminder of the systemic risks embedded in our software supply chain, demanding immediate action from system administrators to patch glibc and developers to rigorously sanitize input for character conversion functions. It advances the conversation for security leaders by clearly articulating a critical vulnerability and the necessary institutional response.