So my name is Alex Bulozel, and I'm here to present on my research on reverse engineering Windows Defender's antivirus emulator. A little about me before we get started. I am a security researcher at For All Secure. You may know the company from their victory at the Cyber Grand Challenge two years ago at DEF CON 24 with the Mayhem CRS. I also do firmware reverse engineering and cyber policy at Riverloop Security. And I'm a very proud alumnus of RPI and RPI Sec. They're playing over in the CTF right now, and I want to say good luck, guys. And this is my first time speaking at DEF CON, so it's great to be here. This work is my personal research and is my own views, not those of my employers or anyone else I've previously worked for. Before we get started, I do want to say this presentation is a deeply technical look at reverse engineering Windows Defender's binary emulator. And as far as I know, the first conference talk to really look at reverse engineering the antivirus emulator for any AV product. It's not an evaluation of Windows Defender. I'm not going to tell you whether this is a good product. You should use it in your network or not. I'm not going to tell you whether it catches viruses effectively relative to other AVs or anything like that. And also, this talk does not address Windows Defender ATP or any other technology under the Windows Defender name. This is about Windows Defender antivirus, the traditional endpoint AV product. So an outline of this talk, I'm going to go through an introduction, then talk about my tooling and process, how I did what I did, then reverse engineering and the real media presentation, a bit on vulnerability research, and then we'll conclude. So, why look at Windows Defender antivirus? This is Microsoft's built-in AV product that is installed by default on all Windows systems. And on Windows 10, it runs by default, which means that over 50% of Windows 10 systems have Windows Defender antivirus running. The Defender name now seems to cover a variety of mitigations and security controls built into Microsoft OSes. So you have, you know, Control Flow Guard, EMET, ATP, all these different things now get lumped under, you know, Windows Defender Device Guard, Windows Defender Application Guard, Windows Defender XS. Split Guard, and so forth. Again, here we're focused on Windows Defender antivirus. And it also runs unsandboxed as NT Authority System, meaning if you found a vulnerability inside Defender, that would give you initial RC, if you could exploit that. It would also give you a PrevEsc up to system, and you'd be running inside an AV process. So the AV would be unlikely to catch you doing anything malicious, because it's not going to flag itself, say, doing something malicious, writing a file, injecting another process, and so forth. It's also surprisingly easy for attackers to reach. I've not tried this myself. But friends of mine at Google Project Zero have told me that you could send an executable to someone who has a Gmail account open. And if they have that Gmail open in a background tab, Chrome, the Chrome browser will cache the downloaded file that just hits the inbox. That'll hit like a mini filter driver on the Windows OS. And then the file that's written to Desk will be passed off to Defender to be scanned. So you can actually reach this in a remote fashion, even though you would think this is a traditional host-based protection system. My motivation came from this tweet from Tavis Ormandy. At Google Project Zero, who about a year ago found some vulnerabilities in Defender's JavaScript engine with Natalie Silvanovich, also of Project Zero. And I had a background in reverse engineering antivirus software, did some work we called AV Leak with Jeremy Blackthorn, who's here in the audience. A couple years ago, presented that at Black Hat and Woot. But I never actually analyzed Windows Defender, and I always wanted to. And I also had this interest in JavaScript engines. So I took on Defender and looked at the JavaScript engine for about four months, then presented that work and moved on to reverse engineering the Windows engine. And then I took on Windows Emulator, which I'm here to talk about today. So our target is mpengine.dll. This is the main DLL that provides Windows Defender's scanning functionality. It's a very large miner. It's about 12 megabytes large. And again, this is not the part of Defender that's, say, doing hooking for system calls or filtering disk writes. This is the main scanning engine. This, you take a buffer of data and you say, this is malicious or it's not malicious. That's its purpose. And inside mpengine.dll. We have a variety of scanning engines. I'm focusing today on the Windows Binary Emulator, which is one of many scanning engines. Before we go into my work on the Windows Binary Engine, I just want to quickly recap what I did reverse engineering the JavaScript Engine. This bit.ly link there will take you to that presentation. And this was presented at a recon Brussels in Brussels, Belgium, back in February. So Windows Defender has a JavaScript engine that's used for analysis of potentially malicious JavaScript code. And I reversed it from binary. I reversed it from binary. used a custom loader and shell for dynamic experimentation with help from Rolf Rolls. So thanks, Rolf. Throughout the JavaScript engine, I found AV instrumentation callbacks that inform the heuristic antivirus portion of Defender about actions that the potentially malicious JavaScript is taking that it then uses to determine whether this is malicious JavaScript or not, say, for example, an exploit. And I also found that the developers seem to prioritize security at the cost of performance. So the JavaScript engine is very pared down, stripped down, doesn't have jitting or many of the other features and optimizations that make modern JavaScript engines fast. On the other hand, I found it to be relatively secure and the attack surface to be relatively pared down. You'll see some common themes like that throughout this presentation today. As far as related and prior work goes, there's really only a handful of prior publications on reverse engineering antivirus software at all, let alone the emulators within them. There is, of course, the work I mentioned, AV Leak, which I did with some collaborators at RPI, some of whom are here. There's also work from Hoxian Koret touching on this. There's Tavis Ormandy's work at Google Project Zero. And there actually are some talks from the AV industry itself, such as Mihaly Chirac's talk from, I believe this was Hack.lu, I think 10 years ago, as an AV industry developer talking about how Bitdefender's emulator works. But really, there's not been a lot of offensive work or work from people who don't work in the AV industry looking at these systems. I'd also mention that patents are a great source of sort of open source intelligence about how AVs work. Chris DeMoss called that out in his presentation, looking at patents on x86 processors. Similarly, you can find a lot of patents that describe undocumented functionality within AVs or how these particularly complex mechanisms work. All right, moving into a background on emulation itself. So there's this traditional AV model, and I think a lot of people have this idea about how AVs may work, which is that they scan files and look for known malware signatures, such as file hashes, sequences of bytes, or files that are not available to them. And they look for known malware signatures, such as file traits, and they might have some heuristics about, say, imports, or they recognize a static MD5 hash, or they recognize a particular snippet of code that's known to be associated with a given malware family. But this is really an outdated model. And this is an outdated model, you know, 15, 20 years ago, this was outdated. Because malware could evade these hard-coded signatures with packed code by creating novel binaries, you know, packing obfuscation. You heard a lot about polymorphic viruses back in the early 2000s. So the solution that, again, 15 to 20 years ago, the AV industry came up with was runtime dynamic analysis on the endpoint through emulation. So actually running these unknown binaries in a virtualized environment and looking for signatures there. This technology goes by a number of names. You may hear it called sandboxing, heuristic analysis, dynamic analysis, detonation, virtualization, and so forth. At the end of the day, it's all emulation, and that's what we're talking about today. So an overview of emulators in general, you begin by loading a potentially malicious unknown binary that you can't identify with more expensive analyses. Or less expensive analyses, rather, such as hashing or heuristics based on imports. You're going to run the binary in an emulated environment. So you're going to have a CPU emulator for the particular architecture of the binary, generally x86. You're going to run that in this emulator, and throughout running, you're going to collect these observations, and you'll terminate at some point, such as length of time at run, number of instructions that have been executed, number of API calls, amount of memory the malware has used, or so forth. And throughout this, you're collecting heuristic observations about the malware's behavior, that inform detections. You might also look for things like if the malware calls create file, and writes a known malware signature with create file, you'd hook that implementation, and every create file you would look for, say, a known malware signature or a known malware hash at that point. Moving into talking about tooling and process, how I did what I did. Reverse engineering-wise, I used pretty standard industry tools like IDA and Bindiff for patch analysis. So as Google Project Zero was discovering some vulnerabilities, I was able to look at the diff updates of the DLL and find what had changed, how Microsoft tried to mitigate vulnerabilities inside Defender. I found overall, there's about 30,000 functions across this massive 12 megabyte DLL. So this is enormous, probably one of the largest binaries I've ever taken on reversing. Obviously, people look at firmwares that are much larger, but this is really, absolutely monolithic for a single Windows DLL. What does make this job a lot easier is that Microsoft publishes PDBs, and that's basically debug databases that have symbols and symbols, and sometimes type information for the binaries. Dynamic analysis-wise, AVs are generally harder to look at than traditional software, and dynamic analysis does require some work on the part of the user, the reverse engineer. In Defender's case, it's a protected process, meaning that even if your system or admin on your local system, you cannot attach the process to debug it. Even if you have SED bug privilege or anything like that, you still can't attach. It's protected by the OS. The solution to this is to go into kernel debugger and, for example, debug an entire VM and then attach the process from the kernel, but that's very expensive and just annoying to do. So introspection is also challenging. Actually, if you can, say, pause in a breakpoint, actually understanding what's going on in the emulator state can be difficult with a debugger, even though you have a debugger running. Scanning on demand can be difficult to trigger. If you want to scan a binary, you might have to go into a GUI interface, click a couple buttons, select something, choose it. It's a pain to do that. You want an automated interface, just say scan this file, scan that file, scan the other file. And code here reachability may be configuration or heuristics dependent, meaning that local settings about, say, how aggressive the scanning is, what time limits you allow the scanner to have, all of these can get in the way of effective scanning. The solution is to build a custom loader for these AV binaries. And it was nice that I was able to start with some work that Tavis Orman did, Google Project Zero did, on building his own custom harness for Defender, which I then extended extensively. So first off, I'm going to talk a little bit about Tavis's existing system. I'm going to talk a little bit about Tavis's existing work, which she called Load Library. So Tavis built a PE loader for Linux. So this is able to take a Windows DLL on Linux and load it up and then actually run it. This is not a full replacement for something like Wine or any other Windows emulation. This is just enough to get Windows Defender itself running and shimming out system calls on Windows that Defender will be making to Linux implementations. So talking through how Tavis's tool works, and the link here will take you to the GitHub project. We begin with a Linux binary, just standard user binary. And it's going to load and resolve imports for MPEngine.dll. So this is just the process of taking the DLL, relocating it in memory, doing standard DLL loading process, putting it in a read-write-execute memory buffer there on Linux. Then the IIT, the import address table, you're going to go through and shim out the implementations of various Windows APIs with Linux replacements. So for example, create file is replaced by a call to open file or FF. Inside this engine, you have an emulator. And for now, just remember that there's a table called Gsyscalls, which is a table of function pointers to various emulations of Windows API functions. And on the outside, we have our malware binary. With here, we have the standard MZ header on the binary. We're going to call a function exported by Defender called rsignal. And this is the main entry point to Defender. We give it a buffer of data and it's going to come back with a malware classification. We then go through a process of selecting a scanning engine. So Defender may do some initial analyses with things like static hashes. If those fail and it can't determine whether this is a malicious binary or not, they're ultimately going to route it into the emulator. The emulator will run, make its determination whether this is a malicious binary or not, and then come back with a virus identification, or it might say this is just benign. So a quick demo. I'm going to show you scanning with mpclient. This is Tavis Ormondes unmodified. Harness for Windows Defender. So here we're scanning the ecar test file. This is an industry standard test file for any AV. And we see we scan the file and it comes back and says we found ecar.com. So that's kind of a demo. We're actually taking this Windows code, running it here on Linux and seeing what happens when we scan a binary. In addition to using this harness from Tavis, I did some dynamic analysis with customized code coverage tools developed by Marquis Gossidam of RET2 Systems, a fellow RPI Sec alumnus as well. And Marquis made a tool called Lighthouse that lets you scan a binary or run a binary under Dynamo.rio or PIN, collect coverage information, and visualize that in IDA Pro. So you can see here in this control flow graph, the basic blocks are those that have been hit during a given scan. And I found this the extremely powerful and useful tool when I was doing my reverse engineering. I did find it interesting to see Halvar Flake, just about a month or two ago, gave a keynote at SSTIC, where he was talking about challenges of introspectibility with binaries, and how it can be very difficult to introspect and analyze and debug binaries, and how ultimately that's a hindrance to security. And Halvar explicitly called out the challenges of analyzing Windows Defender as one example of this, where because Defender is in a privileged process on Windows, you can't analyze it under a tool like PIN or Dynamo Rio. Of course, we're running on Linux, so we sidestepped the whole issue of the protected process, and we can actually run and visualize coverage. Okay, now moving into the meat of the presentation, talking about reverse engineering the emulator itself. First off, I'm going to talk about startup of the engine, then we're moving to CPU emulation, instrumentation, and then the Windows environment and emulation. So first off, the first thing that has to happen when we want to emulate a given binary is we have to load it in and initialize the emulator and get everything started up. So we're going to call... We're going to call the rsignal function, which provides this entry point that Defender is scanning, and we give it this buffer of data to be scanned, to be classified, and it will return the malware classification. So these results are actually going to be cached as well. There's lots of stuff going on in the back end we don't really care about. We ultimately care about just going into the emulator itself. So the emulator has to be initialized. We have to allocate memory for execution. We have to initialize various C++ objects that are involved in the emulation process itself. Various subsystems within Defender. For example, the object manager. We have to create an object manager instance. We have to set up the virtual file system and so forth. We're going to load the binary that's to be analyzed, resolve its imports and things like that, and then initialize virtual DLLs in this emulated process memory space. These are akin to the real DLLs in our real Windows system that provide Windows API functionality. Throughout this process, Defender is collecting heuristic observations about the binary, and you can see these on the right side here. For example, things like PEA, suspicious. Suspicious section size. So these might inform some heuristic classifications in Defender because there's a suspicious section size. Maybe this is malware. We'll also be doing things like in the bottom right, you can see some min-win resolution resolving API MS, some of the API set DLLs. And here in the bottom left, I have this example of when we're setting up a name for the binary to be emulated, you can see that if the binary is a Windows executable, it'll be called myapp.exe. This is something you could write. You could write a face of malware that says, if my name is myapp.exe, I won't run. I know that I'm running inside Defender. And indeed, if you Google this string, you will find malware binaries online that explicitly look for the name myapp.exe and choose not to run if they see it. After startup and initialization, we're going to move into talking about CPU emulation. So technically, what Defender does is not so much emulation as it is dynamic translation. This is akin to what Kimu, the quick emulator, does, which is basically taking assembly code of a given language. Lifting it up into an IL or an intermediate representation, and then taking that IL and then dumping it out with a JIT engine into executable code. So Defender supports a number of architectures. You can see here in the enum on the right, ranging from x86 of three different flavors to ARM and even VM Protect. So they can take VM Protect opcodes, lift those into an IL, and dump them out into sanitized x86 to be run and analyzed, as well as ARM. Now, this subsystem is incredibly complicated and not really a primary focus of my research. But I'll give you a brief overview of it in the next few slides. We begin with the architecture to IL lifting process, which are these giant functions that are architecture underscore to IL. You can see an example from x86 to IL translator, just an absolutely massive, ugly switch case. Thousands of switch cases. It gets super slow when you load this in. And basically what they're doing here is grabbing a byte of opcode from an x86 opcode. Looking at that, determining what it is, and then emitting the according or related Windows Defender engine representation for that binary operation. And you can see an example here in the bottom right, where all push instructions lift to 13 in the Windows Defender IL. There's also, after we lift to the IL, there is an IL emulator that runs in software. So we can actually run binaries in software. I never observed this being run during my research. Did some code coverage analysis. Never saw this being hit. My intuition is that this is so that we can support analysis of x86 binaries on non-x86 hosts. So, for example, if you're running Windows Defender on Windows for ARM, you don't have to have a IL to ARM JIT engine. You can just run it in software. Now, as far as the IL to x86 JIT translation, we're taking IL code and then translating a basic block at a time, similar to the way Kimu does things. And I did observe this JIT being used during my research. Defender will actually handle unique instructions that it can't handle with emulation through software-bound emulation. So if it can't JIT an instruction out, it'll actually generate a call directly into a function that does that. We're going to show that in the next slide. But just you can see here, circled in red on the left, you can actually see the opcodes being constructed. So they're actually constructing a move and immediate and then call the immediate, calling directly into a function, handling a particularly unique architectural instruction or event. Over here on the right. You can actually see the LEA opcode actually being omitted, the opcode in x86 is 8D. So as you're dumping out from the LEA IL instruction down to x86, you do 8D and then you XOR that with a register to register in value to create a valid x86 instruction. Microsoft actually documented this in 2005 at Virus Bulletin with a paper called Defeating Polymorphism Beyond Emulation. And it's definitely worth checking out. And it's really remarkable that Microsoft was experimenting with this technology. Almost 15 years ago, IELTS are so hot right now, everyone's playing with IELTS for things like Binary Ninja or various program analyses. But Microsoft was doing this on the endpoint, you know, on your computer, your grandma's computer, everyone's computer, 15 years ago. They were lifting up the IELTS, jitting them out, doing analyses on them. It's very impressive, I found. So then we have these architecture-specific escape handlers for these unique architectural events that we can't emulate with the JIT engine. You can look at this offline, see an exact listing of some of these enums. And an example of one of these functions would be this software-bound emulation of the x86 CPU ID instruction. So this is an instruction that provides unique information about a given x86 CPU. And here it's emulated in software. So I've shown here, I wrote a malware binary that does CPU ID with this argument hex 80001. And when we run this binary inside Defender's analysis engine, we'll get this code coverage. And we'll actually see that it will bounce off the block where that same immediate is set. We'll see that it's compared. And then we do it on the true branch because the immediate that our code was doing matches up with the immediate here in software. And then they can emulate CPU ID by setting register state accordingly. All right. Moving into talking about my instrumentation, which is a big enabler for the rest of my research. So the problem with analyzing Windows Defender, again, I said there's very little introspection. It's very difficult to tell what's going on inside of it. All you really get out of it is virus identification. Now you could exploit virus identification as sort of a side channel to extract information about inside the engine. And indeed, that's what I did with the AVLeak project a couple of years ago. I was exploiting malware identifications as a side channel to get information about what's going on inside various AV emulators. But this is really slow and inefficient. So a smarter technique is to go in and sort of give us a malware eyes view of what's going inside in the engine. So mpengine.dll has various functions that are invoked when various Windows APIs are called by malware running inside of it. And we can then hook those emulation functions. And provide our own implementations so we can create a one or two way IO path to share information with the outside. And also in turn inform the malware binary inside about what actions we want it to take. So let me give you a diagram of that. This is the original load library diagram I showed you. This is Tavis Ormandy's tool, kind of in an unmodified state. This is how it works. And I went in and I hooked the gsyscalls table. This is the table of about 120 functions providing emulations for various Windows APIs. I hooked it and replaced those implementations with my own implementations of various common functions like output debug string A or WinExec. So when these functions are now called by our malware binary inside the engine, instead our functions are invoked. So here's an example of our output debug string A hook. And the process we have to take on which is resolving the relative offsets of these functions. And then setting hooks in the read write execute DLL buffer kind of in our Linux process. So what this looks like is this. Here in the top right. We have our IDA Pro disassembly or decompilation rather of Windows Defender's emulation of output debug string A. Basically a no op. All it does is retrieve a single parameter off the virtual stack. And then bump the tick count. So it bumps the time a little bit in the emulator. And here in the center of the screen, I have my reimplementation of this function. So we're going to walk through this step by step. First off, we have our declaration. So this takes a void pointer. PEvars T is a massive about half megabyte large structure passed to all these Windows API emulations. We don't want to know an exact definition of that function. So we just provide, take a void pointer. Just say we're not going to worry about it. It's just a pointer. Then we have this local thing to hold parameters to the function. So the function has parameters passed to it in the virtualized emulated environment. And we want to interact with those. So we have to make some space for them. We're going to use a function internal defender to pull off one parameter from the virtual stack. So we're going in talking, you know, looking at the virtual ESP and EVP state. In this virtual stack. So we're going to use a virtual memory space and then pulling off the four byte value that was there. I'm actually calling back into defender from my hook function to do that. Then I'm calling a function get string that's going to translate a virtual address inside the emulator to a real address that we can interact with locally. And now we can just print that string to standard out. So this sounds like a lot, but let me show you a quick demo of it in action. So here I have a malware binary that's going to say hello DEF CON when we run it. It just goes output ux string a hello DEF CON. We're now going to scan that binary inside my hooked and modified version of Tabas's load library tool. And you'll see here it says hello DEF CON now. Going back to Visual Studio, we're going to add a new line. This is a live demo. Of course, this is a pre-recorded video because the DEF CON organizers this year wanted us to do pre-recorded videos. But I was doing this live. I just rebuilt the binary. And here scanning it again. It's now going to say hello DEF CON. And then also this is a live demo. So this is what's happening. So what's happening is inside the emulator, our malware binary is calling this function. And because we've hooked the implementation of the output debug string a emulation in Defender, our function is being called instead. And we're going to run it one more time, I believe, with some more information. You can see here we have a more rich debug output. And we can see things like the exact addresses passed to it from the virtual memory space. So this was a big enabler for the rest of my research. The fact that I had this sort of window into what's going on inside the emulator. I can have my malware binary inside, take observations, and then post them out to the outside world. As far as my malware binary goes, I call it myapp.exe. Again, that's the name of all binaries running inside Defender's engine. It does this I.O. communication with output debug string a and some other functions. On the right side, you'll see a list of factors that I found could impede emulation and the ways I get around them. So I had to really massage the linker, optimizations, imports, in order to get binaries that were consistently emulated by Defender. And I'll be releasing some code at the end of this talk that will have a very simple Visual Studio project that I found I was able to get. It consistently emulated when scanned with load library. Finally, as far as the reverse engineering goes, moving into the Windows emulation and the Windows environment. I think the most interesting part of this presentation. I'm going to start off by talking about the user mode environment. So this is the emulation of a fake Windows user mode. So in Windows Defender, there is a virtual file system. As any real system would have a file system and files that malware might look at, Defender virtualizes one. There's about 1500 functions on their virtual file system and you'll see a variety of things in there. Mostly it's fake executables that are there for malware binaries to, for example, infect or do different things to that could be indicators that they are in fact malicious binaries. So I'll do a quick demo of dumping the file system. Again, using that mechanism that I showed you of posting data out without the debug string a. We're able to enumerate the entire file system and dump it in just a few seconds. I did here actually use a slightly more sophisticated hook where I was doing WinExec and I'll show some examples in my backup slides. It's not as simple as just output debug string a-ing them. But you can see here in just a second or two, we dumped the entire virtual file system from inside Windows Defender. We had a malware binary go inside there, enumerate all the files that it could see and then dump them out. And when we, after we dump them out, we see that there's about 1500 of them in this virtual file system. And you'll see things like this. The word goat repeated thousands of times over. In a file called aaa-touchmenot.exe. My intuition is that this binary is right there on the C drive. And it's there so that a malware binary might read that file in and say send it over the network or encrypt it or do some indicator that we are indeed malware. So maybe if you touch it, that might be an indicator that you're malicious. The reason it has the word goat pasted thousands of times over, presumably it is a goat file. That's sort of an AV industry term for a sacrificial file, like a sacrificial goat. That you can let get infected or changed or encrypted by malware in order to have the malware kind of show its true intent. So that was an interesting artifact. Again, this is also something that you could write malware that says if I see the word goat thousands of times over in a file called aaa-touchmenot, I know I'm running inside Defender, therefore I'm not going to run. I'm not going to do anything malicious. We'll see fake config files. You can see that these are very clearly written by a real human with comments like blah blah and, you know, generic SQL queries. We have a virtual registry that has thousands of files. We have thousands of entries and enumerating the whole registry and dumping that out. We'll see things like this. So, for example, there's a registry entry for World of Warcraft. Presumably there's malware that maybe looks for World of Warcraft registry entry and touches it. So if we saw a call to, say, regopenkey on World of Warcraft, that might be an indicator of potential malicious intent. We'll see various other fake processes running on the system. And these are not real processes. They're just when you call, you know, the callback function to enumerate all processes, you'll see this fake listing. And highlighted at the bottom in yellow there is our function, myapp.exe. A quick demo of that, dumping the process listing, again using this same mechanism that I developed. So there you can see, real time, just took less than a second. We dumped the entire process listing. All right, back to the presentation. In addition to this environment, we have Windows user mode code that runs to provide emulations of various Windows API functions. And there are generally two types of Windows API emulations. Akin to those Windows API functions in a real Windows system. There are those that stay in user mode, which are ones that stay in the emulator. And those that resolve into a syscall, just like a trap to a native emulation here in Defender. Symbols indicate that these emulated virtual DLLs that are in the emulator environment are called VDLLs. And because they are simply DLLs, once we have a file system dump, we can just go reverse that dump, or reverse those DLLs by throwing them in IDA. And they're standard Windows PE files. When we look at them, they're definitely not the real implementations of things like kernel32 that you would see in a real system. So we'll see things like this. In kernel32, if we call get username, it'll return a hard-coded string of John Doe. This is, again, something we could use to create a VSM hour that says if I see the username John Doe, I'm not going to run. We'll see a computer named Hal9000, ostensibly an Arthur C. Clarke Space Odyssey 2001 reference. So again, you could write malware that looks for Hal9000 and know you're running inside Defender. We'll also see very simple limitations of functions like RTL getCurrentPib. All that function takes is it needs to just go grab a memory segment at FS18. So they actually support memory segmentation at the architectural level, so they can just do that actual instruction inside the emulator. Or we'll see complex functions like RTL setSancleSecurityScripter just nopped out. They just returned zero. More functions just stubbed out, returning zero, negative one, and so forth. They're just triggering an interrupt. So lots of complex functions are not fully emulated by Defender. We'll also see things like this. Again, more unique strings and identifiers that we know were running inside Defender, like these German IP addresses and references to German websites. Maybe a German programmer developed this particular DLL emulation. So that covers some of the user-mode code and the very simple emulations, those that just return hard-coded names like John Doe or Hal9000. How about the user-kernel-privilege boundary? And how do we get into more complex emulations, such as those requiring access to a virtual file system? These functions are implemented with a hyper-call-like instruction called apicall. This is, of course, not a real x86 instruction with the opcode 0fff0, and then a 4-byte-immediate describing the particular function to be invoked. But when this instruction is called on the virtual CPU, it's going to generate a call into a native mpengine.dll function that provides emulation of these unique functions. So these are complex functions that modify system state or may require particularly complex handling. And so in copy-file-worker, we have an API call to kernel32.copy-file.wworker. The virtual CPU sees that instruction, generates a call directly into this emulation of that function, and then it's emulated there in software in mpengine.dll. This is a great attack surface if you found any vulnerabilities in these native emulation functions. You could use these to break out of the emulator and infect the native host. This disassembly here is provided by an IDAProcessor module, and I'll have an article coming out in POCR GTFO issue 19 describing exactly how this IDAProcessor extension module works. So once we have these apicall instructions running, they're going to trigger a call to a function that looks at the gsyscalls table, which is a big table of these function pointers and these hashes. That's going to look for the 4-byte immediate that was called from the apicall instruction and then dispatch to the appropriate function that matches up with it. So kind of a workflow of what this looks like. Inside the emulator here, we have kernel32.output-debug string a. It's going to do things like log the number of times it was called. So if it's called more than 900 times, that might trigger some unique behavior. But ultimately, it's going to resolve down into this function apicall kernel32.output-debug string a. Which is then going to use the apicall instruction. You can see the 0fff f0 bb1480 b2. It's going to see that instruction. And then the hypercall is going to step in and basically transition us into native emulation out of this managed dynamic translation context. And we're going to hit the native emulation for output-debug string a. Of course, this is what we hooked when we had our own output-debug string a implementation that I was using to post information out of the emulator. Enumerating the emulated functions that have native emulations. These are them. The yellow functions are those that are not found on real Windows systems. So they're specific to Defender, for example, for debug functionality or unique backdoor management. Here's more of them, including a number of VFS functions, which are for low-level access to the virtual file system. So all these native emulation functions take a pevarst, a very large half-megabyte large structure containing everything about a given emulation context. And then we have templated parameters functions that are used to retrieve parameters to the function from the emulated stack. And then programmatic APIs for manipulating return values, register state, the CPU tick count, or time. All that sort of stuff can be programmatically managed through manipulations of the pevarst structure. Virtual memory can be interacted with with an API similar to that found in many emulation engines, such as Unicorn Engine, where we can memory map virtual memory into our real memory space and manipulate it there. And there are wrapper functions for common operations, like reading a single byte, writing a single D word, reading or writing wide strings or regular char stars. These all have kind of these utility functions wrapped around them to make them easier for developers. Moving into kernel internals. So we've talked about the user mode code. We've talked about how the user mode code gets into kernel mode or the native emulations. Let's look at how those native emulations are themselves implemented. So the Windows kernel provides a number of facilities to any binary. This is ntoskernel.exe and associated drivers. And these are really the core of the Windows OS or the NT kernel. These include examples like the object manager, process management, file system access, the registry through registry hives, and synchronization primitives for IPC. First off, we're going to talk about the object manager. This is an essential part of the Windows executive that provides management for handles. So anytime you are opening a file, a socket, so forth, it's going to go through the object manager. And Defender supports five types of objects. So these are file, thread, event, mutant, which is a singular of mutex, and semaphore. And these are stored in the big object manager map here in mpengine.dll. They're stored in memory as C++ objects, and they all inherit from a common parent class, object manager object. We then have subclasses like file object or mutant object. And you can see I've made a little larger for the font the unique traits to those particular C++ objects, such as the mfile handle thing in the file object, or the wait count variable for a mutex, if various processes can wait on a given mutex. C++ RTTI is used to cast between these subclasses to their parent class when they're retrieved. And the object manager can be interacted with programmatically by these various functions. So if we open a mutant, they're going to grab that object and then mess with it. If we open a file object, it's actually going to call through a function object manager, get file object, which will first check the type and then explicitly use RTTI to cast to a file object and fail if the retrieved handle is not indeed a file handle. We'll also see things like the pseudo handle for current process is emulated as hex1234. Again, a trait of the emulator we could use to write evasive malware based on seeing that our own handle is 1234. We have a virtual file system that provides emulation and access to a file system. And this is accessed through the standard NTDLL, NTWriteFile, NTCreateFile, and so forth APIs, as well as these lower-level VFS functions, which provide sort of a backdoor, unsanitized access to the file system emulation. Finally, moving into talking about AV instrumentation, so the heuristics and analyses the AV is doing throughout the runtime. So there are some internal functions that are exposed through the HyperCall API call interface, and I've summarized them here. And we're going to look at a few of these. First off, MPReportEvent, which is used to communicate information about malware binary actions with Defender's heuristic detection engine. So these are in some of these user mode emulations, such as getUsername or getComputerName. Those don't require trapping into a full native emulation, and that would increase the attack surface greatly if they all did, but we do want to inform Defender that the given function was called. So if getSystemDirectory is called, it'll report event 12331, or if you create a process and you do it suspended, it'll do hex 3018, but it'll say create suspended, specifically noting that a process like that was created. MPReportEvent can be called in more cases. You can see here just more examples. This is called thousands of times throughout these VDLLs. And a more concrete example of how this might play into AV identification of potentially malicious binaries is here where we see that if we call terminateProcess on a PID in the 700 range, which you'll note that all these various AV processes are in the 700 range, it'll trigger a call to MPReportEvent 12349, but it'll also say AV. So if you try to terminateProcess on an AV, that's probably a good indicator you're malicious. NTControlChannel is sort of a backdoor interface for administering the engine. This is something Tavis Ormandy hit, and I went here and reverse engineered the 32 switch case options of this function and showed you what they all do. So these do things like manipulate the rewrite microcode, manipulate register state, all sorts of stuff. Great attack surface and definitely something that shouldn't be open to malware binaries running inside the emulator. We're going to conclude by talking about vulnerability research. Let's start off by trying to understand some prior vulnerabilities discovered by Tavis Ormandy at Google Project Zero. So Tavis discovered this API call instruction that I talked about, and he was able to call directly into native emulations of functions rather than passing through their API call stubs by just generating the API call instructions on the fly, as you can see here. And then Tavis was hitting internal debug functions like NTControlChannel, which when you give it option hex 12, it goes to rewrite microcode, and this code here lets the user specify the count in a tight loop, and with the user-specified count, we only have, I think, 1,000 elements allocated for the new microcode information, but the user can give it, say, 2,000, and we have a linear buffer overflow. Microsoft patched this by adding a check that the count is no greater than 1,000, and if it is, it returns zero. Tavis also looked at the virtual file system, and by calling directly into these unsanitized functions to access the virtual file system, was able to basically get a linear heap read and write primitive by creating a file with these, you know, strange sizes, and this sequence of calls could crash the engine with an out-of-bounds write. Now, I looked at the mitigations that Microsoft put in for the abuse of the API call instruction, which were primarily that Tavis himself was generating the API call instruction on the fly from the malwares.txt section, and then Microsoft added a check that says, is the call to the API call instruction, is it coming from a VDL page? And if it's not, it's going to deny the user the ability to invoke a native emulation function. This means that these API call instructions can only be invoked from code pages that are associated with a given VDL. They cannot be called from the malware binary. And in fact, if you call them, it'll do mpsetattribute, which will basically set a heuristic that you tried to call the API call instruction from your .txt section. This is really, really weird, probably a strong indicator of malicious intent. And I found that I could bypass this mitigation by simply finding the API call stubs in memory in our VDLs, which I can reverse engineer, and that can just bounce off the API call instruction and hit these interfaces with my own controlled arguments. So this is not good. I did report this to Microsoft, and they told me this is not a trust boundary, kind of a classic Microsoft response to a lot of vulnerability disclosures. That's not quite a trust boundary, you know, unless you actually found an actual vulnerability, like, you know, actual buffer overflow in there. The fact that there's this logical flaw that I can hit internal debug interfaces and do things like stop emulation right then and there or change microcode in the emulator, that's evidently not a vulnerability, according to Microsoft. So an example of a bypass here doing something pretty benign, just we're going to hit output debug string A. So I found in kernel32 the offset of output debug string A, and I can resolve that address and then treat that as a function pointer and just bounce off this emulation, and when this runs, we hit output debug string A. Now, more maliciously, we can sort of hit NT control channel, again, that internal debug interface left in by developer, so maybe debug or administer the engine, and we can set our own heuristics, like, for example, if we call virate body found, it will trigger an immediate malware detection. So a quick demo of that. So in this video, you can see we're calling output debug string A in the legitimate way, and then calling it with our output debug string A of use through this unintended interface kind of left there in the VDLL code page. Once we run and compile this binary, and we'll also hit NT control channel as well. And we're going to use NT control channel to check the exact version number of the engine. This was done in the February 2018 build of the engine. So with our kind of RET2 API call technique, we run this binary, and we'll see we hit debug string A the normal way, then through the API call with kind of the bypass from Microsoft's mitigation, so we have a controlled argument going in there. And we also show that we can hit NT control channel with a controlled argument as well. Now, again, the implications of this is we can hit these internal debug interfaces with attacker-controlled arguments, probably not a good idea. Finally, I want to talk a bit about fuzzing. So I was able to then fuzz emulated APIs, basically working out some more complex mechanisms to allow our changes for the channel to be a two-way I.O. channel, not just an output channel. And I took MWR Labs' OSX kernel fuzzer, which generate random values to fuzz the OSX kernel, and I folded that in with my code, generating random values at each time. And then I pushed those into the emulator, and I was able to do things like fuzz NT write file, and actually reproduce Tavis' crash, but in a unique way that got around the sanitization that NT write file normally does. I reproduced his crash in VFS write, but through NT write file without having to abuse the API call instructions. You can see in this demo here, we're going to do that. We're going to resolve the address of NT write file, and then fuzz that. And this whole mechanism here with the params, this is a more complex interface that I have for passing information in and out of the emulator. And basically on the outside of the emulator, we're generating fuzz input to give to inside of it. And we're calling NT write file with those fuzz parameters and seeing what happens. So running this, you're going to see it just run for quite a while. It's just going to keep running. In my experience, it took about seven minutes running single-threaded to around 8,000 system calls per second to reproduce Tavis' crash. Again, this is not a smart fuzzer. There's no AFL. There's no code cover information. It's just a dumb, random values at Windows Defender in order to fuzz it. There's our demo. And moving into the conclusion. We covered tooling and instrumentation, CPU emulation basics for X86 binaries, and a bit on vulnerability research and fuzzing for Windows Defender. We didn't cover a whole lot of other stuff. For example, X64 emulation, ARM emulation, VM protect emulation. The 16-bit emulation, there is a full DOS emulator aside from the Win32, you know, modern Windows system emulator. There's a 16-bit emulation built into Defender. Really interesting attack surface as well. Probably not as well as Windows Defender. It's not as well looked at as the 32-bit one. We didn't look at the threading model, how you can do multi-threading for binaries inside emulators. That's always a source of problems for MV emulators at large. So, worth looking at. We're also analysis for .NET binaries. We're primarily looking at Windows PE binaries that are just compiled X86 code. Also inside MP Engine, we have unpackers, parsers, a JavaScript engine, which you can see in my Recon Brussels talk. Other scanning engines and a .NET engine. Now, I want to say that people love to talk about AVs and what they can and can't do. Where they weigh or may not be vulnerable. But there's not a lot of ground truth about AVs in the public. And I think there should be more. I think they're a really fascinating target to analyze. I think they're a lot of fun. I think this is much more interesting to me, at least, than looking at malware. Actually seeing how malware gets caught and mitigated and detected. And you also learn a whole lot about, say, NT kernel internals and object managers and things like that. It gives you an impetus to look at all these different technologies. A bit on Hoxian's work, but there's really not a whole lot out there. I really like this tweet from Hoxian where he said, if you Google antivirus internals, all you find is me, him, and then Tavis Armandy. I would say if you like this sort of work, definitely grab a copy of his book. It's an awesome book and really underappreciated by people. Just some really incredible work that went into that. I'll be releasing some code later. Here's my GitHub. I'll also tweet about this. So no worry, you don't have to take a picture of the slide. But I'll be sharing some of the harnesses that I built and IDA disassembler for the API. I'll also be publishing an article in POCR GTFO issue 19, describing more of this with more technical details of some of these technologies. And that concludes the presentation. I'll have a whole lot more slides being released online after this. This is only about 50% of the material that I prepared for today. My JavaScript slides are over there at that bit.ly link. I want to thank all my friends, Tavis, Marcus, Hoxian, and then numerous friends who helped me edit this presentation and get it here to DEF CON. Hit me up on Twitter if you have any questions. I have open DMs. Thank you very much. . . . . . .