Past, Present, Future of Windows Exploitation

hi all

this is v0.1 of this post and in this post i’m going to have a review and brief history on exploitation with focus on windows .

this post will be  done III part :

  • part I     : brief history of buffer overflow
  • part II   : history of windows exploitation from windows 2000 to windows 7
  • part III : feature of exploitation

Part I  : brief history of buffer overflow

Starring : Robert morris , Aleph_one , Solar designer , Matt Conover , Casper Dik

it’s been long time after :

morris worm in 1988 (first known computer worm that used a buffer overflow to attack)

aleph one wrote Smashing The Stack For Fun Profit in phrack 49 in ~1996

so he start taking about detailed strcpy exploitation :

Matt Conover wrote first detailed heap overflow tutorial in 1999 heap tut

and solar designer wrote first generic heap exploit on windows netscape exploit

==============================================
at that times because of really low OS memory protections and also low application specific protections (can also called CPU and compilers problem !) , a poor input validation and an insecure memory copy was enough to corrupting memory (mostly in stack area) and overwriting a function return address and getting control of instruction pointer (IP , EIP) and then by storing malicious code (called shellcode) and using a pointer (mostly stack pointer (ESP)) execution flow can be change and pointer to attacker malicious (or educational ;) )  code.

so OS developers and security guys had to think about memory protections and casper dik in nov 1996 wrote a kernel run-time patch to implement non-executable-stacks for Solaris 2.4 to 2.5.1 http://seclists.org/bugtraq/1996/Nov/57

and later solar designer released same thing to remove executable permission for stack on the linux here

and around ~2000 solar designer made return-to-libc attacks to return in executable page and functions in memory for bypassing non-executable memory. the basic idea was  after controlling executing flow return to some function like system() and executing a single command or …. but there was a problem and the attacker was limit in payload selection and can’t use advanced payloads .

so around ~2000 we had :

  • basic / intermediate stack overflows
  • basic heap overflows
  • basic / intermediate format strings (killed so soon !)
  • basic memory protections
  • basic bypass memory protections
  • also some other type of memory corruptions (not so general)

=========================================

part II  : history of windows exploitation from windows 2000 to windows 7

Starring : Alexander Sotirov , Mark Dowd , John McDonald, Chris Valasek , Chris Anley , Brett Moore , David litchfield , Nicolas Waisman , Dave Aitel , Halvar Flake ,  Cesar Cerrudo , Matt Miller , ken johnson , S.K Chong ,  Dionysus Blazakis  , hd moore , FlashSky , Ruben Santamarta .

welcome to windows world !

i wanna start from windows 2000  final version of NT family because i think older windows are not interesting enough to talk about .

exploit developers golden age : microsoft was is supporting and making money from windows 2k and unfortunately forgot  protect you from buffer overflow attacks . so old and classic attacks works like a charm and just  maybe in some case  we saw very complex  and smart vulnerabilities but exploitation by itself was not that hard (maybe just some application specific filters / protections )

so because of that poor protection we saw great worms like :

blaster worm one of historic worms ever that used a RPC vuln for attack and fixed in http://www.microsoft.com/technet/security/bulletin/MS03-026.mspx

and maybe you can remember : “billy gates why do you make this possible ? Stop making money and fix your software!! “

and this cool picture :


slammer worm a great and fast worm that used an SQL Server buffer overflow for attack. that fixed after 6 month !!! in :

http://www.microsoft.com/technet/security/bulletin/MS02-039.mspx

sasser worm another great worm that used lsass remote overflow vulnerability and fixed in: http://www.microsoft.com/technet/security/bulletin/MS04-011.mspx

but there is a question these worms targeted windows XP and 2003 as well too ? yes !

because microsoft did  that great job in windows XP service pack 0 and 1 as well as windows 2003 service pack 0.

also we had lots of great and reliable exploits like :

DCOM RCP Exploit  here by flashsky (xfocus guy)

MS Windows (RPC DCOM) Remote Exploit here by hd moore

Great Kill Bill exploit here (targeting ANS.1) by Alexander Sotirov

MS Windows Plug-and-Play here by sl0ppy and houseofdabus and others .

also some GUI tools for easy exploitation for those even don’t know how they can compile and run an exploit like : RPC GUI v2 – r3L4x.exe

but why we had lots of juicy and clicky – clicky exploits ? there is two main reasons :

1- poor generic OS / application layer  memory protection

2- cool generic public memory exploitation related researches

classic windows stack overflows

lots of great and detailed papers in this area i just wanna link a few of them :

1- Win32 Buffer Overflows (Location, Exploitation and Prevention) by dark spyrit in 1999

http://www.phrack.com/issues.html?issue=55&id=15#article

2- S.K Chong Win32 Stack Based Buffer Overflow Walkthrough  in july 2002

http://www.scan-associates.net/papers/win32_bo_walkthrough.txt

3- Nish Bhalla’s series on  Writing Stack Based Overflows on Windows in 2005

http://www.packetstormsecurity.org/papers/win/

if i want to have brief description of them they all are talking about finding a reliable return address in  a reliable Dynamic Linked Library (MOST in OS DLL’s kernel32.dll ntdll.dll shell32.dll user32.dll and … ) and then after overwriting a function return address by sending big value to not good checked input variable and getting program execution flow redirect that flow to address in DLL that address is mostly JMP / call /  PUSH ESP (stack pointer)  or EBP (base pointer) because most of time in classic stack overflow attacker store her / his malicious code in the stack and a JMP / CALL / PUSH ESP RET will lead his / her to jump to start of shellcode .thats all!

classic windows heap overflows

1 –  Third Generation Exploitation smashing heap on 2k by halvar Flake in 2002

http://www.blackhat.com/presentations/win-usa-02/halvarflake-winsec02.ppt

2- Exploiting the MSRPC Heap Overflow two part by Dave Aitel (MS03-026) sep 2003

http://freeworld.thc.org/root/docs/exploit_writing/msrpcheap.pdf

http://freeworld.thc.org/root/docs/exploit_writing/msrpcheap2.pdf

3- david litchfield did a great detailed penetration in black hat 2004

https://www.blackhat.com/presentations/win-usa-04/bh-win-04-litchfield/bh-win-04-litchfield.ppt

if i want to have brief description of them they all are talking about exploiting unlink macro and using write4 (where + what) and actually ability of writing 4byte (32bit ) of selected address in memory by using specific function pointers like :

  • UnhandledExceptionFilter
  • VectoredExceptionHandling
  • RtlEnterCriticalSection
  • TEB Exception Handler
  • Application specific function pointer

…..

kernel based Windows overflows (not so classic)

because of Inexorability of  this type of attacks i want to share all of most notable history in this area here : (note that  i will back to heap and stack with protections after in it)

=================

First noticeable whitepaper that stated how to attack kernel based vulns on

windows was done by a Polish group called “sec-labs” around 2003 .

http://www.derkeiler.com/Mailing-Lists/Full-Disclosure/2003-08/0101.html

sec-lab old whitepaper : http://www.artofhacking.com/tucops/hack/windows/live/aoh_win32dcv.htm

sec-lab old exploit : http://www.securityfocus.com/bid/8329/info

(thanks Piotr Bania !)

1- Windows Local Kernel Exploitation by S.K Chong in 2004 (based on sec-lab research)

http://www.packetstormsecurity.org/hitb04/hitb04-sk-chong.pdf

http://www.scan-associates.net/papers/navx.c

2-Windows interrupt context kernel overflow exploit BY FLASHSKY in 2004

3- How to exploit Windows kernel memory pool in 2005 by SoBeIt

http://packetstormsecurity.nl/Xcon2005/Xcon2005_SoBeIt.pdf

4- in 2005 eeye security published great paper about exploiting remote kernel overflows in windows

http://research.eeye.com/html/papers/download/StepIntoTheRing.pdf

5- later in 2005 matt miller published great article called Kernel-mode Payloads on Windows in uninformed

http://www.uninformed.org/?v=3&a=4&t=pdf

6- in 2006 johny cache hd moore and matt miller released Exploiting 802.11 Wireless Driver Vulnerabilities on Windows

http://www.uninformed.org/?v=6&a=2&t=pdf

7- in 2007 Jonathan Lindsay published and did a presentation in BH US 2007 called Attacking the Windows Kernel

http://www.blackhat.com/presentations/bh-usa-07/Lindsay/Whitepaper/bh-usa-07-lindsay-WP.pdf

8- same in  BH US 2007 Yuriy Bulygin did a peresentiation called Remote and Local Exploitation of Network Drivers

http://www.blackhat.com/presentations/bh-usa-07/Bulygin/Presentation/bh-usa-07-bulygin.pdf

9- in 2007 also Ruben Santamarta wrote Exploiting Comon Flaws In Drivers

http://www.reversemode.com/index.php?option=com_content&task=view&id=38&Itemid=1

10- in 2008 Justin Seitz  wrote a paper and called I2OMGMT Driver Impersonation Attack

http://www.immunityinc.com/downloads/DriverImpersonationAttack_i2omgmt.pdf

in that paper Justin  talked about new type of kernel attacks and about i2OMGMT bug that founded by ruben.

11- later in 2008 Kostya Kortchinsky did a presentation called Real World Kernel Pool Exploitation

http://sebug.net/paper/Meeting-Documents/syscanhk/KernelPool.pdf

in that presentation kostya  talked about how he wrote exploit for ms08-001 (Microsoft marked it as not-exploitable !)

12- later in 2008 Cesar Cerrudo wrote Token Kidnapping and a super reliable exploit for windows 2k3 and 2k8

  • artice :
  • http://www.argeniss.com/research/TokenKidnapping.pdf
  • poc 2k3:
  • http://www.argeniss.com/research/Churrasco.zip
  • poc 2k8:
  • http://www.argeniss.com/research/Churrasco2.zip

13- again later in 2008 mxtone wrote a paper called Analyzing local privilege escalations in win32k
http://www.uninformed.org/?v=10&a=2&t=pdf

in that paper he analyzed vulnerabilities and exploitation vector of win32k driver .

14- in ucon 2009  Stephen A. Ridley did a presentation called Intro to Windows Kernel Security Development
download it here

15- Tavis Ormandy, Julien Tinnes and great presentation called There’s a party at ring0 and you’re invited
http://www.cr0.org/paper/to-jt-party-at-ring0.pdf

16- in January 2010 Matthew “j00ru” Jurczyk and Gynvael Coldwind, Hispasec wrote a detailed paper called GDT and LDT in Windows kernel vulnerability exploitation.
http://vexillium.org/dl.php?call_gate_exploitation.pdf
in that  paper they describes some possible ways of exploiting kernel-mode write-what-where vulnerabilities in a stable manner

17- later  they did a presentation called Case Study of Recent Windows Vulnerabilities in HITB 2010

Windows memory protections !

OK so now we are going back to user-land this time with memory protections !

due to  lots of generic exploitation methods as well as lots of worms  ! Microsoft decided to use of memory protections in hardware and software layer. so from windows XP SP2 (Windows XP Tablet PC Edition 2005) , Windows Server 2003 Service Pack 1 (OS level) and from visual studio 2003 (compiler level) added lots of memory protections functionality.

here i’m going to have brief history of them and then  i will introduce  great researchers and their research against memory protections .

1- Data Execution Prevention (DEP)

DEP is a security feature included in modern Microsoft Windows operating systems that is intended to prevent an application or service from executing code from a non-executable memory region. This helps prevent certain exploits that store code via a buffer overflow, for example.

hardware-enforced DEP for CPUs that can mark memory pages as non-executable, and software-enforced DEP with a limited prevention for CPUs that do not have hardware support.

in windows XP SP2 and windows 2003 sp1 and sp2 you can get access on DEP setting by editing boot.ini in noexecute section.

there is four options :

1- OptIn : DEP only will work for all of windows services as well as  necessary programs.

2- OptOut: DEP  will work for all of windows services as well as  all of 3d-party installed program but you can add some process as            exception from controll panel.

3- AlwaysOn : fully protected by DEP no exception is acceptable.

4- AlwaysOff : Go to hell DEP , turns DEP off .

most of CPUs those are made after 2004 (AMD , Intel) can support hardware DEP.

read more on DEP : http://support.microsoft.com/kb/875352

/GS (Buffer Security Check)

GS (a.k.a stack cookie) is a compiler option that added from visual studio 2003 and will detects some buffer overruns that overwrite the return address, a common technique for exploiting code that does not enforce buffer size restrictions. This is achieved by injecting security checks into the compiled code.

so by using /GS flag compiler will add __security_init_cookie() function to your program and each time you want to overwrite a function return address you actually overwrite cookie as well and so comparison of cookie will fall so process will be terminate and you can’t use your return address.

for more detail read : http://msdn.microsoft.com/en-us/library/Aa290051

/SAFESEH

a linked option also system functionality added in visual studio 2005. when a program is linked with /SAFESEH in header of file will be contain of a acceptable Exception Handler Table. so each time an exception occurs and attacker wants overwrite a record from exception handler the ntdll dispatcher will understand this and will terminate program execution.

for more detail read : http://msdn.microsoft.com/en-us/library/9a89h429(VS.80).aspx

ASLR

Windows Vista, 2008 server, and Windows 7 offer yet another built-int security technique (like PAX), which randomizes the base addresses of executables, dll’s, stack and heap in a process’s address space (in fact, it will load the system images into 1 out of 256 random slots, it will randomize the stack for each thread, and it will randomize the heap as well).
in simple explanation if you want use an address in system in one of system dll’s   after your target system got restart your address is changed and not valid anymore so exploitation will fail again.

for more detail read : here

SEHOP

used in most modern windows operation systems like 2008 and 7 . the idea beyond this new mitigation comes from matt miller article called Preventing the Exploitation of SEH Overwrites. for detailed explanation of this protection just read flowing link :

http://blogs.technet.com/srd/archive/2009/02/02/preventing-the-exploitation-of-seh-overwrites-with-sehop.aspx

Heap Protection

Microsoft also introduce to some new heap protections like heap meta cookie , safe unlinking , and in newer systems (after vista) function pointer obfuscation and so on …

==================================================

Advanced Windows Exploitation (bypassing filter and protections )

after 2005 exploitation getting harder and harder and number of public and “white-hat” hackers who can made a reliable multi platform exploit for modern windows OS was not too much.

in this section i want to have review on most important and noticeable researches against protections.

1- Third Generation Exploitation smashing heap on 2k by halvar Flake in 2002

http://www.blackhat.com/presentations/win-usa-02/halvarflake-winsec02.ppt

windows 2k heap exploitation.

2- chris anley wrote Creating Arbitrary Shellcode In Unicode Expanded Strings

http://www.net-security.org/dl/articles/unicodebo.pdf

this was first public article about unicode based shellcode and is also known as “Venetian” shellcode. the method explained in this paper was good enough to making poor ASCII shellcodes .

3- Dave aitel advanced windows exploitation in 2003

http://www.immunityinc.com/downloads/immunity_win32_exploitation.final2.ppt

in that talk dave talked about no so typical windows exploitation and start making game more advanced .


4- Defeating the Stack Based Buffer Overflow Prevention Mechanism of Microsoft Windows 2003 Server by david litchfield

http://www.ngssoftware.com/papers/defeating-w2k3-stack-protection.pdf

this paper actually was first detailed paper about abusing SEH (structured exception handler)  and the generic way to bypass /GS  and also write not lots of public exploit are using this method for exploitation so it also can called one of most important research in windows exploitation history.

5- reliable heap exploits  (matt Conover  in cansecwest 2004 ) and after that Windows Heap Exploitation (Win2KSP0 through WinXPSP2)

http://cybertech.net/~sh0ksh0k/projects/winheap/XPSP2%20Heap%20Exploitation.ppt

i think that was one of most important heap related research in history of windows exploitation a great and gentle introduction to overwrite a chunk on lookaside list for bypassing safe unlinking and also give lots of great information  about windows heap manager internals .

6- later in 2004 matt miller wrote an article Safely Searching Process Virtual Address Space

http://www.hick.org/code/skape/papers/egghunt-shellcode.pdf

this article was first great and public article about using egg-hunter shellcode and it’s about when we have limited memory space for our shellcode and we can store our big and main shellcode some-where in memory. this can be also called practical introduction to search shellcodes .

7- later in 2004  skylined wrote on IE exploit and used a technology called Heap Spray

http://www.exploit-db.com/exploits/612

heap spray is one of most important technologies even in modern exploitation and it’s about code that sprays the heap attempts to put a certain sequence of bytes at a predetermined location in the memory of a target process by having it allocate (large) blocks on the process’ heap and fill the bytes in these blocks with the right values. They commonly take advantage from the fact that these heap blocks will roughly be in the same location every time the heap spray is run.

for a few years heap spray was just used in java script and mostly in browsers but today modern attackers are using anything possible to allocate more heap for sparing .  like action script , silver light , bmp files and … and not just in browsers !  from my point of view heap spray is like cheating in modern exploitation !

8- bypassing hardware-enforced DEP skape (matt miller) Skywing (ken johnson) (in October 2005)

http://www.uninformed.org/?v=2&a=4&t=pdf

yay ! they finally did it . hardware enforced DEP bypassed by using a return to libc style attack . in simple explanation  the problem was in not CPU the problem and weakness was in windows related API that was used for setting DEP for various process. and the API was NtSetInformationProcess. but there was some simple problem in that article like they forget talk about it we need to to have EBP always writable.

9- Exploiting Freelist[0] On XP Service Pack 2 by brett moore (dec 2005)

download here

this is was another great example of bypassing heap protections by using Freelist[0] and really useful is some case .

10 -  later in 2005 matt miller published great article called Kernel-mode Payloads on Windows in uninformed

http://www.uninformed.org/?v=3&a=4&t=pdf

this article was great article for porting exploits to kernel-land.

11-  in 2006 johny cache hd moore and matt miller released Exploiting 802.11 Wireless Driver Vulnerabilities on Windows

http://www.uninformed.org/?v=6&a=2&t=pdf

good example of real-world driver exploitation.

12-  in 2007  Ruben Santamarta wrote Exploiting Comon Flaws In Drivers

Read it here

note that before ruben we can find lots of great research about this topic but  ruben makes  it different . he  made a tool that called kartoffel which is a great driver fuzzer for finding IOCTL vulnerabilities  in drivers. but kartoffel was not main reason to make it different.

after he wrote kartofell and published lots of detailed advisories in various vendor drivers , windows driver exploitation got speed and changed to one of focusable area in exploitation .

13- Heap Feng Shui in JavaScript by Alexander sotirov (2007)

http://www.blackhat.com/presentations/bh-europe-07/Sotirov/Presentation/bh-eu-07-sotirov-apr19.pdf

notable improvements to skylined heap spray technology . heap spray was good but blind and not so reliable is some case.  Heap Feng Shui is great research about doing advanced FU in heap  (heap manipulation) it will lead you to have more control on heap.

14- Understanding and bypassing Windows Heap Protection by Nicolas Waisman (2007)

http://kkamagui.springnote.com/pages/1350732/attachments/579350

nico is one of a few guys that focused on windows heap he also developed immunity debugger heaplib and did lots of great heap related researches. he is one of world leading heap !

15- Heaps About Heaps by brett moore (in 2008)

http://www.insomniasec.com/publications/Heaps_About_Heaps.ppt

that was one of most complete researches about heap. yes that is just a few slides but great hint if you want do something on heap !

16- Bypassing browser memory protections in Windows Vista  by Mark Dowd and Alex Sotirov (in 2008)

http://taossa.com/archive/bh08sotirovdowd.pdf

one of most greatest exploitation related research with a focus on bypassing browsers memory protections in vista .

great  generic .net shellcode trick (loading a .net dll and use shellcode in it),  java spraying , deep into  combined protections  and great ways to bypassing them.

17 – Attacking the Vista Heap by ben hawkes (in 2008)

http://www.ruxcon.org.au/files/2008/hawkes_ruxcon.pdf

great research about vista heap internals and some ways to bypassing vista heap protections.

18- Return oriented programming Exploitation without Code Injection by Hovav Shacham  (and others ) (in 2008)

http://cseweb.ucsd.edu/~hovav/dist/blackhat08.pdf

not a so new technology. it’s just our old code reuse ! but with great official introduction he call it  Return-Oriented-Programming (now known as ROP ). this technology is great to bypass permanent DEP (vista / 7 / 2008) (because you can’t use return-to-libc style attack anymore)

19- Cesar Cerrudo wrote Token Kidnapping and a super reliable exploit for windows 2k3 and 2k8 (2008)

http://www.argeniss.com/research/TokenKidnapping.pdf

20- Defeating DEP Immunity Way by Pablo sole (2008)

http://www.immunityinc.com/downloads/DEPLIB.pdf

first automation of ROP . thats it ;)

21- Practical Windows XP2003 Heap Exploitation (bh 2009) by John McDonald and Chris Valasek.

http://www.blackhat.com/presentations/bh-usa-09/MCDONALD/BHUSA09-McDonald-WindowsHeap-PAPER.pdf

if you want write a heap exploit for modern OS . you should read this one . most complete heap related article .

22- Bypassing SEHOP  by Stefan Le Berre Damien Cauquil (in 2009)

http://www.sysdream.com/articles/sehop_en.pdf

cool and good research ! but ALSR will make it not so useful because SEHOP = SEHOP + ASLR

23- Interpreter Exploitation  : Pointer Inference and JIT Spraying by Dionysus Blazakis (2010)

http://www.semantiscope.com/research/BHDC2010/BHDC-2010-Paper.pdf

http://www.semantiscope.com/research/BHDC2010/BHDC-2010-Slides-v2.pdf

Great ! exploitation is still alive . generic exploitation method for bypassing DEP and ASLR together . if you read and understand it you can write lots of exploits for windows 7 !

24- write-up of Pwn2Own 2010 by  Peter Vreugdenhil (2010)

http://vreugdenhilresearch.nl/Pwn2Own-2010-Windows7-InternetExplorer8.pdf

a great and short article about how to own DEP+ASLR without any 3rd-party plugin

(used two vulnerability and toke around 4 minutes)

25- ruben santamarta all in one 0day presented in rootedCON (2010)

http://wintercore.com/downloads/rootedcon_0day_english.pdf

some great idea for bypassing IE XSS Filter and protected mod not exploitation specific but it’s great for being combined with other exploitation methods .

=========================================================

history of some not so typical windows exploits:

in this section i’m going to archive some of interesting exploits i saw you can learn lots of things from them !

1- one of first real-world HW-DEP bypass Exploit by devcode : here

2- bypassing DEP by returning into HeapCreate by toto : here

3- first public ASLR bypass exploit by using partial overwrite  by skape (matt miller) : here

4- heap spray and bypassing DEP by skylined : here

5- first public exploit that used ROP  for bypassing DEP in adobe lib TIFF vulnerability : here (is this case ASLR bypass is possible !)

6-  exploit codes of bypassing browsers memory protections : here

7-  Cesar Cerrudo PoC’s on Tokken TokenKidnapping .  PoC for  2k3: here , PoC 2k8: here

8- Tavis Ormandy KiTra0d an exploit works from win 3.1 to win 7 . PoC here (metasploit updated module works more interesting !)

9- old ms08-067 metasploit module multi-target and DEP bypass  PoC here

10- PHP 6.0 Dev str_transliterate() Buffer overflow – NX + ASLR Bypass (using ROP and Brute Forcing ASLR) PoC here

11- Stephen Fewer SMBv2 Exploit . PoC here

note 1  :there is lots of other interesting exploits in windows platform you can just find them in here and also here .

note 2: i saw lots of other great and advanced exploits in commercial packages . (they are commercial so forget them ;) )

===================================================

history of related windows exploitation books !

in this section i’m going to archive some books about windows exploitation.

1- Exploiting Software How to Break Code By (Greg Hoglund, Gary McGraw)

2- The Art of Software Security Assessment: Identifying and Preventing Software Vulnerabilities (By Mark Dowd, John McDonald)

3- Buffer Overflow Attacks: Detect, Exploit, Prevent (by James C. Foster)

4- Windows Internals (by Mark Russinovich , David A. Solomon, Alex Ionescu)

5-  The Shellcoders Handbook Discovering and Exploiting Security

(by Jack Koziol, David Litchfield, Dave Aitel, Chris Anley, Sinan Eren, Neel Mehta, and Riley Hassell)

6- Software Vulnerability Guide ( by HERBERT H. THOMPSON , SCOTT G. CHASE)

7- ADVANCED WINDOWS DEBUGGING (by Mario Heward , Daniel Pravat)

8- Reversing: Secrets of Reverse Engineering

9- great step by step exploit writing tutorials by my friend Peter Van Eeckhoutte :


  1. Exploit writting tutorial part 1:Stack Based Overflowshere
  2. Exploit writting tutorial part 2: Stack Based Overflows – jumping to shellcode – here
  3. Exploit writting tutorial part 3: SEH Based Exploits – here
  4. Exploit writting tutorial part 3b: SEH Based Exploits - just another example  - here
  5. Exploit writting tutorial part 4: From Exploit to Metasploit – here
  6. Exploit writting tutorial part 5:  speed up basic exploit development – here
  7. Exploit writting tutorial part 6: Bypassing GS, SafeSeh, SEHOP, HW DEP and ASLR – here
  8. Exploit writting tutorial part 7: Unicode – from 0×00410041 to calc – here
  9. Exploit writting tutorial part 8: Win32 Egg Hunting - here
  10. Exploit writting tutorial part 9: Introduction to Win32 shellcoding – here

also he wrote a cool immunity debugger PyCommand called PveFindAddr i think this python script is necessary for speed-up exploit development for newbie or expert exploit developers and i found it so useful , it have some cool features like finding instructions for code reuse and ROP also finding state of memory protections and finding best return address in your situation.

this is not complete lits of exploitation related book / articles list i just listed those had at least one windows specific chapter .

PART III : Future of exploitation

Starring : T.B.A

1- exploitation is not and will not die.

2- just will change and being more harder also won’t be ” just for fun” like before.

3- writing reliable exploits will take time and time == money and now exploit development is acceptable specific job in security area !

4- fame == money as well (also is lovely by itself) .  so you will see other great researches in various security fields ;)

5- if you read all of resources exist in post you can be a great exploit developer ; )

PS1 : during writing this post due to lots of links and peoples on it maybe i forgot some notable people / article you can alert me about them just by shahin [at] abysssec.com

PS2 : i wrote this post so fast (and took long time !) i will edit my Misspellings and grammatical in good time.

i need to go and take 0XCC00FFEE .

have fun .

Immunity Debugger PeDetect and the art of signature generation

hello to you all

i,m really sorry for our late  in posting we really working on lots of things … before starting about our subject i should  tell you about our advisories and exploits we are not  really full-disclosure believers but still we will post some more exploits and advisories at  :

http://www.exploit-db.com/author/abysssec

so stay tuned.

OK let’s start  ….

=========================================

before start if you are not familiar with PE  : The Portable Executable (PE) format is a file format for executables, object code, and DLLs, used in 32-bit and 64-bit versions of Windows operating systems. The term “portable” refers to the format’s versatility in numerous environments of operating system software architecture.

for more information  :  http://en.wikipedia.org/wiki/Portable_Executable

- now the first question is what is a signature ?

a signature actually  is what that means but in computer world and more specific in reverse engineering and binary auditing  world a signature is a sequence of  unique instructions (actually their representation op-codes) in target binary.

for better understanding please watch figure 1

figure 1 – a c++ compiled binary opened in immunity debugger

reminiscence : an opcode (operation code) is the portion of a machine language instruction that specifies the operation to be performed.

in above figure it have tree red rectangular :

  • first rectangular are RVA (relative virtual address) of instructions
  • second rectangular are OP-Codes (will be execute)
  • third rectangular are  readable assembly instructions

so we will search for a sequence of unique op-codes (so sequence of instructions)  in our target binary and those byte will be signature of our binary. simple enough eh ?

- what and who need to use a signature ?

  • most of anti-virus (and other anti-things)
  • and almost all of PE Detection tools

so now you can imagine how  an anti-virus company can detect a malware and how  PE-Detection tools  (witch areused for detecting signature in compiled binary and determine compiler / packer / compressor and … )  works .

- next question is why we need care about signatures:

  • before starting any fuzzing / reversing / auditing project we need to about our target binary
  • identify binaries those have not any signatures
  • with them we can speed up our reversing and we can find available tools against our target binary

-how we can find signatures in binaries ?

we should search for static and constant location (static instructions) in our file but how we can find them? for answer to this question please watch PE file layout again :

figure 2 – PE file layout

we can search for signatures in a few areas :

  • around program entry point (where program instructions will start execution …)
  • from offset (from top to bottom)

each executable file have some other locations can be good for generating signature those are :

  • around import table (where functions will be import)
  • start and end of sections (optional section specially)
  • name of optional / static sections
  • ….

so we can just open the executable  under debugger and copy a few OP-Codes from entry point and we are done ? of course not ! because in lots of situations entry point could be change  refer to various factors like :

  • initializing addresses / variables with state of program
  • if we are in fighting against a packer / compressor / cryptor / there are several technologies they can use for hiding / changing instructions …

note : these changes are more on not “just compiled binaries” it means those have a packer / protector and ….

so how we can find reliable signatures ?

we need to research about variant program situations  and then we can understand which bytes/instructions are constant and which are not then we  can ignore dynamic bytes and rely to static bytes.

before a  real case study i just want explain how packer/protectors works :

a packer will do what it sounds : packing a program. think  about winzip it will comperes the program and actually will decrease size of program .

elementary packers just will compress the portable executable and will change entry point to decompression section for better understanding just watch below figure.

figure 3 How typical packer runtime works

1. Original data is located somewhere in the packer code data section
2. Original data is uncompressed to the originally linked location
3. Control is transferred to original code entry point (OEP)

Ok now you know how a basic packer works but today modern packers are not just compressor they will use a lots of anti-debugging  technologies against debugger / disassembler to make reverser life harder. this technologies are out of scope of  this post.

Ok for example if we want to make  a signature for a new packer / protector we need to pack / protect variant  executable (it’s better  to test on different compiler / size)  and then watch which byte of files are changed and which one are static !

you can use binary copy option in immunity debugger for starting our test

figure 4 binary copy

this program is  packed with a really simple and good packer named FSG.

and my first signature will be :

87 25 5C AD 41 00 61 94 55 A4 B6 80 FF 13 73 F9 33 C9 FF 13 73 16 33

so now i need to pack more files and check my selected Op-codes to know which one are changed and then we will replace changed op codes with ?? .  after a few try we will get a signature like  :

87 25 ?? ?? ?? ?? 61 94 55 A4 B6 80 FF 13 73 F9 33 C9 FF 13 73 16 33

so if i search for these bytes i can find i can find them in any program those are packed with FSG v2 !

this example is really really simple for advanced packer we need really test more bytes to be sure our signature is good enough but from my experience  length between 30-70 byte  from entry point are good enough.

if you be smart you will select good instructions like sections those have 16-bit registers and instructions those are not used all times. so an example of really good signature can be below figure (taken from symantec slides) :

figure 5 ( a really good signature )

OK. now you can make you own signatures just by spending a few time on each target . there are several tools can be use for detecting  signatures if executable most popular of them are :

  • PEiD
  • RDG Packer Detector
  • PE Detective

but all of them have a same problem not so update signatures ! so if you have a program that is packed by a really new packer or just a few byte take changed from their signature  most of them will fail (intelligent signature detection is out of scope of this post) . so what we can do ? we should have our own database for our job .

so i collect all of existing signature database (those i found) in internet and i removed stupid and duplicated signature from the list those are :

  • BoB at Team PEiD signature database
  • Panda Security customized signature database
  • Diablo2002 signature database
  • ARteam members signature database
  • SnD members signature database
  • Fly signature database
  • and …

after i combined all of their signature databases i changed a few of important signature to be more general and i added some new signature to my list  and my final list right now have around 5064 unique and 4268 from entry point signature.

PEiD can parse external signatures and it’s nice but i liked to have detection in my debugger so i searched for a signature detection library in python (i like python) and with a quick search i found nice Pefile coded by Ero Carrera can handle all of our requirement in working with PE file not only handling signatures you can download it at :

http://code.google.com/p/pefile/

so i decide to use this library to write a pycommand for immunity debugger fortunately i found a copy of a pefile in immunity debugger lib ! so all i have to do is writing a few line of code that can read my database and test it against my binary and tell me the output .
so here is my complete script also have a option for auto-update  .

#!/usr/bin/env python
 
'''
 This script is for identify packer/protector and compiler used in your target binary
 the first version have more than about 5000 signatures ... we will try to updates signatures monthly
 and for now it will use entry point scaning method ...
 
 Tree Important Notes :
 First  the database signatures are reaped by lots of people we should thanks them : BoBSoft at Team PEID  , fly , diablo2oo2 and others you can find their name in list ...
 Second A big thanks to Ero Carrera for his nice python pefile lib the hard part of processing singanutes is done by his library .
 Third  we updated some of signatures and will keep update them monthly  for detection newer version of packers / comprassion algorithm (hopefully) 
 
 thanks to nicolas waisman / Muts (offsec) and all of abysssec memebers ...
 
 Feel free to contact me with admin [at] abysssec.com
'''
 
#import python libraries
import os
import sys
import getopt
import pefile
import immlib
import peutils
import hashlib
import shutil
import urllib
 
__VERSION__ = '0.2'
 
DESC= "Immunity PyCommand PeDectect will help you to identfy packer / protection used in target binary"
USAGE = "!PeDetect"
 
#global
downloaded = 0
 
#Using debugger functionality
imm = immlib.Debugger()
 
# pedram's urllib_hook
def urllib_hook (idx, slice, total):
    global downloaded
 
    downloaded += slice
 
    completed = int(float(downloaded) / float(total) * 100)
 
    if completed > 100:
        completed = 100
 
    imm.Log("   [+] Downloading new signatures ... %d%%" % completed)
 
# Downloader function
def get_it (url, file_name):
    global downloaded
 
    downloaded = 0
    u = urllib.urlretrieve(url, reporthook=urllib_hook)
    #imm.Log("")
    shutil.move(u[0], file_name)
 
# Calculate MD5Checksum for specific file
def md5checksum(fileName, excludeLine="", includeLine=""):
    m = hashlib.md5()
    try:
        fd = open(fileName,"rb")
    except IOError:
        imm.Log("Unable to open the file in readmode:", filename)
        return
    content = fd.readlines()
    fd.close()
    for eachLine in content:
        if excludeLine and eachLine.startswith(excludeLine):
            continue
        m.update(eachLine)
    m.update(includeLine)
    return m.hexdigest()
 
# Simple Usage Function
def usage(imm):
    imm.Log("!PeDetect -u (for updating signature ... )" )
 
# Auto-Update function
def update():
 
    # Using urlretrieve won't overwrite anything
    try:
        download = urllib.urlretrieve('http://abysssec.com/AbyssDB/Database.TXT')
    except Exception , problem:
        imm.Log ("Error : %s"% problem)
 
    # Computation MD5 cheksum for both existing and our current database
    AbyssDB = md5checksum(download[0])
    ExistDB = md5checksum('Data/Database.TXT')
 
    imm.Log(" [!] Checking for updates ..." , focus=1, highlight=1)
    imm.Log("")
    imm.Log(" [*] Our  database checksum : %s "%AbyssDB)
    imm.Log(" [*] Your database checksum : %s "%ExistDB)
    imm.Log("")
 
    if AbyssDB != ExistDB:
 
        imm.Log("[!] Some update founds updating ....")        
 
        # Removing existing one for be sure ...
        if os.path.exists('Data/Database.txt'):
            os.remove('Data/Database.txt')
 
        # Download latest database
        try:
            get_it("http://abysssec.com/AbyssDB/Database.TXT", "Data/Database.txt")
        except Exception,mgs:
            return " [-] Problem in downloading new database ..." % mgs
 
        imm.log("   [+] Update Comepelete !")
 
    else:
        imm.Log(" [!] You have our latest database ...")
 
# Main Fuction
def main(args):
 
    if args:
        if args[0].lower() == '-u':
            update()
        else:
            imm.Log("[-] Bad argumant use -u for update ...")
            return  "[-] Bad argumant use -u for update ..."
    else:
        try:
            # Getting loded exe path
            path = imm.getModule(imm.getDebuggedName()).getPath()
        except Exception, msg:
            return "Error: %s" % msg
 
        # Debugged Name
        name = imm.getDebuggedName()
 
        # Loading loaded pe !
        pe = pefile.PE(path)
 
        # Loading signatures Database
        signatures = peutils.SignatureDatabase('Data/Database.TXT')
 
        # Mach the signature using scaning entry point only !
        matched = signatures.match(pe , ep_only=True)        
 
        imm.Log("===================  Abysssec.com  =======================")
        imm.Log("")
        imm.Log("[*] PeDetect By Shahin Ramezany" , focus=1, highlight=2)
        #imm.Log("=============================================================")
        imm.Log("[*] Total loaded  signatures : %d" % (signatures.signature_count_eponly_true + signatures.signature_count_eponly_false + signatures.signature_count_section_start))
        imm.Log("[*] Total ep_only signatures : %d" % signatures.signature_count_eponly_true)
        #imm.Log("=============================================================")
        imm.Log("")
 
        # Signature found or not found !
        if matched:
            imm.log("[*] Processing : %s " % name)
            imm.Log("[+] Signature Found  : %s "   % matched , focus=1, highlight=1)
            imm.Log("")
        else:
            imm.log("[*] Processing   %s !" % name)
            imm.Log("   [-] Signatue Not Found !" , focus=1, highlight=1)
            imm.Log("")
 
    # Checking for arguements !
        if not args:
            usage(imm)
 
        return "[+] See log window (Alt-L) for output / result ..."

for using this script you just need copy PeDetect.py in you PyCommand directory in immunity debugger python then copy Database.TXT in DATA folder in immunity debugger. after this you just need run it from immunity debugger command bar using !PeDetect you can see the output of this script against some files…


figure 6 – output of PeDetect against not packed file


figure 7 – output against  packed file

also this have an argument !PeDetect -u for updating your signature to our latest database. notice that my script will use md5checksum so your changes meaning it won’t be same as my database and your database will be update automatically.

figure 8 – update command

PS : after i wrote this i saw another PyCommand named scanpe wrote by BoB at PeiD it’s really good and have PE scan option but have not update update so no more new signatures …

references :

  • Automatic Generation of String Signatures for Malware Detection
  • Signature Generation by korupt (http://korupt.co.uk)
  • Team PEiD forums
  • Immunity Debugger online documentation
  • FSecure – reverse engineering slides
  • My time

download PeDetect (database + pycommand) from : (please read the ReadMe.txt for installation guide)

http://abysssec.com/files/PeDetect.zip

happy new years !

cheers

The Portable Executable (PE) format is a file format for executables, object code, and DLLs, used in 32-bit and 64-bit versions of Windows operating systems. The term “portable” refers to the format’s versatility in numerous environments of operating system software architecture.

Microsoft Patch Analysis (binary diffing)

hello again to all our patient readers

it’s been a long time since we wrote our last post’s ?! first of all i should say sorry for late in blog updates but the first reason is  we are really busy in these days with accomplish our projects . the second reason was changing our server . and finally the third reason is starting abysssec inc with a professional team for accomplish new projects and services . in soon future we have lots of good news may that’s interest you . so please be patient to see our news on our new index (that come soon as soon possible)

===================================================================

today i wanna talk about Microsoft security patch’s analysis  . as you know this year and specially last month’s of this year was a nightmare for M$ windows because we saw MS08-067 – MS08-068 – MS08-006 and MS08-001 and etc . and as you know too publishing real and working exploits is going to die and just you can see commercial exploits on time .

i saw this picture in one of Mr Nicolas Waisman  presentation and i believe to mind of this picture :

my goal from this introduction is if you want an exploit on publishing time you just have two chose :

1- write your own exploit

2- buy commercial exploit for your requirement vulnerability

- if you are a super millionaire you can buy all commercial exploits from variant security research teams and we are one of them ;)

- and if you are not you and you like and you need an exploit on time you should write your own exploit . and writing exploit for modern operation system’s is not easy because you need bypass a dozen of memory protections (such as DEP / ASLR / SAFSEH / Safe unlinking   and etc …  (from OS to commercial target software) also i believe this Mr Dave Aitel sentence : Not only are bugs expensive but the techniques for reliably exploiting bugs becomes expensive .

anyway becoming a real exploit coder is not easy but it’s possible and i should quote and notice another sentence that is : Modern Exploits – Do You Still Need To Learn Assembly Language (ASM) ( you can read full post here : (http://www.darknet.org.uk/2008/09/modern-exploits-do-you-still-need-to-learn-assembly-language-asm/)

i,m fully sure learning assembly language will help you in all of exploit development levels from reversing and understanding vulnerability to writing reliable exploit code for modern operation system’s .

after you can understand assembly code you can supposition high level code and thereupon you can identify vulnerability from discrepancy between patched and unpatched binaries (however advanced tools and IDA plugin’s make your life easier and you can identify vulnerable code / function if a few minutes)  this technic is called binary diffing. in future i,ll discuss a few advanced trick and methods , that’s improve your speed and analysis but for now i just talk about main of binary diffing on Microsoft security patch’s .

first step is downloading patch from Microsoft . the best way is searching on Microsoft site for your target bulletin . for example see MS08-067 (my favorite bug in this year :D )

just you need click on your target os and download the path.

after you downloaded the patch as you know you should not install the patch and you need extract patch data

with /x command .for example extracting ms08-067 patch :

the output of executing atop command is extract all date inside the patch . and in this example result is :

as you can see in this patch we have just one file and that is a dll named netapi32.dll so we can understand vulnerable function is in this dll .

next step is find vulnerable (unpatched) file (or files) on your system and then you can rename patched file to filename_patched.XXX and then you can analysis and notice changes in patched and unpatched files.

for accomplish this procedure you can use different tools and ways . but using IDA Pro is one of best and logical ways you can use for this procedure . you can understand changes without any plugins and auxiliary tools but for imporving speed and getting better result you have tree choice .

1- using bindiff (exclusive commercial IDA plugin and best auxiliary too analysis

for example you can see patch analysis video for MS08-001 (TCP/IP Kernel Pool Overflow)  here :

http://www.zynamics.com/files/ms08001.swf

2- using Eeye DiffingSuite  i like this tools because it’s really easy to use and effective .

you can download this tools from following link :

http://research.eeye.com/html/Tools/download/DiffingSuiteSetup.exe

and also you see tree good video about analysis different patched with this tools

- analysing MS06-033 : http://research.eeye.com/html/tools/tutorials/BDS_v_MS06-033.htm

- analysing MS06-007 : http://research.eeye.com/html/tools/tutorials/MS06-007.htm

- analysing MS06-036 : http://research.eeye.com/html/tools/tutorials/MS06-036%20Analysis.htm

after videos please read following link (a good work from Mr stephen lawler) about full reverse of MS08-067 patch using DiffingSuite and IDA pro cheerfully because it contain divisor of work :

http://www.dontstuffbeansupyournose.com/?p=35

3- using tenable security PatchDiff . PatchDiff is another IDA Pro Plugin (like bindiff) but have a big difference with Bindiff this plugin is free !

you can see a video about this plugin here :

http://cgi.tenablesecurity.com/tenable/pdiff2.swf.html

and you can download this plugin from following link :

http://cgi.tenablesecurity.com/tenable/dl.php?p=patchdiff2-2.0.5.zip

using this plugin is so easy but i discuss a few about this plugin  . frist of all you need patched and unpatched binaries after this you just first need open unpatched binary IDA and save disassembly in idb file after that you should open patched binary and save disassembly result to another idb file :

since  this you just need open unpatched IDB using plugin to understating discrepancy . after this step as Mr Nicolas Pouvesle (pathdiff plugin author) discussed graph nodes can be synchronized by double clicking on a given node. Graphs use the following colors:

  • white: identical nodes
  • grey: unmatched nodes
  • red: matched nodes
  • tan: identical nodes (different crc)

for example you see patchdiff result for MS08-067 patch :

and :

if you be smart you can write a high level simulator code for vulnerable function . for example Mr Alexander Sotirov wrote a simulator of vulnerable function :


#include

// This is the decompiled function sub_5B86A51B in netapi32.dll on XP SP3
// and sub_6EA11D4D on Vista SP1

int ms08_067(wchar_t* path)
{
wchar_t* p;
wchar_t* q;
wchar_t* previous_slash = NULL;
wchar_t* current_slash = NULL;
wchar_t ch;

#ifdef VISTA
int len = wcslen(path);
wchar_t* end_of_path = path + len;
#endif

// If the path starts with a server name, skip it

if ((path[0] == L’\\’ || path[0] == L’/') &&
(path[1] == L’\\’ || path[1] == L’/'))
{
p = path+2;

while (*p != L’\\’ && *p != L’/') {
if (*p == L’\0′)
return 0;
p++;
}

p++;

// make path point after the server name

path = p;

// make sure the server name is followed by a single slash

if (path[0] == L’\\’ || path[0] == L’/')
return 0;
}

if (path[0] == L’\0′) // return if the path is empty
return 1;

// Iterate through the path and canonicalize ..\ and .\

p = path;

while (1) {
if (*p == L’\\’) {
// we have a slash

if (current_slash == p-1) // don’t allow consequtive slashes
return 0;

// store the locations of the current and previous slashes

previous_slash = current_slash;
current_slash = p;
}
else if (*p == L’.’ && (current_slash == p-1 || p == path)) {
// we have \. or ^.

if (p[1] == L’.’ && (p[2] == L’\\’ || p[2] == L’\0′)) {
// we have a \..\, \..$, ^..\ or ^..$ sequence

if (previous_slash == NULL)
return 0;

// example: aaa\bbb\..\ccc
// ^ ^ ^
// | | &p[2]
// | |
// | current_slash
// |
// previous_slash

ch = p[2];

#ifdef VISTA
if (previous_slash >= end_of_path)
return 0;

wcscpy_s(previous_slash, (end_of_path-previous_slash)/2, p+2);
#else // XP
wcscpy(previous_slash, &p[2]);
#endif

if (ch == L’\0′)
return 1;

current_slash = previous_slash;
p = previous_slash;

// find the slash before p

// BUG: if previous_slash points to the beginning of the
// string, we’ll go beyond the start of the buffer
//
// example string: \a\..\

q = p-1;

while (*q != L’\\’ && q != path)
q–;

if (*p == L’\\’)
previous_slash = q;
else
previous_slash = NULL;
}
else if (p[1] == L’\\’) {
// we have \.\ or ^.\

#ifdef VISTA
if (current_slash != NULL) {
if (current_slash >= end_of_path)
return 0;
wcscpy_s(current_slash, (end_of_path-current_slash)/2, p+2);
goto end_of_loop;
}
else { // current_slash == NULL
if (p >= end_of_path)
return 0;
wcscpy_s(p, (end_of_path-p)/2, p+2);
goto end_of_loop;
}
#else // XP
if (current_slash != NULL) {
wcscpy(current_slash, p+2);
goto end_of_loop;
}
else { // current_slash == NULL
wcscpy(p, p+2);
goto end_of_loop;
}
#endif
}
else if (p[1] != L’\0′) {
// we have \. or ^. followed by some other char

if (current_slash != NULL) {
p = current_slash;
}
*p = L’\0′;
return 1;
}
}

p++;

end_of_loop:
if (*p == L’\0′)
return 1;
}
}

// Run this program to simulate the MS08-067 vulnerability

int main()
{
return ms08_067(L”\\c\\..\\..\\AAAAAAAAAAAAAAAAAAAAAAAAAAAAA”);
}

final steps are identify vulnerable function / understaning function parameters and write a POC code for controlling EIP .

for example Mr stephen lawler wrote a c program for checking MS08-067 vulnerability by taking the offset between sub_7CDDB23D and the load address of NETAPI32.DLL :


#include

#include

int wmain(int argc, wchar_t **argv)

{

HMODULE netapi32 = LoadLibraryW(argv[1]);

void (__stdcall *foo)(PWCHAR);

WCHAR buf[4096];

*(PVOID*)&foo = (PVOID)(((PUCHAR)netapi32) + 0×1b23d);

//__asm { int 3 }

wcscpy(buf, argv[2]);

foo(buf);

wprintf(L”%s\n”, buf);

}

and finnaly he got a crash :

after getting first crash you just need getting eip and write exploit for vulnerability .

finally i should say sorry for disheveled writing . the reason of this is size of this subject in next post i talk directly about patch analysis tricks and i,ll anlysis another interesting Microsoft Patch step by step .

thank you for your time and attention

best regards

shahin.r

Categories


Get Adobe Flash player