Skip to content
Memory corruption Write-up Advanced

Vulnerabilities in the TPM 2.0 reference implementation code

Francisco Falcon Follow

Published on blog.quarkslab.com

Bounty$20,000total stated by author View original

Posted Tue 14 March 2023 Author Francisco Falcon Category Vulnerability Tags TPM, Trusted Platform Module, CVE-2023-1017, CVE-2023-1018, vulnerability, 2023

Francisco Falcon, on blog.quarkslab.com

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

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

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

Context

This write-up covers two vulnerabilities found in the Trusted Platform Module (TPM) 2.0 reference implementation code published by the Trusted Computing Group (TCG). The two bugs are an out-of-bounds write tracked as CVE-2023-1017 and an out-of-bounds read tracked as CVE-2023-1018. They affected several TPM 2.0 software implementations, including the virtual TPMs used by virtualization software, as well as a number of hardware TPMs.

The research was motivated by Windows 11, released in October 2021, which requires a TPM 2.0. To run Windows 11 in a virtual machine, virtualization software must provide a TPM to the guest, either by passing through the host hardware TPM or by supplying a virtual TPM. The author treated the virtual TPM as new attack surface reachable from inside a guest, with the potential for a virtual machine escape.

Both bugs can be triggered from user-mode applications by sending malicious TPM 2.0 commands with encrypted parameters. Because they originate in the reference implementation, they reached further than expected: every virtualization product the author tested, and hardware implementations as well.

The author notes that most assessments (exploitability, impact, affected platforms) are based on analysis of software virtual TPMs, which can be debugged easily for dynamic analysis. Debugging Hyper-V's virtual TPM is harder because it runs as an IUM process. Getting runtime visibility into the firmware of a discrete TPM chip, which has no debugging interfaces, is a different problem, and the few TPM firmware updates the author tried to analyse were encrypted. The lack of specific assessment of hardware TPMs does not mean they are unaffected; it means impact could not be evaluated for most of them. Using the published PoC, the author did verify that at least some discrete TPM chips are vulnerable: after attempting the OOB write, the chip stopped responding (it no longer recognised commands) and required a hard reboot of the computer to become operational again.

Setup

The work is analysis of the TCG reference implementation plus testing with the PoC against virtual TPMs and at least some discrete TPM chips. The affected platforms the author could demonstrate with the PoC are:

  • The TPM 2.0 reference implementation, Trusted Platform Module Library Specification, Family "2.0", Level 00, Revision 01.59, November 2019 (the latest version available at the time of the research).
  • Microsoft Hyper-V on Windows 10, affected module TPMEngUM.dll version 10.0.19041.1415.
  • VMware Workstation version 16.2.4 build-20089737, affected module tpm2emu.exe (no version information in the executable).
  • Libtpms/SWTPM, used by Qemu and VirtualBox, compiled from the master branch at commit [redacted].
  • Nuvoton hardware TPM, firmware version 1.3.0.1.
  • In general, all TPM 2.0 implementations whose firmware is based on the TCG reference implementation are expected to be affected.

The list is explicitly non-exhaustive: it contains products where the bugs were demonstrated with the PoC, and other virtual or physical TPMs are very likely vulnerable too.

The author also discusses cloud exposure. All major cloud providers offer instances with virtual TPMs: Amazon AWS NitroTPM, Microsoft Azure virtual TPMs as part of Trusted Launch, Google Cloud virtual TPMs as part of Shielded VMs, and Oracle Cloud Infrastructure virtual TPMs as part of Shielded Instances. Providers using a virtual TPM based on the TCG reference implementation are expected to be vulnerable. For Google Cloud, the linked blog post says the core of their virtual TPM comes from code published by IBM, extracted automatically from the full TPM 2.0 spec source, and the author verified the bugs in CryptParameterDecryption are present in it. For Microsoft Azure, the documentation says the virtual TPM is compliant with the TPM 2.0 spec, and the author verified the virtual TPM in the Hyper-V version available on Windows 10 is vulnerable; the bugs were also present in Microsoft's open source reference implementation. For AWS and Oracle Cloud Infrastructure the author has little detail beyond the NitroTPM documentation stating it conforms to the TPM 2.0 specification with a link to the TCG website.

Finding it

The starting point is the TPM 2.0 feature of session-based parameter encryption. As described in the Trusted Platform Module Library Specification, Family 2.0, Part 1: Architecture, Section 21, several TPM 2.0 commands have parameters that may need to be encrypted going to or from the TPM, to ensure confidentiality. The specification says:

Text
Not all commands support parameter encryption. If session-based encryption is allowed, only the first
parameter in the parameter area of a request or response may be encrypted. That parameter must have
an explicit size field. Only the data portion of the parameter is encrypted. The TPM should support
session-based encryption using XOR obfuscation. Support for a block cipher using CFB mode is platform
specific. These two encryption methods (XOR and CFB) do not require that the data be padded for
encryption, so the encrypted data size and the plain-text data size is the same.

[...]

Session-based encryption uses the algorithm parameters established when the session is started and
values that are derived from the session-specific sessionKey.

[...]

If sessionAttributes.decrypt is SET in a session in a command, and the first parameter of the command is
a sized buffer, then that parameter is encrypted using the encryption parameters of the session.

A TPM 2.0 command with encrypted parameters is laid out as a base command header, then a handleArea, then a sessionArea, then the (encrypted) parameterArea:

Text
+---------------------+
|                     |
|                     |
| Base command header |
|                     |
|                     |
+---------------------+
|                     |
|     handleArea      |
|                     |
+---------------------+
|                     |
|    sessionArea      |
|                     |
+---------------------+
|                     |
|   parameterArea     |
|                     |
+---------------------+

The author followed how the reference implementation parses this structure. In ExecCommand.c, ExecuteCommand checks that the authorizationSize field of the sessionArea is at least 9 (marker [1]). It then computes the start of the parameterArea, located right after the sessionArea, into parmBufferStart ([2]), computes the size of the parameterArea into parmBufferSize ([3]), and calls ParseSessionBuffer() ([4]) passing parmBufferStart and parmBufferSize ([5], [6]):

Text
//           ExecuteCommand()
//
//     The function performs the following steps.
//     a) Parses the command header from input buffer.
//     b) Calls ParseHandleBuffer() to parse the handle area of the command.
//     c) Validates that each of the handles references a loaded entity.
//
//     d) Calls ParseSessionBuffer() () to:
//          1) unmarshal and parse the session area;
//          2) check the authorizations; and
//          3) when necessary, decrypt a parameter.

       [...]

LIB_EXPORT void
ExecuteCommand(
    unsigned    int      requestSize,       //   IN: command buffer size
    unsigned    char    *request,           //   IN: command buffer
    unsigned    int     *responseSize,      //   OUT: response buffer size
    unsigned    char    **response          //   OUT: response buffer
    )
{
        [...]
        // Find out session buffer size.
        result = UINT32_Unmarshal(&authorizationSize, &buffer, &size);
        if(result != TPM_RC_SUCCESS)
            goto Cleanup;
        // Perform sanity check on the unmarshaled    value. If it is smaller than
        // the smallest possible session or larger    than the remaining size of
        // the command, then it is an error. NOTE:    This check could pass but the
        // session size could still be wrong. That    will be determined after the
        // sessions are unmarshaled.
[1]     if(    authorizationSize < 9
            || authorizationSize > (UINT32) size)
        {
             result = TPM_RC_SIZE;
             goto Cleanup;
        }
        // The sessions, if any, follows authorizationSize.
        sessionBufferStart = buffer;
        // The parameters follow the session area.
[2]     parmBufferStart = sessionBufferStart + authorizationSize;
        // Any data left over after removing the authorization sessions is
        // parameter data. If the command does not have parameters, then an
        // error will be returned if the remaining size is not zero. This is
        // checked later.
[3]     parmBufferSize = size - authorizationSize;
        // The actions of ParseSessionBuffer() are described in the introduction.
[4]     result = ParseSessionBuffer(commandCode,
                                    handleNum,
                                    handles,
                                    sessionBufferStart,
                                    authorizationSize,
[5]                                 parmBufferStart,
[6]                                 parmBufferSize);
        [...]

ParseSessionBuffer in SessionProcess.c parses the sessionArea. If a session has the Decrypt attribute set ([1]) and the command code allows parameter encryption, it calls CryptParameterDecryption() ([2]), propagating parmBufferSize ([3]) and parmBufferStart ([4]):

Text
//           ParseSessionBuffer()
//
//       This function is the entry function for command session processing. It iterates sessions in session area
//       and reports if the required authorization has been properly provided. It also processes audit session and
//       passes the information of encryption sessions to parameter encryption module.
//
//       Error Returns                   Meaning
//
//       various                         parsing failure or authorization failure
//
TPM_RC
ParseSessionBuffer(
    TPM_CC              commandCode,                    //   IN:   Command code
    UINT32              handleNum,                      //   IN:   number of element in handle array
    TPM_HANDLE          handles[],                      //   IN:   array of handle
    BYTE               *sessionBufferStart,             //   IN:   start of session buffer
    UINT32              sessionBufferSize,              //   IN:   size of session buffer
    BYTE               *parmBufferStart,                //   IN:   start of parameter buffer
    UINT32              parmBufferSize                  //   IN:   size of parameter buffer
    )
{
        [...]
        // Decrypt the first parameter if applicable. This should be the last operation
        // in session processing.
        // If the encrypt session is associated with a handle and the handle's
        // authValue is available, then authValue is concatenated with sessionAuth to
        // generate encryption key, no matter if the handle is the session bound entity
        // or not.
[1]     if(s_decryptSessionIndex != UNDEFINED_INDEX)
        {
           // Get size of the leading size field in decrypt parameter
           if(    s_associatedHandles[s_decryptSessionIndex] != TPM_RH_UNASSIGNED
               && IsAuthValueAvailable(s_associatedHandles[s_decryptSessionIndex],
                                       commandCode,
                                       s_decryptSessionIndex)
             )
           {
                extraKey.b.size=
                    EntityGetAuthValue(s_associatedHandles[s_decryptSessionIndex],
                                       &extraKey.t.buffer);
           }
           else
           {
                extraKey.b.size = 0;
           }
           size = DecryptSize(commandCode);
[2]        result = CryptParameterDecryption(
                         s_sessionHandles[s_decryptSessionIndex],
                         &s_nonceCaller[s_decryptSessionIndex].b,
[3]                      parmBufferSize, (UINT16)size,
                         &extraKey,
[4]                      parmBufferStart);

The function that does the in-place decryption is CryptParameterDecryption in CryptUtil.c:

Text
//       [redacted]   CryptParameterDecryption()
//
//       This function does in-place decryption of a command parameter.
//
//       Error Returns                  Meaning
//
//       TPM_RC_SIZE                    The number of bytes in the input buffer is less than the number of
//                                      bytes to be decrypted.
//
TPM_RC
CryptParameterDecryption(
   TPM_HANDLE          handle,                 //   IN: encrypted session handle
   TPM2B              *nonceCaller,            //   IN: nonce caller
   UINT32              bufferSize,             //   IN: size of parameter buffer
   UINT16              leadingSizeInByte,      //   IN: the size of the leading size field in
                                               //       byte
   TPM2B_AUTH         *extraKey,               //   IN: the authValue
   BYTE               *buffer                  //   IN/OUT: parameter buffer to be decrypted
   )
{
   SESSION         *session = SessionGet(handle); // encrypt session
   // The HMAC key is going to be the concatenation of the session key and any
   // additional key material (like the authValue). The size of both of these
   // is the size of the buffer which can contain a TPMT_HA.
   TPM2B_TYPE(HMAC_KEY, ( sizeof(extraKey->t.buffer)
                         + sizeof(session->sessionKey.t.buffer)));
   TPM2B_HMAC_KEY          key;            // decryption key
   UINT32                  cipherSize = 0; // size of cipher text
   pAssert(session->sessionKey.t.size + extraKey->t.size <= sizeof(key.t.buffer));
   // Retrieve encrypted data size.
   if(leadingSizeInByte == 2)
   {
       // The first two bytes of the buffer are the size of the
       // data to be decrypted
[1]    cipherSize = (UINT32)BYTE_ARRAY_TO_UINT16(buffer);
[2]    buffer = &buffer[2];    // advance the buffer
   }
#ifdef TPM4B
   else if(leadingSizeInByte == 4)
   {
       // the leading size is four bytes so get the four byte size field
       cipherSize = BYTE_ARRAY_TO_UINT32(buffer);
       buffer = &buffer[4];    //advance pointer
   }
#endif
   else
   {
       pAssert(FALSE);
   }
[3] if(cipherSize > bufferSize)
       return TPM_RC_SIZE;
   // Compute decryption key by concatenating sessionAuth with extra input key
   MemoryCopy2B(&key.b, &session->sessionKey.b, sizeof(key.t.buffer));
   MemoryConcat2B(&key.b, &extraKey->b, sizeof(key.t.buffer));
   if(session->symmetric.algorithm == TPM_ALG_XOR)
       // XOR parameter decryption formulation:
       //    XOR(parameter, hash, sessionAuth, nonceNewer, nonceOlder)
       // Call XOR obfuscation function
[4]    CryptXORObfuscation(session->authHashAlg, &key.b, nonceCaller,
                                  &(session->nonceTPM.b), cipherSize, buffer);
   else
       // Assume that it is one of the symmetric block ciphers.
[5]    ParmDecryptSym(session->symmetric.algorithm, session->authHashAlg,
                             session->symmetric.keyBits.sym,
                             &key.b, nonceCaller, &session->nonceTPM.b,
                             cipherSize, buffer);
   return TPM_RC_SUCCESS;
}

Two problems stand out in this function.

Bug #1, the OOB read (CVE-2023-1018): at [1] the function uses the BYTE_ARRAY_TO_UINT16 macro to read the 16-bit cipherSize field from the buffer pointed to by parmBufferStart, without checking that any parameter data exists past the session area. The only length check was in ExecuteCommand, and it only verified that the sessionArea is at least 9 bytes. If a malformed command has no parameterArea past the sessionArea, the TPM reads memory past the end of the command. The macro performs no bounds check:

Text
#define BYTE_ARRAY_TO_UINT16(b)         (UINT16)( ((b)[0] << 8) \
                                                + (b)[1])

The UINT16_Unmarshal function should have been used instead, since it performs proper size checks before reading from a buffer.

Bug #2, the OOB write (CVE-2023-1017): if a proper parameterArea is supplied (avoiding bug #1), its first two bytes are interpreted as cipherSize at [1], and at [2] the buffer pointer is advanced by 2. At [3] there is a sanity check that bails out if cipherSize is greater than the actual buffer size, but after reading the 16-bit field and advancing the pointer by 2, the function forgets to subtract 2 from bufferSize to account for the two bytes already processed. A cipherSize value larger by 2 than the remaining data therefore passes the check. When CryptXORObfuscation() or ParmDecryptSym() is called at [4] or [5] to decrypt the data following the cipherSize field, the TPM writes 2 bytes past the end of the buffer.

The author notes that a 2-byte OOB write may not look powerful, but points to previous work by colleagues Damiano Melotti and Maxime Rossi Bellom, who obtained code execution on Google's Titan M chip with an OOB write of a single byte with value 0x01.

Exploitation

Reproducing either bug requires sending two commands to the target TPM. The first is always TPM2_StartAuthSession, to start an authorization session. For simplicity the symmetric algorithm can be TPM_ALG_XOR. The response contains a session handle. The second command must support parameter encryption; the author used TPM2_CreatePrimary, though a few other commands should probably work as well. The session handle from step 1 goes in the sessionArea, and the Decrypt flag is set in sessionAttributes.

Step 1: start an authorization session

Send TPM2_StartAuthSession with TPM_ALG_XOR as the symmetric algorithm. The report does not give the exact byte layout of this command; it only states that the response contains a session handle that is used in the next step.

Step 2a: trigger the OOB read (bug #1)

Send TPM2_CreatePrimary with a minimal valid sessionArea and no data after it, that is, with a missing parameterArea. The report does not reproduce the raw bytes of this command. The effect is that CryptParameterDecryption reads the 16-bit cipherSize from just past the end of the command.

Step 2b: trigger the OOB write (bug #2)

Send TPM2_CreatePrimary with a total size equal to the maximum supported TPM command size, 0x1000 bytes. This time a parameterArea is included, with the cipherSize field set to 0xfe5, which the report describes as 0x1000 - sizeof(command_base_header) - sizeof(handleArea) - sizeof(sessionArea), followed by 0xfe3 bytes of any value to fill the place of the encrypted parameter and complete the 0x1000 bytes of the whole command. The report does not reproduce the raw bytes of this command either. Because bufferSize was not reduced by the 2 bytes of the size field, the check at [3] passes and the decryption writes 2 bytes past the end of the command buffer.

Proof-of-Concept

The author published a PoC to reproduce both vulnerabilities as a .zip download. It contains a Python version meant to be run on Linux systems and a C version for running from a Windows machine. The report does not include the PoC source inline.

Root cause

The root cause is in the TCG reference implementation, in CryptParameterDecryption in CryptUtil.c, and it propagates to every implementation built from that code.

  • The OOB read comes from reading the 16-bit cipherSize with BYTE_ARRAY_TO_UINT16, a macro with no bounds check, instead of a checked unmarshalling routine such as UINT16_Unmarshal. The earlier check in ExecuteCommand only enforces a minimum sessionArea size of 9 bytes and does not guarantee that a parameterArea follows.
  • The OOB write comes from a bookkeeping error: after consuming the 2-byte size field and advancing the buffer pointer, the function does not subtract those 2 bytes from bufferSize. The sanity check cipherSize > bufferSize therefore allows a cipherSize 2 bytes larger than the remaining data, and the decryption routines write 2 bytes past the end of the buffer.

Why existing defences did not stop it: the only length validation on the parameter area is the check in ExecuteCommand, which is insufficient for both bugs, and the macro used for the size field performs no bounds checking. The report does not describe any other mitigation in the reference code.

Impact

  1. OOB read: CryptParameterDecryption in CryptUtil.c can read 2 bytes past the end of the received TPM command. If an affected TPM does not zero the command buffer between commands, the function can read whatever 16-bit value was left there by the previous command. This is implementation-dependent: VMware does not clear the command buffer between requests, so the OOB read can access the previous command's data; Hyper-V's virtual TPM pads unused bytes with zeros on every request, so the OOB access reads only zeros.

  2. OOB write: CryptXORObfuscation/ParmDecryptSym in CryptUtil.c, called from CryptParameterDecryption, can write 2 bytes past the end of the command buffer, causing memory corruption. The author considers this the more interesting bug. Whether something useful can be overwritten depends on how each implementation allocates the command buffer:

  • VMware uses an oversized buffer of size 0x10000, far larger than the usual maximum TPM command size of 0x1000 bytes.
  • Hyper-V uses a static variable of size 0x1000 as the command buffer.
  • SWTPM uses malloc() to allocate a command buffer of size 0x1008 (8 bytes for a send command prefix that can modify the locality, plus 0x1000 bytes for the maximum TPM command size).

So the chance of having something useful adjacent to the buffer is highly implementation-dependent, and the same reasoning applies to hardware TPM firmware, where it depends entirely on how the vendor allocates the incoming command buffer.

For cloud, the author notes that a malicious actor could attempt to exploit the virtual TPM to escape from a virtual machine and compromise the host system. Google Cloud's virtual TPM core comes from IBM code extracted from the spec source, and the bugs were verified present there. Azure's hypervisor is based on Hyper-V, which was verified vulnerable on Windows 10, so the author expects the bugs to be present on Azure as well. For AWS and Oracle Cloud Infrastructure the author had little detail beyond documentation stating conformance to the TPM 2.0 specification.

For hardware, the author verified at least some discrete TPM chips are vulnerable: after the OOB write attempt the chip stopped responding and needed a hard reboot. Most hardware TPMs could not be evaluated because firmware updates were encrypted and there was no runtime visibility.

Fix

Reference implementation: the Trusted Computing Group published errata version 1.4 for the TCG Trusted Platform Module Library, with suggested fixes for both bugs.

Software products:

  • Microsoft patched Hyper-V in the March 2023 security update. Their impact assessment for the OOB write is low in TPM 2.0 in Pluton/HCL/Overlake/Manticore standard server for Azure, because the overwrite is only 2 bytes and their team did not identify a consistent and easily achievable way to obtain EoP or RCE with only 2 bytes.
  • Microsoft patched their open source reference implementation in commit [redacted].
  • VMware was expected to issue fixes in April 2023.
  • Libtpms patched the bugs in commit [redacted].
  • Chromium OS patched the vulnerabilities in commit [redacted].
  • IBM patched their open source implementation in commit [redacted].

Hardware products:

  • Nuvoton published security advisory SA-003 for their NPCT65x TPM chip.
  • Lenovo published security advisory LEN-118320 regarding affected products using that Nuvoton TPM.

The author advises checking the computer manufacturer's website for TPM firmware updates.

Variants to test

These are follow-ups derived from the report's reasoning, not suggestions made in the report itself.

  1. Test other commands that support parameter encryption. The author used TPM2_CreatePrimary and said a few other commands should probably work. A positive result is the same OOB read or write behaviour when the Decrypt flag is set on a session for another command with a sized first parameter.

  2. Test the 4-byte leading size path. The code has a TPM4B branch that reads a 4-byte size field and advances the buffer by 4. If a build is compiled with TPM4B, check whether the same missing subtraction of the size-field length from bufferSize is present. A positive result is the same kind of out-of-bounds write on the 4-byte path.

  3. Probe command buffer hygiene on other virtual TPMs. Send a command that leaves a recognisable 16-bit value at the end of the buffer, then trigger the OOB read with a missing parameterArea. A positive result is that the read returns the leftover value rather than zeros, showing the buffer is not cleared between requests.

  4. Probe buffer allocation on other virtual TPMs. Trigger the OOB write with a full-size command and observe whether the process crashes, corrupts adjacent state, or silently continues. A positive result is a crash or observable corruption, which indicates something useful is adjacent to the command buffer.

  5. Test hardware TPMs with the published PoC. A positive result is the chip becoming unresponsive after the OOB write attempt and requiring a hard reboot, as the author observed on at least some discrete chips.

  6. Test other implementations derived from the TCG reference code, including cloud virtual TPMs. A positive result is reproduction of either bug with the PoC, which would indicate the implementation inherits the vulnerable CryptParameterDecryption.

Disclosure timeline

The report includes a non-exhaustive timeline of events relevant to disclosure:

  • 2022-11-24: Quarkslab sent the report to VMware and to Microsoft (with PoC); VMware acknowledged.
  • 2022-11-25: Quarkslab notified CERT/CC and opened a VINCE case; tracked as VU#782720.1 and VU#782720.2.
  • 2022-11-28: Quarkslab notified CERT-FR; CERT-FR, CERT/CC and Google acknowledged; Quarkslab filed with Google's security issue tracker noting the GCP Shielded VM vTPM likely uses the reference implementation; CERT/CC asked about a disclosure date; Quarkslab set the date to February 28th, 2023; Google requested a Linux PoC, which was sent.
  • 2022-11-29: Report sent to STMicroelectronics (automated acknowledgement); CERT/CC reserved two CVE IDs; Google asked whether TCG was notified and whether a coordinated embargo applied; Microsoft said the report met its security servicing criteria; Quarkslab explained the February 28th date to Google; Cisco began tracking internally.
  • 2022-12-02: Quarkslab noticed more than 1600 vendors (up from 43 the prior day) had access on VINCE and asked CERT/CC; CERT/CC said the expansion was intended because PC OEM and hardware vendors wanted to reach their supply chains; Quarkslab warned of higher leak probability; Aruba Networks asked for a Linux PoC and Quarkslab provided a Python PoC using /dev/tpm0; Intel said it was investigating; Fujitsu PSIRT asked whether TPM chips were analysed, and Quarkslab said hardware TPMs were not analysed due to lack of debugging or monitoring.
  • 2022-12-04: Nuvoton said current versions of their TPM chip firmware are not affected.
  • 2022-12-05: TCG VRT said it was tracking and coordinating triage; SUSE Linux identified libtpms as affected and asked whether maintainers were notified; Quarkslab said it had not notified them and deferred to CERT/CC; CERT/CC said it had notified the IBM security group; Google said it shared the PoC internally and was coordinating with TCG; Quarkslab asked Google about fix dates and scope; TCG said its VRT was engaged; a CERT notified parties that information was publicly available on the issue tracker of a China-based Linux distribution.
  • 2022-12-06: CERT/CC said the China-based distribution had removed public access on request; the coordinated date remained February 28th, 2023.
  • 2022-12-07: Call between CERT/CC and Quarkslab; both agreed not to change the date and to speed up vendor fixes; CERT/CC got permission to share the PoC with the US DHS CISA Threats team; Microsoft asked for more reproduction information.
  • 2022-12-08: CERT-JP said it had notified multiple Japanese vendors about the embargo date.
  • 2022-12-09: New PoC versions for Linux and Windows posted on VINCE.
  • 2022-12-12: Quarkslab asked Google for an update and fix date.
  • 2022-12-13: Crestron Electronics asked whether DeviceIOControl error 87 (Invalid Parameter) from the Windows PoC meant the TPM was not vulnerable; Quarkslab said the error revealed a PoC bug that would be fixed, and that determining vulnerability without logs, debugging or source requires time-consuming firmware reverse engineering; Siemens asked whether older TCG TPM versions were affected, and Quarkslab said the bugs are in the TPM 2.0 spec code and present in IBM ibmswtpm2 TPM 2.0 releases dating back to at least March 21st, 2017, so any TPM 2.0 implementation based on them is likely affected, and TPM 1.2 was not checked.
  • 2022-12-14: Infineon stated its TPM chips are not affected; Microsoft reiterated its request for reproduction information.
  • 2022-12-16: Quarkslab updated the PoCs fixing a bug that prevented testing certain TPMs; asked Google for updates and noted a fix was committed to Chromium OS TPM2 code on December 1st, so knowledge of the bugs was considered public; provided Microsoft a detailed description of how to debug the Hyper-V vTPM; Microsoft confirmed it could reproduce the bugs.
  • 2022-12-18: Google agreed with the February 28th, 2023 date and said it was working with TCG and CERT.
  • 2022-12-19: Microsoft asked whether disclosure could move to April 2023 to align with its security release; Quarkslab said CERT/CC coordinates disclosure and, given other vendors and a public fix, acceleration was more likely than delay, and suggested discussing with CERT/CC.
  • 2022-12-23: PoCs updated to query and print TPM manufacturer strings.
  • 2022-12-26: PoCs updated to query and print firmware versions, with output from a run identifying a vulnerable chip.
  • 2023-01-03: Google VRP said the bugs did not meet reward criteria as they do not affect Google products, but passed the report to Chrome VRP.
  • 2023-01-05: Google said it considered the code changes public but not an embargo break per discussion with CERT and TCG, and could not answer the rollout question.
  • 2023-01-09: VMware asked whether disclosure could extend to end of March or April.
  • 2023-01-16: Quarkslab told VMware the bugs should be considered public knowledge and the process involved multiple vendors plus CERT and TCG, so moving the date would be difficult; asked Google VRP to clarify eligibility, noting the Chromium OS fix suggested at least one product was affected.
  • 2023-01-17: Google said the issue went to the VRP panel for reconsideration; Chrome VRP said it was considering the issue and granted access to its bug tracker entry, dated January 4th, which said the bugs were reported externally, were fixed, and were deemed not exploitable.
  • 2023-02-01: STMicroelectronics reported its products are not affected.
  • 2023-02-02: Chrome VRP awarded 20K USD for the bugs.
  • 2023-02-08: Call with CERT to synchronise; Quarkslab agreed to publish technical details on March 14th, with CERT and TCG publishing advisories and errata on February 28th.
  • 2023-02-15: Microsoft said it would try to accelerate patches and asked to preview the blog post; Quarkslab provided an updated PoC and agreed to send a draft.
  • 2023-02-28: CERT/CC published its vulnerability note; TCG published its security advisory and errata.
  • 2023-03-06: Nuvoton and Lenovo published security advisories; libtpms added test cases.
  • 2023-03-09: Microsoft committed a fix to its open source reference implementation.
  • 2023-03-10: Draft of the blog post sent to Microsoft.
  • 2023-03-13: Microsoft replied with its impact assessment for Azure servers.
  • 2023-03-14: The blog post was published.

The author thanks Iván Arce for valuable inputs and ideas and for handling a complicated disclosure process with many parties involved.

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

What happened, in plain words

In March 2023, a security researcher published a blog post on the Quarkslab blog describing two bugs he had found in a piece of software called the Trusted Platform Module (TPM) 2.0 reference implementation. A reference implementation is the official example code that a standards body publishes so that hardware and software makers can build their own versions of a thing. In this case the standards body is the Trusted Computing Group (TCG), a nonprofit organisation that writes and maintains the TPM specification.

The two bugs are:

  • An out-of-bounds write, tracked as CVE-2023-1017. "Out-of-bounds write" means a program writes data past the end of the memory area it was given, into memory that belongs to something else.
  • An out-of-bounds read, tracked as CVE-2023-1018. "Out-of-bounds read" means a program reads data from past the end of the memory area it was given, picking up whatever happens to be there.

A CVE is a public catalogue number for a known security flaw, so that everyone can refer to the same bug unambiguously.

These bugs were not confined to one product. Because they live in the shared reference code, they turned up in several software TPMs, including the virtual TPMs that virtualisation software hands to virtual machines, and in a number of hardware TPM chips as well.

The researcher explains that the work started because of Windows 11. Windows 11, released in October 2021, requires a TPM 2.0 to install. That means if you want to run Windows 11 inside a virtual machine, the virtualisation software has to give that virtual machine a TPM, either by passing through the real TPM chip on the physical computer or by creating a pretend, software-only TPM. The researcher saw this as new attack surface: a new way for code running inside a virtual machine to reach the software that runs the virtual machine, with the long-term possibility of a virtual machine escape, where an attacker breaks out of the virtual machine and takes over the physical host.

Both bugs can be triggered from ordinary user-mode applications, meaning normal programs that a user runs, by sending specially crafted TPM 2.0 commands that use encrypted parameters. Because the bugs come from the reference code, they reached much further than the researcher first expected: every virtualisation product he tested, and hardware implementations too.

The researcher is careful about what he could and could not check. Most of his conclusions about exploitability, impact and which platforms are affected come from analysing software virtual TPMs, because those can be debugged easily. Debugging the virtual TPM inside Microsoft Hyper-V is harder because it runs as an IUM process (Isolated User Mode, a special protected kind of Windows process). Getting a look at what happens at runtime inside the firmware of a physical TPM chip, which sits in its own chip with no debugging interfaces, is a different problem entirely. Even reading the firmware statically was hard: the few TPM firmware updates he managed to obtain were encrypted. So the absence of a detailed assessment of hardware TPMs does not mean they are safe; it means he could not evaluate most of them. Using the proof-of-concept code published with the blog post, he did confirm that at least some discrete TPM chips are vulnerable: after attempting the out-of-bounds write, the chip stopped responding, meaning it no longer recognised commands, and the computer needed a hard reboot to work again.

Affected platforms

The researcher lists the products where he could actually demonstrate the bugs with his proof-of-concept. He stresses that the list is not exhaustive: other virtual or physical TPMs are very likely vulnerable too.

  • The TPM 2.0 reference implementation itself, in the latest version available at the time of the research: Trusted Platform Module Library Specification, Family "2.0", Level 00, Revision 01.59, November 2019.
  • Microsoft Hyper-V on Windows 10. The affected module is TPMEngUM.dll version 10.0.19041.1415. A module here means one file of program code inside the larger product.
  • VMware Workstation version 16.2.4 build-20089737. The affected module is tpm2emu.exe, and the executable carries no version information.
  • Libtpms/SWTPM, a software TPM used by Qemu and VirtualBox, compiled from the master branch at commit [redacted]. A commit is a saved snapshot in a code repository, identified by a long string of characters.
  • A Nuvoton hardware TPM, firmware version 1.3.0.1. Firmware is the software built into a chip.
  • In general, every TPM 2.0 whose firmware is based on the TCG reference implementation is expected to be affected.

A threat to cloud computing

Cloud computing means renting computers over the internet instead of owning them. All the major cloud providers offer virtual machines with virtual TPMs, which raises an interesting scenario: a malicious person who controls a virtual machine could try to exploit these bugs in the virtual TPM to escape from the virtual machine and compromise the physical host underneath.

The providers mentioned are:

  • Amazon AWS, with NitroTPM.
  • Microsoft Azure, which provides virtual TPMs as part of Trusted Launch.
  • Google Cloud, which offers virtual TPMs as part of Shielded VMs.
  • Oracle Cloud Infrastructure, which provides virtual TPMs as part of Shielded Instances.

Any provider whose virtual TPM is based on the TCG reference implementation is expected to be vulnerable. For Google Cloud, the linked blog post says the core of their virtual TPM comes from code published by IBM, extracted automatically from the full source of the TPM 2.0 specification, and the researcher verified that the bugs in the CryptParameterDecryption function are present in it. For Microsoft Azure, the documentation says the virtual TPM is compliant with the TPM 2.0 specification, and the researcher verified that the virtual TPM in the Hyper-V version available on Windows 10 is vulnerable; the bugs were also present in Microsoft's open source reference implementation. For Amazon AWS and Oracle Cloud Infrastructure, he has little detail beyond the NitroTPM documentation saying it conforms to the TPM 2.0 specification, with a link to the TCG website.

Fixes

Reference implementation

The Trusted Computing Group published errata version 1.4 for the TCG Trusted Platform Module Library, with suggested fixes for both bugs. Errata are corrections published after a document or specification has gone out.

Software products

  • Microsoft patched the bugs in Hyper-V in its March 2023 security update. Microsoft's assessment of the impact of the out-of-bounds write is low for TPM 2.0 in Pluton/HCL/Overlake/Manticore standard server for Azure, because the overwrite is only 2 bytes and their team did not identify a consistent and easily achievable way to obtain EoP or RCE with only 2 bytes. EoP means elevation of privilege, getting more rights than you should have; RCE means remote code execution, running your own code on someone else's machine.
  • Microsoft also patched its open source reference implementation in commit [redacted].
  • VMware was expected to issue fixes in April 2023.
  • Libtpms patched the bugs in commit [redacted].
  • Chromium OS patched the vulnerabilities in commit [redacted].
  • IBM patched its open source implementation in commit [redacted].

Hardware products

  • Nuvoton published security advisory SA-003 for its NPCT65x TPM chip. A security advisory is a public notice from a vendor about a security problem and what to do about it.
  • Lenovo published security advisory LEN-118320 about affected products that use that Nuvoton TPM.

The researcher advises checking the website of your computer manufacturer for TPM firmware updates.

Technical details

A primer on TPM encrypted parameters

Before the bugs make sense, you need to know how a TPM command can carry encrypted data. The Trusted Platform Module Library Specification, Family 2.0, Part 1: Architecture, Section 21, titled "Session-based encryption", explains that several TPM 2.0 commands have parameters that may need to be encrypted on the way to or from the TPM. A parameter is simply an input or output value of a command. Encrypting it keeps it confidential, so that someone watching the traffic cannot read it.

The specification says, quoted exactly:

Text
Not all commands support parameter encryption. If session-based encryption is allowed, only the first
parameter in the parameter area of a request or response may be encrypted. That parameter must have
an explicit size field. Only the data portion of the parameter is encrypted. The TPM should support
session-based encryption using XOR obfuscation. Support for a block cipher using CFB mode is platform
specific. These two encryption methods (XOR and CFB) do not require that the data be padded for
encryption, so the encrypted data size and the plain-text data size is the same.

[...]

Session-based encryption uses the algorithm parameters established when the session is started and
values that are derived from the session-specific sessionKey.

[...]

If sessionAttributes.decrypt is SET in a session in a command, and the first parameter of the command is
a sized buffer, then that parameter is encrypted using the encryption parameters of the session.

In plain words, line by line:

  • Not every command supports encryption of its parameters.
  • When it is allowed, only the first parameter can be encrypted, and that parameter must carry an explicit size field, meaning the data is preceded by a number saying how long it is.
  • Only the data part is encrypted, not the size field.
  • The TPM should support a simple method called XOR obfuscation. XOR is a basic mathematical operation on bits; obfuscation here means scrambling the data so it looks meaningless without the key.
  • A stronger method using a block cipher in CFB mode is optional and depends on the platform. A block cipher encrypts data in fixed-size chunks; CFB is one particular way of chaining those chunks.
  • Neither method needs padding, so the encrypted data is exactly the same length as the original.
  • The encryption uses values agreed when the session was started, plus a session key.
  • If a session in a command has its decrypt attribute set, and the first parameter is a sized buffer, that parameter is encrypted with that session's settings.

A TPM 2.0 command with encrypted parameters is laid out as a base command header, then a handleArea, then a sessionArea, then the encrypted parameterArea. The diagram from the report:

Text
+---------------------+
|                     |
|                     |
| Base command header |
|                     |
|                     |
+---------------------+
|                     |
|     handleArea      |
|                     |
+---------------------+
|                     |
|    sessionArea      |
|                     |
+---------------------+
|                     |
|   parameterArea     |
|                     |
+---------------------+

Think of the command as a parcel with four stacked sections. The header is the label saying what kind of command it is. The handle area lists which TPM objects the command refers to, a handle being a reference number for an object inside the TPM. The session area carries the authorisation session, which is the login-like context proving who is asking. The parameter area carries the actual data, possibly encrypted.

The researcher then followed how the reference implementation reads this structure. In the file ExecCommand.c, the function ExecuteCommand checks that the authorizationSize field of the sessionArea is at least 9 (marker [1]). It then works out where the parameterArea starts, right after the sessionArea, and stores that in parmBufferStart ([2]). It works out the size of the parameterArea and stores that in parmBufferSize ([3]). Then it calls ParseSessionBuffer() ([4]), passing parmBufferStart and parmBufferSize ([5], [6]).

Text
//           ExecuteCommand()
//
//     The function performs the following steps.
//     a) Parses the command header from input buffer.
//     b) Calls ParseHandleBuffer() to parse the handle area of the command.
//     c) Validates that each of the handles references a loaded entity.
//
//     d) Calls ParseSessionBuffer() () to:
//          1) unmarshal and parse the session area;
//          2) check the authorizations; and
//          3) when necessary, decrypt a parameter.

       [...]

LIB_EXPORT void
ExecuteCommand(
    unsigned    int      requestSize,       //   IN: command buffer size
    unsigned    char    *request,           //   IN: command buffer
    unsigned    int     *responseSize,      //   OUT: response buffer size
    unsigned    char    **response          //   OUT: response buffer
    )
{
        [...]
        // Find out session buffer size.
        result = UINT32_Unmarshal(&authorizationSize, &buffer, &size);
        if(result != TPM_RC_SUCCESS)
            goto Cleanup;
        // Perform sanity check on the unmarshaled    value. If it is smaller than
        // the smallest possible session or larger    than the remaining size of
        // the command, then it is an error. NOTE:    This check could pass but the
        // session size could still be wrong. That    will be determined after the
        // sessions are unmarshaled.
[1]     if(    authorizationSize < 9
            || authorizationSize > (UINT32) size)
        {
             result = TPM_RC_SIZE;
             goto Cleanup;
        }
        // The sessions, if any, follows authorizationSize.
        sessionBufferStart = buffer;
        // The parameters follow the session area.
[2]     parmBufferStart = sessionBufferStart + authorizationSize;
        // Any data left over after removing the authorization sessions is
        // parameter data. If the command does not have parameters, then an
        // error will be returned if the remaining size is not zero. This is
        // checked later.
[3]     parmBufferSize = size - authorizationSize;
        // The actions of ParseSessionBuffer() are described in the introduction.
[4]     result = ParseSessionBuffer(commandCode,
                                    handleNum,
                                    handles,
                                    sessionBufferStart,
                                    authorizationSize,
[5]                                 parmBufferStart,
[6]                                 parmBufferSize);
        [...]

Line by line in plain words:

  • The comment block at the top describes what the function does: it reads the command header, reads the handle area, checks that each handle points to something loaded, and then calls ParseSessionBuffer() to read the session area, check authorisations and, when needed, decrypt a parameter.
  • ExecuteCommand takes the size of the incoming request, a pointer to the request bytes, a place to store the response size and a place to store the response pointer. A pointer is a memory address, like a house number telling the program where the data lives.
  • UINT32_Unmarshal reads a 32-bit number from the buffer into authorizationSize. Unmarshalling means turning a stream of bytes back into structured values. If that fails, the function jumps to cleanup.
  • At [1], the sanity check: if authorizationSize is smaller than 9, or larger than the remaining size of the command, the function returns a size error. The comment itself warns that this check can pass while the session size is still wrong, and that this will be determined later.
  • sessionBufferStart = buffer; records where the session area begins.
  • At [2], parmBufferStart is set to the start of the session area plus authorizationSize, which is exactly where the parameter area begins.
  • At [3], parmBufferSize is set to whatever is left of the command after the session area. The comment notes that if the command has no parameters, an error will be returned later if the remaining size is not zero.
  • At [4], ParseSessionBuffer is called with the command code, the number of handles, the handles, the session start and size, and at [5] and [6] the parameter start and size.

The function ParseSessionBuffer in SessionProcess.c reads the sessionArea. If a session has the Decrypt attribute set ([1]) and the command code allows parameter encryption, it calls CryptParameterDecryption() ([2]), passing along parmBufferSize ([3]) and parmBufferStart ([4]):

Text
//           ParseSessionBuffer()
//
//       This function is the entry function for command session processing. It iterates sessions in session area
//       and reports if the required authorization has been properly provided. It also processes audit session and
//       passes the information of encryption sessions to parameter encryption module.
//
//       Error Returns                   Meaning
//
//       various                         parsing failure or authorization failure
//
TPM_RC
ParseSessionBuffer(
    TPM_CC              commandCode,                    //   IN:   Command code
    UINT32              handleNum,                      //   IN:   number of element in handle array
    TPM_HANDLE          handles[],                      //   IN:   array of handle
    BYTE               *sessionBufferStart,             //   IN:   start of session buffer
    UINT32              sessionBufferSize,              //   IN:   size of session buffer
    BYTE               *parmBufferStart,                //   IN:   start of parameter buffer
    UINT32              parmBufferSize                  //   IN:   size of parameter buffer
    )
{
        [...]
        // Decrypt the first parameter if applicable. This should be the last operation
        // in session processing.
        // If the encrypt session is associated with a handle and the handle's
        // authValue is available, then authValue is concatenated with sessionAuth to
        // generate encryption key, no matter if the handle is the session bound entity
        // or not.
[1]     if(s_decryptSessionIndex != UNDEFINED_INDEX)
        {
           // Get size of the leading size field in decrypt parameter
           if(    s_associatedHandles[s_decryptSessionIndex] != TPM_RH_UNASSIGNED
               && IsAuthValueAvailable(s_associatedHandles[s_decryptSessionIndex],
                                       commandCode,
                                       s_decryptSessionIndex)
             )
           {
                extraKey.b.size=
                    EntityGetAuthValue(s_associatedHandles[s_decryptSessionIndex],
                                       &extraKey.t.buffer);
           }
           else
           {
                extraKey.b.size = 0;
           }
           size = DecryptSize(commandCode);
[2]        result = CryptParameterDecryption(
                         s_sessionHandles[s_decryptSessionIndex],
                         &s_nonceCaller[s_decryptSessionIndex].b,
[3]                      parmBufferSize, (UINT16)size,
                         &extraKey,
[4]                      parmBufferStart);

In plain words:

  • The comment block says this function is the entry point for processing the session area. It goes through the sessions, reports whether the required authorisation was provided, handles audit sessions and passes encryption session information to the module that does the decryption.
  • The function takes the command code, the number of handles, the array of handles, the start and size of the session buffer, and the start and size of the parameter buffer.
  • At [1], it checks whether a decrypt session index is defined, meaning a session in this command asked for decryption.
  • If the session is associated with a handle and that handle's authorisation value is available, that value is copied into extraKey, which will be mixed into the decryption key. Otherwise extraKey is empty.
  • size = DecryptSize(commandCode); asks how many bytes the leading size field of this command's encrypted parameter occupies.
  • At [2], CryptParameterDecryption is called with the session handle, the caller's nonce (a random value used once, to keep sessions fresh), at [3] the parameter buffer size and the size of the leading size field, the extra key, and at [4] the parameter buffer start.

The function that actually decrypts in place is CryptParameterDecryption in CryptUtil.c. "In place" means it overwrites the same memory it read from, rather than copying to a new buffer.

Text
//       [redacted]   CryptParameterDecryption()
//
//       This function does in-place decryption of a command parameter.
//
//       Error Returns                  Meaning
//
//       TPM_RC_SIZE                    The number of bytes in the input buffer is less than the number of
//                                      bytes to be decrypted.
//
TPM_RC
CryptParameterDecryption(
   TPM_HANDLE          handle,                 //   IN: encrypted session handle
   TPM2B              *nonceCaller,            //   IN: nonce caller
   UINT32              bufferSize,             //   IN: size of parameter buffer
   UINT16              leadingSizeInByte,      //   IN: the size of the leading size field in
                                               //       byte
   TPM2B_AUTH         *extraKey,               //   IN: the authValue
   BYTE               *buffer                  //   IN/OUT: parameter buffer to be decrypted
   )
{
   SESSION         *session = SessionGet(handle); // encrypt session
   // The HMAC key is going to be the concatenation of the session key and any
   // additional key material (like the authValue). The size of both of these
   // is the size of the buffer which can contain a TPMT_HA.
   TPM2B_TYPE(HMAC_KEY, ( sizeof(extraKey->t.buffer)
                         + sizeof(session->sessionKey.t.buffer)));
   TPM2B_HMAC_KEY          key;            // decryption key
   UINT32                  cipherSize = 0; // size of cipher text
   pAssert(session->sessionKey.t.size + extraKey->t.size <= sizeof(key.t.buffer));
   // Retrieve encrypted data size.
   if(leadingSizeInByte == 2)
   {
       // The first two bytes of the buffer are the size of the
       // data to be decrypted
[1]    cipherSize = (UINT32)BYTE_ARRAY_TO_UINT16(buffer);
[2]    buffer = &buffer[2];    // advance the buffer
   }
#ifdef TPM4B
   else if(leadingSizeInByte == 4)
   {
       // the leading size is four bytes so get the four byte size field
       cipherSize = BYTE_ARRAY_TO_UINT32(buffer);
       buffer = &buffer[4];    //advance pointer
   }
#endif
   else
   {
       pAssert(FALSE);
   }
[3] if(cipherSize > bufferSize)
       return TPM_RC_SIZE;
   // Compute decryption key by concatenating sessionAuth with extra input key
   MemoryCopy2B(&key.b, &session->sessionKey.b, sizeof(key.t.buffer));
   MemoryConcat2B(&key.b, &extraKey->b, sizeof(key.t.buffer));
   if(session->symmetric.algorithm == TPM_ALG_XOR)
       // XOR parameter decryption formulation:
       //    XOR(parameter, hash, sessionAuth, nonceNewer, nonceOlder)
       // Call XOR obfuscation function
[4]    CryptXORObfuscation(session->authHashAlg, &key.b, nonceCaller,
                                  &(session->nonceTPM.b), cipherSize, buffer);
   else
       // Assume that it is one of the symmetric block ciphers.
[5]    ParmDecryptSym(session->symmetric.algorithm, session->authHashAlg,
                             session->symmetric.keyBits.sym,
                             &key.b, nonceCaller, &session->nonceTPM.b,
                             cipherSize, buffer);
   return TPM_RC_SUCCESS;
}

In plain words:

  • The comment block says the function decrypts a command parameter in place, and that it returns a size error if the input buffer holds fewer bytes than are to be decrypted.
  • The function takes the session handle, the caller's nonce, the size of the parameter buffer, the size in bytes of the leading size field, the extra key and the buffer itself.
  • SessionGet(handle) looks up the session object for this handle.
  • The comment explains that the key used for the HMAC (a keyed hash used to check integrity) will be the session key joined with any extra key material such as the authorisation value.
  • key will hold the decryption key, and cipherSize starts at zero and will hold the size of the encrypted data.
  • pAssert is a check that aborts if the combined key sizes would overflow the key buffer.
  • If the leading size field is 2 bytes, at [1] the first two bytes of the buffer are read as a 16-bit number into cipherSize, and at [2] the buffer pointer is moved forward by 2 so it now points at the encrypted data itself.
  • If the code was compiled with the TPM4B option, there is a branch for a 4-byte size field, which reads a 32-bit number and moves the pointer forward by 4.
  • Otherwise the code asserts false, meaning this should never happen.
  • At [3], the sanity check: if cipherSize is larger than bufferSize, return a size error.
  • The decryption key is built by copying the session key and then appending the extra key.
  • If the session uses XOR, at [4] CryptXORObfuscation is called with the hash algorithm, the key, the caller nonce, the TPM nonce, cipherSize and the buffer.
  • Otherwise, at [5], ParmDecryptSym is called for a symmetric block cipher, with the algorithm, hash algorithm, key size, key, nonces, cipherSize and buffer.
  • On success it returns success.

Vulnerabilities in the CryptParameterDecryption function

Two problems stand out in this function.

Bug #1, the out-of-bounds read (CVE-2023-1018). At [1], the function uses the BYTE_ARRAY_TO_UINT16 macro to read the 16-bit cipherSize field from the buffer pointed to by parmBufferStart, without checking that any parameter data exists past the session area. The only length check happened earlier, in ExecuteCommand, and it only verified that the sessionArea is at least 9 bytes. So if a malformed command has no parameterArea past the sessionArea, the TPM reads memory past the end of the command. The macro does no bounds check at all:

Text
#define BYTE_ARRAY_TO_UINT16(b)         (UINT16)( ((b)[0] << 8) \
                                                + (b)[1])

In plain words, this macro takes two bytes at the address b, shifts the first one left by 8 bits and adds the second, producing a 16-bit number. It never asks whether those two bytes are actually inside the buffer. The UINT16_Unmarshal function should have been used instead, because it checks the available size before reading.

Bug #2, the out-of-bounds write (CVE-2023-1017). If a proper parameterArea is supplied, avoiding bug #1, its first two bytes are interpreted as cipherSize at [1], and at [2] the buffer pointer is moved forward by 2. At [3] there is a sanity check that bails out if cipherSize is greater than the actual buffer size. But after reading the 16-bit field and moving the pointer by 2, the function forgets to subtract 2 from bufferSize to account for the two bytes it already consumed. So a cipherSize value that is 2 larger than the remaining data still passes the check. When CryptXORObfuscation() or ParmDecryptSym() is called at [4] or [5] to decrypt the data after the cipherSize field, the TPM writes 2 bytes past the end of the buffer.

The researcher notes that a 2-byte out-of-bounds write may not sound powerful, but points to earlier work by colleagues Damiano Melotti and Maxime Rossi Bellom, who obtained code execution on Google's Titan M chip with an out-of-bounds write of a single byte with value 0x01.

Impact

  1. Out-of-bounds read: CryptParameterDecryption in CryptUtil.c can read 2 bytes past the end of the received TPM command. If an affected TPM does not zero the command buffer between commands, the function can read whatever 16-bit value was left there by the previous command. This depends on the implementation: VMware does not clear the command buffer between requests, so the out-of-bounds read can access the previous command's data; Hyper-V's virtual TPM pads unused bytes with zeros on every request, so the out-of-bounds access reads only zeros.

  2. Out-of-bounds write: CryptXORObfuscation and ParmDecryptSym in CryptUtil.c, called from CryptParameterDecryption, can write 2 bytes past the end of the command buffer, causing memory corruption. The researcher considers this the more interesting bug. Whether something useful can be overwritten depends on how each implementation allocates the command buffer:

  • VMware uses an oversized buffer of size 0x10000, far larger than the usual maximum TPM command size of 0x1000 bytes.
  • Hyper-V uses a static variable of size 0x1000 as the command buffer. A static variable is a fixed piece of memory reserved for the whole life of the program.
  • SWTPM uses malloc() to allocate a command buffer of size 0x1008: 8 bytes for a send command prefix that can modify the locality, plus 0x1000 bytes for the maximum TPM command size. malloc() is the standard way a program asks the operating system for a block of memory; locality is a TPM concept describing which environment is talking to the chip.

So the chance of having something useful next to the buffer is highly implementation-dependent, and the same reasoning applies to hardware TPM firmware, where it depends entirely on how the vendor allocates the incoming command buffer.

For the cloud, the researcher notes that a malicious actor could try to exploit the virtual TPM to escape from a virtual machine and compromise the host. Providers using a virtual TPM based on the TCG reference implementation are expected to be vulnerable. Google Cloud's virtual TPM core comes from IBM code extracted from the specification source, and the bugs were verified present there. Azure's hypervisor is based on Hyper-V, which was verified vulnerable on Windows 10, so the researcher expects the bugs to be present on Azure as well. For AWS and Oracle Cloud Infrastructure he had little detail beyond documentation stating conformance to the TPM 2.0 specification.

For hardware, the researcher verified that at least some discrete TPM chips are vulnerable: after the out-of-bounds write attempt the chip stopped responding and needed a hard reboot. Most hardware TPMs could not be evaluated because firmware updates were encrypted and there was no runtime visibility.

Triggering the bugs

To reproduce either bug, you send two commands to the target TPM. The first is always TPM2_StartAuthSession, which starts an authorisation session. For simplicity you can choose TPM_ALG_XOR as the symmetric algorithm. The response contains a session handle. The second command must support parameter encryption; the researcher used TPM2_CreatePrimary, though a few other commands should probably work too. The session handle from step 1 goes in the sessionArea, and the Decrypt flag is set in sessionAttributes.

Step 1: start an authorisation session

Send TPM2_StartAuthSession with TPM_ALG_XOR as the symmetric algorithm. The report does not give the exact byte layout of this command; it only says the response contains a session handle used in the next step. The reason for this step is that decryption of a parameter only happens inside a session that was set up to decrypt, so you need a session first.

Step 2a: trigger the out-of-bounds read (bug #1)

Send TPM2_CreatePrimary with a minimal valid sessionArea and no data after it, that is, with a missing parameterArea. The report does not reproduce the raw bytes of this command. The effect is that CryptParameterDecryption reads the 16-bit cipherSize from just past the end of the command. The reason for this shape is to make the code read where no data was supplied.

Step 2b: trigger the out-of-bounds write (bug #2)

Send TPM2_CreatePrimary with a total size equal to the maximum supported TPM command size, 0x1000 bytes. This time a parameterArea is included, with the cipherSize field set to 0xfe5, which the report describes as 0x1000 - sizeof(command_base_header) - sizeof(handleArea) - sizeof(sessionArea), followed by 0xfe3 bytes of any value to fill the place of the encrypted parameter and complete the 0x1000 bytes of the whole command. The report does not reproduce the raw bytes of this command either. Because bufferSize was not reduced by the 2 bytes of the size field, the check at [3] passes and the decryption writes 2 bytes past the end of the command buffer.

Proof-of-Concept

The researcher published a proof-of-concept, a small program that demonstrates the bug, as a .zip download. It contains a Python version meant to be run on Linux systems and a C version for running from a Windows machine. The report does not include the proof-of-concept source inline.

Root cause

The root cause is in the TCG reference implementation, in CryptParameterDecryption in CryptUtil.c, and it spreads to every implementation built from that code.

  • The out-of-bounds read comes from reading the 16-bit cipherSize with BYTE_ARRAY_TO_UINT16, a macro with no bounds check, instead of a checked unmarshalling routine such as UINT16_Unmarshal. The earlier check in ExecuteCommand only enforces a minimum sessionArea size of 9 bytes and does not guarantee that a parameterArea follows.
  • The out-of-bounds write comes from a bookkeeping error: after consuming the 2-byte size field and moving the buffer pointer, the function does not subtract those 2 bytes from bufferSize. The sanity check cipherSize > bufferSize therefore allows a cipherSize 2 bytes larger than the remaining data, and the decryption routines write 2 bytes past the end of the buffer.

Why existing defences did not stop it: the only length validation on the parameter area is the check in ExecuteCommand, which is insufficient for both bugs, and the macro used for the size field performs no bounds checking. The report does not describe any other mitigation in the reference code.

Variants to test

These are follow-ups derived from the report's reasoning, not suggestions made in the report itself.

  1. Test other commands that support parameter encryption. The researcher used TPM2_CreatePrimary and said a few other commands should probably work. A positive result is the same out-of-bounds read or write when the Decrypt flag is set on a session for another command with a sized first parameter.

  2. Test the 4-byte leading size path. The code has a TPM4B branch that reads a 4-byte size field and moves the buffer by 4. If a build is compiled with TPM4B, check whether the same missing subtraction of the size-field length from bufferSize is present. A positive result is the same kind of out-of-bounds write on the 4-byte path.

  3. Probe command buffer hygiene on other virtual TPMs. Send a command that leaves a recognisable 16-bit value at the end of the buffer, then trigger the out-of-bounds read with a missing parameterArea. A positive result is that the read returns the leftover value rather than zeros, showing the buffer is not cleared between requests.

  4. Probe buffer allocation on other virtual TPMs. Trigger the out-of-bounds write with a full-size command and observe whether the process crashes, corrupts adjacent state, or silently continues. A positive result is a crash or observable corruption, which indicates something useful is next to the command buffer.

  5. Test hardware TPMs with the published proof-of-concept. A positive result is the chip becoming unresponsive after the out-of-bounds write attempt and requiring a hard reboot, as the researcher observed on at least some discrete chips.

  6. Test other implementations derived from the TCG reference code, including cloud virtual TPMs. A positive result is reproduction of either bug with the proof-of-concept, which would indicate the implementation inherits the vulnerable CryptParameterDecryption.

Disclosure timeline

The report includes a non-exhaustive timeline of events relevant to disclosure. Coordinated disclosure is the practice of telling vendors privately first and publishing details only after fixes are ready.

  • 2022-11-24: Quarkslab sent the report to VMware and to Microsoft (with proof-of-concept); VMware acknowledged.
  • 2022-11-25: Quarkslab notified CERT/CC and opened a VINCE case; tracked as VU#782720.1 and VU#782720.2. CERT/CC is a coordination centre for security incidents; VINCE is its portal for sharing reports with vendors.
  • 2022-11-28: Quarkslab notified CERT-FR; CERT-FR, CERT/CC and Google acknowledged; Quarkslab filed with Google's security issue tracker noting the GCP Shielded VM virtual TPM likely uses the reference implementation; CERT/CC asked about a disclosure date; Quarkslab set the date to February 28th, 2023; Google requested a Linux proof-of-concept, which was sent.
  • 2022-11-29: Report sent to STMicroelectronics (automated acknowledgement); CERT/CC reserved two CVE IDs; Google asked whether TCG was notified and whether a coordinated embargo applied; Microsoft said the report met its security servicing criteria; Quarkslab explained the February 28th date to Google; Cisco began tracking internally.
  • 2022-12-02: Quarkslab noticed more than 1600 vendors (up from 43 the prior day) had access on VINCE and asked CERT/CC; CERT/CC said the expansion was intended because PC OEM and hardware vendors wanted to reach their supply chains; Quarkslab warned of higher leak probability; Aruba Networks asked for a Linux proof-of-concept and Quarkslab provided a Python proof-of-concept using /dev/tpm0; Intel said it was investigating; Fujitsu PSIRT asked whether TPM chips were analysed, and Quarkslab said hardware TPMs were not analysed due to lack of debugging or monitoring. /dev/tpm0 is the device file on Linux through which programs talk to the TPM.
  • 2022-12-04: Nuvoton said current versions of their TPM chip firmware are not affected.
  • 2022-12-05: TCG VRT said it was tracking and coordinating triage; SUSE Linux identified libtpms as affected and asked whether maintainers were notified; Quarkslab said it had not notified them and deferred to CERT/CC; CERT/CC said it had notified the IBM security group; Google said it shared the proof-of-concept internally and was coordinating with TCG; Quarkslab asked Google about fix dates and scope; TCG said its VRT was engaged; a CERT notified parties that information was publicly available on the issue tracker of a China-based Linux distribution.
  • 2022-12-06: CERT/CC said the China-based distribution had removed public access on request; the coordinated date remained February 28th, 2023.
  • 2022-12-07: Call between CERT/CC and Quarkslab; both agreed not to change the date and to speed up vendor fixes; CERT/CC got permission to share the proof-of-concept with the US DHS CISA Threats team; Microsoft asked for more reproduction information.
  • 2022-12-08: CERT-JP said it had notified multiple Japanese vendors about the embargo date.
  • 2022-12-09: New proof-of-concept versions for Linux and Windows posted on VINCE.
  • 2022-12-12: Quarkslab asked Google for an update and fix date.
  • 2022-12-13: Crestron Electronics asked whether DeviceIOControl error 87 (Invalid Parameter) from the Windows proof-of-concept meant the TPM was not vulnerable; Quarkslab said the error revealed a proof-of-concept bug that would be fixed, and that determining vulnerability without logs, debugging or source requires time-consuming firmware reverse engineering; Siemens asked whether older TCG TPM versions were affected, and Quarkslab said the bugs are in the TPM 2.0 specification code and present in IBM ibmswtpm2 TPM 2.0 releases dating back to at least March 21st, 2017, so any TPM 2.0 implementation based on them is likely affected, and TPM 1.2 was not checked.
  • 2022-12-14: Infineon stated its TPM chips are not affected; Microsoft reiterated its request for reproduction information.
  • 2022-12-16: Quarkslab updated the proof-of-concepts fixing a bug that prevented testing certain TPMs; asked Google for updates and noted a fix was committed to Chromium OS TPM2 code on December 1st, so knowledge of the bugs was considered public; provided Microsoft a detailed description of how to debug the Hyper-V virtual TPM; Microsoft confirmed it could reproduce the bugs.
  • 2022-12-18: Google agreed with the February 28th, 2023 date and said it was working with TCG and CERT.
  • 2022-12-19: Microsoft asked whether disclosure could move to April 2023 to align with its security release; Quarkslab said CERT/CC coordinates disclosure and, given other vendors and a public fix, acceleration was more likely than delay, and suggested discussing with CERT/CC.
  • 2022-12-23: Proof-of-concepts updated to query and print TPM manufacturer strings.
  • 2022-12-26: Proof-of-concepts updated to query and print firmware versions, with output from a run identifying a vulnerable chip.
  • 2023-01-03: Google VRP said the bugs did not meet reward criteria as they do not affect Google products, but passed the report to Chrome VRP. VRP stands for Vulnerability Reward Program, a scheme that pays researchers for reporting bugs.
  • 2023-01-05: Google said it considered the code changes public but not an embargo break per discussion with CERT and TCG, and could not answer the rollout question.
  • 2023-01-09: VMware asked whether disclosure could extend to end of March or April.
  • 2023-01-16: Quarkslab told VMware the bugs should be considered public knowledge and the process involved multiple vendors plus CERT and TCG, so moving the date would be difficult; asked Google VRP to clarify eligibility, noting the Chromium OS fix suggested at least one product was affected.
  • 2023-01-17: Google said the issue went to the VRP panel for reconsideration; Chrome VRP said it was considering the issue and granted access to its bug tracker entry, dated January 4th, which said the bugs were reported externally, were fixed, and were deemed not exploitable.
  • 2023-02-01: STMicroelectronics reported its products are not affected.
  • 2023-02-02: Chrome VRP awarded 20K USD for the bugs.
  • 2023-02-08: Call with CERT to synchronise; Quarkslab agreed to publish technical details on March 14th, with CERT and TCG publishing advisories and errata on February 28th.
  • 2023-02-15: Microsoft said it would try to accelerate patches and asked to preview the blog post; Quarkslab provided an updated proof-of-concept and agreed to send a draft.
  • 2023-02-28: CERT/CC published its vulnerability note; TCG published its security advisory and errata.
  • 2023-03-06: Nuvoton and Lenovo published security advisories; libtpms added test cases.
  • 2023-03-09: Microsoft committed a fix to its open source reference implementation.
  • 2023-03-10: Draft of the blog post sent to Microsoft.
  • 2023-03-13: Microsoft replied with its impact assessment for Azure servers.
  • 2023-03-14: The blog post was published.

The researcher thanks Iván Arce for valuable inputs and ideas and for handling a complicated disclosure process with many parties involved.

Glossary

  • TPM (Trusted Platform Module): a small chip or software component that stores keys and measurements and can prove the state of a computer.
  • TPM 2.0: the current version of the TPM specification.
  • Reference implementation: the official example code published by a standards body, which vendors copy or adapt.
  • TCG (Trusted Computing Group): the nonprofit organisation that writes and maintains the TPM specification.
  • CVE: a public catalogue number for a known security flaw.
  • Out-of-bounds write: a program writing data past the end of the memory area it was given.
  • Out-of-bounds read: a program reading data from past the end of the memory area it was given.
  • Memory corruption: damage to memory caused by writing where the program should not.
  • Virtual machine: a pretend computer running as a program on a real computer.
  • Virtualisation software: software that creates and runs virtual machines.
  • Virtual TPM: a TPM implemented in software and given to a virtual machine.
  • Virtual machine escape: an attack where code inside a virtual machine breaks out and takes over the host.
  • Attack surface: all the ways an attacker can reach and interact with a system.
  • User-mode application: a normal program running with ordinary user rights, not inside the operating system kernel.
  • Hyper-V: Microsoft's virtualisation product.
  • IUM process (Isolated User Mode): a specially protected kind of Windows process.
  • Firmware: software built into a chip or device.
  • Discrete TPM: a TPM that is a separate physical chip.
  • Hard reboot: turning a computer fully off and on again.
  • Module: one file of program code inside a larger product.
  • Commit: a saved snapshot in a code repository, identified by a long string.
  • Errata: corrections published after a document or specification has gone out.
  • Security advisory: a public notice from a vendor about a security problem and what to do about it.
  • EoP (elevation of privilege): getting more rights than you should have.
  • RCE (remote code execution): running your own code on someone else's machine.
  • Parameter: an input or output value of a command.
  • Session: a login-like context in which a command is authorised and possibly encrypted.
  • Session handle: a reference number identifying a session inside the TPM.
  • Handle: a reference number for an object inside the TPM.
  • Nonce: a random value used once, to keep sessions fresh.
  • XOR: a basic operation on bits, used here to scramble data.
  • Obfuscation: scrambling data so it looks meaningless without the key.
  • Block cipher: an encryption method that works on fixed-size chunks of data.
  • CFB mode: one particular way of chaining block cipher chunks.
  • Padding: extra bytes added to make data a required length.
  • Symmetric algorithm: an encryption method where the same key encrypts and decrypts.
  • HMAC: a keyed hash used to check integrity.
  • Pointer: a memory address telling a program where data lives.
  • Buffer: a block of memory used to hold data temporarily.
  • Unmarshalling: turning a stream of bytes back into structured values.
  • Macro: a short piece of code that the compiler expands in place.
  • Bounds check: a check that data stays inside its allowed memory area.
  • In place: overwriting the same memory that was read, rather than copying elsewhere.
  • Static variable: a fixed piece of memory reserved for the whole life of the program.
  • malloc(): the standard way a program asks the operating system for a block of memory.
  • Locality: a TPM concept describing which environment is talking to the chip.
  • Proof-of-concept (PoC): a small program that demonstrates a bug.
  • Coordinated disclosure: telling vendors privately first and publishing details only after fixes are ready.
  • CERT/CC: a coordination centre for security incidents.
  • VINCE: CERT/CC's portal for sharing reports with vendors.
  • VRP (Vulnerability Reward Program): a scheme that pays researchers for reporting bugs.
  • /dev/tpm0: the device file on Linux through which programs talk to the TPM.
  • Reverse engineering: working out how a program works by examining it, often without source code.
  • TPM2_StartAuthSession: the TPM command that starts an authorisation session.
  • TPM2_CreatePrimary: a TPM command that creates a primary key, used here because it supports parameter encryption.
  • TPM_ALG_XOR: the identifier for the XOR algorithm in the TPM specification.
  • cipherSize: the variable holding the size of the encrypted data.
  • bufferSize: the variable holding the size of the buffer.
  • parmBufferStart / parmBufferSize: variables holding where the parameter area starts and how big it is.
  • authorizationSize: the field saying how big the session area is.
  • sessionArea / handleArea / parameterArea: the three sections of a TPM command after the header.
  • Decrypt flag / sessionAttributes.decrypt: the setting that tells the TPM to decrypt the first parameter.
  • 0x1000 / 0x10000 / 0x1008 / 0xfe5 / 0xfe3 / 0x01: numbers written in hexadecimal, base 16, a common way to write memory sizes and values in computing.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

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