NO-MERCY Posted February 25, 2014 Report Posted February 25, 2014 Hello RST ...First : This Article written by : Jared DeMott | Security Researcher jared.demott@bromium.comyou can download This article as pdf from here :--vhttp://bromiumlabs.files.wordpress.com/2014/02/bypassing-emet-4-1.pdfSrc : Bypassing EMET 4.1 | Bromium Labssecond : This very important ... your focus pls :-/---------------------Table of Contents :---------------------2.0.0 Executive Summary 3.0.0 Results Summary 4.0.0 Methodology and Techniques Used 5.0.0 Introduction 6.0.0 ROP Background -- 6.1.0 EMET ROP Protections -- 6.1.1 LoadLibrary-- 6.1.2 MemProt-- 6.1.3 Caller -- 6.1.4 SimExecFlow -- 6.1.5 StackPivot 7.0.0 Bypassing EMET ROP Protections Using Sample Programs -- 7.1.0 Experiment Setup -- 7.2.0 Caller -- 7.3.0 LoadLibrary-- 7.4.0 MemProt-- 7.5.0 SimExecFlow -- 7.6.0 StackPivot -- 7.7.0 Example Problem Summary 8.0.0 Real World Example -- 8.1.0 A Better Version -- 8.2.0 EMET Blocks the Exploit -- 8.3.0 Upgrading to Bypass EMET -- 8.4.0 Real World Summary 9.0.0 Related Work 10.0.0 Conclusions 11.0.0 Disclosure and Thoughts on Repair 12.0.0 Bibliography Lets Start : 2.0.0 Executive SummaryThe goal of this study is to gauge how difficult it is to bypass the protections offered by EMET, a popular Microsoft zero-day prevention capability. We initially focused on just the ROP protections, but later expanded the study to include a realworld example. We were able to bypass EMET’s protections in example code and with a real world browser exploit. Theprimary novel elements in our research are:-- 1. Deep study regarding the ROP protections, using example applications to show how to bypass each of the fiveROP checks in a generic manner.-- 2. Detailed real world example showing how to defeat all relevant protections. Including a technique to bypass thestack pivot protection, shellcode complete with an EAF bypass, and more. The bypasses leverage genericlimitations, and are not easily repaired.The impact of this study shows that technologies that operate on the same plane of execution as potentially maliciouscode, offer little lasting protection. This is true of EMET and other similar userland protections.3.0.0 Results SummaryWe found that each protection either did not apply in our examples or could be bypassed. Table 1 shows a brief summary.4.0.0 Methodology and Techniques UsedWe studied EMET 4.0 and 4.1. We use a typical modern computer, and focus on 32 bit userland processes running on 64bit Windows 7. None of the ROP protections are implemented for 64 bit processes (Dabbadoo, 2013) and thus a studythere was not very interesting. The only kernel specific mitigation is the NullPage mitigation designed to make NULLpointer exploits difficult, which also wasn’t as interesting as userland process mitigation bypasses. Also, we focus onbypassing EMET defenses rather than on tricks to disable EMET (which would likely be just as effective).5.0.0 IntroductionAs part of the ongoing effort at Microsoft to making computing more trustworthy, they have released a protection forWindows known as EMET, or Enhanced Mitigation Experience Toolkit. Microsoft researchers Neil Sikka (Sikka, 2012),Elias Bachaalany (Bachaalany, 2013), and others have given excellent technical talks on EMET.EMET is a product which can be installed in Windows with the intent of adding further mitigations, to stop commonexploit patterns and techniques. Many of the ROP 1 protections in EMET came from the second place winner (Fratric,2012) BlueHat prize contest in 2012 2 . Since I was one of the winners (3 rd place), who also submitted a ROP protection, Ifigured I would circle around and see how robust the mitigations that made it into EMET are.Note :-1 Return-oriented programming - Wikipedia, the free encyclopedia6.0.0 ROP BackgroundROP, or return-oriented programming, is a modern exploitation technique. ROP is an evolution of the ret2lib 3 code reuseidea: bouncing through code that already exists when new code cannot yet be injected and executed because of memoryprotections. The typical attacker approach is to minimize the ROP portion (because it is painful to write), and use ageneric payload (called a shellcode) after the ROP portion. Thus, the ROP portion traditionally just changes executablepermission on the current page to execute, or allocates a new executable page. But first, a pivot is often required. That is,the stack pointer needs to be adjusted such that it points into attacker controlled data, because each gadget (small/usefulchunk of existing code) is just an address which is returned into, and typically ends with a return instruction, to executethe next gadget.6.1.0 EMET ROP ProtectionsEMET offers 5 ROP protections, which can be enabled and disabled for each protected application. Figure 1 shows eachof the protections. All of them are enabled for our sample program called vuln_prog.exe. Each of the protections isdescribed in brief below.Figure 1: The 5 EMET ROP Protections6.1.1 LoadLibraryLoading a library is a common need in attacker shellcode; to pull in various API functionality. Thus, LoadLibrary ishooked (detoured as it’s called) and extra sanity checking is done to ensure its use is “valid”. For example, UNC pathsare disallowed. How robust is this checking? That is the question we wonder about each of these protections.Also note: there are about 50 functions which are considered “critical”, e.g. hooked. They are jump hooked. Whichmeans it may be possible to jump around the hooks as a possible bypass 4 . This technique is well known and may be DLLspecific so we did not investigate that approach.Note :-2 Microsoft BlueHat Prize Contest3 Return-to-libc attack - Wikipedia, the free encyclopedia4 EMET uses “anti-detours” to prevent the simplest form of the jump-around bypass. Attackers will need to carry over and replicatemore opcodes from the different function prologues and not just the first 5 bytes hooked by the JMP, as is commonly done.6.1.2 MemProtThe MemProt rule checks memory protection functions like VirtualProtect to make sure they are not trying to mark stackmemory as executable for shellcode to be run in.6.1.3 CallerBefore a critical API is allowed to run, EMET disassembles backwards from the return address (and upwards) and verifiesthat the target is CALLed and not RETurned or JMPed into.6.1.4 SimExecFlowAfter a critical API completes, this protection simulates execution forward to ensure the code following it looks normal(and not ROP). The first return address is given on the stack. The subsequent return addresses are deduced by simulatinginstructions that modify the stack/frame pointer. Each return address must be preceded by a call instruction to appearnormal. For both the Caller and SimExecFlow check, legitimate code could break the rule at times, making me wonderabout the robustness of this check.6.1.5 StackPivotUpon entering a critical function, EMET checks to ensure that the stack pointer is within the threads upper and lowerspecified stack limit. This, guards against pivoting the stack pointer to, say, heap memory controlled by the attacker.7.0.0 Bypassing EMET ROP Protections Using Sample ProgramsWe discuss the work toward bypassing each of the 5 protections below.7.1.0 Experiment SetupEMET 4.x was first installed on our test computer. To test the 5 ROP protections, we created a simple program(vuln_prog.exe) which has a trivial stack 5 buffer overflow vulnerability via a file read. That program is protected byEMET as shown in Figure 1. For the vulnerability, we assume that the attacker has:--1. control over the input to trigger the bug--2. an additional memory leak/information disclosure bug 6--3. and can thus find gadgets in memory in the discovered and sizable DLL.To simulate those conditions we cheat a bit:1. We use msvcr71.dll as our discovered DLL, since it was so often abused in the past 7 .2. We therefore don’t have to spend much time fiddling with a real memory leak bug, and searching for gadgets(since that is not the focus of this study). In some cases we even disable ASLR on the main binary and addgadgets to the .exe if proper gadgets aren’t immediately obvious in msvcr71.dll. The assumption is commongadgets can always be found, we just didn’t want to spend time on that. Thus, any part of this experiment couldbe changed (the type of vulnerability, the discovered DLLs, etc.) to affect negatively or positively the findings.7.2.0 CallerOne of the most straight forward checks is to see if a detoured function is called, or RETed into (the latter being bad).Figure 3 shows the event log for the ROP chain shown in Figure 2.Note :-5 We later also created one with a heap overflow to test the StackPivot protection.6 Some would argue that these ideal exploitation conditions are rare, but as shown in the real world section, it is not so rare.7 https://www.corelan.be/index.php/security/corelan-ropdb/ and http://www.whitephosphorus.org/sayonara.txtFigure 2: Typical VirtualAlloc ROP chainFigure 3: EMET Blocking the VA ROP codeEMET successfully blocked a typical VirtualProtect/VirtualAlloc based ROP chain. The log says “CallerCheck Failed”and some details are given.While there may exist multiple ways to bypass this check, the simplest are probably:? Use an API other than VirtualProtect/VirtualAlloc, where such APIs exist; E.g. use a non-protected function? Or find existing code that does a valid ‘call’ to one of those two APIsWe choose the first, and called the MSDN Beep function 8 that is within msvcr71.dll. That worked, but seemed too trivialto be an impressive bypass, since Beep doesn’t do anything useful. So we also choose the latter approach. Figure 4Note :-8 Beep function (Windows)shows a call to VirtualAlloc found in msvcr71.dll. Figure 5 shows the new ROP chain. Figure 6 shows that we are nowable to bypass this EMET check and run shellcode. The !vprot command in Figure 6 shows that we did in fact allocate apage with read-write-execute permissions. Note: the shellcode is simply three increment operations and a softwarebreakpoint (int 3).Figure 4: VirtualAlloc Call in msvcr71.dllFigure 5: New VirtualAlloc ROP ChainFigure 6: CallerCheck BypassedInterestingly, this simple technique, bypasses all of the other ROP checks as well. We know this because no other EMETalerts are triggered. If you are not doing certain behaviors as part of your attack, certain checks will never be triggered.But, this example isn’t real enough, because it lacks a meaningful payload. So, we exchanged the simple NOP/breakpointshellcode we had, to a stock Metasploit 9 reverse shell payload. Let’s explore this more in the next section.7.3.0 LoadLibraryFigure 7 shows that EMET will catch a stock Metasploit payload. And it happens at the LoadLibrary (LL), but it’sbecause of the caller check. The LL rule just checks to see if a UNC path is used to load a remote DLL, which we do not.As before we can call to LL, rather than jump for a bypass here. If we do that, Figure 8 is we see.Figure 7: Stock Metasploit PayloadFigure 8 shows that EMET caught our Metasploit payload, but only after the attack succeeded. A non-ROP rule calledEAF filtering gets triggered 10 . We’ll explain the EAF check in detail in the real world section of this paper.Note :9 Penetration Testing Software | Metasploit10 Normally the EAF check would trigger before the Shellcode finishes running, and the damage is done, but in this case it wastriggered after we exit the reverse shell. Either way, the EAF check is trivial to bypass as is shown later.Figure 8: EMET Blocks a Connect Back Metasploit Payload after the shell is closedRather than use a typical Metasploit payload (which EMET may catch), we created our own shellcode (Figure 9) whichperforms similar actions. For example, LoadLibrary and GetProcAddress are used, as they would be in real payloads(except we CALL rather than JMP as Metasploit does).Figure 9: Custom LoadLibrary ShellcodeFigure 10 shows the new ROP chain, which uses the custom shellcode we copy into the VirtualAlloc’ed page. Theshellcode works to bypass EMETs ROP protections; shown in Figure 11.Figure 10: ROP Chain for our Custom LoadLibrary payloadFigure 11: Custom LoadLibrary Payload Bypasses EMET ChecksThe bypass works because we do not directly RET/JMP into detoured functions. Rather we find locations in code that callthe functions of interest and instead RET to those locations.7.4.0 MemProtThe MemProt rule is triggered when VirtualProtect is called, and checks to see if we are remarking stack pages. Since wedo not use VirtualProtect to mark stack pages with this shellcode, this rule is inherently bypassed.7.5.0 SimExecFlowSimExecFlow is trigger after a critical call. It is similar to the caller check triggered before a call. SimExecFlow attemptsto verify that the flow of execution that is about to happen is legitimate code; not ROP code. It does this primarily bychecked to see if legitimate calls were used rather than RETs to locations. Since we return to code that legitimately callsthe critical function (VirtualAlloc), this is rule is also bypassed.7.6.0 StackPivotWe do a pivot in our attack, but since (in our first example) the attacker controlled data is on the stack, this check passeswithout issues. To make things more interesting, we constructed another program where our input is on the heap. Wechanged the bug to be a function pointer overwrite on the heap. In light of the current threat landscape (better OSmitigations and less simple bugs), this type of attack is more common than stack overflows.To bypass the StackPivot check, we first use a relocation copy loop to move our ROP chain from the heap to the stack. Inour code it is all one assembly code, but in reality it would be a series of ROP gadgets chained together to achieve a similar result. Next we call VirtualAlloc. Then we copy our custom shellcode to the RWX address from VirtualAlloc.Each of the copy operations are shown in Figure 12.The payload we ultimately run is the same as in Figure 9. The pivot copy loop and payload to VA copy are shown inFigure 13. One critical question would be: can such gadgets really be found? We assume that they could be, based on anumber of papers that aim to show the Turing-completeness of ROP (Homescu, 2012) techniques. In the next section, weexperiment with a real world problem to investigate this assertion.7.7.0 Example Problem Summary-- 1. We did not directly RET into critical APIs, and thus bypassed the Caller and SimExecFlow rules.-- 2. We avoided UNC paths to bypass the LoadLibrary rule.-- 3. We did not attempt to use VirtualProtect on stack pages, thus bypassing the MemProt rule.-- 4. We avoided the StackPivot rule by (copying and) running our core ROP chain on the stack, and then jumping towherever our shellcode was.Figure 12: Heap --> Stack --> VirtualAlloc’ed MemoryFigure 13: Pivot Copy and Shellcode Copy8.0.0 Real World ExampleCVE-2012-4969 is a use-after-free (UAF) IE bug reported on September, 14 2012 by Eric Romang. There is a publicexploit for it in Metasploit. Like all Metasploit modules, the exploit is not sophisticated because it depends on thepresence of a non-ASLR module. EMET will block the Metasploit exploit, because by default EMET forces all modulesto use ASLR. Also, as shown in the prior sections, EMET will block standard Metasploit payloads.8.1.0 A Better VersionWe have a better exploit for this same bug. It comes from Peter Vreugdenhil of Exodus Intelligence. His exploit is moresophisticated in the sense that it dynamically finds the base address of ntdll.dll 11 , builds a ROP chain based on thataddress, and runs a custom WinExec shellcode 12 . After some minor tweaks to the ROP chain, the exploit workedperfectly in our 64bit Windows 7 VM against 32bit IE 9, without EMET installed.8.2.0 EMET Blocks the ExploitWe tried the exploit again, but now with EMET 4.1 installed. EMET blocks the exploit via the stack pivot check 13 .That’s because this exploit attempts to use VirtualProtect to mark the heap as RWX while ESP (because of the stackpivot) is pointing to the heap, rather than the legitimate stack.8.3.0 Upgrading to Bypass EMETWe were curious to see if the exploit could be enhanced to bypass EMET 4.1, using the research we discussed earlier inthe paper. Primarily of interest, we wanted to see if we could develop a generic EMET bypass technique for the stackpivot check, because this protection has not been publically bypassed to our knowledge 14 . Other researches (see relatedworks section) have talked about ideas or techniques to bypass some of the other protections.Note :11 The base address of ntdll.dll is determined based on the pointers at shared data: 0x7ffe0340. These pointers were only set on 32bitcode running on 64 bit Windows. This shared data bug has now been fixed in Windows. However, this same UAF IE flaw could bemodified to leak the base address of a DLL in another way, so the fact that the original technique is now patched is not very relevant.12 Based on Berend-Jan Wever’s code such as: win-exec-calc-shellcode - A small, null-free Windows shellcode that executes calc.exe (x86/x64, all OS/SPs) - Google Project Hosting13 Or sometimes the EMET checks will just cause the application to crash, and not properly report the EMET exception, but either waythe exploit is blocked. For certain failure types, like the StackPivot check, EMETs reporting capability is a bit unreliable in ourexperience. This is perhaps due to EMETs exception chain being damaged.14 After writing this paper we found out that Dan Rosenberg had a very similar idea some years earlier: Security Research by Dan RosenbergOur stack pivot bypass idea is simple (and similar in spirit to the example problem previously discussed):1. Pivot the stack pointer to the heap as normal2. Use a first stage ROP chain to “pop-copy” the second stage ROP chain to the stack3. Unpivot back to the stack and execute the second stage, which uses VirtualProtect to mark the heap as executable4. For the final stage, jump off the stack, back to the heap and execute a EMET friendly exploit payloadThe pop copy we used is based on ntdll 15 and works as shown in Figure 14.Figure 14: Pop-CopyThe pop-copy works by popping a DWORD from the input data, and copying it to the desired location (the stack in this case) via a dereferenced move. Then the destination pointer (the stack) is incremented (by 4 for a 32bit system). Thisparticular pop-copy is not space efficient as it produces a total ROP chain that is six times the original size, but this did not matter in our particular example. Work could likely be done to find a more efficient pop-copy gadget.The second stage ROP chain that executes on the stack operates as shown in Figure 16. This ROP chain operates by marking the relevant heap page R/W/X (read, write, and executable) via a VirtualProtect like function. The Figure 16chain works by setting up arguments for a call to an undocumented ntdll function, NtProtectVirtualMemory, which is a system call. We found that NtProtectVirtualMemory is only hooked when “deep hooks” are enabled. Since deep hooks are off by default, this is a wonderful discovery. Perhaps deep hooks will stay disable for some time as well, due to compatibility issues 16 . The unhooked version of NtProtectVirtualMemory for WOW64 17 IE is pictured in Figure 15.Finally, the second stage ROP chain jumps back to the start of shellcode that is on the executable heap page.Figure 15: Ntdll!NtProtectVirtualMemoryNote:15 The hex number in front of each pictured ROP gadget is the offset which is added to the base address of ntdll to achieve the propergadget address with ntdll.16 After discussing the matter with the EMET team, they claim the compatibility problems are with other security software, and not theprotected applications. They are reconsidering turning deep hooks on by default.17 WoW64 - Wikipedia, the free encyclopediaFigure 16: Second Stage ROP ChainEach of the gadgets shown in Figure 16 is wrapped in the pop-copy gadget shown in Figure 14. Figure 17 shows the firsttwo gadgets wrapped in a pop-copy. Appended to that final string is the actual shellcode to be executed. After the typicalexploit development challenges, plus an interesting challenge described in the next paragraph, we succeeded in bypassingthe EMET stack pivot check. The exploit payload is a variation of a typical WinExec shellcode, which simply starts up acalculator, as is the norm for such demonstration exploits.Figure 17: Wrapping ROP chain in pop-copyFor our final trick, we do not just bypass the stack pivot, or merely all the ROP checks, but we bypass all of the EMETchecks in our enhanced exploit. Once we had the stack pivot protection bypassed, EMET was blocking our exploit withthe EAF (Exploit Address Filtering) check (as was happening in our earlier Metasploit payload example). So, we had toadd stub code based on Poitr Bania’s 18 Windows XP EAF bypass idea. As far as we know, this bypass is also new as it relates to Windows 7 19 , because we had to modify Bania’s idea to get it working. Figure 18 shows the EAF bypassshellcode. The bypass works by calling NtSetContextThread to disable the current threads hardware breakpoints, which ishow EMET detects that a shellcode is attempting to resolve functions via the export table.Note :18 http://piotrbania.com/all/articles/anti_emet_eaf.txtFigure 18: EAF Bypass For Win7 32bit on 64bit8.4.0 Real World SummaryWe bypass or ignore all 12 EMET protections with this exploit. In particular, we were required to focus on bypassing: 1. The stack pivot protection. We avoided it by using a pop-copy to the stack, a second pivot to the stack to executecritical ROP code, and a final jump back to an EMET friendly payload. 2. The EAF filtering. We disabled this protection, by clearing the debug registers, which are key to the protection. 3. Finally, and surprisingly, we bypass the remaining checks by calling an unprotected version of VirtualProtect 20 .9.0.0 Related WorkWe are not the first researchers to show that EMET could be bypassed. The following is a partial list of other researchersthat have conducted EMET research:? SkyLined showed how to bypass the export address filtering in EMET 2.0 21 .? Shahriyar Jalayeri 22 bypassed EMET 3.5 by resolving the ZwProtectVirtualMemory system call via a sharedmemory pointer, to mark his shellcode R/W/X. Once his shellcode was running he disabled EMET as his primarybypass technique. He released an exploit for a CVE-2011-1260.? Aaron Portnoy showed how to bypass EMET 4.0 during a Nordic Security Conference talk (Portnoy, 2013).? 0xdabbad00 released a paper called EMET 4.1 Uncovered (Dabbadoo, 2013), in which he explains EMET, anddiscusses some hypothetical strengths and weaknesses of the EMET protections.Note :19 In particularly, we’re using the 32bit version of Internet Explorer 9, on 64bit Windows 7.20 Enabling the non-default deep hooks would help catch this bypass, but we assume other bypasses could be found, and doubt userswill change from the default EMET settings.10.0.0 ConclusionsDeciding whether a program is good or bad was essentially determined to be impossible by Alan Turing in 1936 – before the first computer was ever built 23 . Each EMET rule is a check for a certain behavior. If alternate behaviors can achieve the attacker objectives, bypasses are possible. In fact, the ROP protections from the second place BlueHat Prize winner that made it into EMET do not stop ROP at all. The notion of checking at critical points is akin to treating the symptoms of a cold, rather than curing the cold. Perhaps one of the other prize submissions would have better addressed the problem of code reuse.However, as was seen in our research, deploying EMET does mean attackers have to work a little bit harder; payloads need to be customized, and EMET bypass research needs to be conducted. Thus, EMET is good for the price (free), but it can 24 be bypassed by determined attackers. Microsoft freely admits that it is not a prefect protection, and comments from Microsoft speakers at conference talks admit that as well. The objective of EMET is not perfection, but to raise the cost of exploitation 25 . So the question really is not can EMET be bypassed. Rather, does EMET sufficiently raise the cost of exploitation? The answer to that is likely dependent upon the value of the data being protected. For organizations withdata of significant value, we submit that EMET does not sufficiently stop customized exploits.11.0.0 Disclosure and Thoughts on RepairThis whitepaper was provided to Microsoft long before speaking about these weaknesses publicly, to provide Microsoft with opportunity to address short comings. In particularly we believe addressing the following weaknesses would help:1. Hook NtProtectVirtualMemory by default2. Create a new EAF protection scheme 263. Check more than one CALL deep to see if code was RETed into4. Expand the ROP mitigations to cover 64 bit codeBut even with those fixes, many of the weaknesses are generic in nature and unlikely to be sufficiently addressed by userland protection technologies like EMET. E.g. EMET does not protect against kernel vulnerabilities, or help against non-exploit attacks such as Java sandbox escapes. Other similar technologies like Anti-Exploit 27 and Core Force 28 suffer from the same generic problem: mitigations that run on an even playing field with malicious code will/can be bypassed given sufficient attacker interest. To counter such attacks, we believe that an approach that does not rely on exploitation payload based vectors is needed. As demonstrated, exploit payloads continue to evolve 29 .Note :21 Original link dead, but mentioned here: '[Full-disclosure] Bypassing Export address table Address Filter' - MARC22 EMET 3.5 with ROP Mitigation Bypassed by Expert, Microsoft Responds23 Halting problem - Wikipedia, the free encyclopedia24 Depending on the exact nature of the bug and exploitation scenario: UAF bugs can typically defeat DEP/ASLR in browsers.25 Security Research & Defense - Site Home - TechNet Blogs26 Though that still wouldn’t stop shellcode that doesn’t use EA resolution27 https://www.malwarebytes.org/antiexploit/28 Corelabs site29 On a personal note: Though EMET is far from perfect, I personally see Microsoft making more of an effort toward securitycompared to other large vendors; for that I applaud them.12.0.0 BibliographyBachaalany, E. (2013). Inside EMET 4.0. Recon. Montreal: http://recon.cx/2013/slides/Recon2013-Elias%20Bachaalany-Inside%20EMET%204.pdf#!Dabbadoo. (2013). EMET 4.1 Uncovered. http://0xdabbad00.com/wp-content/uploads/2013/11/emet_4_1_uncovered.pdf.Fratric, I. (2012). Runtime Prevention of Return-Oriented Programming Attacks. BlueHat Prize Contest.https://ropguard.googlecode.com/svn/trunk/doc/ropguard.pdf.Homescu, e. a. (2012). Microgadgets: Size Does Matter In Turing-complete Return-oriented. WOOT. Bellevue:https://www.usenix.org/system/files/conference/woot12/woot12-final9.pdf.Portnoy, A. (2013). Bypassing all of the things. Nordic Security Conference ? The venue for all people interested in security ? Aaron Portnoy – Bypassing All of the Things.Sikka, N. (2012). Microsoft EMET Exploit Mitigation. NullCon Security Conference. Delhi: !------------------EOF-----------------------Regrads NO-MERCY 1 Quote