The Fundamental Weakness. “ If it executes, we can unpack it.”
Fundamental Weakness No matter how an executable is packed, it MUST be unpacked at runtime for my CPU to run it!  My CPU has to run the plaintext, unpacked binary at some stage! I don’t care if its packed using 2048bit RSA, my CPU only runs straight x86 ASM. Its all really about the timing. If we want to get the unpacked data, we need to know the exact moment and location where the data will be unpacked and available. It may only be available and intact for a very short amount of time.
PE Unpacking
Objectives of PE Unpacking Re-create the executable, in its original form, before it was packed. This allows us to perform static analysis on the now unpacked ‘payload’ data. We should not need the PE packer stub again, so we can delete it. Bring the executable back to its virgin state. Before it was packed.
Objectives of PE Unpacking Step #1. Locate the OEP (Original Entry Point) jump. After the PE packer has finished unpacking itself and has populated the Import Address Table of the ‘.PACKED-DATA’, it will usually reset/clear any stack registers it was using. Shortly after this, a jump/call will occur that will start the execution of the now unpacked data.  This is the OEP Jump The destination of this jump is the EntryPoint of the unpacked data!
It looks something like this.
Objectives of PE Unpacking Step #2 – For The Old School Only If your true old school you of-cause use Softice (A ring0 debugger). At this stage you need to manually suspend the application at the OEP JMP (Pause the process) Modify the OEP jump/call to be an infinite loop (JMP EIP). If you use OllyDBG, just ignore this. Guy on the left uses Softice, in-fact he use to work at Compuware.
-- Softice JMP EIP --
Objectives of PE Unpacking Step #3 :Dump the executable memory image The application is currently unpacked in memory, but has not yet begun to execute the unpacked data. We need to dump the memory image of the executable back to disk. We use a process dumping tool. After the memory image is dumped to disk we are left with a snapshot which contains both the unpacked (payload) data, and the PE packers ‘unpacking’ stub.
Objectives of PE Unpacking Step #4 : Change EntryPoint of dumped image. The dumped executable’s EntryPoint still points to the start of the PE Packer, the ‘unpacking’ routine. We want the executable to start running the unpacked data first, not the PE packer, we don’t need the PE packer anymore! We know the Original EntryPoint is 004035B0h, this is where the PE packer was going to jump to.
 
Objectives of PE Unpacking Step #4 Continued… Calculate the EntryPoint RVA All PE values are stored in RVA format. (Relative Virtual Address, an offset from the BaseImage) The BaseImage is where the application begins in memory. RVA EntryPoint =  OriginalEntryPoint – BaseImage 004035B0h  - 00400000h = 35B0h The Original EntryPoint is 35b0h bytes into the executable!
Objectives of PE Unpacking Step #4 Continued… Change the EntryPoint value in the PE header. Using a PE editor, such as LordPE/ProcDump we change the executables EntryPoint value to 35b0h. If we execute the executable now, it will start executing the unpacked data first, not the PE packer!
Objectives of PE Unpacking The dumped executable image is almost able to run, but it is still missing one vital piece of information. It does not have a valid Import Address Table! The current import address table is that of the PE packer itself! It only has three entries! LoadLibaryA() GetProcAddress() ExitProcess() Remember: The PE-packer uses LoadLibaryA/GetProcAddress to populate the Import Address Table of .PACKED-DATA!
Objectives of PE Unpacking Step #5: Rebuild the Import Address Table We need to find the Import Address Table of our now unpacked data. We need Windows to populate our import table with the correct values for each external function at runtime. Without it, the executable will not run.    and static analysis is also harder. We will overwrite the PE packers own Import Address Table (which only had three entries) with the correct table.
Objectives of PE Unpacking To do this, we use: ImpRec – Google “ImpRec MackT UCF” ImpRec will search the executable image in memory (starting from the OEP value) and should find our Import Address Table. We then dump it back to disk.
Objectives of PE Unpacking Once we have a copy of the import address table on disk, we re-insert it into the dumped executable. Overwriting the old Import Address Table with our “full bodied” table. Now when we execute the binary windows will populate the Import Address Table with the correct values, allowing us to use external functions. Code execution will start at the unpacked data, and bob’s your uncle!
Demo #1 PE Unpacking - UPX. Ok so we know what we want to do, lets do it. Notepad.exe Packed with UPX  (the  Ultimate Packer for eXecutables) UPX can be unpacked with upx.exe –d We will modify this binary though so upx will not recognize it, and fail to unpack it. Ok lets unpack it by hand.
PE Unpacking: Automation
PE Unpacking: Automation. That was easy, because UPX is an easy PE packer. Although it was easy it still took time. Time = Money Having to unpack 100 UPX packed binaries would become really tedious. Tedious = Not fun! Since we now know how UPX works, we should automate the unpacking process. So, lets write a quick, automated unpacking script for any UPX packed binary, so we don’t have to do this by hand again.
PE Unpacking: Automation. To do this will use OllyScript (The scripting language plugin for OllyDBG) OllyScript simulates a user’s debugging session within OllyDBG. We can place breakpoints, step, run, do all the normal OllyDBG tasks, only script them. OllyScript is important when dealing with PE packers, it can take hours to unpack a single protector. You don’t want to do it too often! Learning OllyScript is a  must  if you plan on doing any unpacking of your own.
PE Unpacking: Automation. We know the UPX code flow goes like this #1 – The target application is un-compressed. #2 – UPX will populate the packed data’s Import Table. #3 – POPAD #4 – JMP <OEP> The golden rule of UPX is “The first unconditional JMP after POPAD is the OEP JMP” This works on all versions of UPX, very simple.
PE Unpacking: Automation. So we write a script which does something like.. Search for the first POPAD in the code. Place a breakpoint on it Run the application Search for the next JMP instruction. Breakpoint again. Run the application again. We end up at the OEP JMP..  Finished.
Demo #2 PE Unpacking: Automation
PE Packers: Getting Tricky.
So far we have only looked at UPX, a straight-forward relatively friendly PE packer. UPX is a great way to learn how PE packers work, in essence all packers are very similar if not identical to UPX. But rarely are packers so straight-forward to follow and logical in nature. Most PE packers are designed with a focus on anti-unpacking, they don’t want you to unpack them!  The golden rule still applies though, eventually a packer must execute the unpacked code. Its just a matter of when! Getting Tricky.
Getting Tricky. #1 – Exceptions SEH - Structured Exception Handler  “ When an exception occurs, go here to handle the exception” The Goal:  Create an exception handler to catch an exception, then raise an exception. The Idea:  Code flow is passed to the SE handler. A major part of the PE-packer could be inside the SE handler. SEH code is used as a discreet way of going somewhere. Can also confuse novice reverse engineering attempts
Getting Tricky. Each SEH frame consists of two pointers. A pointer to the prev SEH frame.  A pointer to the exception handler for the current frame. If no exception handler is found to handle the exception, you end up with an ‘Unhandled exception’ A pointer to the SEH chain is kept inside FS:[0]  Thread Information Block - http://en.wikipedia.org/wiki/Win32_Thread_Information_Block
Getting Tricky. Example: PUSH TestVE.00401C84  ; Push to the stack the new top SE handler location MOV EAX,DWORD PTR FS:[0]  ; Save the existing top SE handler location to EAX PUSH EAX   ; Push it back to the stack, its now the second SE handler MOV DWORD PTR FS:[0],ESP   ; Move a pointer to the newly created SEH chain into FS:[0] XOR EDX, EDX   ; Clear EDX DIV EDX   ; Divide by zero exception 00401C84 is now the first SE handler. The old SE handler is now the second handler. When we land on DIV EDX we will cause an exception, this exception will be handled by the top SE handler.  Tell OllyDBG to Ignore all exceptions Set a breakpoint on 00401C84 Run the application.
#2 – Detecting a debugger Great way to try to stop a pesky reverse engineer is to detect his debugger. Windows API Calls. A call to IsDebuggerPresent() will return > 0 if the process is currently running in the context of a debugger, such as OllyDbg. Unable to detect kernel debuggers such as Softice Many other Windows API’s can be used to detect a debugger.  ZwQueryProcessInformation()  CheckIsRemoteDebuggerPresent() SetDebugPrivilege () Getting Tricky.
Getting Tricky. IsDebuggerPresent API just returns a byte in the PEB. The PEB (Process Environment Block) is a process specific area of user land memory which contains details of each running process. We find the location of the PEB from the TIB.  TIB->PEB->isProcessBeingDebugged Example: MOV EAX,DWORD PTR FS:[18]  ; Get the location of the TIB  MOV EAX,DWORD PTR DS:[EAX+30] ; Get the location of the PEB MOVZX EAX,BYTE PTR DS:[EAX+2]  ; Second byte of PEB = isProcessBeingDebugged.  EAX > 0 , debugger is present.
Getting Tricky. Many different ways to defeat debugger checks. Automatic plug-ins for OllyDBG HideOD, IsDebuggerPresent These plug-in’s hide a debuggers presence by keeping the PEB isBeingDebugged flag at 0 They use other methods to hide from each of the debugger detection API’s in Windows.  Rule of thumb: Use the plug-ins, its fast and they work! Else, manually set the PEB IsDebuggerPresent byte to 0. Using the OllyDBG command line plug-in “ set byte ptr ds:[fs:[30]+2]] = 0“ Manually patch your way out of a debugger check.
Demo #3 PE Unpacking - Nspack. Reg.exe Registration executable for Nspack commercial Chinese written PE packer Uses SE Handlers, its polymorphic and is multi-layered. “ One other benefit of using Nspack is that your programs will be harder to crack or reverse-engineer. In order for your programs to be modified, the shell added by Nspack must first be removed, which is more difficult to do. “
Demo #4 Almost finished!! No presentation at a hacker conference is complete without some 0day remote shell! Give it up, for an OllyScript bind shell exploit! All your debuggers are belong to me!
Conclusion PE packing an executable is not hard. Even a modified UPX can thwart static analysis attempts. When unpacking an executable, we don’t need to know exactly how its payload is packed.  All PE packers must unwrap themselves eventually, we can leave this to the PE packer. We are simply an observer, until we find the OEP. Then dump the executable image to disk. Redirect the EntryPoint to the discovered OEP. Rebuild the Import Address Table. Script it, so we never have to do it again!
Questions ? http://www.security-assessment.com [email_address]
Links/References Iczelion Win32 ASM Page - http://win32assembly.online.fr/ EXE Tools – http://www.exetools.com Yates2k R.E  - http://www.yates2k.net/ Programmers Tools - http://programmerstools.org/ RETeam.org – http://reteam.org ARTeam Research – http://arteam.accessroot.com LordPE - http://mitglied.lycos.de/yoda2k/LordPE/info.htm TIB - http://en.wikipedia.org/wiki/Win32_Thread_Information_Block PEB - http://undocumented.ntinternals.net/UserMode/Undocumented%20Functions/NT%20Objects/Process/PEB.html  OpenRCE – http://www.openrce.org Security-Assessment.com – http://www.security-assessment.com

More Related Content

PPT
PE Packers Used in Malicious Software - Part 1
PPTX
Operating System Assignment Help
PPTX
Computer Science Assignment Help
PPTX
Computer Science Homework Help
PDF
CyberLink LabelPrint 2.5 Exploitation Process
PPTX
Exploit Development: EzServer Buffer Overflow oleh Tom Gregory
TXT
Mona cheatsheet
PPTX
Operating System Engineering Quiz
PE Packers Used in Malicious Software - Part 1
Operating System Assignment Help
Computer Science Assignment Help
Computer Science Homework Help
CyberLink LabelPrint 2.5 Exploitation Process
Exploit Development: EzServer Buffer Overflow oleh Tom Gregory
Mona cheatsheet
Operating System Engineering Quiz

What's hot (17)

TXT
Exploit techniques - a quick review
PPTX
System call (Fork +Exec)
PPT
intro unix/linux 10
PDF
Construire son JDK en 10 étapes
PDF
maXbox Starter 42 Multiprocessing Programming
PPTX
Programming Assignment Help
PPT
Internal representation of files ppt
PPTX
Systemcall1
PPT
Shell scripting - By Vu Duy Tu from eXo Platform SEA
ODP
Perl one-liners
PPT
Unit 1
ODP
Php in 2013 (Web-5 2013 conference)
KEY
Deploying and maintaining your software with RPM/APT
PPT
PDF
No instrumentation Golang Logging with eBPF (GoSF talk 11/11/20)
PDF
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
PDF
Kernel Recipes 2019 - Faster IO through io_uring
Exploit techniques - a quick review
System call (Fork +Exec)
intro unix/linux 10
Construire son JDK en 10 étapes
maXbox Starter 42 Multiprocessing Programming
Programming Assignment Help
Internal representation of files ppt
Systemcall1
Shell scripting - By Vu Duy Tu from eXo Platform SEA
Perl one-liners
Unit 1
Php in 2013 (Web-5 2013 conference)
Deploying and maintaining your software with RPM/APT
No instrumentation Golang Logging with eBPF (GoSF talk 11/11/20)
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
Kernel Recipes 2019 - Faster IO through io_uring
Ad

Similar to PE Packers Used in Malicious Software - Part 2 (20)

PPTX
Reversing malware analysis training part7 unpackingupx
PDF
Reversing & malware analysis training part 7 unpacking upx
PPT
Infragard Sept08
PDF
Strategies to design FUD malware
PDF
Manual Unpacking Of Upx Packed Executable Using Ollydbg and Importrec
PPTX
Intro to Reverse Engineering
PPTX
Reversing malware analysis training part3 windows pefile formatbasics
PDF
Binary art - Byte-ing the PE that fails you (extended offline version)
PPT
Reverse engineering
PDF
Binary art - Byte-ing the PE that fails you (live version)
PDF
Bypassing anti virus scanners
PPTX
OS Internals and Portable Executable File Format
PPTX
Remnux tutorial-1 Statically Analyse Portable Executable(PE) Files
PDF
A bit more of PE
PDF
OPCDE Crackme Solution
ODP
x86 & PE
PDF
Bypassing anti virus scanners
PPTX
Ben Agre - Adding Another Level of Hell to Reverse Engineering
PDF
Finding Xori: Malware Analysis Triage with Automated Disassembly
ODP
Such a weird Processor: messing with opcodes (...and a little bit of PE) (Has...
Reversing malware analysis training part7 unpackingupx
Reversing & malware analysis training part 7 unpacking upx
Infragard Sept08
Strategies to design FUD malware
Manual Unpacking Of Upx Packed Executable Using Ollydbg and Importrec
Intro to Reverse Engineering
Reversing malware analysis training part3 windows pefile formatbasics
Binary art - Byte-ing the PE that fails you (extended offline version)
Reverse engineering
Binary art - Byte-ing the PE that fails you (live version)
Bypassing anti virus scanners
OS Internals and Portable Executable File Format
Remnux tutorial-1 Statically Analyse Portable Executable(PE) Files
A bit more of PE
OPCDE Crackme Solution
x86 & PE
Bypassing anti virus scanners
Ben Agre - Adding Another Level of Hell to Reverse Engineering
Finding Xori: Malware Analysis Triage with Automated Disassembly
Such a weird Processor: messing with opcodes (...and a little bit of PE) (Has...
Ad

More from amiable_indian (20)

PDF
Phishing As Tragedy of the Commons
PDF
Cisco IOS Attack & Defense - The State of the Art
PDF
Secrets of Top Pentesters
PPS
Workshop on Wireless Security
PDF
Insecure Implementation of Security Best Practices: of hashing, CAPTCHA's and...
PPS
Workshop on BackTrack live CD
PPS
Reverse Engineering for exploit writers
PPS
State of Cyber Law in India
PPS
AntiSpam - Understanding the good, the bad and the ugly
PPS
Reverse Engineering v/s Secure Coding
PPS
Network Vulnerability Assessments: Lessons Learned
PPS
Economic offenses through Credit Card Frauds Dissected
PPS
Immune IT: Moving from Security to Immunity
PPS
Reverse Engineering for exploit writers
PPS
Hacking Client Side Insecurities
PDF
Web Exploit Finder Presentation
PPT
Network Security Data Visualization
PPT
Enhancing Computer Security via End-to-End Communication Visualization
PDF
Top Network Vulnerabilities Over Time
PDF
What are the Business Security Metrics?
Phishing As Tragedy of the Commons
Cisco IOS Attack & Defense - The State of the Art
Secrets of Top Pentesters
Workshop on Wireless Security
Insecure Implementation of Security Best Practices: of hashing, CAPTCHA's and...
Workshop on BackTrack live CD
Reverse Engineering for exploit writers
State of Cyber Law in India
AntiSpam - Understanding the good, the bad and the ugly
Reverse Engineering v/s Secure Coding
Network Vulnerability Assessments: Lessons Learned
Economic offenses through Credit Card Frauds Dissected
Immune IT: Moving from Security to Immunity
Reverse Engineering for exploit writers
Hacking Client Side Insecurities
Web Exploit Finder Presentation
Network Security Data Visualization
Enhancing Computer Security via End-to-End Communication Visualization
Top Network Vulnerabilities Over Time
What are the Business Security Metrics?

Recently uploaded (20)

PPT
Geologic Time for studying geology for geologist
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PDF
CloudStack 4.21: First Look Webinar slides
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
Developing a website for English-speaking practice to English as a foreign la...
PDF
Getting started with AI Agents and Multi-Agent Systems
PDF
Architecture types and enterprise applications.pdf
PDF
Getting Started with Data Integration: FME Form 101
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPTX
Tartificialntelligence_presentation.pptx
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PDF
Unlock new opportunities with location data.pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
WOOl fibre morphology and structure.pdf for textiles
PDF
Hindi spoken digit analysis for native and non-native speakers
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PPTX
O2C Customer Invoices to Receipt V15A.pptx
Geologic Time for studying geology for geologist
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
CloudStack 4.21: First Look Webinar slides
Taming the Chaos: How to Turn Unstructured Data into Decisions
DP Operators-handbook-extract for the Mautical Institute
Developing a website for English-speaking practice to English as a foreign la...
Getting started with AI Agents and Multi-Agent Systems
Architecture types and enterprise applications.pdf
Getting Started with Data Integration: FME Form 101
Group 1 Presentation -Planning and Decision Making .pptx
Tartificialntelligence_presentation.pptx
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
Unlock new opportunities with location data.pdf
Assigned Numbers - 2025 - Bluetooth® Document
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
WOOl fibre morphology and structure.pdf for textiles
Hindi spoken digit analysis for native and non-native speakers
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
O2C Customer Invoices to Receipt V15A.pptx

PE Packers Used in Malicious Software - Part 2

  • 1. The Fundamental Weakness. “ If it executes, we can unpack it.”
  • 2. Fundamental Weakness No matter how an executable is packed, it MUST be unpacked at runtime for my CPU to run it! My CPU has to run the plaintext, unpacked binary at some stage! I don’t care if its packed using 2048bit RSA, my CPU only runs straight x86 ASM. Its all really about the timing. If we want to get the unpacked data, we need to know the exact moment and location where the data will be unpacked and available. It may only be available and intact for a very short amount of time.
  • 4. Objectives of PE Unpacking Re-create the executable, in its original form, before it was packed. This allows us to perform static analysis on the now unpacked ‘payload’ data. We should not need the PE packer stub again, so we can delete it. Bring the executable back to its virgin state. Before it was packed.
  • 5. Objectives of PE Unpacking Step #1. Locate the OEP (Original Entry Point) jump. After the PE packer has finished unpacking itself and has populated the Import Address Table of the ‘.PACKED-DATA’, it will usually reset/clear any stack registers it was using. Shortly after this, a jump/call will occur that will start the execution of the now unpacked data. This is the OEP Jump The destination of this jump is the EntryPoint of the unpacked data!
  • 6. It looks something like this.
  • 7. Objectives of PE Unpacking Step #2 – For The Old School Only If your true old school you of-cause use Softice (A ring0 debugger). At this stage you need to manually suspend the application at the OEP JMP (Pause the process) Modify the OEP jump/call to be an infinite loop (JMP EIP). If you use OllyDBG, just ignore this. Guy on the left uses Softice, in-fact he use to work at Compuware.
  • 8. -- Softice JMP EIP --
  • 9. Objectives of PE Unpacking Step #3 :Dump the executable memory image The application is currently unpacked in memory, but has not yet begun to execute the unpacked data. We need to dump the memory image of the executable back to disk. We use a process dumping tool. After the memory image is dumped to disk we are left with a snapshot which contains both the unpacked (payload) data, and the PE packers ‘unpacking’ stub.
  • 10. Objectives of PE Unpacking Step #4 : Change EntryPoint of dumped image. The dumped executable’s EntryPoint still points to the start of the PE Packer, the ‘unpacking’ routine. We want the executable to start running the unpacked data first, not the PE packer, we don’t need the PE packer anymore! We know the Original EntryPoint is 004035B0h, this is where the PE packer was going to jump to.
  • 11.  
  • 12. Objectives of PE Unpacking Step #4 Continued… Calculate the EntryPoint RVA All PE values are stored in RVA format. (Relative Virtual Address, an offset from the BaseImage) The BaseImage is where the application begins in memory. RVA EntryPoint = OriginalEntryPoint – BaseImage 004035B0h - 00400000h = 35B0h The Original EntryPoint is 35b0h bytes into the executable!
  • 13. Objectives of PE Unpacking Step #4 Continued… Change the EntryPoint value in the PE header. Using a PE editor, such as LordPE/ProcDump we change the executables EntryPoint value to 35b0h. If we execute the executable now, it will start executing the unpacked data first, not the PE packer!
  • 14. Objectives of PE Unpacking The dumped executable image is almost able to run, but it is still missing one vital piece of information. It does not have a valid Import Address Table! The current import address table is that of the PE packer itself! It only has three entries! LoadLibaryA() GetProcAddress() ExitProcess() Remember: The PE-packer uses LoadLibaryA/GetProcAddress to populate the Import Address Table of .PACKED-DATA!
  • 15. Objectives of PE Unpacking Step #5: Rebuild the Import Address Table We need to find the Import Address Table of our now unpacked data. We need Windows to populate our import table with the correct values for each external function at runtime. Without it, the executable will not run.  and static analysis is also harder. We will overwrite the PE packers own Import Address Table (which only had three entries) with the correct table.
  • 16. Objectives of PE Unpacking To do this, we use: ImpRec – Google “ImpRec MackT UCF” ImpRec will search the executable image in memory (starting from the OEP value) and should find our Import Address Table. We then dump it back to disk.
  • 17. Objectives of PE Unpacking Once we have a copy of the import address table on disk, we re-insert it into the dumped executable. Overwriting the old Import Address Table with our “full bodied” table. Now when we execute the binary windows will populate the Import Address Table with the correct values, allowing us to use external functions. Code execution will start at the unpacked data, and bob’s your uncle!
  • 18. Demo #1 PE Unpacking - UPX. Ok so we know what we want to do, lets do it. Notepad.exe Packed with UPX (the Ultimate Packer for eXecutables) UPX can be unpacked with upx.exe –d We will modify this binary though so upx will not recognize it, and fail to unpack it. Ok lets unpack it by hand.
  • 20. PE Unpacking: Automation. That was easy, because UPX is an easy PE packer. Although it was easy it still took time. Time = Money Having to unpack 100 UPX packed binaries would become really tedious. Tedious = Not fun! Since we now know how UPX works, we should automate the unpacking process. So, lets write a quick, automated unpacking script for any UPX packed binary, so we don’t have to do this by hand again.
  • 21. PE Unpacking: Automation. To do this will use OllyScript (The scripting language plugin for OllyDBG) OllyScript simulates a user’s debugging session within OllyDBG. We can place breakpoints, step, run, do all the normal OllyDBG tasks, only script them. OllyScript is important when dealing with PE packers, it can take hours to unpack a single protector. You don’t want to do it too often! Learning OllyScript is a must if you plan on doing any unpacking of your own.
  • 22. PE Unpacking: Automation. We know the UPX code flow goes like this #1 – The target application is un-compressed. #2 – UPX will populate the packed data’s Import Table. #3 – POPAD #4 – JMP <OEP> The golden rule of UPX is “The first unconditional JMP after POPAD is the OEP JMP” This works on all versions of UPX, very simple.
  • 23. PE Unpacking: Automation. So we write a script which does something like.. Search for the first POPAD in the code. Place a breakpoint on it Run the application Search for the next JMP instruction. Breakpoint again. Run the application again. We end up at the OEP JMP.. Finished.
  • 24. Demo #2 PE Unpacking: Automation
  • 26. So far we have only looked at UPX, a straight-forward relatively friendly PE packer. UPX is a great way to learn how PE packers work, in essence all packers are very similar if not identical to UPX. But rarely are packers so straight-forward to follow and logical in nature. Most PE packers are designed with a focus on anti-unpacking, they don’t want you to unpack them! The golden rule still applies though, eventually a packer must execute the unpacked code. Its just a matter of when! Getting Tricky.
  • 27. Getting Tricky. #1 – Exceptions SEH - Structured Exception Handler “ When an exception occurs, go here to handle the exception” The Goal: Create an exception handler to catch an exception, then raise an exception. The Idea: Code flow is passed to the SE handler. A major part of the PE-packer could be inside the SE handler. SEH code is used as a discreet way of going somewhere. Can also confuse novice reverse engineering attempts
  • 28. Getting Tricky. Each SEH frame consists of two pointers. A pointer to the prev SEH frame. A pointer to the exception handler for the current frame. If no exception handler is found to handle the exception, you end up with an ‘Unhandled exception’ A pointer to the SEH chain is kept inside FS:[0] Thread Information Block - http://en.wikipedia.org/wiki/Win32_Thread_Information_Block
  • 29. Getting Tricky. Example: PUSH TestVE.00401C84 ; Push to the stack the new top SE handler location MOV EAX,DWORD PTR FS:[0] ; Save the existing top SE handler location to EAX PUSH EAX ; Push it back to the stack, its now the second SE handler MOV DWORD PTR FS:[0],ESP ; Move a pointer to the newly created SEH chain into FS:[0] XOR EDX, EDX ; Clear EDX DIV EDX ; Divide by zero exception 00401C84 is now the first SE handler. The old SE handler is now the second handler. When we land on DIV EDX we will cause an exception, this exception will be handled by the top SE handler. Tell OllyDBG to Ignore all exceptions Set a breakpoint on 00401C84 Run the application.
  • 30. #2 – Detecting a debugger Great way to try to stop a pesky reverse engineer is to detect his debugger. Windows API Calls. A call to IsDebuggerPresent() will return > 0 if the process is currently running in the context of a debugger, such as OllyDbg. Unable to detect kernel debuggers such as Softice Many other Windows API’s can be used to detect a debugger. ZwQueryProcessInformation() CheckIsRemoteDebuggerPresent() SetDebugPrivilege () Getting Tricky.
  • 31. Getting Tricky. IsDebuggerPresent API just returns a byte in the PEB. The PEB (Process Environment Block) is a process specific area of user land memory which contains details of each running process. We find the location of the PEB from the TIB. TIB->PEB->isProcessBeingDebugged Example: MOV EAX,DWORD PTR FS:[18] ; Get the location of the TIB MOV EAX,DWORD PTR DS:[EAX+30] ; Get the location of the PEB MOVZX EAX,BYTE PTR DS:[EAX+2] ; Second byte of PEB = isProcessBeingDebugged. EAX > 0 , debugger is present.
  • 32. Getting Tricky. Many different ways to defeat debugger checks. Automatic plug-ins for OllyDBG HideOD, IsDebuggerPresent These plug-in’s hide a debuggers presence by keeping the PEB isBeingDebugged flag at 0 They use other methods to hide from each of the debugger detection API’s in Windows. Rule of thumb: Use the plug-ins, its fast and they work! Else, manually set the PEB IsDebuggerPresent byte to 0. Using the OllyDBG command line plug-in “ set byte ptr ds:[fs:[30]+2]] = 0“ Manually patch your way out of a debugger check.
  • 33. Demo #3 PE Unpacking - Nspack. Reg.exe Registration executable for Nspack commercial Chinese written PE packer Uses SE Handlers, its polymorphic and is multi-layered. “ One other benefit of using Nspack is that your programs will be harder to crack or reverse-engineer. In order for your programs to be modified, the shell added by Nspack must first be removed, which is more difficult to do. “
  • 34. Demo #4 Almost finished!! No presentation at a hacker conference is complete without some 0day remote shell! Give it up, for an OllyScript bind shell exploit! All your debuggers are belong to me!
  • 35. Conclusion PE packing an executable is not hard. Even a modified UPX can thwart static analysis attempts. When unpacking an executable, we don’t need to know exactly how its payload is packed. All PE packers must unwrap themselves eventually, we can leave this to the PE packer. We are simply an observer, until we find the OEP. Then dump the executable image to disk. Redirect the EntryPoint to the discovered OEP. Rebuild the Import Address Table. Script it, so we never have to do it again!
  • 37. Links/References Iczelion Win32 ASM Page - http://win32assembly.online.fr/ EXE Tools – http://www.exetools.com Yates2k R.E - http://www.yates2k.net/ Programmers Tools - http://programmerstools.org/ RETeam.org – http://reteam.org ARTeam Research – http://arteam.accessroot.com LordPE - http://mitglied.lycos.de/yoda2k/LordPE/info.htm TIB - http://en.wikipedia.org/wiki/Win32_Thread_Information_Block PEB - http://undocumented.ntinternals.net/UserMode/Undocumented%20Functions/NT%20Objects/Process/PEB.html OpenRCE – http://www.openrce.org Security-Assessment.com – http://www.security-assessment.com