Incursus Absconditus

Friday, March 13, 2015

During red team post exploitation I sometimes run into jump boxes leading to test environments, production servers, DMZs, or other organizational branches. As these systems are designed to act as couriers of outbound traffic, hijacking SSH sessions belonging to other users can be useful. So what do you do when you have full control over a jump box and want to leverage another user's outbound SSH access to tunnel into another segment? What if you don't have passwords, keys, shouldn't drop binaries, and SSH is protected by 2-factor authentication? Roll up your sleeves and trust your command line Kung Fu!

This post will cover two approaches to hijacking SSH sessions, without credentials, with the goal inserting dynamic port forwards on the fly. The two stages at which I'll approach hijacking sessions are: (1) upon session creation, and (2) when a live SSH session exists inside of screen (more common than you'd think). In each case our final goal is to create a tunnel inside another user's active session in order to gain access to outbound routes on the terminating SSHD host.

Hijacking SSH on Creation:

To hijack newly created SSH sessions we can leverage a feature known as SSH multiplexing. This feature allows for the creation of control sockets that enable an attacker to create their own sessions inside the original user' socket, without re-authentication. The ControlMaster feature was introduced in OpenSSH 4, and has was previously referenced in H D Moore and Val Smith's Tactical Exploitation presentation. I also demonstrated the attack in a talk/class of mine entitled, The Poor Man's Rootkit. In this post I will show two means to force the creation of master sockets, and then how to inject port forwards into them.

ControlMaster via SSH Client Config:

The most common way to deploy ControlMaster sockets is by altering the system wide SSH client config.

Inserting ControlMaster options into ssh_config on hop_1

These settings will cause all new SSH sessions to create a persistent brokering master socket.I've used %h in control socket commands to represent the target host, %h can be any char(s).

Master socket created in ControlPath

Connecting to the socket:

This socket can be used to create further sessions, without credentials, even after the original user exits their session.

Creating a session using a master socket.

Adding a dynamic tunnel:

Remember our end goal is to pivot into other network segments. The following command will create a dynamic tunnel inside an existing master socket.

Dynamic port forward added to live socket

Removing the socket:

Simply exiting the multiplexed sessions will not close the master socket. In order to close the socket you must explicitly send an exit request.

Shutting down the master socket

SSH ControlMaster via Shell Functions:

Another way to leverage this hijacking technique, that I haven't seen shared before, is by abusing the fact that master sockets may be created through SSH client option flags. As such, we can use a shell function to intercept a user's SSH client commands and inject our own ControlMaster arguments.

Flow of traffic in this attack:

Using SSH ControlMaster sockets and socket options we can now hijack SSH sessions and inject port forwards, all without authentication.
Now to tackle sessions in progress...

Hijacking Active SSH Sessions:

It is not uncommon for users to create screen sessions to house SSH connections to other boxes they are working on. What most users do not realize is that these session can be hijacked and have port forwards injected into them on the fly.

Hunting for screen sessions:
One way to find screen sessions is to look under /var/run/screen. Or you can enumerate a single user by issuing an incomplete screen -r command.

Hunting for screen sessions

Bypassing screen pts/tty restrictions:

Accessing the screen sessions of another user is not as straight forward su'ing and viewing; this is where many attackers give up. su to a user to interact with their screen session and you will find yourself staring at one of the following errors: "Cannot open your terminal '/dev/pts/#' - please check." or "Must be connected to a terminal."

Error when trying to access another user's screen session

One way to bypass this restriction is to use the script binary to wrap the su'd user session.

Using script to bypass screen pts/tty restrictions

Adding a tunnel on the fly:

A rarely used feature of SSH is the escape sub-shell. If you are using a means other than SSH to control your access to the jump box you can leverage escape sequences to add port forwards into another user's established session. Use ~C to drop into the SSH sub-shell, then -D:<port> to add a dynamic forward on the fly. To remove the forward use ~C followed by -KD:<port>

Adding port forwards with SSH escape commands

If you are using SSH for your primary shell the above example willnot work from inside screen.This is due to the fact that your own outermost SSH client will catch the escape characters. Not to worry, I'll show you a way around that!

Creating tunnels with screen stuffing:

Screen has a feature that allows you to "Stuff" the contents of a buffer into its input queue. The stuffed text is parsed as if it had been typed from inside screen, allowing us to bypass escape characters being caught by outer SSH sessions.

Stuffing screen to create a port forward

Stuffing screen to shutdown a port forward

A note on stealthy stuffing: Stuff'd text is visible inside a screen session's scroll back. You can prevent this by altering the scroll back length on the fly. This can be done by changing the scrollback to 0 lines before your command, clearing the screen, then setting it back.

Tuesday, October 14, 2014

There has been a great deal of sharing of client side techniques of late, so I thought I'd toss out a tip. A means to have a PE executable terminate and delete itself while running on a modern Windows system. The technique we will use is not new, but is one I discovered independently while tinkering with thread injection techniques a few years back.

If you have worked with a modern Windows systems you are familiar, at least on an abstract level, that once an executable has been mapped to virtual memory you cannot delete the file from disk until the handle is closed. Self-deleting a "Persisted memory-mapped file" is often solved by writing a secondary script (.bat||.ps1||.vbs) to disk as a clean-up stub. A cleaner way to do this is to spawn a windowless process in a new process group and inject code to terminate the calling PE, and remove the file from disk. This post includes a purposefully verbose example written in python to attempt to clearly illustrate this technique.

Since many people are familiar with the CreateThread function, due to it's popularity in shellcode execution, we will use the CreateRemoteThread function for our examples. The only difference people already familiar with CreateThread will notice is that CreateRemoteThread takes a process handle argument denoting the remote process into which we injected our code.

Attempt to Delete Executable from Modern Windows System:

If you've ever attempted to delete an open file on a modern Windows system you are familiar with the following dialog.

Self Removal Via Remote Thread Injection:

In order to terminate and delete a running PE we will use two things: the full file path and the current process id. If you are using an interpreted language, you may also wish to know whether the processes is running as a standalone script or from inside a packed executable.

State Detection:

As many people are using Python with things like pyinstaller, p2exe, or cx_Freeze to pack up interpreted code. Creating code that works when run as a script or a packed PE can useful. In this example I use Thomas Heller's (ctypes and py2exe notoriety) suggestions found here to determine the state of the file, script, or exe.

Building our Payload:

As this point of this post is clarify the deletion method and not about writing shellcode that calls DeleteFileA from kernel32.lib, I will use slightly modified shellcode from the Metasploit project's WinExec payload. I change the value of uCmdSHow to cause our commands to run without a visible window. The second part of our shellcode is a bit of a hack, but hopefully it makes things accessible and clear to the reader. Since we aren't writing our own shellcode, and don't have access to SleepEx, we use ping along with an unreachable address and a known timeout to create a sleep state. The purpose of this sleep is to ensure that the call to taskkill has completed terminating the primary process before we attempt to remove it from disk. In writing your own code you may choose to simply have the process exit() before removing the file. I find terminating the process to be a more aggressive form of removal when triggering this method of self-deletion on errors or signals.Command String -

Remote Process:

You can use any process for which you can request appropriate handle permissions, however, I recommend you open a new process that will not be interacted with by users. Additionally, be mindful of process load time when using thread creation flags that request immediate execution. For these reason I will use notepad.exe.

Injection Process:

There are four stages to our remote thread injection. First we must request access to interact with the remote process we are targeting as our cleanup helper via OpenProcess. Once we have a handle with appropriate permission, we allocate enough memory for our payload with VitualAllocEx. Now that we have a space to write our payload, we copy our buffer into the space using WriteProcessMemory. If the write succeeds, we can kick off our code with CreateRemoteThread. There are many ways to perform remote thread injection, those shown here are among the most common and easy to follow.

Note: You can also start your helper process then inject a suspended thread that is triggered from your primary process based on later signals, exceptions, or states. I shy away from this as it leaves a larger footprint in the process list.

Libraries and Compilation:

Common libraries/methods that can provide access to the functions necessary for this approach:

When compiling code that uses this method, due to difference in size of PROCESS_ALL_ACCESS between windows versions, be certain to set _WIN32_WINNT || _WIN32_WINNT_WINXP appropriately. Alternatively, you can simply compile your code on a system relative to the oldest Windows version your code will target.

Example Self Deleting File:

The following code will self delete using remote threat injection as either a raw python script or when ran as an executable.
I've tried to make the significance of each Windows function argument as clear as possible. Code on github.

Cleanup:

I encourage people to explore other methods of code injection and self deletion, there's lots of great tricks out there to be learned. Additionally, consider adding timeout dates to your client-sides that cause self-deletion to trigger before payload execution if a client-side is ever executed outside of scoped testing dates.

Friday, August 1, 2014

We all can get a little lazy relying on the frameworks that have arisen due to the monetization of offensive skills. In light of this, I wanted to make a short post to inspire people to explore what can still be done by rubbing two sticks together in a shell.TL;DR - The command line. Use it more, and harder.

Food for Thought

There are thousands of command line tips, tricks, and hacks. I'll toss out a few examples I've used in the last month to get your creativity flowing.

Reverse SSL Shell:

A simple reverse shell using fifos and openssl s_client. There's a great deal you can do with this tool, take a look at the server options.

Why bother cracking a password when you can have a user type it for you?
This can also be done with an alias. Which can be hidden with control characters (think ^M).

Spy on Stdin by Tracing System Calls:

Need to know what a user is typing in their tty?

sudo strace -f -p <tty_pid> 2>&1 | grep -o -e 'read(., \".*", 1)'

Note: We follow forks with -f in order to grab subprocess and sudo password input.

Fun with stdin Pipes:

Don't want the user to see your sudo wrapper, a command, or specific argument? There are dozens of ways to avoid logging with escapes and sub-shells (mail, gdb, ash).

But what about creating a pipe of standard in?

$(< /dev/stdin)
<anything you want>
^D^D

How could you further hide the process with shell wrappers, aliases, symlinks, exec renames?
What I'm getting at here is, never underestimate the power of leveraging built-in tools in unintended ways.

The Mindset

For me, this style of thinking is the true sense of "hacking." Learning about an environment or system until you understand what you can make it do, irrespective of what it was intended to do.

Next time you look at a system, environment, or command, ask yourself the following. Does it: create sockets, alter data, read files, elevate privileges, control the flow of data, alter appearances to a user or process, impact commands before or after execution, alter keyboard entry, import anything from anywhere... ? The list and impact is only limited by your creativity.

Friday, June 6, 2014

- Exploiting Local Interprocess Command Sockets -

How this came to be:
A few weekends ago I was working through exercises from the folks at Offensive Security when the VPN connection died. ifconfig told me that the tap interface was down, out of habit I fired off netstat to see what other connections were established, something strange stood out. There was a root-owned process listening in the Registered Ports range, the port number didn't ring a bell.

Digging deeper with lsof, the process turned out to be KeepNote, an open source tool used by OffSec students and pentesters alike to organize their notes.

This is the story of how that netstat became a root shell.

Creating the Perfect Storm

The Protocol:
The first step in our exploration is figuring out exactly what traffic goes over this socket.

The KeepNote help menu hints of an interprocess command functionality present in the software.

Watching the IPC in action we discover a clear-text protocol with an unknown numeric string common across sessions.

To test whether this string plays a role in authentication and or authorization, we replay the session via a raw socket.

We just might have something here...

The Pin:
The numeric string appears to be the sole authentication mechanism in the protocol, let's track down how it is created.
A look at the source code reveals the following function. We now know that authentication is based off a key space of 1,000,001 pins

The Socket:
Just how feasible it is to brute force this pin, and what controls are in place?
For this we search for instances of the socket listen and accept methods.

Note: Here we discover the port is randomized on process startup.

We have a listen backlog of 1, however, the manner in which connections are accepted in no way prevents brute forcing the pin. Use of the loopback interface lends additional advantage in the form of a speed increase, and elimination of the need to carefully handle timeouts.

The Port:

Port randomization in open_socket() forces us to create a means by which to reliably map the PID to a PORT number. Many of you will shout: netstat, lsof, ss, ps, fuser! If you explore these solutions you’ll find the -p flag and process to socket information is not available to non-privileged users.

We grep /proc for potential representations of the port number and find hex representing the socket pair present in /proc/<pid>/net/tcp. We are able to leverage state information in the file to further identify the socket. From the enum in tcp_states.h we know 0A represents a TCP_LISTEN state.

We now have everything we need to discover, map, and crack the IPC pin. Onward to code execution!

The Commands:
After some exploration, leveraging extension installation functionality seems the most likely path to execution of code.

Investigation of the extension format reveals they are zipped archives containing an informational XML file and the Python code for the extension.

Reviewing the code, there appears to be an "Extension" class inherited from keepnote.gui.extension.Extension, we choose this as our target for execution.

By poisoning the __init__ method of this class, we can gain execution when an instance of the class is created. Importantly, we do so with low likelihood of disrupting normal execution flow.

The Payload:
Our first attempt at using the install command results in a user prompt. We could social engineer the interaction as follows, but this is less than ideal:

Digging for alternate ways to instantiate an extension, we find on_temp_extension(). This function initializes a single session extension instance without user interaction. It lacks functionality to unpack our archive, so we'll need to extract the extension contents ourselves.

User interaction required.

Silent extension installation.

We now have everything we need to escalate privileges on the system.The Mitigation:
In order to mitigate this attack, I recommend starting KeepNote with the --newproc flag. Use of this flag will prevent the command socket from being created. As the project does not appear to be under active development, and exposure to this vulnerability is rather low, turning off the IPC socket will be an
acceptable mitigation for most users.

I have contacted the primary author of the project out of courtesy.

Note, this blog is in no way a commentary on the competency of the authors of the project, many of whom I'm certain are more capable developers than myself; thanks for the great software folks!

Note: I've also written a threaded version of this POC, however, under Python 2.7.* the GIL drastically impacts the speed of the attack. A speed increase can be had by leveraging taskset to force process affinity to one core, however, if speed is a major concern, C is the answer.

Enough Talk, uid=0 Time!

Hijacking the KeepNote IPC socket to execute arbitrary code.

In order to demonstrate this vulnerability, we create a user with no privileged group membership or sudoer privileges. We then use this account to exploit the IPC socket, gaining a root shell.

Saturday, March 8, 2014

- Leaving a Key Under the Mat -

Why Do This:
On a recent engagement, I ran into a well-meaning individual who, after being briefed about our team's access to their network, decided to reboot compromised hosts and change user credentials in the middle of the testing. After losing multiple shells that weren't actually being detected, I decided to spend that evening after work creating a method to let myself back in.

There are numerous common persistence methods, however, leaving behind registry keys, start-up configurations, or any permanent files was strictly out of the question. Additionally, I wanted the source of reentry to be remotely triggered, C&C independent, and any changes to the system should appear plausibly legitimate.

What We Want:

No files left behind: binaries, vbs, ps1, batch, mof, xml...

Persistence across sessions and reboots

Functional under non-privileged user accounts

No need for user credentials or interaction

Ability to reinfect unique hosts individually

Self cleaning, independent of system access

Configurable time-based poling

Remotely Mutable C2 Addressing

C2 & payload only visible during reinfection window

Plausibly believable configurations

The means of persistence on which I settled was Microsoft's Background Intelligent Transfer Service (BITS), and the associated bitsadmintool:

Nothing is New:

Bitsadmin has received some coverage of late, most notable are the following examples.

Use of the /SetNotifyFlags 1 causes BITS to "Generate an event [ONLY] when all files in the job have been transferred."

Leveraging /SetNotifyCmdLine we issue the /Complete command and subsequently execute our payload. Without use of /Complete BITS will leave our files in a tmp state and not move them to the correct directory within the file system. This usage of /SetNotifyCmdLine along with /Complete seem to be missing from most examples of using this tool.

Utilizing the %RANDOM% variable in our /AddFile command, along with environment variables in our /SetCustomHeaders command, we create a host-specific HTTP request header and trigger file. We can now easily identify each machine and trigger their reinfection independently of one another.

Issuing the above commands results in the following request being sent to our C&C server:

Component Two: Monitoring our Backdoor
We can monitor BITS requests in our Apache access.log as follows, or we can do better...

To generate a log that leverages our custom file names and request headers, we add some Apache CustomLog and SetEnvIf directives to /etc/apache2/sites-enabled/000-default

After restarting Apache, we now have a BITS only log with the exact information we need:

Unfortunately, we aren't quite done yet. If our BITS job sends a HEAD requests for a file that does not exist we completely lose access.

From MSDN:

ERROR — A nonrecoverable error occurred; the transfer will not be retried.

Component Three: Priming BITS with schtasks.exe
To solve the problem of BITS entering an error state, we use schtasks to resume our job at regular intervals. This will allow our backdoor to persist regardless of the state of our C&C, or presence of a trigger-file.
Crafting our Scheduled Task

Important Settings:# The /resume flag will restart our BITS job if it has entered an error state
/TR %WINDIR%\system32\sbitsadmin.exe /resume...# Utilizing a "schedule modifier" we create a task whose actions will trigger every X minutes.
/SC minute /MO <X># Using an end date and end time we set an expiration date for our task
/ED <DATE> /ET <TIME># Using the /Z flag causes our task to self delete at the specified end date and time
/Z# Run as %USERNAME% executes our task under a compromised user without need for credentials
/IT /RU %USERNAME%
Our Newly Created Task
This task will automatically delete itself once it has reached the end date and time.

A note on plausible configurations and persistence methods:
Some will argue that we could simply utilize this scheduled task to trigger a download and execution request at a regular interval. Perhaps pole for a powershell script. They are not incorrect, however, I prefer to leverage the innocuous appearance of the task. I am of the mind that not exposing our C&C IP or Domain name in our scheduled task puts us at a lower risk of discovery; the average user, and even administrator, is highly unlikely to view the details of our BITS job. The curious are likely only to run common informational commands such as bitsadmin /list and bitsadmin /info, not revealing our C&C information without the /verbose flag. An even more nefarious attacker might go as far as to point their C&C DNS at a legitimate Windows Update server until needed, making the HTTP call back traffic appear legitimate up to and after reinfection. I certainly would never suggest doing such a thing, but yield that the more believable the configuration, the more effective the backdoor.

Enough Talk, Lets Do This Thing!

Combing bitsadmin and schtasks we can deploy a backdoor by pasting the following into our shell.

Demo Time:

Deploy the Backdoor:
A callback interval of 2 minutes is used for testing, 60-90 minutes is quieter for actual use.

Phoning Home:
The initial schtasks /run triggers our first phone home as seen in our monitoring log.

Losing our Session:
After killing the session, I rebooted the box, then logged on, off, and on again as two different users.
Our backdoor phones home soon after the user under whom it was deployed logs on.

Reinfecting the Host:
We deploy a payload using the custom trigger-file name for the machine we wish to target.

Host Acquires Payload:
The host whose trigger-file we used pulls down our payload.

Back in Business:
Successful transfer triggers /SetNotifyCmdLine to /Complete our download and executes the payload.
I used a self-deleting PE, you could also use a blank file to trigger a reflective powershell execution.

At this point the BITS job is removed. You can redeploy the backdoor by pasting it back into your shell. If you ever need to preemptively clean the backdoor use:

bitsadmin /reset && schtasks /delete /TN <taskname> /F

Rising from the dead: Mutable C2 Addressing

There are two reasons we use a domain name and not a static IP to host our trigger-files. First, we can use a domain that looks potentially legitimate. Second, it allows us to change C&C reinfection hosts in case your original IP gets blocked. This will take some time, as it relies on propagation of a new A/AAAA record and the expiration of any DNS cache; still better than losing our access.

After about an hour the request arrives at our new C&C and we are back in again!

Compromise, Infection, Loss of Shell, Persistence, Reinfection

At this point, anyone defending the network should be reacting something like this.

How'd We Do?:

No files left behind: binaries, vbs, ps1, batch, mof, xml... ✓

Persistence across sessions and reboots ✓

Functional under non-privileged user accounts ✓

No need for user credentials or interaction ✓

Ability reinfect unique hosts individually ✓

Self cleaning, independent of system access ✓-

Configurable time-based poling ✓

Remotely Mutable C2 Addressing ✓

C2 & payload only visible during reinfection window ✓

Plausibly believable configurations ✓

Shortcomings:

When the bitadmin /resume command is run by task scheduler, under a non-system level account, the user may see a small flash as the argument is passed to cmd.exe. This can be prevented by creating the task under a system account, or having the task only trigger on idle time.

The BITS job is removed automatically upon success, however, if the task is removed and the BITS job never completes, it will remain in the queue in an inactive ERROR state and will not be tried again. You can prevent this a number of ways: another task, a secondary trigger... I'll leave that practice up to you. I personally am not terribly concerned about it.

So there you have it, highly resilient persistence that cleanly expires with your engagement.Go learn something ...@ThemsonMester