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 arrive at of personal together with individual information of a sensitive nature, such every bit biometric identifiers, payment information together with 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 answer to these use-cases together with more, mobile device manufacturers stimulate got opted for the creation of a “Trusted Execution Environment” (TEE), which tin give the axe live used to safeguard the information processed inside it. In the Android ecosystem, 2 major TEE implementations be - Qualcomm’s QSEE together with Trustonic’s Kinibi (formerly <t-base). Both of these implementations rely on ARM TrustZone safety extensions inward lodge to facilitate a modest “secure” operating system, inside which “Trusted Applications” (TAs) may live executed.

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

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

I would similar to bill that piece the electrical current designs beingness reviewed may live incompatible with some devices’ use-cases, improved designs are beingness developed every bit a final result 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 master copy application processor, every bit good every bit across the SoC. TrustZone facilitates the creation of 2 safety contexts; the “Secure World” together with the “Normal World”. Each physical processor is split upwards 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 current safety nation is accessible on the organisation bus, peripherals on the SoC tin give the axe live designated to either globe past times simply sampling this value.

TrustZone’s software model provides each globe with its ain copies of both lower privilege levels -- EL0 together with EL1. This allows for the execution of different operating organisation kernels simultaneously - i running inward the “Secure World” (S-EL1), piece some other runs inward the “Normal World” (EL1). However, the world-split is non solely symmetrical; for example, the hypervisor extensions (EL2) are non available inward 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 modest “security-conscious” operating systems inside which a laid of trusted applications (TAs) may live executed. These TrustZone-based TEEs are proprietary components together with are provided past times the device’s manufacturers.

To lay it inward context - what nosotros usually refer to every bit “Android” inward our hateful solar daytime to hateful solar daytime lives is simply the code running inward the “Normal World”; the Linux Kernel running at EL1 together with the user-mode applications running at EL0. At the same time, the TEE runs inward the “Secure World”; the TEE OS runs inward 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” together with Trustonic’s “Kinibi”. These operating systems run amongst Android together with render several primal features to it. These features include access to biometric sensors, hardware-bound cryptographic operations, a “trusted user-interface” together with much more.

Since the “Secure World”’s implementation is closely tied to the hardware of the device together with the available safety mechanisms on the SoC, the TEE OSs require back upwards from together with 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 give the axe live seen inward the schematic above, inward lodge for the “Normal World” to live able to interact with the TEE together with the applications inside it, the authors of the TEE must also render user-libraries, daemons together with pith drivers for the “Normal World”. These components are together with so utilised past times the “Normal World” inward 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, together with that of the TEE OS’s pith itself. The interaction with the TEE’s pith is mostly performed past times the trusted applications running nether it. As such, the logical foremost 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 inward a trusted application together with exploit it to gain code execution. While this may audio similar a daunting task, think that trusted applications are simply pieces of software that procedure user-supplied data. These applications aren’t written inward retentiveness prophylactic languages, together with are executed inside opaque environments - a belongings which usually doesn’t lend itself good to security.  

Bearing all this inward mind, how tin give the axe nosotros start analysing the trusted applications inward 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, inward Qualcomm’s illustration the format used to shop the applications was non documented until recently. Nonetheless, some attempts stimulate got been made to reverse engineer the format resulting inward tools that allow converting the proprietary file format into a regular ELF file. Once an ELF file is produced, it tin give the axe later live analysed using whatever run-of-the-mill disassembler. What’s more, inward a recent positive tendency of increased transparency, Qualcomm has released official documentation detailing the file format inward 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 assist 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 give the axe maintain on to the adjacent stair - acquiring the trustlet images (from a firmware prototype or from the device), converting them to a measure format, together with loading them upwards inward 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) together with 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 alter inward 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 impairment done past times a unmarried malicious (or compromised) trustlet. Of course, piece inward regulation these advantages are substantial, we’ll encounter later on how they truly map onto the TEEs inward question.

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

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

To respond this question, we’ll stimulate got to separately explore each TEE implementation.

QSEE Revocation


As we’ve mentioned above, Qualcomm has late released (excellent) documentation detailing the secure kick sequence on Qualcomm devices, including the mechanisms used for prototype authentication. As trusted applications running nether QSEE are component division of the same full general architecture described inward this document, nosotros may gain primal 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, together with 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 primal corresponding to the lastly certificate inward the embedded certificate chain. Moreover, the root certificate inward the chain is validated against a “Root Key Hash” which is stored inward the device’s ROM or fused into one-time-programmable memory on the SoC.

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

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

Ah-ha! Well, let’s maintain reading together with encounter if nosotros come upwards across to a greater extent than pertinent information regarding the acre inward question.

Continuing our review of the document, it appears that Qualcomm has elected to add together unique OU fields to the certificates inward the embedded chain, denoting several attributes relating to the signature algorithm of the prototype beingness loaded. One such acre of special 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 special software image”. Interesting!

The acre is comprised of 2 concatenated values:


The document together with so goes on to explain:

“...If eFuse values indicated that the electrical current version was ‘1’, together with so this prototype would neglect verification. Version enforcement is done inward lodge to forestall loading an older, mayhap vulnerable, version of the prototype that has a valid signature attached.”

At this dot nosotros stimulate got all the information nosotros need. It appears that the discipline of prototype revocation has non eluded Qualcomm -- we’re already off to a skilful start. However, in that location are a few to a greater extent than questions inward demand of an respond yet!

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

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

As nosotros tin give the axe encounter above, the IMAGE_ID value assigned to the Widevine trustlet is 0xC. But what well-nigh the other trustlets inward the Pixel’s firmware? Inspecting them reveals a surprising fact -- all trustlets part the same prototype identifier.

More importantly, however, it appears that the version counter inward the Widevine application on the Pixel is 0. Does this hateful that no vulnerabilities or other security-relevant issues stimulate got been flora inward that trustlet since the device foremost shipped? That seems similar a flake of a stretch. In lodge to larn a meliorate persuasion of the electrical current nation of affairs, nosotros demand a piddling to a greater extent than data.

Luckily, I stimulate got a collection of firmware images that tin give the axe 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 together with Motorola. To collect the needed data, nosotros tin give the axe simply write a short script to extract the version counter from every trustlet inward every firmware image. Running this script on the firmware collection would allow us to assess how many devices stimulate got used the trustlet revocation characteristic inward the past times to revoke whatever vulnerable trusted application (since their version counter would stimulate 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 inward all firmware images comprise version number 0.

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

In fact, nosotros already know the respond to this question. Last twelvemonth I performed research into the Widevine trustlet every bit introduce on the Nexus 6 together with flora (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 component division of my firmware collection. Nonetheless, all of these devices inward my collection (including the Nexus 6) did non revoke the vulnerable trustlet, together with every bit such stimulate got remained vulnerable to this issue. While some devices (such every bit the Nexus 6) stimulate got shipped patched versions of the trustlet, simply providing a patched version without incrementing the version counter has no lawsuit whatsoever.

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

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

One mightiness live tempted to advise 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 sectionalisation (thus raising the bar for a would-be attacker). However, due to the pattern 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 uncomplicated API wherein it is only provided with a buffer containing the trustlet’s binary past times user-space. This buffer is together with so passed on to TrustZone inward lodge for the trustlet to live authenticated together with 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 together with more. Not a brusk listing past times whatever stretch…

So what well-nigh devices unaffected past times the previously disclosed Widevine vulnerability? It is solely possible that these devices are affected past times other bugs; either soundless undiscovered, or simply non public. It would for certain live surprising if no bugs whatsoever stimulate got been flora inward whatever of the trustlets on these devices inward the interim.

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

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


Putting all of the higher upwards 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 inward the illustration of trustlet revocation. Specifically, on devices where a replay protected retentiveness block (RPMB) is available, it tin give the axe 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, inward 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 stimulate got indeed enabled this feature. Perhaps i explanation for the lack of revocation is that some devices are either lacking a RPMB, or stimulate got non blown the aforementioned eFuse inward 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 stimulate 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 together with 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 travel past times the authentication (and would thence neglect to load). As of now, it seems that in that location is no skilful solution for this situation. Indeed, all Nexus together with Pixel devices are shipped with an unlocked bootloader, together with are thence 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 advise naive solutions, such every bit embedding a whitelist of “allowed” trustlet hashes inward the TEE OS’s pith itself. Thus, when trustlets are loaded, they may also live verified against this listing to ensure they are allowed past times the electrical current version TEE OS. This proffer is non meritless, but is non robust either. For starters, this proffer would require incrementing the version counter for the TEE OS’s prototype (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 prototype 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 current permissions needed to bear out the attack.

Nonetheless, a meliorate solution to this employment (rather than a stop-gap mitigation) is soundless needed. We hope that past times underscoring all of these issues plaguing the electrical current 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 inward 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 give the axe utilization that vulnerability inward lodge to larn elevated code execution with the “system_server” procedure on Android. This allows us greater liberty inward exploring the mechanisms used inward the “Normal World” related to Trustonic’s TEE.

Unfortunately, different Qualcomm, no documentation is available for the prototype authentication procedure carried out past times Trustonic’s TEE. Be that every bit it may, nosotros tin give the axe soundless start our inquiry past times inspecting the trustlet images themselves. If nosotros tin give the axe concern human relationship for every unmarried slice of information stored inward 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 inward Trustonic’s TEE is documented inward their public header files. In fact, the format itself is called the “MobiCore Loadable Format” (MCLF), together with harkens dorsum to G&D’s MobiCore TEE, from which Trustonic’s TEE has evolved.

Using the header files together with inspecting the binary inward tandem, nosotros tin give the axe slice together the entire format to shop the trustlet’s metadata every bit good every bit its code together with information segments. As a result, nosotros larn inward at the next layout:

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

At this point, nosotros stimulate got accounted for all but a unmarried blob inward the trustlet’s binary - indeed, every bit shown inward the prototype above, next the information segment, in that location appears to live an opaque blob of some sort. It would stand upwards to argue that this blob would stand upwards 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 together with brand sure that is the case.

Unfortunately, in that location appear to live no references inward the header files to a blob of this kind. With that inward mind, how tin give the axe 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 together with loading trusted applications. Once nosotros seat the relevant code, nosotros should live able to isolate the treatment of the signature blob together with deduce its format.

At this point, however, this is easier said than done. We soundless stimulate got no noesis of where the TEE OS’s binary is stored, how it may live extracted, together with what code is responsible for loading it into place. However, some related piece of work has been done inward 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 inward EL3 (which is based on ARM’s Trusted Firmware), we’re interested inward dissecting the code running inward S-EL1 (namely, the TEE OS).

By applying the same methodology described past times Fernand, nosotros tin give the axe charge the SBOOT binary from an extracted firmware prototype into IDA together with laid out analysing it. Since SBOOT is based on ARM’s Trusted Firmware architecture, all we’d demand to do is follow the logic upwards to the dot at which the TEE OS is loaded past times the bootloader. This element is also referred to every bit “BL32” inward 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 pith 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 together with analyse it tin give the axe simply search for the string “VERSION_-+A0”, which denotes the starting fourth dimension of the TEE OS’s pith image. As for the image’s base of operations address - past times inspecting the absolute branches together with the address of the VBAR inward the pith nosotros tin give the axe 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 together with 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 prototype authentication module tin give the axe live converted into regular ELF files (and later analysed). Therefore, nosotros tin give the axe simply apply the same procedure to convert Kinibi’s pith (“tbase”, every bit introduce on Samsung’s Qualcomm-based devices) into an ELF file which tin give the axe together with so 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 advise that whatever authentication code is introduce inward one, is also introduce inward the other.

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

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

The component division extracts Earth primal information (the modulus together with Earth exponent). Then, it calculates the SHA-256 digest of Earth primal together with ensures that it matches Earth primal hash embedded inward the kernel’s binary. If so, it uses the extracted world primal together with the embedded signature inward the blob to verify the signature on the trustlet itself (which is performed on its entire contents upwards to the signature blob). If the verification succeeds, the trustlet is loaded.

At long last, nosotros are finally able to concern human relationship for every unmarried flake inward 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 inward the MCLF header. However, it for certain doesn’t seem similar this value is beingness used past times the loading logic nosotros traced exactly a brusk piece ago. Nevertheless, it’s possible that we’ve simply missed some relevant code.

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

...And the results are in! Every unmarried trusted application inward 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 together with firmware versions (and thence doesn’t seem to stand upwards for a value used for incremental versions or for revocation). All inward all, it for certain 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 seek 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” together with ending inward the “Secure World”’s TEE. Doing so volition assist us figure out which user-mode components we’ll demand to interact with inward 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 together with so routed to Trustonic’s TEE driver). One such command tin give the axe live used to charge a trustlet into the TEE.

The daemon may charge trustlets from i of 2 paths - either from the organisation sectionalisation ("/system/app/mcRegistry"), or from the information sectionalisation ("/data/app/mcRegistry"). Since inward our illustration nosotros would similar to avoid modifying the organisation partition, nosotros volition simply house our binary inward 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 inward 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) inward the information partition's registry directory, together with 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 give the axe connect to it. Nonetheless, much similar inward Qualcomm’s case, the listing of such processes seems to include the bulk of privileged processes running on the system. Indeed, a really partial listing of which includes the DRM server, organisation server, the book daemon, mediaserver together with indeed whatever organisation application (you tin give the axe uncovering the full list inward the number tracker).

From together with so on, the daemon simply contacts Trustonic’s driver together with issues a specific laid of ioctls which drive it to travel past times on asking to the TEE. It should live noted that access to the driver is also available to quite a broad arrive at of processes (once again, the full list tin give the axe live seen inward the number tracker).

Now that we’re sufficiently informed well-nigh the loading process, nosotros tin give the axe larn ahead together with endeavour to charge an old trustlet. Let’s simply accept an old version of the “fingerprint” trustlet together with house it into the registry directory nether the information partition. After issuing a charge asking to the daemon together with 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 stimulate 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 menage unit of measurement at nowadays supports rollback prevention characteristic for trustlets together with this is fully supported since Milky Way S8/S8+ devices”

Indeed, it appears that the number has been addressed inward the newest version on Trustonic’s TEE - Kinibi 400. Simply searching for relevant strings inward the TEE OS binary provided inward 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) inward lodge to forestall old trustlets from beingness rolled back. As the implementation is proprietary, to a greater extent than inquiry is needed inward lodge to determine how this characteristic is implemented.

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

Without specialised hardware used to shop the version counter or some other identifier which tin give the axe live utilised to forestall rollback, it seems similar in that location is non much that tin give the axe live done to address the number inward older devices. Nonetheless, every bit nosotros stimulate got no visibility into the actual safety components on the SoC, it is non clear whether a laid upwards 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 inward the future.

Deciding On Influenza A virus subtype H5N1 Target


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

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

After comparing a few trusted applications against their older versions, it is straightaway 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 give the axe pull upon previous research. Last year, piece doing some cursory inquiry into the trusted applications available on Samsung’s Exynos devices, I discovered a yoke of trivial vulnerabilities inward the “OTP” trustlet running nether that platform. These vulnerabilities stimulate got since been “fixed”, but every bit the trustlets are non revoked, nosotros tin give the axe 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 give the axe 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 inward the OTP trustlet belatedly lastly year. Although the vulnerability has been “patched”, attackers tin give the axe simply follow the steps higher upwards to charge the old version of the trustlet into the TEE together with exploit it freely.  

The number we’re going to exploit is a uncomplicated 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 encounter 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 uncomplicated loop which waits for notifications from the TEE OS informing it of an incoming command.

Once a command is issued past times a user inward the “Normal World”, the TEE OS notifies the trusted application, which later processes the incoming information using the “process_cmd” function. Reversing this component division nosotros tin give the axe encounter the trustlet supports many different commands. Each command is assigned a 32-bit “command ID”, which is placed at the starting fourth dimension 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”, inward lodge to accept a user-provided OTP token together with decrypt it using the TEE’s TrustZone-bound unwrapping mechanism

This component division receives several arguments, including the length of the buffer to live unwrapped. However, it appears that inward 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 foremost 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 await at the placement of items inward the buffer for a valid give away 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 together with is solely attacker-controlled. Supplying an arbitrarily large value volition thence final result inward a stack overflow. All that’s left at nowadays is to create upwards one's heed on a stack alignment using which nosotros tin give the axe overwrite the homecoming address at the halt of the stack frame together with hijack the command flow. For the sake of convenience, let’s simply homecoming direct from “otp_unwrap” to the master copy processing component division - “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, together with 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 give the axe live delegated to read together with 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 give the axe direct invoke whatever component division inward 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 inward the trusted application are huge. In fact, they’re so large that there’s no demand for a stack pin inward lodge to fit our ROP chain inward retentiveness (which is exactly every bit well, every bit a brusk search for i yielded no obvious results). Instead, nosotros tin give the axe simply shop our chain on the stack frames leading from the vulnerable component division all the way upwards 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, together with on the large stack for intermediate processing. Using the stack inward 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 starting fourth dimension of our ROP chain’s gadgets, followed past times a sequence of ROP gadgets needed to prepare arguments together with telephone phone a function. Once we’re done, nosotros tin give the axe simply fill upwards the remainder 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 stimulate got to worry well-nigh restoring nation either.

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

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

Security Mitigations


We’ve already seen how a relatively straightforward vulnerability tin give the axe live exploited inside Kinibi’s TEE. Surprisingly, it appeared that in that location were few mitigations inward 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 together with 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, together with 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 inward 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 phone each of the functions supported past times the TEE’s measure libraries. It contains a wealth of code, including gadgets to telephone phone functions, gadgets that invoke the TEE OS’s syscalls, perform message-passing together with much more. And, unfortunately, this library is also mapped into a constant address inward 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 flora inside a trustlet running nether Trustonic’s TEE tin give the axe thence live exploited without requiring prior information well-nigh the address-space of the trustlet (thus lowering the bar for remotely exploitable bugs).

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

Indeed, all QSEE trustlets are loaded into the same modest physically contiguous arrive at of retentiveness carved out of the device’s master copy memory. This part (referred to every bit the “secapp-region” inward the device tree) is dedicated to the TEE, together with 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 inward 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 give the axe theoretically utilise a 64-bit virtual address infinite (allowing for high entropy ASLR), the ASLR enabled past times QSEE is express around ix bits (therefore with 355 guesses, an assaulter would stimulate got a 50% adventure 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 assaulter to reload it together with endeavour to approximate the base of operations address i time again.

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

Stack Cookies together with Guard Pages


What well-nigh other exploit mitigations? Well, i of the most mutual mitigations is the inclusion of a stack cookie - a unique value which tin give the axe live used to uncovering instances of stack smashing together with abort the program’s execution.

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

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

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

Identically, Qualcomm’s TEE does non render guard pages betwixt the globals, heap together with stack - they are all simply carved out of the unmarried information segment provided to the trustlet. As a result, overflows inward whatever of these information structures tin give the axe 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 likely clear plenty that compromising TEEs on Android seems similar a relatively straightforward task. Since both TEEs lag behind inward 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 together with to a greater extent than trusted applications are added, finding a vulnerability inward the foremost house is becoming an increasingly straightforward task. Indeed, simply listing the number of trusted applications on the Milky Way S8, nosotros tin give the axe encounter 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 inward whatever way, in that location may live no argue to farther secure it.

To respond this question, we’ll encounter how compromising the TEE tin give the axe live incredibly powerful tool, allowing attackers to fully subvert the organisation inward many cases.

In Qualcomm’s case, i of the system-calls provided past times QSEE allows any trustlet to map inward 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 laid on has been demonstrated inward the past. Once code execution is gained inward the context of a trustlet, it tin give the axe scan the physical address infinite for the Linux Kernel, together with i time flora tin give the axe patch it inward retentiveness to innovate a backdoor.

And what of Trustonic’s TEE? Unlike QSEE’s model, trustlets are unable to map-in together with modify physical memory. In fact, the safety model used past times Trustonic ensures that trustlets aren’t capable of doing much at all. Instead, inward lodge to perform whatever meaningful operation, trustlets must ship a asking to the appropriate “driver”. This pattern 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 inward the TEE is indeed feasible.

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

Sensitive operations, such every bit mapping-in together with 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 give the axe live abused past times a trustlet.

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

One such illustration 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 inward lodge to ensure that it is non tampered with.

Samsung has elected to split upwards TIMA’s functionality inward two; the driver mentioned higher upwards provides the powerfulness to map inward physical memory, piece an accompanying trusted application consumes these services inward lodge to perform the integrity measurements themselves. In whatever case, the halt final result is that the driver provides APIs to both read together with write physical retentiveness - a capability which is usually reserved for drivers alone.

Since this functionality could live leveraged past times attackers, Samsung has rightly decided to enforce a UUID whitelist inward lodge to forestall access past times arbitrary trusted applications. Reversing the driver’s code, nosotros tin give the axe encounter that the whitelist of allowed trusted applications is embedded inside the driver. Quite surprisingly, however, it is no brusk 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) together with biometric identifiers.

Afterword


While the motivation behind the inclusion of TEEs inward mobile devices is positive, the electrical current implementations are soundless lacking inward many regards. The introduction of novel features together with the e'er increasing number of trustlets final result inward a unsafe expansion of the TCB. This fact, coupled with the electrical current lack of exploit mitigations inward 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 upwards for revocation of trusted applications, or simply neglect to do so inward practice. As long every bit this remains the case, flaws inward 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 inward many cases TEEs savour 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

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

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