SlideShare a Scribd company logo
Introduction to Python for Security
Professionals
Overview
• Knowing a scripting language can save loads of
time when dealing with manual, repetitive
tasks
• Python is a nice language to learn because the
syntax isn’t too complicated and there are a
lot of 3rd party modules that can do heavy
lifting for you
Overview Cont.
• This talk will lightly touch on some basics about
the language and introduce some syntax
• Then we will talk about some use cases for
Python so you can see what can be accomplished
once you learn the language
• We are going to run through stuff quickly, this
talk is designed to be used as a reference for later
But I Do Not Write Code
• You might think “I don’t know how to write code”, and you
may tune this talk out because you think you wont
understand it
Learning to Code
• Learning a programming language is like starting a
friction fire….it takes a bit of work up front, but once
you get the initial ember the fire starts quickly
Why Learn a Scripting Language?
• You can’t rely on automated tools
• Many tasks can be automated to save time
• Writing a tool for something gives you a
deeper understanding on the topic
Now for the boring stuff….syntax and
some intro stuff
Running Python Code
• Python can be run directly from the binary on the CLI:
• Python code can be written directly into a Python interpreter:
• Python code can be placed in a file:
Python Interpreter
• Once you drop into the Python interpreter you can start to
write your Python code on the fly
• This is very useful for quickly testing syntax/logic before
putting it into a more complex script
• I generally have a file up on part of my screen and the
interpreter up and validate syntax/logic in the interpreter and
then pull it over to my final script.
Indentation
• Python does force indentation
• For loops, conditional statements, functions,
etc. all will require indentation
• Some people uses spaces (2 or 4) and some
use tabs. The documented standard via
Python.org is 4 spaces
Data Types
• Understanding how to manipulate and work with various data types will
help you a lot when you start to write more complex code
• Two common data types in Python are strings and integers
• The type() function can be used to check the data type of a given variable
or object:
Python Strings
• There are loads of functions to manipulate strings
• You can extract part of the string by referencing its offset in the string
• You can find the length of a string by using the len() function
Python Integers
• Python Integers can not only be combined in print statements but they
can also perform basic math functions:
Python Lists
• Python lists are a collection of data types
• The string function “split()” breaks a line up into a list
• You can print an element of an array based on its offset and add and
remove items with “.append” and “.remove”
Python help() function
• Python has a built-in function that is very useful to leverage
when developing code in the interpreter
• This function is similar to Linux man pages
• Below is the syntax to check the help menu for the “type()”
function:
Exploring a Function
• To further explore how to use a function you can revisit the
help() method
• The split() function is very useful for breaking up a string by a
certain character.
• Below we concatenate a string and then split it by the “:”:
Creating and Reading Files
• The ability to create and read in files in Python allow for you to create reports from
your tools output and read in input files to parse
• When we execute the first line of code on line 2 we are creating a file object
pointed to by the variable “file”, but you could use any variable name
• The main difference between reading and writing a file is the ‘w’ for write, and ‘r’
for read. There is also a the ‘a’ for appending to an existing file
For Loops
• For loops can be useful ways to iterate through a list or range of items. Below we
see the syntax to go from a range of “1000” to “1024” and print a statement for
each item in the range:
• For loops can also be used to iterate through a file:
Conditional Statements
• Conditional statements in Python are very useful to performing some action if a
condition has occurred. The basic syntax for (if/elif/else) conditional logic is
below:
• We only print the string “Do Search!” if the domain is equal to ‘google.com’. This a
very simple example to demonstrate the concept and syntax. This concept will be
leveraged heavily in further code snippets later in the course.
Creating Functions
• One common way to leverage a function is to have a snippet of code that
performs some action and returns the output. Below is some basic pseudo
code demonstrating this concept
• The basic syntax is def <functionName>: followed by the body of the
function being indented
Exception Handling
• As you start to write your own Python tools you will undoubtedly hit some
conditions when errors will occur:
– Can’t connect to the host
– Syntax error
– No data is returned from a particular function
– Etc.
• How do you handle these various errors? You can do so with a simple
Try/Except loop in Python. The snippet below will pass all errors and
create what looks like “error-free” code:
Python Skeleton Script
• Up till now we have been showing example code in the Python interpreter
• You can also store your code in a file
• Below is a skeleton script you can leverage to structure your code.
Python Modules
• Python modules are one of the most powerful features
• They extend functionality for your Python script. So if you wanted to
make a web request, you could just import the module “urllib” instead of
having to write all the code from scratch.
• There are many built-in modules and 3rd party modules developed by the
InfoSec community
Some Useful Python Modules
Python OS module
• The OS module is extremely useful because you can essentially run any OS
command using the function “os.system”
• As you might imagine the ability to run OS commands from a Python script
can be very handy and help with a number of automation use cases we
will explore later in the course
Python Sys Module
• The sys module is a quick way to pull in arguments given at the command
line into your script
• The sys arguments are passed in as a list starting with 0 is the script name
and 1 is the next argument, 2 is the next and so on
Python Subprocess Module
• As you begin to create Python scripts you will likely find yourself
leveraging os.system and subprocess.Popen because they let you run OS
commands.
• The main difference between os.system and subprocess.Popen is that
subprocess allows you to redirect STDOUT to a variable in Python.
Python Subprocess Module Cont.
• You might wonder why you’d want to use the subprocess module because
the syntax is a lot more complicated than the OS module
• The ability to redirect the output of a command to a variable is extremely
valuable because now you can modify or parse the output, or do
something else with the output in the script
• Here is another example of the syntax for the subprocess module to run a
system command:
Python Pseudo-Terminal Module
• A raw shell is a command shell (cmd.exe, /bin/sh) bound to a network
socket and either thrown back to the attacker (reverse shell), or bound to
a listening port.
• Raw shells don’t handle STDIN/STDOUT/STDERR the same way terminal
access does (SSH access, directly at the keyboard, etc.).
• Python’s Pseudo-Terminal module can upgrade your raw shell!
• What this means is typing certain commands in a raw shell can break
“dork” the shell. The easiest way to experience this first hand is to toss a
netcat shell back to yourself.
Python Pseudo-Terminal Module Cont.
• To demonstrate this we will spawn a quick reverse shell using netcat
– Start a listener and connect to the listening port with a shell
– Now we can inspect the raw shell command execution:
Python Pseudo-Terminal Module Cont.
• As you can see in the previous slide you don’t see the command prompt.
This is because the prompt is sent over STDERR and this isn’t handled in a
raw shell
• Now lets look at the syntax to spawn a Pseudo-terminal in the raw shell:
• This is a quick one liner in Python that directly executes the code in the
quotes. It is important to note the varying quotes from outer being
double and inner being single. The following will produce a syntax error:
Python Pseudo-Terminal Module Cont.
• Below you can see the affect of spawning a pseudo-terminal in the raw
shell. As you can see this is much better shell access to the system:
Python Optparse Module
• The optparse module is a module to build in command-line switches to
your scripts
• It is very useful because it even will build in a help menu with “-h”
• You’ll need to import optparse in the script and the syntax below shows
how you can add in a variable/CLI argument of “-r”:
Reading User Input
• In Python you may run into a situation when you want to capture input from a
user and then execute some further logic.
• This can be accomplished using Python’s “raw_input()” function:
• In the code snippet above, we prompted the user for their name and stored the
string in the “name” variable.
Making Web Requests - urllib
• When performing web application assessments, the ability to craft web
requests in Python is essential
• Python has many libraries to support interaction with web resources
(urllib, urllib, requests, BeautifulSoup, etc.) We are going to explore
several of these in the course
• Below is the basic syntax to make a web request in Python using urllib:
Making Web Requests – urllib cont.
• Once we make the request with urllib we have many built-in functions we
could leverage.
• Two useful functions are “headers” which will return the server response
headers, and “getcode” which will return the status code:
Parsing HTML
• Parsing HTML is a very common task to perform when doing web
application testing.
• HTML has various tags that the page is broken down into (<head>, <body>,
<a href>, etc.)
• BeautifulSoup is a very useful Python module to parse HTML
• It lets you extract information from a request based on HTML tags
Parsing HTML Cont.
• Below you can see the syntax to extent our previous web request example
to include it being parsed with BeautifulSoup:
• Now we can print various parts of the response based on the HTML tags.
Parsing HTML Cont.
• You can also have it search the entire document to find all tags that match
the tag of interest using the “find_all” function.
• This is very useful for attempting to extract all the <a href> links from a
response.
• That could be any tag of interest (<iframe>, <p>, <ul>, etc.)
Compiling Python Scripts to EXEs
• Python scripts can be compiled into a Portable Executable (PE) file format
using PyInstaller
• This is beneficial if you want to run your code on a Windows system that
doesn’t have Python installed
• Take the example script below:
Compiling Python Scripts to EXEs Cont.
• We can compile that script into an executable using PyInstaller
• The syntax is likely a lot easier than you might initially expect
• Now your code can run directly from the executable as opposed to using
Python as the interpreter
Now For Fun Stuff: Use Cases
Web Vulnerability Scanner
• Simple example – could be improved by pulling in a list of
URLs to run against a longer list of resources:
Web Vulnerability Scanner Cont.
• <!--Web Testing Framework (WTF) -->
Parsing Data (Nmap)
• Needing to parse a file is a common use case for scripting. Below is an example of
parsing Nmap to extract open ports and formatting the URL properly
Sending Email
• Yea you can send a lot 
Sending Email
• Example pulled from python.org:
Reverse Shell
• You can do a fancy 1-liner:
• This same logic can be broken down into a file
to better understand
• Next slide will show an example from
TrustedSec
Reverse Shell
Exploitation (Shellshock)
• Good example of a bleeding edge vulnerability
that required tool development to check
across systems
• Couldn’t wait for a tool to have a check for it,
had to take action immediately
Exploitation (Shellshock) Cont.
• ShellShock Example:
Python Scripting: Resources
• Resources to Learn Python:
– Primal Security Tutorial Series:
• http://www.primalsecurity.net/tutorials/python-tutorials/
– Books (Violent Python, Black Hat Python, Gray Hat Python)
– Free Online:
• https://docs.python.org/2/tutorial/
• https://wiki.python.org/moin/BeginnersGuide/Programmers
• http://www.codecademy.com/en/tracks/python
– Python Courses:
• Google’s Free Python course:
– https://developers.google.com/edu/python/
• SecurityTube.net’s Python Scripting Expert course:
– http://www.securitytube-training.com/online-courses/securitytube-python-scripting-expert/
Summary
• To stay ahead of the curve you can’t always
rely on automated tools
• Being able to create your own quick scripts to
automate tasks can save you loads of time in
nearly in job function
• Learn a scripting language, its fun! 

More Related Content

What's hot (20)

PDF
CNIT 123 Ch 10: Hacking Web Servers
Sam Bowne
 
PDF
Privilege escalation from 1 to 0 Workshop
Hossam .M Hamed
 
PPT
Security and Linux Security
Rizky Ariestiyansyah
 
PPT
Ppt of socket
Amandeep Kaur
 
PDF
Mobile Application Penetration Testing
BGA Cyber Security
 
PPTX
Windows firewall
VC Infotech
 
PDF
Threat Intelligence
Deepak Kumar (D3)
 
PPTX
Network security (vulnerabilities, threats, and attacks)
Fabiha Shahzad
 
PPTX
seminar report on Sql injection
Jawhar Ali
 
PPTX
Fundamentals of Network security
APNIC
 
PPT
Data security in local network using distributed firewall ppt
Sabreen Irfana
 
PPT
Network Intrusion Detection System Using Snort
Disha Bedi
 
PDF
FINAL REPORT ON ENTERPRISE NETWORK
KulsumKhan13
 
PDF
Nikto
Sorina Chirilă
 
PDF
Ch 5: Port Scanning
Sam Bowne
 
PDF
Mobile Application Security
cclark_isec
 
PDF
Static Code Analysis
Annyce Davis
 
PPT
RedHat Linux
Apo
 
PPTX
Network defenses
Prachi Gulihar
 
PPTX
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
Soroush Dalili
 
CNIT 123 Ch 10: Hacking Web Servers
Sam Bowne
 
Privilege escalation from 1 to 0 Workshop
Hossam .M Hamed
 
Security and Linux Security
Rizky Ariestiyansyah
 
Ppt of socket
Amandeep Kaur
 
Mobile Application Penetration Testing
BGA Cyber Security
 
Windows firewall
VC Infotech
 
Threat Intelligence
Deepak Kumar (D3)
 
Network security (vulnerabilities, threats, and attacks)
Fabiha Shahzad
 
seminar report on Sql injection
Jawhar Ali
 
Fundamentals of Network security
APNIC
 
Data security in local network using distributed firewall ppt
Sabreen Irfana
 
Network Intrusion Detection System Using Snort
Disha Bedi
 
FINAL REPORT ON ENTERPRISE NETWORK
KulsumKhan13
 
Ch 5: Port Scanning
Sam Bowne
 
Mobile Application Security
cclark_isec
 
Static Code Analysis
Annyce Davis
 
RedHat Linux
Apo
 
Network defenses
Prachi Gulihar
 
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
Soroush Dalili
 

Viewers also liked (13)

PDF
Python build your security tools.pdf
TECHNOLOGY CONTROL CO.
 
PDF
Python for Penetration testers
Christian Martorella
 
PDF
Workshop - Linux Memory Analysis with Volatility
Andrew Case
 
PDF
Creating Your Own Threat Intel Through Hunting & Visualization
Raffael Marty
 
PDF
Cyber after Snowden (OA Cyber Summit)
Open Analytics
 
PPTX
MOLOCH: Search for Full Packet Capture (OA Cyber Summit)
Open Analytics
 
PDF
Big Data Visualization
Raffael Marty
 
PDF
Workshop: Big Data Visualization for Security
Raffael Marty
 
PPTX
Data-Driven Threat Intelligence: Useful Methods and Measurements for Handling...
Alex Pinto
 
PPTX
The Cyber Threat Intelligence Matrix
Frode Hommedal
 
PDF
No Easy Breach DerbyCon 2016
Matthew Dunwoody
 
PPTX
Taking the Attacker Eviction Red Pill (v2.0)
Frode Hommedal
 
PPTX
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
Carol Smith
 
Python build your security tools.pdf
TECHNOLOGY CONTROL CO.
 
Python for Penetration testers
Christian Martorella
 
Workshop - Linux Memory Analysis with Volatility
Andrew Case
 
Creating Your Own Threat Intel Through Hunting & Visualization
Raffael Marty
 
Cyber after Snowden (OA Cyber Summit)
Open Analytics
 
MOLOCH: Search for Full Packet Capture (OA Cyber Summit)
Open Analytics
 
Big Data Visualization
Raffael Marty
 
Workshop: Big Data Visualization for Security
Raffael Marty
 
Data-Driven Threat Intelligence: Useful Methods and Measurements for Handling...
Alex Pinto
 
The Cyber Threat Intelligence Matrix
Frode Hommedal
 
No Easy Breach DerbyCon 2016
Matthew Dunwoody
 
Taking the Attacker Eviction Red Pill (v2.0)
Frode Hommedal
 
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
Carol Smith
 
Ad

Similar to Introduction to Python for Security Professionals (20)

PDF
Tutorial on-python-programming
Chetan Giridhar
 
PPTX
Learn Python The Hard Way Presentation
Amira ElSharkawy
 
ODP
An Intro to Python in 30 minutes
Sumit Raj
 
PDF
Python for web security - beginner
Sanjeev Kumar Jaiswal
 
PPT
Python ppt
Mohita Pandey
 
PDF
How To Tame Python
Mohd Anwar Jamal Faiz
 
PDF
Introduction to python 3
Youhei Sakurai
 
PDF
Pyhton-1a-Basics.pdf
Mattupallipardhu
 
PPT
Python for Engineers and Architects Stud
RaviRamachandraR
 
PDF
Python_Session
siva ram
 
PDF
python-handbook.pdf
RaviKumar76265
 
PDF
Python intro
Abhinav Upadhyay
 
PPTX
Introduction-to-Python-Programming1.pptx
vijayalakshmi257551
 
PPT
iNTRODUCATION TO PYTHON IN PROGRAMMING LANGUAGE
shuhbou39
 
PPT
python1.pptpppppppppppppppppppppppppppppppp
divijareddy0502
 
PPT
Learn Python in three hours - Python is an experiment
Anil Yadav
 
PPT
python programing 101 presentation ... Let's start
Mohsen Hefni
 
PPT
pythegggggeeeeeeeeeeeeeeeeeeeeeeeon1.ppt
HamidKhemili
 
PPT
uso del lenguaje de programación python en métodos numéricos..ppt
angelca13
 
PPT
into python.pptinto python.pptinto python.ppt
yatakonakiran2
 
Tutorial on-python-programming
Chetan Giridhar
 
Learn Python The Hard Way Presentation
Amira ElSharkawy
 
An Intro to Python in 30 minutes
Sumit Raj
 
Python for web security - beginner
Sanjeev Kumar Jaiswal
 
Python ppt
Mohita Pandey
 
How To Tame Python
Mohd Anwar Jamal Faiz
 
Introduction to python 3
Youhei Sakurai
 
Pyhton-1a-Basics.pdf
Mattupallipardhu
 
Python for Engineers and Architects Stud
RaviRamachandraR
 
Python_Session
siva ram
 
python-handbook.pdf
RaviKumar76265
 
Python intro
Abhinav Upadhyay
 
Introduction-to-Python-Programming1.pptx
vijayalakshmi257551
 
iNTRODUCATION TO PYTHON IN PROGRAMMING LANGUAGE
shuhbou39
 
python1.pptpppppppppppppppppppppppppppppppp
divijareddy0502
 
Learn Python in three hours - Python is an experiment
Anil Yadav
 
python programing 101 presentation ... Let's start
Mohsen Hefni
 
pythegggggeeeeeeeeeeeeeeeeeeeeeeeon1.ppt
HamidKhemili
 
uso del lenguaje de programación python en métodos numéricos..ppt
angelca13
 
into python.pptinto python.pptinto python.ppt
yatakonakiran2
 
Ad

More from Andrew McNicol (12)

PPT
BSidesJXN 2017 - Improving Vulnerability Management
Andrew McNicol
 
PPT
BSides Philly Finding a Company's BreakPoint
Andrew McNicol
 
PPT
BSidesJXN 2016: Finding a Company's BreakPoint
Andrew McNicol
 
PPT
BSidesDC 2016 Beyond Automated Testing
Andrew McNicol
 
PPT
Beyond Automated Testing - RVAsec 2016
Andrew McNicol
 
PPTX
Pentesting Tips: Beyond Automated Testing
Andrew McNicol
 
PPTX
How To Start Your InfoSec Career
Andrew McNicol
 
PPTX
BSides_Charm2015_Info sec hunters_gathers
Andrew McNicol
 
PPTX
Introduction to Penetration Testing
Andrew McNicol
 
PPTX
Introduction to Malware Analysis
Andrew McNicol
 
PPTX
Tcpdump hunter
Andrew McNicol
 
PDF
OSINT for Attack and Defense
Andrew McNicol
 
BSidesJXN 2017 - Improving Vulnerability Management
Andrew McNicol
 
BSides Philly Finding a Company's BreakPoint
Andrew McNicol
 
BSidesJXN 2016: Finding a Company's BreakPoint
Andrew McNicol
 
BSidesDC 2016 Beyond Automated Testing
Andrew McNicol
 
Beyond Automated Testing - RVAsec 2016
Andrew McNicol
 
Pentesting Tips: Beyond Automated Testing
Andrew McNicol
 
How To Start Your InfoSec Career
Andrew McNicol
 
BSides_Charm2015_Info sec hunters_gathers
Andrew McNicol
 
Introduction to Penetration Testing
Andrew McNicol
 
Introduction to Malware Analysis
Andrew McNicol
 
Tcpdump hunter
Andrew McNicol
 
OSINT for Attack and Defense
Andrew McNicol
 

Recently uploaded (20)

PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Digital Circuits, important subject in CS
contactparinay1
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 

Introduction to Python for Security Professionals

  • 1. Introduction to Python for Security Professionals
  • 2. Overview • Knowing a scripting language can save loads of time when dealing with manual, repetitive tasks • Python is a nice language to learn because the syntax isn’t too complicated and there are a lot of 3rd party modules that can do heavy lifting for you
  • 3. Overview Cont. • This talk will lightly touch on some basics about the language and introduce some syntax • Then we will talk about some use cases for Python so you can see what can be accomplished once you learn the language • We are going to run through stuff quickly, this talk is designed to be used as a reference for later
  • 4. But I Do Not Write Code • You might think “I don’t know how to write code”, and you may tune this talk out because you think you wont understand it
  • 5. Learning to Code • Learning a programming language is like starting a friction fire….it takes a bit of work up front, but once you get the initial ember the fire starts quickly
  • 6. Why Learn a Scripting Language? • You can’t rely on automated tools • Many tasks can be automated to save time • Writing a tool for something gives you a deeper understanding on the topic
  • 7. Now for the boring stuff….syntax and some intro stuff
  • 8. Running Python Code • Python can be run directly from the binary on the CLI: • Python code can be written directly into a Python interpreter: • Python code can be placed in a file:
  • 9. Python Interpreter • Once you drop into the Python interpreter you can start to write your Python code on the fly • This is very useful for quickly testing syntax/logic before putting it into a more complex script • I generally have a file up on part of my screen and the interpreter up and validate syntax/logic in the interpreter and then pull it over to my final script.
  • 10. Indentation • Python does force indentation • For loops, conditional statements, functions, etc. all will require indentation • Some people uses spaces (2 or 4) and some use tabs. The documented standard via Python.org is 4 spaces
  • 11. Data Types • Understanding how to manipulate and work with various data types will help you a lot when you start to write more complex code • Two common data types in Python are strings and integers • The type() function can be used to check the data type of a given variable or object:
  • 12. Python Strings • There are loads of functions to manipulate strings • You can extract part of the string by referencing its offset in the string • You can find the length of a string by using the len() function
  • 13. Python Integers • Python Integers can not only be combined in print statements but they can also perform basic math functions:
  • 14. Python Lists • Python lists are a collection of data types • The string function “split()” breaks a line up into a list • You can print an element of an array based on its offset and add and remove items with “.append” and “.remove”
  • 15. Python help() function • Python has a built-in function that is very useful to leverage when developing code in the interpreter • This function is similar to Linux man pages • Below is the syntax to check the help menu for the “type()” function:
  • 16. Exploring a Function • To further explore how to use a function you can revisit the help() method • The split() function is very useful for breaking up a string by a certain character. • Below we concatenate a string and then split it by the “:”:
  • 17. Creating and Reading Files • The ability to create and read in files in Python allow for you to create reports from your tools output and read in input files to parse • When we execute the first line of code on line 2 we are creating a file object pointed to by the variable “file”, but you could use any variable name • The main difference between reading and writing a file is the ‘w’ for write, and ‘r’ for read. There is also a the ‘a’ for appending to an existing file
  • 18. For Loops • For loops can be useful ways to iterate through a list or range of items. Below we see the syntax to go from a range of “1000” to “1024” and print a statement for each item in the range: • For loops can also be used to iterate through a file:
  • 19. Conditional Statements • Conditional statements in Python are very useful to performing some action if a condition has occurred. The basic syntax for (if/elif/else) conditional logic is below: • We only print the string “Do Search!” if the domain is equal to ‘google.com’. This a very simple example to demonstrate the concept and syntax. This concept will be leveraged heavily in further code snippets later in the course.
  • 20. Creating Functions • One common way to leverage a function is to have a snippet of code that performs some action and returns the output. Below is some basic pseudo code demonstrating this concept • The basic syntax is def <functionName>: followed by the body of the function being indented
  • 21. Exception Handling • As you start to write your own Python tools you will undoubtedly hit some conditions when errors will occur: – Can’t connect to the host – Syntax error – No data is returned from a particular function – Etc. • How do you handle these various errors? You can do so with a simple Try/Except loop in Python. The snippet below will pass all errors and create what looks like “error-free” code:
  • 22. Python Skeleton Script • Up till now we have been showing example code in the Python interpreter • You can also store your code in a file • Below is a skeleton script you can leverage to structure your code.
  • 23. Python Modules • Python modules are one of the most powerful features • They extend functionality for your Python script. So if you wanted to make a web request, you could just import the module “urllib” instead of having to write all the code from scratch. • There are many built-in modules and 3rd party modules developed by the InfoSec community
  • 25. Python OS module • The OS module is extremely useful because you can essentially run any OS command using the function “os.system” • As you might imagine the ability to run OS commands from a Python script can be very handy and help with a number of automation use cases we will explore later in the course
  • 26. Python Sys Module • The sys module is a quick way to pull in arguments given at the command line into your script • The sys arguments are passed in as a list starting with 0 is the script name and 1 is the next argument, 2 is the next and so on
  • 27. Python Subprocess Module • As you begin to create Python scripts you will likely find yourself leveraging os.system and subprocess.Popen because they let you run OS commands. • The main difference between os.system and subprocess.Popen is that subprocess allows you to redirect STDOUT to a variable in Python.
  • 28. Python Subprocess Module Cont. • You might wonder why you’d want to use the subprocess module because the syntax is a lot more complicated than the OS module • The ability to redirect the output of a command to a variable is extremely valuable because now you can modify or parse the output, or do something else with the output in the script • Here is another example of the syntax for the subprocess module to run a system command:
  • 29. Python Pseudo-Terminal Module • A raw shell is a command shell (cmd.exe, /bin/sh) bound to a network socket and either thrown back to the attacker (reverse shell), or bound to a listening port. • Raw shells don’t handle STDIN/STDOUT/STDERR the same way terminal access does (SSH access, directly at the keyboard, etc.). • Python’s Pseudo-Terminal module can upgrade your raw shell! • What this means is typing certain commands in a raw shell can break “dork” the shell. The easiest way to experience this first hand is to toss a netcat shell back to yourself.
  • 30. Python Pseudo-Terminal Module Cont. • To demonstrate this we will spawn a quick reverse shell using netcat – Start a listener and connect to the listening port with a shell – Now we can inspect the raw shell command execution:
  • 31. Python Pseudo-Terminal Module Cont. • As you can see in the previous slide you don’t see the command prompt. This is because the prompt is sent over STDERR and this isn’t handled in a raw shell • Now lets look at the syntax to spawn a Pseudo-terminal in the raw shell: • This is a quick one liner in Python that directly executes the code in the quotes. It is important to note the varying quotes from outer being double and inner being single. The following will produce a syntax error:
  • 32. Python Pseudo-Terminal Module Cont. • Below you can see the affect of spawning a pseudo-terminal in the raw shell. As you can see this is much better shell access to the system:
  • 33. Python Optparse Module • The optparse module is a module to build in command-line switches to your scripts • It is very useful because it even will build in a help menu with “-h” • You’ll need to import optparse in the script and the syntax below shows how you can add in a variable/CLI argument of “-r”:
  • 34. Reading User Input • In Python you may run into a situation when you want to capture input from a user and then execute some further logic. • This can be accomplished using Python’s “raw_input()” function: • In the code snippet above, we prompted the user for their name and stored the string in the “name” variable.
  • 35. Making Web Requests - urllib • When performing web application assessments, the ability to craft web requests in Python is essential • Python has many libraries to support interaction with web resources (urllib, urllib, requests, BeautifulSoup, etc.) We are going to explore several of these in the course • Below is the basic syntax to make a web request in Python using urllib:
  • 36. Making Web Requests – urllib cont. • Once we make the request with urllib we have many built-in functions we could leverage. • Two useful functions are “headers” which will return the server response headers, and “getcode” which will return the status code:
  • 37. Parsing HTML • Parsing HTML is a very common task to perform when doing web application testing. • HTML has various tags that the page is broken down into (<head>, <body>, <a href>, etc.) • BeautifulSoup is a very useful Python module to parse HTML • It lets you extract information from a request based on HTML tags
  • 38. Parsing HTML Cont. • Below you can see the syntax to extent our previous web request example to include it being parsed with BeautifulSoup: • Now we can print various parts of the response based on the HTML tags.
  • 39. Parsing HTML Cont. • You can also have it search the entire document to find all tags that match the tag of interest using the “find_all” function. • This is very useful for attempting to extract all the <a href> links from a response. • That could be any tag of interest (<iframe>, <p>, <ul>, etc.)
  • 40. Compiling Python Scripts to EXEs • Python scripts can be compiled into a Portable Executable (PE) file format using PyInstaller • This is beneficial if you want to run your code on a Windows system that doesn’t have Python installed • Take the example script below:
  • 41. Compiling Python Scripts to EXEs Cont. • We can compile that script into an executable using PyInstaller • The syntax is likely a lot easier than you might initially expect • Now your code can run directly from the executable as opposed to using Python as the interpreter
  • 42. Now For Fun Stuff: Use Cases
  • 43. Web Vulnerability Scanner • Simple example – could be improved by pulling in a list of URLs to run against a longer list of resources:
  • 44. Web Vulnerability Scanner Cont. • <!--Web Testing Framework (WTF) -->
  • 45. Parsing Data (Nmap) • Needing to parse a file is a common use case for scripting. Below is an example of parsing Nmap to extract open ports and formatting the URL properly
  • 46. Sending Email • Yea you can send a lot 
  • 47. Sending Email • Example pulled from python.org:
  • 48. Reverse Shell • You can do a fancy 1-liner: • This same logic can be broken down into a file to better understand • Next slide will show an example from TrustedSec
  • 50. Exploitation (Shellshock) • Good example of a bleeding edge vulnerability that required tool development to check across systems • Couldn’t wait for a tool to have a check for it, had to take action immediately
  • 51. Exploitation (Shellshock) Cont. • ShellShock Example:
  • 52. Python Scripting: Resources • Resources to Learn Python: – Primal Security Tutorial Series: • http://www.primalsecurity.net/tutorials/python-tutorials/ – Books (Violent Python, Black Hat Python, Gray Hat Python) – Free Online: • https://docs.python.org/2/tutorial/ • https://wiki.python.org/moin/BeginnersGuide/Programmers • http://www.codecademy.com/en/tracks/python – Python Courses: • Google’s Free Python course: – https://developers.google.com/edu/python/ • SecurityTube.net’s Python Scripting Expert course: – http://www.securitytube-training.com/online-courses/securitytube-python-scripting-expert/
  • 53. Summary • To stay ahead of the curve you can’t always rely on automated tools • Being able to create your own quick scripts to automate tasks can save you loads of time in nearly in job function • Learn a scripting language, its fun! 