Langsung ke konten utama

Trust Issues: Exploiting Trustzone Tees

Posted past times Gal Beniamini,

Mobile devices are becoming an increasingly privacy-sensitive platform. Nowadays, devices procedure a broad hit of personal in addition to individual information of a sensitive nature, such every bit biometric identifiers, payment information in addition to cryptographic keys. Additionally, modern content protection schemes demand a high bird of confidentiality, requiring stricter guarantees than those offered past times the “regular” operating system.

In response to these use-cases in addition to more, mobile device manufacturers get got opted for the creation of a “Trusted Execution Environment” (TEE), which tin live used to safeguard the information processed inside it. In the Android ecosystem, 2 major TEE implementations be - Qualcomm’s QSEE in addition to Trustonic’s Kinibi (formerly <t-base). Both of these implementations rely on ARM TrustZone safety extensions inwards lodge to facilitate a pocket-size “secure” operating system, inside which “Trusted Applications” (TAs) may live executed.

In this spider web log post service we’ll explore the safety properties of the 2 major TEEs introduce on Android devices. We’ll run across how, despite their highly sensitive vantage point, these operating systems currently lag behind modern operating systems inwards damage of safety mitigations in addition to practices. Additionally, we’ll uncovering in addition to exploit a major blueprint number which affects the safety of most devices utilising both platforms. Lastly, we’ll run across why the integrity of TEEs is crucial to the overall safety of the device, making a instance for the demand to increment their defences.

Unfortunately, the blueprint number outlined inwards this spider web log post service is hard to address, in addition to at times cannot live fixed without introducing additional dedicated hardware or performing operations that peril rendering devices unusable. As a result, most Qualcomm-based devices in addition to all devices using Trustonic’s Kinibi TEE versions prior to 400 (that is, all Samsung Exynos devices other than the Milky Way S8 in addition to S8 Plus) stay affected past times this issue. We hope that past times raising awareness to this number nosotros volition aid force for a to a greater extent than secure designs inwards the future.

I would similar to banking concern annotation that piece the electrical flow designs beingness reviewed may live incompatible with some devices’ use-cases, improved designs are beingness developed every bit a resultant of this inquiry which may live accessible to a larger proportion of devices.

TrustZone TEEs


TrustZone forms a hardware-based safety architecture which provides safety mechanisms both on the primary application processor, every bit good every bit across the SoC. TrustZone facilitates the creation of 2 safety contexts; the “Secure World” in addition to the “Normal World”. Each physical processor is dissever into 2 virtual processors, i for each of the aforementioned contexts.

As its call implies, the “Secure World” must stay protected against whatever attacks launched past times the “Normal World”. To do so, several safety policies are enforced past times hardware logic that prevents the “Normal World” from accessing the “Secure World”’s resources. What’s more, every bit the electrical flow safety nation is accessible on the organisation bus, peripherals on the SoC tin live designated to either basis past times simply sampling this value.

TrustZone’s software model provides each basis with its ain copies of both lower privilege levels -- EL0 in addition to EL1. This allows for the execution of different operating organisation kernels simultaneously - i running inwards the “Secure World” (S-EL1), piece some other runs inwards the “Normal World” (EL1). However, the world-split is non exclusively symmetrical; for example, the hypervisor extensions (EL2) are non available inwards the “Secure World”.

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs
*TOS: Trusted Operating System

On Android devices, TrustZone engineering is used amid other things to implement pocket-size “security-conscious” operating systems inside which a laid of trusted applications (TAs) may live executed. These TrustZone-based TEEs are proprietary components in addition to are provided past times the device’s manufacturers.

To set it inwards context - what nosotros unremarkably refer to every bit “Android” inwards our 24-hour interval to 24-hour interval lives is exactly the code running inwards the “Normal World”; the Linux Kernel running at EL1 in addition to the user-mode applications running at EL0. At the same time, the TEE runs inwards the “Secure World”; the TEE OS runs inwards the “Secure World”’s EL1 (S-EL1), whereas trusted applications run nether S-EL0.

Within the Android ecosystem, 2 major TEE implementations exist; Qualcomm’s “QSEE” in addition to Trustonic’s “Kinibi”. These operating systems run amongst Android in addition to render several telephone substitution features to it. These features include access to biometric sensors, hardware-bound cryptographic operations, a “trusted user-interface” in addition to much more.

Since the “Secure World”’s implementation is closely tied to the hardware of the device in addition to the available safety mechanisms on the SoC, the TEE OSs require back upward from in addition to integration with the before parts of the device’s bootchain, every bit good every bit low-level components such every bit the bootloader.

Lastly, every bit tin live seen inwards the schematic above, inwards lodge for the “Normal World” to live able to interact with the TEE in addition to the applications inside it, the authors of the TEE must also render user-libraries, daemons in addition to meat drivers for the “Normal World”. These components are in addition to then utilised past times the “Normal World” inwards lodge to communicate with the TEE.

Exploring the TEEs


Like whatever other operating system, the safety of a Trusted Execution Environment is hinged upon the integrity of both its trusted applications, in addition to that of the TEE OS’s meat itself. The interaction with the TEE’s meat is mostly performed past times the trusted applications running nether it. As such, the logical inaugural of all stair to assessing the safety of the TEEs would live to larn a foothold inside the TEE itself.

To do so, we’ll demand to uncovering a vulnerability inwards a trusted application in addition to exploit it to gain code execution. While this may audio similar a daunting task, retrieve that trusted applications are exactly pieces of software that procedure user-supplied data. These applications aren’t written inwards retentiveness rubber languages, in addition to are executed inside opaque environments - a holding which usually doesn’t lend itself good to security.  

Bearing all this inwards mind, how tin nosotros start analysing the trusted applications inwards either of these platforms? Recall that the implementations are proprietary, so fifty-fifty the file formats used to shop the applications may non live public.

Indeed, inwards Qualcomm’s instance the format used to shop the applications was non documented until recently. Nonetheless, some attempts get got been made to reverse engineer the format resulting inwards tools that allow converting the proprietary file format into a regular ELF file. Once an ELF file is produced, it tin later live analysed using whatever run-of-the-mill disassembler. What’s more, inwards a recent positive tendency of increased transparency, Qualcomm has released official documentation detailing the file format inwards its entirety, allowing to a greater extent than robust inquiry tools to live written every bit a result.
Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

As for Trustonic, the trusted applications’ loadable format is documented inside Trustonic’s publically available header files. This saves us quite some hassle. Additionally, some plugins are available to aid charge these applications into pop disassemblers such every bit IDA.

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

Now that we’ve acquired the tools needed to inspect the trusted applications, nosotros tin boot the bucket on on to the adjacent stair - acquiring the trustlet images (from a firmware epitome or from the device), converting them to a measure format, in addition to loading them upward inwards a disassembler.

However, before nosotros do so, let’s accept a minute to reverberate on the trustlet model!

Revisiting the Trustlet Model


To allow for increased flexibility, modern TEEs are designed to live modular, rather than monolithic chunks of code. Each TEE is designed every bit a “general-purpose” operating system, capable of loading arbitrary trustlets (conforming to some specification) in addition to executing them inside a “trusted environment”.  What nosotros refer to every bit a TEE is the combination of the TEE’s operating system, every bit good every bit the applications running inside it.

There are many advantages to this model. For starters, changes to a unmarried trustlet only require updating the application’s binary on the filesystem, without necessitating whatever modify inwards other components of the TEE. This also allows for the creation of a privilege separation model, providing sure privileges to some trustlets piece denying them to others. Perhaps most importantly, this enables the TEE OS to enforce isolation between the trustlets themselves, thus limiting the potential harm done past times a unmarried malicious (or compromised) trustlet. Of course, piece inwards regulation these advantages are substantial, we’ll run across later on how they genuinely map onto the TEEs inwards question.

Regardless, piece the advantages of this model are quite clear, they are non completely gratis of charge. Recall, every bit we’ve mentioned above, that trusted applications are non invulnerable. Once vulnerabilities are establish inwards these applications, they tin live used to gain code execution inside the TEE (in fact, we’ll write such an exploit later on!).

However, this begs the enquiry - “How tin trustlets live revoked i time they’ve been establish to live vulnerable?”. After all, simply fixing a vulnerability inwards a trustlet would live pointless if an assailant could charge old vulnerable trustlets exactly every bit easily.

To response this question, we’ll get got to separately explore each TEE implementation.

QSEE Revocation


As we’ve mentioned above, Qualcomm has late released (excellent) documentation detailing the secure boot sequence on Qualcomm devices, including the mechanisms used for epitome authentication. As trusted applications running nether QSEE are portion of the same full general architecture described inwards this document, nosotros may gain telephone substitution insights into the revocation procedure past times reviewing the document.

Indeed, Qualcomm’s signed images are regular ELF files which are supplemented past times a unmarried special “Hash Table Segment”. This segment includes 3 distinct components: the SHA-256 digest of each ELF segment, a signature blob, in addition to a certificate chain.


Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

The signature is computed over the concatenated blob of SHA-256 hashes, using the individual telephone substitution corresponding to the lastly certificate inwards the embedded certificate chain. Moreover, the root certificate inwards the chain is validated against a “Root Key Hash” which is stored inwards the device’s ROM or fused into one-time-programmable memory on the SoC.

Reading through the document, nosotros apace come upward across the next relevant statement:

“The Attestation certificate used to verify the signature on this hash segment also includes additional fields that tin bind restrictions to the signature (preventing “rolling back” to older versions of the software image, …”

Ah-ha! Well, let’s maintain reading in addition to run across if nosotros come upward across to a greater extent than pertinent information regarding the acre inwards question.

Continuing our review of the document, it appears that Qualcomm has elected to add together unique OU fields to the certificates inwards the embedded chain, denoting several attributes relating to the signature algorithm of the epitome beingness loaded. One such acre of exceptional involvement to our pursuits is the “SW_ID”. According to the document, this acre is used to “bind the signature to a particular version of a exceptional software image”. Interesting!

The acre is comprised of 2 concatenated values:


The document in addition to then goes on to explain:

“...If eFuse values indicated that the electrical flow version was ‘1’, in addition to then this epitome would neglect verification. Version enforcement is done inwards lodge to forbid loading an older, perchance vulnerable, version of the epitome that has a valid signature attached.”

At this dot nosotros get got all the information nosotros need. It appears that the acre of report of epitome revocation has non eluded Qualcomm -- we’re already off to a practiced start. However, in that location are a few to a greater extent than questions inwards demand of an response yet!

Let’s start past times taking a unmarried trustlet, say the Pixel’s Widevine trustlet, in addition to inspecting the value of the SW_ID acre encoded inwards its attestation certificate. As this is a DER-encoded X.509 certificate, nosotros tin parse it using “openssl”:

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

As nosotros tin run across above, the IMAGE_ID value assigned to the Widevine trustlet is 0xC. But what virtually the other trustlets inwards the Pixel’s firmware? Inspecting them reveals a surprising fact -- all trustlets portion the same epitome identifier.

More importantly, however, it appears that the version counter inwards the Widevine application on the Pixel is 0. Does this hateful that no vulnerabilities or other security-relevant issues get got been establish inwards that trustlet since the device inaugural of all shipped? That seems similar a flake of a stretch. In lodge to larn a ameliorate persuasion of the electrical flow nation of affairs, nosotros demand a trivial to a greater extent than data.

Luckily, I get got a collection of firmware images that tin live used for this exact purpose! The collection contains to a greater extent than than 45 different firmware images from many different vendors, including Google, Samsung, LG in addition to Motorola. To collect the needed data, nosotros tin simply write a short script to extract the version counter from every trustlet inwards every firmware image. Running this script on the firmware collection would allow us to assess how many devices get got used the trustlet revocation characteristic inwards the past times to revoke whatever vulnerable trusted application (since their version counter would get got to live larger than zero).

After running the script on my firmware collection, nosotros are greeted with a surprising result: with the exception of a single firmware image, all trustlets inwards all firmware images incorporate version number 0.

Putting it all together, this would imply i of 2 things: either no bugs are e'er establish inwards whatever trustlet, or device manufacturers are failing to revoke vulnerable trustlets.

In fact, nosotros already know the response to this question. Last yr I performed research into the Widevine trustlet every bit introduce on the Nexus 6 in addition to establish (and exploited) a vulnerability allowing arbitrary code execution inside the TEE.

This same vulnerability was also introduce on a broad diversity of other devices from different manufactures, some of whom are also a portion of my firmware collection. Nonetheless, all of these devices inwards my collection (including the Nexus 6) did non revoke the vulnerable trustlet, in addition to every bit such get got remained vulnerable to this issue. While some devices (such every bit the Nexus 6) get got shipped patched versions of the trustlet, simply providing a patched version without incrementing the version counter has no outcome whatsoever.

While I do non get got a sufficiently large firmware collection to perform a to a greater extent than in-depth analysis, previous assessments get got been done regarding the amount of affected devices. Regardless, it remains unknown what proportion of these devices get got correctly revoked the trustlet.

As it happens, exploiting the number on “patched” devices is extremely straightforward, in addition to does non require whatever to a greater extent than privileges than those required past times the original version of the exploit. All an assailant would demand to do is to house the old trustlet anywhere on the filesystem, in addition to modify the path of the trustlet inwards the exploit (a unmarried string) to dot at that novel location (you tin uncovering instance of such an exploit here).

One mightiness live tempted to propose several stop-gap mitigations, such every bit filtering the filesystem path from which trustlets are loaded to ensure that they only originate from the organisation partitioning (thus raising the bar for a would-be attacker). However, due to the blueprint of the API used to charge trustlets, it seems that filtering the filesystem path from which the trustlet is loaded is non feasible. This is since QSEECOM, the driver provided past times Qualcomm to interact with QSEE, provides a unproblematic API wherein it is only provided with a buffer containing the trustlet’s binary past times user-space. This buffer is in addition to then passed on to TrustZone inwards lodge for the trustlet to live authenticated in addition to later loaded. Since the driver only receives a blob containing the trustlet itself, it has no “knowledge” of the filesystem path on which the trustlet is stored, making such verification of the filesystem path harder.

Of course, interaction with QSEECOM is restricted to several SELinux contexts. However, a non-exhaustive listing of these includes the media server, DRM server, KeyStore, book daemon, fingerprint daemon in addition to more. Not a brusque listing past times whatever stretch…

So what virtually devices unaffected past times the previously disclosed Widevine vulnerability? It is exclusively possible that these devices are affected past times other bugs; either soundless undiscovered, or simply non public. It would sure live surprising if no bugs whatsoever get got been establish inwards whatever of the trustlets on these devices inwards the interim.

For example, diffing 2 versions of the Widevine trustlet inwards the Nexus 6P shows several modifications, including changes inwards functions related to telephone substitution verification. Investigating these changes, however, would require a to a greater extent than in-depth analysis of Widevine in addition to is beyond the orbit of this spider web log post.

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs


Putting all of the inwards a higher house together, it seems quite clear that device manufacturers are either unaware of the revocation features provided past times Qualcomm, or are unable to utilization them for i argue or another.

In add-on to the machinery described above, additional capabilities are introduce inwards the instance of trustlet revocation. Specifically, on devices where a replay protected retentiveness block (RPMB) is available, it tin live utilised to shop the version numbers for trustlets, instead of relying on an eFuse. In this scenario, the APP_ID OU is used to uniquely seat each trusted application, allowing for a to a greater extent than fine-grained command over their revocation.

That beingness said, inwards lodge to leverage this feature, devices must live configured with a specific eFuse blown. Since nosotros cannot easily query the condition of eFuses on a large scale, it remains unknown what proportion of devices get got indeed enabled this feature. Perhaps i explanation for the lack of revocation is that some devices are either lacking a RPMB, or get got non blown the aforementioned eFuse inwards advance (blowing a fuse on a production device may live a risky operation).

What’s more, going over our firmware collection, it appears that some manufacturers get got an incomplete agreement of the revocation feature. This is evidenced past times the fact that several firmware images use the same APP_ID for many (and sometimes all) trusted applications, thus preventing the utilization of fine-grained revocation.

There are other challenges every bit good - for example, some vendors (such every bit Google) ship their devices with an unlocked bootloader. This allows users to freely charge whatever firmware version onto the device in addition to utilization it every bit they please. However, revoking trustlets would strip users of the powerfulness to flash whatever firmware version, every bit i time a trustlet is revoked, firmware versions containing trustlets from the previous versions would no longer exceed the authentication (and would hence neglect to load). As of now, it seems that in that location is no practiced solution for this situation. Indeed, all Nexus in addition to Pixel devices are shipped with an unlocked bootloader, in addition to are hence unable to brand utilization of the trustlet revocation characteristic every bit introduce today.

One mightiness live tempted i time once to a greater extent than to propose naive solutions, such every bit embedding a whitelist of “allowed” trustlet hashes inwards the TEE OS’s meat itself. Thus, when trustlets are loaded, they may also live verified against this listing to ensure they are allowed past times the electrical flow version TEE OS. This proposition is non meritless, but is non robust either. For starters, this proposition would require incrementing the version counter for the TEE OS’s epitome (otherwise attackers may rollback that binary every bit well). Therefore, this method suffers from some of the same drawbacks of the currently used approach (for starters, devices with an unlocked bootloader would live unable to utilise it). It should live noted, however, that rewriting the TEE OS’s epitome would to a greater extent than oftentimes than non require raw access to the filesystem, which is strictly to a greater extent than restrictive than the electrical flow permissions needed to acquit out the attack.

Nonetheless, a ameliorate solution to this occupation (rather than a stop-gap mitigation) is soundless needed. We hope that past times underscoring all of these issues plaguing the electrical flow implementation of the revocation characteristic (leading to it beingness virtually unused for trustlet revocation), the conversation volition shift towards alternate models of revocation that are to a greater extent than readily available to manufacturers. We also hope that device manufacturers that are able to utilization this feature, volition live motivated to do so inwards the future.

Kinibi Revocation


Now, let’s laid our sights on Trustonic’s Kinibi TEE. In our analysis, we’ll utilization the Samsung Milky Way S7 Edge (SM-G935F) - this is an Exynos-based device running Trustonic’s TEE version 310B. As we’ve already disclosed an Android privilege escalation vulnerability a few months ago, nosotros tin utilization that vulnerability inwards lodge to larn elevated code execution with the “system_server” procedure on Android. This allows us greater liberty inwards exploring the mechanisms used inwards the “Normal World” related to Trustonic’s TEE.

Unfortunately, different Qualcomm, no documentation is available for the epitome authentication procedure carried out past times Trustonic’s TEE. Be that every bit it may, nosotros tin soundless start our inquiry past times inspecting the trustlet images themselves. If nosotros tin occupation organisation human relationship for every unmarried slice of information stored inwards the trustlet binary, nosotros should live able to seat the location of whatever version counter (assuming, of course, such a counter exists).

As we’ve mentioned before, the format used past times trusted applications inwards Trustonic’s TEE is documented inwards their public header files. In fact, the format itself is called the “MobiCore Loadable Format” (MCLF), in addition to harkens dorsum to G&D’s MobiCore TEE, from which Trustonic’s TEE has evolved.

Using the header files in addition to inspecting the binary inwards tandem, nosotros tin slice together the entire format to shop the trustlet’s metadata every bit good every bit its code in addition to information segments. As a result, nosotros become far at the next layout:

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

At this point, nosotros get got accounted for all but a unmarried blob inwards the trustlet’s binary - indeed, every bit shown inwards the epitome above, next the information segment, in that location appears to live an opaque blob of some sort. It would stand upward to argue that this blob would stand upward for the trustlet’s signature (as otherwise that would imply that unsigned trusted applications could live loaded into the TEE). However, since we’d similar to brand sure that all bits are accounted for, we’ll demand to dig deeper in addition to brand sure that is the case.

Unfortunately, in that location appear to live no references inwards the header files to a blob of this kind. With that inwards mind, how tin nosotros brand sure that this is indeed the trustlet’s signature? To do so we’ll demand to contrary engineer the loading code inside the TEE OS responsible for authenticating in addition to loading trusted applications. Once nosotros seat the relevant code, nosotros should live able to isolate the treatment of the signature blob in addition to deduce its format.

At this point, however, this is easier said than done. We soundless get got no noesis of where the TEE OS’s binary is stored, how it may live extracted, in addition to what code is responsible for loading it into place. However, some related piece of work has been done inwards the past. Specifically, Fernand Lone Sang of Quarkslab has published a two-part article on reverse-engineering Samsung’s SBOOT on the Milky Way S6. While his piece of work is focused on analysing the code running inwards EL3 (which is based on ARM’s Trusted Firmware), we’re interested inwards dissecting the code running inwards S-EL1 (namely, the TEE OS).

By applying the same methodology described past times Fernand, nosotros tin charge the SBOOT binary from an extracted firmware epitome into IDA in addition to get down analysing it. Since SBOOT is based on ARM’s Trusted Firmware architecture, all we’d demand to do is follow the logic upward to the dot at which the TEE OS is loaded past times the bootloader. This constituent is also referred to every bit “BL32” inwards the ARM Trusted Firmware terminology.

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

After reversing the relevant code flows, nosotros finally uncovering the location of the TEE OS’s meat binary embedded inside the SBOOT image! In the involvement of brevity, nosotros won’t include the entire procedure here. However, anyone wishing to extract the binary for themselves in addition to analyse it tin simply search for the string “VERSION_-+A0”, which denotes the outset of the TEE OS’s meat image. As for the image’s base of operations address - past times inspecting the absolute branches in addition to the address of the VBAR inwards the meat nosotros tin deduce that it is loaded into virtual address 0x7F00000.

Alternatively, in that location exists some other (perhaps much easier) way to inspect Kinibi’s kernel. It is a good known fact that Qualcomm supports the execution of non one, but 2 TEEs simultaneously. Samsung devices based on Qualcomm’s SoCs brand utilization of this characteristic past times loading both QSEE in addition to Kinibi at the same time. This allows Samsung to access features from both TEEs on the same device. However, we’ve already seen how images loaded past times Qualcomm’s epitome authentication module tin live converted into regular ELF files (and later analysed). Therefore, nosotros tin simply apply the same procedure to convert Kinibi’s meat (“tbase”, every bit introduce on Samsung’s Qualcomm-based devices) into an ELF file which tin in addition to then live readily analysed.

Since the file format of trusted applications running nether Kinibi TEE on Qualcomm devices appears identical to the i used on Exynos, that would propose that whatever authentication code is introduce inwards one, is also introduce inwards the other.

After some reversing, nosotros seat the relevant logic responsible for authenticating trusted applications beingness loaded into Kinibi. The microkernel inaugural of all verifies the arguments inwards the MCLF header, such every bit its “magic” value (“MCLF”). Next, it inspects the “service type” of the epitome beingness loaded. By next the code’s flow nosotros become far at the portion used to authenticate both organisation trustlets in addition to drivers - exactly what we’re after! After analysing this function’s logic, nosotros finally become far at the construction of the signature blob:

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

The portion extracts the populace telephone substitution information (the modulus in addition to the populace exponent). Then, it calculates the SHA-256 digest of the populace telephone substitution in addition to ensures that it matches the populace telephone substitution hash embedded inwards the kernel’s binary. If so, it uses the extracted populace telephone substitution together with the embedded signature inwards the blob to verify the signature on the trustlet itself (which is performed on its entire contents upward to the signature blob). If the verification succeeds, the trustlet is loaded.

At long last, nosotros are finally able to occupation organisation human relationship for every unmarried flake inwards the trustlet. But… Something appears to live amiss - where is the version counter located? Out of the entire trustlet’s binary, in that location is but a unmarried value which may serve this purpose -- the “Service Version” acre inwards the MCLF header. However, it sure doesn’t seem similar this value is beingness used past times the loading logic nosotros traced exactly a brusque piece ago. Nevertheless, it’s possible that we’ve simply missed some relevant code.

Regardless, nosotros tin cheque whether whatever revocation using this acre is taking house inwards do past times leveraging our firmware collection i time again! Let’s write a brusque script to extract the service version acre from every trusted application in addition to run it against the firmware repository…

...And the results are in! Every unmarried trusted application inwards my firmware repository appears to utilization the same version value - “0”. While in that location are some drivers that utilization a different value, it appears to live consistent across devices in addition to firmware versions (and hence doesn’t seem to stand upward for a value used for incremental versions or for revocation). All inwards all, it sure seems every bit though no revocation it taking place.

But that’s soundless non plenty quite enough. To ensure that no revocation is performed, we’ll demand to attempt it out for ourselves past times loading a trustlet from an old firmware version into a to a greater extent than recent version.

To do so, we’ll demand to gain some insight into the user-mode infrastructure provided past times Trustonic. Let’s follow the execution flow through the procedure of loading a trustlet - starting at the “Normal World” in addition to ending inwards the “Secure World”’s TEE. Doing so volition aid us figure out which user-mode components we’ll demand to interact with inwards lodge to charge our ain trustlet.

When a privileged user-mode procedure wishes to charge a trusted application, they do so past times sending a asking to a special daemon provided past times Trustonic - “mcDriverDaemon”. This daemon allows clients to number requests to the TEE (which are in addition to then routed to Trustonic’s TEE driver). One such command tin live used to charge a trustlet into the TEE.

The daemon may charge trustlets from i of 2 paths - either from the organisation partitioning ("/system/app/mcRegistry"), or from the information partitioning ("/data/app/mcRegistry"). Since inwards our instance nosotros would similar to avoid modifying the organisation partition, nosotros volition simply house our binary inwards the latter path (which has an SELinux context of “apk_data_file”).

While the charge asking itself issued to the daemon specifies the UUID of the trustlet to live loaded, the daemon only uses the UUID to locate the binary, but does non ensure that the given UUID matches the i encoded inwards the trustlet's header. Therefore, it’s possible to charge whatever trustlet (regardless of UUID) past times placing a binary with an arbitrary UUID (e.g., 07050501000000000000000000000020) inwards the information partition's registry directory, in addition to later sending a charge asking with the same UUID to the daemon.
Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

Lastly, the communication with the daemon is done via a UNIX domain socket. The socket has an SELinux context which limits the number of processes that tin connect to it. Nonetheless, much similar inwards Qualcomm’s case, the listing of such processes seems to include the bulk of privileged processes running on the system. Indeed, a rattling partial listing of which includes the DRM server, organisation server, the book daemon, mediaserver in addition to indeed whatever organisation application (you tin uncovering the full list inwards the number tracker).

From in addition to then on, the daemon simply contacts Trustonic’s driver in addition to issues a specific laid of ioctls which drive it to exceed on asking to the TEE. It should live noted that access to the driver is also available to quite a broad hit of processes (once again, the full list tin live seen inwards the number tracker).

Now that we’re sufficiently informed virtually the loading process, nosotros tin become ahead in addition to endeavour to charge an old trustlet. Let’s simply accept an old version of the “fingerprint” trustlet in addition to house it into the registry directory nether the information partition. After issuing a charge asking to the daemon in addition to next the dmesg output, nosotros are greeted with the next result:

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

There nosotros get got it -- the trustlet has been successfully loaded into the TEE, confirming our suspicions!

After contacting Samsung regarding this issue, we’ve received the next official response:

Latest Trustonic kinibi 400 household unit of measurement at nowadays supports rollback prevention characteristic for trustlets in addition to this is fully supported since Milky Way S8/S8+ devices”

Indeed, it appears that the number has been addressed inwards the newest version on Trustonic’s TEE - Kinibi 400. Simply searching for relevant strings inwards the TEE OS binary provided inwards the Milky Way S8’s firmware reveals some possible hints every bit to the underlying implementation:

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

Based on these strings alone, it appears that newer devices utilise a replay protected retentiveness block (RPMB) inwards lodge to forbid old trustlets from beingness rolled back. As the implementation is proprietary, to a greater extent than inquiry is needed inwards lodge to determine how this characteristic is implemented.

With regards to Samsung devices - although revocation appears to live supported inwards the Milky Way S8 in addition to S8 Plus, all other Exynos-based devices stay vulnerable to this issue. In fact, inwards the adjacent portion we’ll write an exploit for a TEE vulnerability. As it happens, this same vulnerability is introduce inwards several different devices, including the Milky Way S7 Edge in addition to Milky Way S6.

Without specialised hardware used to shop the version counter or some other identifier which tin live utilised to forbid rollback, it seems similar in that location is non much that tin live done to address the number inwards older devices. Nonetheless, every bit nosotros get got no visibility into the actual safety components on the SoC, it is non clear whether a prepare is indeed non possible. Perhaps other hardware components could live co-opted to implement some cast of revocation prevention. We stay hopeful that a stop-gap mitigation may live implemented inwards the future.

Deciding On Influenza A virus subtype H5N1 Target


To brand matters to a greater extent than interesting, let’s attempt in addition to seat an “old” vulnerable trustlet (one which has already been “patched” inwards previous versions). Once nosotros uncovering such a trustlet, nosotros could simply insert it into the registry in addition to charge it into the TEE. As it happens, finding such trustlets is rather straightforward - all nosotros get got to do is compare the trustlets from the most recent firmware version with the ones inwards the inaugural of all version released for a specific device -- if in that location get got been whatever security-relevant fixes, nosotros should live able to rails them down.

In addition, nosotros may also live able to utilization vulnerable trustlets from a different device. This would succeed only if both devices portion the same “trusted” populace telephone substitution hash embedded inwards the TEE OS. To investigate whether such scenarios exist, I’ve written some other script which extracts the modulus from each trustlet binary, in addition to grouping together different firmware versions in addition to devices that portion the same signing key. After running this script it appears that both the Milky Way S7 Edge (G935F) in addition to the Milky Way S7 (G930F) utilization the same signing key. As a result, attackers tin charge trustlets from either device into the other (therefore expanding the listing of possible vulnerable trustlets that tin live leveraged to assault the TEE).

After comparing a few trusted applications against their older versions, it is straight off evident that there’s a substantial number of security-relevant fixes. For example, a cursory comparing betwixt the 2 versions of the the “CCM” trustlet (FFFFFFFF000000000000000000000012), revealed 4 added bound-checks which appear to live security-relevant.

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs


Alternately, nosotros tin pull upon previous research. Last year, piece doing some cursory inquiry into the trusted applications available on Samsung’s Exynos devices, I discovered a duo of trivial vulnerabilities inwards the “OTP” trustlet running nether that platform. These vulnerabilities get got since been “fixed”, but every bit the trustlets are non revoked, nosotros tin soundless freely exploit them.

In fact, let’s do exactly that.

Writing Influenza A virus subtype H5N1 Quick Exploit


We’ve already determined that old trustlets tin live freely loaded into Kinibi TEE (prior to version 400). To demonstrate the severity of this issue, we’ll exploit i of 2 vulnerabilities I’ve discovered inwards the OTP trustlet slowly lastly year. Although the vulnerability has been “patched”, attackers tin simply follow the steps inwards a higher house to charge the old version of the trustlet into the TEE in addition to exploit it freely.  

The number we’re going to exploit is a unproblematic stack-overflow. You mightiness rightly assume that a stack overflow would live mitigated against past times modern exploit mitigations. However, looking at the binary it appears that no such mitigation is present! As we’ll run across later on, this isn’t the only mitigation currently missing from Kinibi.

Getting dorsum to the number at hand, let’s start past times agreement the primitive at our disposal. The OTP trustlet allows users to generate OTP tokens using embedded keys that are “bound” to the TrustZone application. Like most other trusted applications, its code to a greater extent than oftentimes than non consists of a unproblematic loop which waits for notifications from the TEE OS informing it of an incoming command.

Once a command is issued past times a user inwards the “Normal World”, the TEE OS notifies the trusted application, which later processes the incoming information using the “process_cmd” function. Reversing this portion nosotros tin run across the trustlet supports many different commands. Each command is assigned a 32-bit “command ID”, which is placed at the outset of the user’s input buffer.

Following the code for these commands, it is apace apparent that many them utilization a mutual utility function, “otp_unwrap”, inwards lodge to accept a user-provided OTP token in addition to decrypt it using the TEE’s TrustZone-bound unwrapping mechanism

This portion receives several arguments, including the length of the buffer to live unwrapped. However, it appears that inwards most call-sites, the length declaration is taken from a user-controlled portion of the input buffer, with no validation whatsoever. As the buffer is inaugural of all copied into a stack-allocated buffer, this allows us to simply overwrite the stack frame with controlled content. To illustrate the issue, let’s accept a expect at the placement of items inwards the buffer for a valid disclose command, versus their location on the stack when copied past times “otp_unwrap”:

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

As we’ve mentioned, the “Token Length” acre is non validated in addition to is exclusively attacker-controlled. Supplying an arbitrarily large value volition hence resultant inwards a stack overflow. All that’s left at nowadays is to create upward one's take away heed on a stack alignment using which nosotros tin overwrite the homecoming address at the terminate of the stack frame in addition to hijack the command flow. For the sake of convenience, let’s simply homecoming straight from “otp_unwrap” to the primary processing portion - “process_cmd”. To do so, we’ll overwrite all the stack frames in-between the 2 functions.

As an added bonus, this allows us to utilise the stack infinite available betwixt the 2 stack frames for the ROP of our choice. Choosing to live conservative i time again, we’ll elect to write a ROP chain that simply prepares the arguments for a function, executes it, in addition to returns the homecoming value dorsum to “process_cmd”. That way, nosotros gain a powerful “execute-function-in-TEE” primitive, allowing us to effectively run arbitrary code inside the TEE. Any read or write operations tin live delegated to read in addition to write gadgets, respectively - allowing us to interact with the TEE’s address space. As for interactions with the TEE OS itself (such every bit organisation calls), nosotros tin straight invoke whatever portion inwards the trusted application’s address infinite every bit if it were our own, using the aforementioned “execution-function” primitive.

Lastly, it’s worth mentioning that the stack frames inwards the trusted application are huge. In fact, they’re so large that there’s no demand for a stack pin inwards lodge to fit our ROP chain inwards retentiveness (which is exactly every bit well, every bit a brusque search for i yielded no obvious results). Instead, nosotros tin simply shop our chain on the stack frames leading from the vulnerable portion all the way upward to “process_cmd”.

Part of the argue for the exorbitantly large stack frames is the fact that most trusted applications do non initialise or utilization a heap for dynamic retentiveness allocation. Instead, they rely solely on global information structures for stateful storage, in addition to on the large stack for intermediate processing. Using the stack inwards such a way increases the odds of overflows occurring on the stack (rather than the non-existent heap). Recall that every bit there’s no stack cookie present, this way that many such issues are trivially exploitable.

Once we’ve finished mapping out the stack layout, we’re more-or-less ready to exploit the issue. All that’s left is to create a stack frame which overwrites the stored LR register to dot at the outset of our ROP chain’s gadgets, followed past times a sequence of ROP gadgets needed to prepare arguments in addition to telephone band a function. Once we’re done, nosotros tin simply fill upward the residual of the remaining infinite with POP-sleds (that is, “POP {PC}” gadgets), until nosotros achieve “process_cmd”’s stack frame. Since that lastly frame restores all non-scratch registers, nosotros don’t get got to worry virtually restoring nation either.

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

You tin uncovering the full exploit code here. Note that the code produces a position-independent binary blob which tin live injected into a sufficiently privileged process, such every bit “system_server.

Security Mitigations


We’ve already seen how a relatively straightforward vulnerability tin live exploited inside Kinibi’s TEE. Surprisingly, it appeared that in that location were few mitigations inwards house holding us back. This is no coincidence. In lodge to pigment a to a greater extent than consummate picture, let’s accept a minute to assess the safety mitigations provided past times each TEE. We’ll perform our analysis past times executing code inside the TEE in addition to exploring it from the vantage dot of a trustlet. To do so, we’ll leverage our previously written code-execution exploits for each platform. Namely, this way we’ll explore Kinibi version 310B every bit introduce on the Milky Way S7 Edge, in addition to QSEE every bit introduce on the Nexus 6.

ASLR

Kinibi offers no cast of ASLR. In fact, all trustlets are loaded into a fixed address (denoted inwards the MCLF header). Moreover, every bit the trustlets’ base of operations address is quite depression (0x1000), this raises the probability of offset-from-NULL dereference issues beingness exploitable.

Additionally, each trustlet is provided with a mutual “helper” library (“mcLib”). This library acts every bit a shim which provides trusted applications with the stubs needed to telephone band each of the functions supported past times the TEE’s measure libraries. It contains a wealth of code, including gadgets to telephone band functions, gadgets that invoke the TEE OS’s syscalls, perform message-passing in addition to much more. And, unfortunately, this library is also mapped into a constant address inwards the virtual address infinite of each trustlet (0x7D01000).

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

Putting these 2 facts together, this way that whatever vulnerability establish inside a trustlet running nether Trustonic’s TEE tin hence live exploited without requiring prior information virtually the address-space of the trustlet (thus lowering the bar for remotely exploitable bugs).

So what virtually Qualcomm’s TEE? Well, QSEE does indeed render a cast of ASLR for all trustlets. However, it is far from ideal - inwards fact, instead of utilising the entire virtual address space, each trustlet’s VAS simply consists of a apartment mapping of a pocket-size segment of physical retentiveness into which it is loaded.

Indeed, all QSEE trustlets are loaded into the same pocket-size physically contiguous hit of retentiveness carved out of the device’s primary memory. This part (referred to every bit the “secapp-region” inwards the device tree) is dedicated to the TEE, in addition to protected against accesses from the “Normal World” past times utilising special safety hardware on the SoC. Consequently, the larger the “secapp” region, the less retentiveness is available to the “Normal World”.

The “secapp” part commonly spans about 100MB inwards size. Since, every bit we’ve noted before, QSEE trustlets VAS consists of a apartment mapping, this way that the amount of entropy offered past times QSEE’s ASLR implementation is express past times the “secapp” region’s size. Therefore, piece many devices tin theoretically utilise a 64-bit virtual address infinite (allowing for high entropy ASLR), the ASLR enabled past times QSEE is express unopen to nine bits (therefore with 355 guesses, an assailant would get got a 50% take away chances of correctly guessing the base of operations address). This is farther aided past times the fact that whenever an illegal access occurs inside the TEE, the TEE OS simply crashes the trustlet, allowing the assailant to reload it in addition to endeavour to gauge the base of operations address i time again.

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

Stack Cookies in addition to Guard Pages


What virtually other exploit mitigations? Well, i of the most mutual mitigations is the inclusion of a stack cookie - a unique value which tin live used to notice instances of stack smashing in addition to abort the program’s execution.

Analysing the trustlets introduce on Samsung’s devices in addition to running nether Trustonic’s TEE reveals that no such protection is present. As such, every stack buffer overflow inwards a trusted application tin live trivially exploited past times an assailant (as we’ve seen above) to gain code execution. This is inwards contrast to QSEE, whose trustlets include randomised pointer-sized stack cookies.

Lastly, what virtually protecting the mutable information segments available to each trustlet - such every bit the stack, heap in addition to globals? Modern operating systems tend to protect these regions past times delimiting them with “guard pages”, thus preventing attackers from using an overflow inwards i construction inwards lodge to corrupt the other.

However, Trustonic’s TEE seems to carve both the globals in addition to the stack from the trustlet’s information segment, without providing whatever guard page inbetween. Furthermore, the stack is located at the terminate of the information segments, in addition to global information structures are placed before it. This layout makes it ideal for an assailant to either overflow the stack into the globals, or vice-versa.

Identically, Qualcomm’s TEE does non render guard pages betwixt the globals, heap in addition to stack - they are all simply carved out of the unmarried information segment provided to the trustlet. As a result, overflows inwards whatever of these information structures tin live used to target whatever of the others.

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

TEEs As Influenza A virus subtype H5N1 High Value Target


At this point, it is belike clear plenty that compromising TEEs on Android seems similar a relatively straightforward task. Since both TEEs lag behind inwards term of exploit mitigations, it appears that the bar for exploitability of vulnerabilities, i time found, is rather low.

Additionally, every bit to a greater extent than in addition to to a greater extent than trusted applications are added, finding a vulnerability inwards the inaugural of all house is becoming an increasingly straightforward task. Indeed, simply listing the number of trusted applications on the Milky Way S8, nosotros tin run across that it contains no fewer than xxx trustlets!

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

Be that every bit it may, i mightiness rightly wonder what the possible implications of code-execution inside the TEE are. After all, if compromising the TEE does non assist attackers inwards whatever way, in that location may live no argue to farther secure it.

To response this question, we’ll run across how compromising the TEE tin live incredibly powerful tool, allowing attackers to fully subvert the organisation inwards many cases.

In Qualcomm’s case, i of the system-calls provided past times QSEE allows any trustlet to map inwards physical memory belonging to the “Normal World” every bit it pleases. As such, this way whatever compromise of a QSEE trustlet automatically implies a total compromise of Android every bit well. In fact, such an assault has been demonstrated inwards the past. Once code execution is gained inwards the context of a trustlet, it tin scan the physical address infinite for the Linux Kernel, in addition to i time establish tin patch it inwards retentiveness to innovate a backdoor.

And what of Trustonic’s TEE? Unlike QSEE’s model, trustlets are unable to map-in in addition to modify physical memory. In fact, the safety model used past times Trustonic ensures that trustlets aren’t capable of doing much at all. Instead, inwards lodge to perform whatever meaningful operation, trustlets must ship a asking to the appropriate “driver”. This blueprint is conducive to security, every bit it essentially forces attackers to either compromise the drivers themselves, or uncovering a way to leverage their provided APIs for nefarious means. Moreover, every bit in that location aren’t every bit many drivers every bit in that location are trustlets, it would appear that auditing all the drivers inwards the TEE is indeed feasible.

Although trustlets aren’t granted different sets of “capabilities”, drivers tin distinguish betwixt the trusted applications requesting their services past times using the caller’s UUID. Essentially, well-written drivers tin verify that whichever application consumes their services is contained inside a “whitelist”, thus minimising the exposed assault surface.

Sensitive operations, such every bit mapping-in in addition to modifying physical retentiveness are indeed unavailable to trusted applications. They are, however, available to any driver. As a result, driver authors must live extremely cautious, lest they unintentionally render a service which tin live abused past times a trustlet.

Scanning through the drivers provided on Samsung’s Exynos devices, nosotros tin run across a diversity of measure drivers provided past times Trustonic, such every bit the cryptographic driver, the “Trusted UI” driver, in addition to more. However, amid these drivers are a few additional drivers authored past times Samsung themselves.

One such instance is the TIMA driver (UUID FFFFFFFFD0000000000000000000000A), which is used to facilitate Samsung’s TrustZone-based Integrity Measurement Architecture. In short, a component of TIMA performs periodic scans of the kernel’s retentiveness inwards lodge to ensure that it is non tampered with.

Samsung has elected to dissever TIMA’s functionality inwards two; the driver mentioned inwards a higher house provides the powerfulness to map inwards physical memory, piece an accompanying trusted application consumes these services inwards lodge to perform the integrity measurements themselves. In whatever case, the terminate resultant is that the driver provides APIs to both read in addition to write physical retentiveness - a capability which is unremarkably reserved for drivers alone.

Since this functionality could live leveraged past times attackers, Samsung has rightly decided to enforce a UUID whitelist inwards lodge to forbid access past times arbitrary trusted applications. Reversing the driver’s code, nosotros tin run across that the whitelist of allowed trusted applications is embedded inside the driver. Quite surprisingly, however, it is no brusque list!

Mobile devices are becoming an increasingly privacy Trust Issues: Exploiting TrustZone TEEs

Perhaps the take-away hither is that having a robust safety architecture isn’t helpful unless it is enforced across-the-board. Adding drivers exposing potentially sensitive operations to a large number of trustlets negates these efforts.

Of course, apart from compromising the “Normal World”, the TEE itself holds many pieces of sensitive information which should stay firmly beyond an attacker’s reach. This includes the KeyMaster keys (used for Android’s total disk encryption scheme), DRM content decryption keys (including Widevine) in addition to biometric identifiers.

Afterword


While the motivation behind the inclusion of TEEs inwards mobile devices is positive, the electrical flow implementations are soundless lacking inwards many regards. The introduction of novel features in addition to the e'er increasing number of trustlets resultant inwards a unsafe expansion of the TCB. This fact, coupled with the electrical flow lack of exploit mitigations inwards comparing to those offered past times modern operating systems, brand TEEs a prime number target for exploitation.

We’ve also seen that many devices lack back upward for revocation of trusted applications, or simply neglect to do so inwards practice. As long every bit this remains the case, flaws inwards TEEs volition live that much to a greater extent than valuable to attackers, every bit vulnerabilities, i time found, compromise the device’s TEE indefinitely.

Lastly, since inwards many cases TEEs bask a privileged vantage point, compromising the TEE may compromise non only the confidentiality of the information processed inside it, but also the safety of the entire device.


Komentar

Postingan populer dari blog ini

Chrome Bone Exploit: 1 Byte Overflow As Well As Symlinks

The next article is an invitee weblog post from an external researcher (i.e. the writer is non a or Google researcher). This post is most a Chrome OS exploit I reported to Chrome VRP inward September. The folks were squeamish to allow me do a invitee post most it, therefore hither goes. The study includes a detailed writeup , therefore this post volition have got less detail. 1 byte overflow inward a DNS library In Apr I constitute a TCP port listening on localhost inward Chrome OS. It was an HTTP proxy built into shill, the Chrome OS network manager. The proxy has at nowadays been removed equally component of a fix, but its source tin give notice nonetheless move seen from an one-time revision: shill/http_proxy.cc . The code is unproblematic in addition to doesn’t seem to incorporate whatever obvious exploitable bugs, although it is real liberal inward what it accepts equally incoming HTTP. It calls into the c-ares library for resolving DNS. There was a possible 1 byte ov...

Exception-Oriented Exploitation On Ios

Posted past times Ian Beer, This postal service covers the regain in addition to exploitation of CVE-2017-2370 , a heap buffer overflow inwards the mach_voucher_extract_attr_recipe_trap mach trap. It covers the bug, the evolution of an exploitation technique which involves repeatedly in addition to deliberately crashing in addition to how to build alive meat introspection features using onetime meat exploits. It’s a trap! Alongside a large number of BSD syscalls (like ioctl, mmap, execve in addition to so on) XNU also has a pocket-sized number of extra syscalls supporting the MACH side of the meat called mach traps. Mach trap syscall numbers start at 0x1000000. Here’s a snippet from the syscall_sw.c file where the trap tabular array is defined: /* 12 */ MACH_TRAP(_kernelrpc_mach_vm_deallocate_trap, 3, 5, munge_wll), /* xiii */ MACH_TRAP(kern_invalid, 0, 0, NULL), /* xiv */ MACH_TRAP(_kernelrpc_mach_vm_protect_trap, 5, 7, munge_wllww), Most of the mach traps a...

Lifting The (Hyper) Visor: Bypassing Samsung’S Real-Time Total Protection

Posted yesteryear Gal Beniamini, Traditionally, the operating system’s total is the concluding security boundary standing betwixt an assaulter together with total command over a target system. As such, additional aid must hold upwards taken inwards lodge to ensure the integrity of the kernel. First, when a organization boots, the integrity of its primal components, including that of the operating system’s kernel, must hold upwards verified. This is achieved on Android yesteryear the verified kicking chain . However, only booting an authenticated total is insufficient—what most maintaining the integrity of the total spell the organization is executing? Imagine a scenario where an assaulter is able to abide by together with exploit a vulnerability inwards the operating system’s kernel. Using such a vulnerability, the assaulter may endeavor to subvert the integrity of the total itself, either yesteryear modifying the contents of its code, or yesteryear introducing novel attacker-co...