Vulnerabilities in the TPM 2.0 reference implementation code

Francisco Falcon (Security Researcher and Reverse Engineer · Quarkslab)

TROOPERS23 · Day 2 · Track 3

Overview

In this insightful talk at TROOPERS, Francisco Falcon, a Security Researcher and Reverse Engineer at Quarkslab, delved into critical vulnerabilities he discovered within the Trusted Platform Module (TPM) 2.0 reference implementation code. The TPM, a cornerstone of modern system security, acts as a secure cryptographic processor, safeguarding sensitive operations from boot integrity verification to full disk encryption keys. Falcon's research was motivated by the ubiquitous presence of TPMs, particularly in virtualized and cloud environments, where a vulnerability could enable stealthy virtual machine escapes or compromise cloud instances.

Watch on YouTube · Slides

Visual summary for Vulnerabilities in the TPM 2.0 reference implementation code by Francisco Falcon
Visual summary for Vulnerabilities in the TPM 2.0 reference implementation code by Francisco Falcon

Key moments

  1. 0:45 Motivation: virtual machine escape via TPM
  2. 7:00 Reference implementation: source code from PDFs
  3. 12:00 Debugging virtual TPMs, Hyper-V's isolated mode
  4. 23:30 First vulnerability: out-of-bounds read explained
  5. 30:50 Second vulnerability: out-of-bounds write explained
  6. 42:00 Exploitation potential: code execution on swtpm
  7. 48:00 Disclosure process challenges and hardware TPM verification

Vulnerabilities in the TPM 2.0 reference implementation code

Speakers: Francisco Falcon, Security Researcher and Reverse Engineer, Quarkslab

Conference: TROOPERS

YouTube: <https://www.youtube.com/watch?v=Gw7YRT2V70>

Overview

In this insightful talk at TROOPERS, Francisco Falcon, a Security Researcher and Reverse Engineer at Quarkslab, delved into critical vulnerabilities he discovered within the Trusted Platform Module (TPM) 2.0 reference implementation code. The TPM, a cornerstone of modern system security, acts as a secure cryptographic processor, safeguarding sensitive operations from boot integrity verification to full disk encryption keys. Falcon's research was motivated by the ubiquitous presence of TPMs, particularly in virtualized and cloud environments, where a vulnerability could enable stealthy virtual machine escapes or compromise cloud instances.

The significance of these findings lies in their widespread impact. The TPM 2.0 reference implementation, published by the Trusted Computing Group (TCG), serves as the foundational codebase for a vast array of TPM products across the industry, including hardware TPMs, firmware-based TPMs, and virtual TPMs offered by major virtualization platforms and cloud providers. A single vulnerability in this core implementation can thus propagate across countless systems, making it a high-value target for security researchers and adversaries alike. Falcon's work not only exposed specific flaws but also highlighted the inherent challenges of securing complex, stateful binary protocols and the critical importance of scrutinizing foundational codebases.

Background

▶ Watch: Motivation: virtual machine escape via TPM (0:45)

The Trusted Platform Module (TPM) is a standardized cryptographic coprocessor designed to provide hardware-based security functions. Specified by the non-profit Trusted Computing Group (TCG), TPMs are integral to modern computing, offering capabilities such as generating and storing cryptographic keys, performing encryption and decryption with both symmetric and asymmetric algorithms, generating and verifying digital signatures, and producing secure random numbers. Common use cases include attestation of the boot process integrity (ensuring system firmware hasn't been compromised), securing keys for full disk encryption solutions like BitLocker, and enabling Digital Rights Management.

TPMs manifest in several forms: Hardware TPMs are dedicated chips, either integrated into the motherboard or discrete modules. Software TPMs are emulations, typically bundled with virtualization solutions like VMware Workstation, Hyper-V, VirtualBox, QEMU, and Parallels. A hybrid approach, Firmware-based TPMs (e.g., Intel Platform Trust Technology PTT, AMD fTPM), runs within the main CPU's trusted execution mode. The proliferation of virtual TPMs is particularly notable, driven by requirements like Windows 11, and they are now standard offerings from major cloud providers such as Amazon Nitro TPM, Microsoft Azure's Trusted Launch, Google Cloud's Shielded VMs, and Oracle Cloud Infrastructure's Shielded Instances.

The TCG provides a reference implementation of the TPM 2.0 specification, written in C, which forms the firmware for many of these diverse TPM products. This implementation is extensive, spanning over 2,500 pages across six PDF documents. Unusually, the C code is embedded directly within these PDF files, intertwined with specification text and diagrams. Microsoft and IBM maintain repositories (on GitHub and SourceForge, respectively) where they extract this code, a process described as "a bit hacky" due to the challenges of scraping code from PDFs. This complex and unconventional development and distribution model inherently introduces potential for security vulnerabilities.

The TPM 2.0 protocol itself is notoriously complex. While user-mode tools (e.g., tpm2-tools on Linux) abstract this complexity for developers, the underlying binary protocol involves intricate state transitions and data structures. For instance, a seemingly simple StartAuthSession command involves numerous conditional logic paths and strict size checks, making manual parsing and understanding a significant challenge.

For security research, virtual TPMs (vTPMs) offer a distinct advantage: debuggability. Unlike hardware TPMs, which provide limited to no observability, vTPMs run as user-mode processes on the host system, allowing researchers to attach debuggers and analyze their behavior. However, Hyper-V's implementation presents a unique hurdle. Its vTPM runs within an Isolated User Mode (IUM), part of a Virtual Machine Secure Process (VMSP), leveraging Virtual Trust Levels (VTLs). This secure environment, higher privileged than traditional user or kernel modes, prevents direct debugger attachment. Falcon overcame this by employing nested virtualization and patching the SkpIsProcessDebuggingEnabled function in the secure kernel via physical memory manipulation, enabling debugging of IUM processes.

Communication with a TPM follows a defined binary protocol. Every command begins with a 10-byte base header (2-byte tag indicating session presence, 4-byte total command size, 4-byte command code). This is followed by an optional handle area (0-3 handles, variable size), an authorization area (4-byte size followed by authorization data), and finally, optional parameters (2-byte size followed by parameter data). The authorization area is crucial, containing a session handle, nonce, and session attributes—a bitfield where flags like decrypt instruct the TPM to decrypt incoming parameters, and encrypt instructs it to encrypt outgoing response parameters. Responses generally mirror this structure but with parameters preceding the authorization area. Understanding these intricate protocol details was essential for identifying and exploiting the vulnerabilities.

Key Findings

▶ Watch: Debugging virtual TPMs, Hyper-V's isolated mode (12:00)

Francisco Falcon's research uncovered two significant vulnerabilities within the TPM 2.0 reference implementation, both residing in the CryptParameterDecryption function responsible for handling encrypted command parameters. These flaws, a CVE-2023-1018 out-of-bounds read and a more critical out-of-bounds write, stem from inadequate bounds checking during binary protocol parsing.

The primary implication of these findings is their widespread impact. Given that the vulnerable code is part of the TCG's reference implementation, it affects a broad spectrum of TPM products across the industry. This includes:

  • Software/Virtual TPMs: VMware Workstation, Microsoft Hyper-V, and QEMU's SWTPM were all verified to be affected.
  • Cloud Virtual TPMs: Major cloud providers like Google Cloud (which uses an IBM-derived reference implementation) and Microsoft Azure (based on Hyper-V) were assessed as likely affected. Amazon Nitro TPM and Oracle Cloud Infrastructure remained in an unknown status.
  • Hardware TPMs: At least one hardware TPM, specifically a Nuvoton chip on a Dell Latitude E5570, was confirmed vulnerable through a denial-of-service attack. Other hardware vendors' claims of non-vulnerability were difficult to independently verify.

While both vulnerabilities originated from the same core parsing logic error, their exploitability and impact varied significantly depending on how individual vendors implemented their command buffer management. The out-of-bounds read had limited practical impact, often disclosing inconsequential data or zeros. However, the out-of-bounds write presented a more severe risk, ranging from denial of service (DoS), as demonstrated on hardware, to potential code execution in specific virtual TPM environments, particularly QEMU's SWTPM. This highlights that even a shared codebase can lead to diverse security outcomes based on implementation-specific memory layouts and compiler optimizations.

Technical Deep Dive

▶ Watch: First vulnerability: out-of-bounds read explained (23:30)

The two vulnerabilities discovered by Francisco Falcon are rooted in the CryptParameterDecryption function, a critical component of the TPM firmware responsible for processing encrypted command parameters. Both flaws highlight a lack of robust bounds checking during the parsing of the binary TPM protocol.

Vulnerability 1: Out-of-Bounds Read (CVE-2023-1018)

The first vulnerability is an out-of-bounds read, assigned CVE-2023-1018. This flaw occurs when the CryptParameterDecryption function attempts to read the cipherSize, a 16-bit value indicating the size of the encrypted parameter data.

Root Cause:

Within CryptParameterDecryption, the code uses a macro called BYTE_ARRAY_TO_UINT16 to read the first two bytes of the parmBuffStart buffer and interpret them as the cipherSize. Crucially, this macro performs a direct memory access without any preceding checks to ensure that parmBuffStart actually points to a valid parameter area, or that there are at least two bytes available to read.

Trigger:

The vulnerability is triggered by crafting a TPM command with the decrypt flag set in the authorization area's session attributes, but omitting the parameter area entirely after the authorization area. When the TPM attempts to process this command, CryptParameterDecryption is invoked. It then blindly tries to read the 2-byte cipherSize from the memory location immediately following the authorization area, which is effectively past the end of the legitimate command buffer.

Fix:

The speaker noted that the TPM reference implementation already provides helper functions for unmarshalling binary data with proper bounds checks, such as UINT16_UNMARSHAL. These helpers take a pointer to the buffer and its remaining size, updating the size after a successful read and returning an error if insufficient data is available. The fix involves replacing the unsafe BYTE_ARRAY_TO_UINT16 macro with the secure UINT16_UNMARSHAL function.

Impact:

The practical impact of this out-of-bounds read was found to be limited. In VMware Workstation's vTPM, the read would retrieve two bytes of stale data from a previous command, as the command buffer was not consistently zeroed out between requests. However, Falcon was unable to exfiltrate this data or leverage it for further exploitation. In Hyper-V's vTPM, the command buffer was padded with zeros, so the out-of-bounds read merely retrieved two null bytes, rendering it harmless. Overall, this vulnerability was deemed low impact for information disclosure.

Vulnerability 2: Out-of-Bounds Write

The second, more impactful vulnerability is an out-of-bounds write, located in the exact same CryptParameterDecryption function. This bug allows an attacker to overwrite two bytes of memory immediately following the command buffer.

Root Cause:

This vulnerability arises from a subtle but critical logical error in how the bufferSize variable is managed. After successfully reading the 2-byte cipherSize from the parmBuffStart buffer (assuming a valid parameter area is present, thus avoiding the first bug), the parmBuffStart pointer is correctly advanced by two bytes. However, the bufferSize variable, which tracks the length of the remaining data in the buffer, is not decremented by two to account for the cipherSize that has just been processed.

Consequence:

Due to bufferSize not being updated, a subsequent sanity check (if (cipherSize > bufferSize) return error;) can be bypassed. An attacker can craft a command where the supplied cipherSize value is exactly two bytes larger than the actual remaining parameter data. Because bufferSize still includes those two bytes that were already "processed" by reading cipherSize, the check cipherSize > bufferSize evaluates to (actual_data_size + 2) > (actual_data_size + 2), which is false, allowing the oversized cipherSize to pass validation.

When the function then calls either CryptXorObfuscation or ParamDecryptSym (depending on the chosen encryption method) to decrypt the parameter data, it uses the inflated cipherSize. This leads to the TPM attempting to decrypt and write two bytes past the allocated end of the parameter data buffer, resulting in an out-of-bounds write of two bytes.

Trigger:

To trigger this, an attacker needs to:

  1. Establish an authorization session using StartAuthSession to obtain a session handle.
  2. Send a command that supports parameter encryption (e.g., CreatePrimary), using the obtained session handle.
  3. Set the decrypt flag in the session attributes.
  4. Provide a parameter area where the cipherSize field is set to (actual_parameter_data_length + 2). This ensures the sanity check passes but causes the subsequent decryption function to write beyond the intended buffer boundary.

Impact and Exploitability:

The exploitability of this 2-byte out-of-bounds write varies significantly across different TPM implementations due to their distinct buffer management strategies:

  • VMware Workstation: VMware allocates an oversized buffer (10,000 bytes for a 1,000-byte max command). The 2-byte overwrite lands harmlessly in the unused padding area, posing no immediate threat.
  • Microsoft Hyper-V: Hyper-V uses a static command buffer of 1,000 bytes. However, compiler optimizations, specifically variable reordering (a known exploit mitigation), often place arrays prone to overflow at the end of a memory region. This means the 2-byte overwrite also lands in a relatively safe, unused area, making exploitation difficult.
  • SWTPM (QEMU): This implementation uses malloc to allocate the command buffer, typically sized exactly for the maximum command (1,000 bytes plus a small prefix, e.g., 1,008 bytes). Here, the 2-byte overwrite directly impacts the heap, making it the most promising target for exploitation. Overwriting heap metadata or adjacent small allocations can be a powerful primitive for achieving arbitrary code execution.

Potential Consequences:

Even with a limited 2-byte write primitive, the consequences can be severe:

  • Code Execution: As highlighted by Falcon, even highly constrained write primitives (e.g., writing a single byte with a specific value) have been leveraged for full compromise of secure hardware, such as the Google Titan M chip. In the context of vTPMs, this could lead to a virtual machine escape and code execution on the host system, a critical concern for cloud environments.
  • Sensitive Data Overwrite: Overwriting two bytes of adjacent sensitive data, such as cryptographic keys or security-critical flags, could lead to compromise of secrets or bypass of security mechanisms.
  • Denial of Service (DoS): The most readily achievable impact, especially on hardware TPMs. Corrupting critical internal state can cause the TPM to become unresponsive, leading to system instability or failure.

Demo / Proof of Concept

▶ Watch: Exploitation potential: code execution on swtpm (42:00)

While the talk did not feature a live, interactive demo, Francisco Falcon meticulously detailed the steps required to trigger both the out-of-bounds read and the out-of-bounds write vulnerabilities, providing visual evidence from his debugging sessions. Crucially, he presented concrete proof of impact with a successful denial-of-service (DoS) demonstration on a physical hardware TPM.

To trigger either vulnerability, a two-step process is required:

  1. Start an Authorization Session: The attacker first sends a StartAuthSession command to the TPM. This command initiates a secure session, and if successful, the TPM responds with a TPM_RC_SUCCESS code and provides a unique session handle (e.g., 0x20000000). This handle is essential for subsequent commands that require an active session.
  2. Send a Vulnerable Command: With the session handle obtained, the attacker then sends another command to the TPM. This command must be one that supports parameter encryption and decryption, such as the CreatePrimary command, which was used in Falcon's proof-of-concept.
  • For the Out-of-Bounds Read (CVE-2023-1018): The attacker includes the session handle and sets the decrypt flag in the session attributes. However, the crucial step is to omit the parameter area entirely from the command. The TPM, expecting a cipherSize field, attempts to read two bytes past the end of the crafted command, triggering the out-of-bounds read. Falcon showed a screenshot from Hyper-V where this read resulted in two null bytes, confirming the vulnerability, albeit with low impact in that specific environment.
  • For the Out-of-Bounds Write: Again, the session handle is included, and the decrypt flag is set. This time, a parameter area is included, but the cipherSize field is deliberately crafted. It is set to a value that is two bytes larger than the actual parameter data present in the command (e.g., if there are 58 bytes of data, cipherSize is set to 60). This bypasses the flawed sanity check. When the TPM attempts to decrypt the parameters, it writes two bytes beyond the allocated buffer, causing the out-of-bounds write. A screenshot from Hyper-V visually confirmed this, showing two bytes immediately following the parameter data being overwritten with the decrypted content.

The most impactful demonstration was the denial of service achieved on a Dell Latitude E5570 laptop equipped with a Nuvoton hardware TPM. By triggering the out-of-bounds write on this physical device, the TPM chip ceased responding to all further commands. This rendered the system's TPM-dependent functions (such as BitLocker or boot attestation) inoperable. To restore TPM functionality, a simple soft reboot was insufficient; a hard reboot (powering off and then restarting the computer) was required. This concrete evidence unequivocally proved that the vulnerability could affect physical hardware, leading to significant operational disruption.

Defensive Implications

▶ Watch: Disclosure process challenges and hardware TPM verification (48:00)

The discovery of vulnerabilities in the TPM 2.0 reference implementation carries profound implications for defenders across the software, hardware, and cloud security landscapes. Addressing these flaws requires a multi-faceted approach, emphasizing patching, secure development practices, and improved verification mechanisms.

  1. Immediate Patching and Supply Chain Awareness: The most critical defensive action is to apply the patches released by the Trusted Computing Group and downstream vendors. Given the widespread adoption of the reference implementation, every vendor utilizing this codebase, whether for hardware, firmware, or virtual TPMs, must ensure their products are updated. This extends to the complex supply chain; organizations need to verify that their hardware and software suppliers have incorporated these fixes. The disclosure process itself underscored this complexity, with CERT/CC providing access to vulnerability details to over 1,600 vendors, highlighting the intricate web of dependencies.
  1. Robust Bounds Checking and Secure Coding Practices: The vulnerabilities fundamentally stemmed from inadequate bounds checking during binary protocol parsing. Developers working on low-level, security-critical firmware like TPMs must prioritize secure coding practices. This includes:
  • Always validating input sizes: Before any memory access, especially when unmarshalling binary data, ensure sufficient buffer space is available.
  • Using safe helper functions: The talk explicitly mentioned that the TPM reference implementation has helper functions like UINT16_UNMARSHAL that perform proper bounds checks. These should be used universally instead of direct memory access macros like BYTE_ARRAY_TO_UINT16.
  • Careful buffer management: When processing data in a buffer, ensure that variables tracking remaining size are consistently updated after data consumption.
  1. Strategic Buffer Allocation and Exploit Mitigations: For implementers of TPM firmware, especially those building virtual TPMs, the way command buffers are allocated and managed significantly impacts exploitability.
  • Oversized buffers: As seen with VMware, allocating buffers significantly larger than the maximum expected command size can effectively turn a small out-of-bounds write into a harmless write into padding.
  • Compiler mitigations: While not a primary defense, understanding how compilers apply mitigations like variable reordering (which places arrays at the end of memory sections to prevent adjacent variable corruption) can inform memory layout decisions.
  • Heap hardening: For implementations like QEMU's SWTPM, which allocate command buffers on the heap, heap hardening techniques are crucial to prevent limited writes from corrupting heap metadata and leading to arbitrary code execution.
  1. Enhanced, State-Aware Fuzzing: The speaker noted that existing fuzzing efforts (e.g., Google's use of libFuzzer on Chromium OS) might be too basic to uncover deep-seated bugs in a highly stateful system like the TPM. Defenders should invest in sophisticated, state-aware fuzzing methodologies. This involves:
  • Understanding protocol states: Fuzzers should be designed to navigate the complex state transitions of the TPM, ensuring that inputs reach deep and rarely-used code paths.
  • Feedback-driven fuzzing: Leveraging code coverage and other feedback mechanisms to guide the fuzzer towards more complex and vulnerable states.
  • Chaining commands: Fuzzing should test sequences of commands, as vulnerabilities often arise from the interplay of multiple operations (e.g., StartAuthSession followed by CreatePrimary).
  1. Improved Hardware TPM Verification and Observability: A significant challenge highlighted was the difficulty in independently verifying the presence or absence of vulnerabilities in hardware TPMs. Defenders currently rely on blind trust from vendors who claim their products are unaffected. This underscores the need for:
  • More transparent hardware security auditing: Mechanisms for independent security researchers to audit TPM firmware on hardware.
  • Enhanced observability: While full debugging on a secure chip is counter-intuitive, limited, secure diagnostic capabilities could aid in post-exploit analysis or vulnerability verification without compromising core security.
  1. Monitoring for Anomalous TPM Behavior: For cloud providers and enterprise IT, monitoring systems should be configured to detect unusual TPM activity. This could include:
  • Unexpected TPM crashes or unresponsiveness: As demonstrated by the DoS on the Dell Latitude, a non-responsive TPM is a clear indicator of a potential attack.
  • Repeated failed TPM commands: A high rate of errors could indicate an attacker attempting to trigger vulnerabilities.
  • Unauthorized changes to boot integrity reports: While not directly related to these specific bugs, it's a general defensive measure for TPMs.

By implementing these defensive strategies, organizations can significantly bolster the security posture of their systems against vulnerabilities in foundational components like the TPM.

Key Takeaways

  • Reference Implementations are Critical Targets: Vulnerabilities in widely adopted reference implementations, like the TPM 2.0 firmware, have a disproportionately large impact, affecting a multitude of hardware, firmware, and software products across various vendors.
  • Complexity Breeds Vulnerabilities: The extreme complexity of the TPM 2.0 specification (2,500+ pages) and its underlying binary protocol, combined with the unusual method of extracting C code from PDF documents, inherently increases the likelihood of security flaws.
  • Virtual TPMs are Invaluable for Research: Virtual TPMs provide critical debuggability, enabling security researchers to analyze and identify vulnerabilities in code that would otherwise be opaque and inaccessible in hardware implementations.
  • Impact Varies by Implementation: Even with a shared vulnerable codebase, the practical impact and exploitability of flaws (especially memory corruption bugs) can vary significantly due to vendor-specific buffer management, memory allocation strategies, and compiler optimizations.
  • Limited Primitives Can Be Powerful: A seemingly minor 2-byte out-of-bounds write, particularly on the heap as seen in QEMU's SWTPM, can potentially lead to severe consequences such as denial of service, sensitive data corruption, or even full code execution and VM escape.
  • Hardware Verification Remains a Challenge: Independently verifying the security posture of hardware TPMs is extremely difficult due to a lack of debugging and observability capabilities, forcing a reliance on vendor assertions unless a crash or other observable malfunction occurs.

About the Speaker(s)

Francisco Falcon is a Security Researcher and Reverse Engineer at Quarkslab, a cybersecurity company specializing in vulnerability research and offensive security. Before joining Quarkslab, he gained experience as an exploit writer at Core Security. His professional interests lie in the low-level aspects of computing security, specifically focusing on reverse engineering, the discovery of vulnerabilities, and the development of exploits.

Reviews

Dr. Zero (Offensive Security Researcher) — STRONG ACCEPT

The fact that the TCG distributes the foundational code for global platform security by embedding C snippets inside 2,500 pages of PDFs isn't a supply chain—it's a hostage situation. Falcon tore into this mess and pulled out a core vulnerability that ripples across virtual and physical environments alike. Strong accept for doing the brutal, unglamorous work of stateful binary protocol analysis.

Heather Calloway (CISO) — MUST SEE

Francisco Falcon’s research on the TPM 2.0 reference implementation is a masterclass in supply chain blast radius. He found memory corruption vulnerabilities in the foundational code that powers everything from physical Dell laptops to Azure virtual machines. This is required reading for anyone managing a large hardware fleet or a multi-cloud footprint, as it fundamentally alters our assumptions about hardware-rooted trust.

→ Top-rated talks at TROOPERS23

All talks from TROOPERS23