SlideShare a Scribd company logo
1 of 53
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

What's hot (20)

Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Event handling
Event handlingEvent handling
Event handling
 
Web Application Penetration Testing
Web Application Penetration Testing Web Application Penetration Testing
Web Application Penetration Testing
 
Blow fish final ppt
Blow fish final pptBlow fish final ppt
Blow fish final ppt
 
Introduction to penetration testing
Introduction to penetration testingIntroduction to penetration testing
Introduction to penetration testing
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Ethical hacking/ Penetration Testing
Ethical hacking/ Penetration TestingEthical hacking/ Penetration Testing
Ethical hacking/ Penetration Testing
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
 
Threads in python
Threads in pythonThreads in python
Threads in python
 
Cryptography
CryptographyCryptography
Cryptography
 
Python Cryptography & Security
Python Cryptography & SecurityPython Cryptography & Security
Python Cryptography & Security
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Rc4
Rc4Rc4
Rc4
 
Brute force-attack presentation
Brute force-attack presentationBrute force-attack presentation
Brute force-attack presentation
 
Introduction to cryptography and types of ciphers
Introduction to cryptography and types of ciphersIntroduction to cryptography and types of ciphers
Introduction to cryptography and types of ciphers
 
User authentication
User authenticationUser authentication
User authentication
 
Denial of service
Denial of serviceDenial of service
Denial of service
 
IP Security
IP SecurityIP Security
IP Security
 
Kali Linux
Kali LinuxKali Linux
Kali Linux
 

Viewers also liked

Workshop - Linux Memory Analysis with Volatility
Workshop - Linux Memory Analysis with VolatilityWorkshop - Linux Memory Analysis with Volatility
Workshop - Linux Memory Analysis with VolatilityAndrew Case
 
Creating Your Own Threat Intel Through Hunting & Visualization
Creating Your Own Threat Intel Through Hunting & VisualizationCreating Your Own Threat Intel Through Hunting & Visualization
Creating Your Own Threat Intel Through Hunting & VisualizationRaffael Marty
 
Cyber after Snowden (OA Cyber Summit)
Cyber after Snowden (OA Cyber Summit)Cyber after Snowden (OA Cyber Summit)
Cyber after Snowden (OA Cyber Summit)Open Analytics
 
MOLOCH: Search for Full Packet Capture (OA Cyber Summit)
MOLOCH: Search for Full Packet Capture (OA Cyber Summit)MOLOCH: Search for Full Packet Capture (OA Cyber Summit)
MOLOCH: Search for Full Packet Capture (OA Cyber Summit)Open Analytics
 
Big Data Visualization
Big Data VisualizationBig Data Visualization
Big Data VisualizationRaffael Marty
 
Workshop: Big Data Visualization for Security
Workshop: Big Data Visualization for SecurityWorkshop: Big Data Visualization for Security
Workshop: Big Data Visualization for SecurityRaffael Marty
 
Data-Driven Threat Intelligence: Useful Methods and Measurements for Handling...
Data-Driven Threat Intelligence: Useful Methods and Measurements for Handling...Data-Driven Threat Intelligence: Useful Methods and Measurements for Handling...
Data-Driven Threat Intelligence: Useful Methods and Measurements for Handling...Alex Pinto
 
The Cyber Threat Intelligence Matrix
The Cyber Threat Intelligence MatrixThe Cyber Threat Intelligence Matrix
The Cyber Threat Intelligence MatrixFrode Hommedal
 
No Easy Breach DerbyCon 2016
No Easy Breach DerbyCon 2016No Easy Breach DerbyCon 2016
No Easy Breach DerbyCon 2016Matthew Dunwoody
 
Taking the Attacker Eviction Red Pill (v2.0)
Taking the Attacker Eviction Red Pill (v2.0)Taking the Attacker Eviction Red Pill (v2.0)
Taking the Attacker Eviction Red Pill (v2.0)Frode Hommedal
 
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017Carol Smith
 

Viewers also liked (13)

Python build your security tools.pdf
Python build your security tools.pdfPython build your security tools.pdf
Python build your security tools.pdf
 
Python for Penetration testers
Python for Penetration testersPython for Penetration testers
Python for Penetration testers
 
Workshop - Linux Memory Analysis with Volatility
Workshop - Linux Memory Analysis with VolatilityWorkshop - Linux Memory Analysis with Volatility
Workshop - Linux Memory Analysis with Volatility
 
Creating Your Own Threat Intel Through Hunting & Visualization
Creating Your Own Threat Intel Through Hunting & VisualizationCreating Your Own Threat Intel Through Hunting & Visualization
Creating Your Own Threat Intel Through Hunting & Visualization
 
Cyber after Snowden (OA Cyber Summit)
Cyber after Snowden (OA Cyber Summit)Cyber after Snowden (OA Cyber Summit)
Cyber after Snowden (OA Cyber Summit)
 
MOLOCH: Search for Full Packet Capture (OA Cyber Summit)
MOLOCH: Search for Full Packet Capture (OA Cyber Summit)MOLOCH: Search for Full Packet Capture (OA Cyber Summit)
MOLOCH: Search for Full Packet Capture (OA Cyber Summit)
 
Big Data Visualization
Big Data VisualizationBig Data Visualization
Big Data Visualization
 
Workshop: Big Data Visualization for Security
Workshop: Big Data Visualization for SecurityWorkshop: Big Data Visualization for Security
Workshop: Big Data Visualization for Security
 
Data-Driven Threat Intelligence: Useful Methods and Measurements for Handling...
Data-Driven Threat Intelligence: Useful Methods and Measurements for Handling...Data-Driven Threat Intelligence: Useful Methods and Measurements for Handling...
Data-Driven Threat Intelligence: Useful Methods and Measurements for Handling...
 
The Cyber Threat Intelligence Matrix
The Cyber Threat Intelligence MatrixThe Cyber Threat Intelligence Matrix
The Cyber Threat Intelligence Matrix
 
No Easy Breach DerbyCon 2016
No Easy Breach DerbyCon 2016No Easy Breach DerbyCon 2016
No Easy Breach DerbyCon 2016
 
Taking the Attacker Eviction Red Pill (v2.0)
Taking the Attacker Eviction Red Pill (v2.0)Taking the Attacker Eviction Red Pill (v2.0)
Taking the Attacker Eviction Red Pill (v2.0)
 
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
 

Similar to Introduction to Python for Security Professionals

web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1Andrei KUCHARAVY
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
 
Introduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfIntroduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfVaibhavKumarSinghkal
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonMohammed Rafi
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1Ahmet Bulut
 
Python indroduction
Python indroductionPython indroduction
Python indroductionFEG
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptxQ-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptxnyomans1
 
Q-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptxQ-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptxJeromeTacata3
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptxArpittripathi45
 
Introduction to Python Programming Basics
Introduction  to  Python  Programming BasicsIntroduction  to  Python  Programming Basics
Introduction to Python Programming BasicsDhana malar
 
python intro and installation.pptx
python intro and installation.pptxpython intro and installation.pptx
python intro and installation.pptxadityakumawat625
 
Python for katana
Python for katanaPython for katana
Python for katanakedar nath
 
Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)Mohan Arumugam
 

Similar to Introduction to Python for Security Professionals (20)

web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1
 
Python intro
Python introPython intro
Python intro
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
Introduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfIntroduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdf
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Class_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdfClass_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdf
 
Python Course In Chandigarh
Python Course In ChandigarhPython Course In Chandigarh
Python Course In Chandigarh
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1
 
Python indroduction
Python indroductionPython indroduction
Python indroduction
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptxQ-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptx
 
Q-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptxQ-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptx
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
 
Introduction to Python Programming Basics
Introduction  to  Python  Programming BasicsIntroduction  to  Python  Programming Basics
Introduction to Python Programming Basics
 
python intro and installation.pptx
python intro and installation.pptxpython intro and installation.pptx
python intro and installation.pptx
 
Python for katana
Python for katanaPython for katana
Python for katana
 
Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)
 
MODULE 1.pptx
MODULE 1.pptxMODULE 1.pptx
MODULE 1.pptx
 

More from Andrew McNicol

BSidesJXN 2017 - Improving Vulnerability Management
BSidesJXN 2017 - Improving Vulnerability ManagementBSidesJXN 2017 - Improving Vulnerability Management
BSidesJXN 2017 - Improving Vulnerability ManagementAndrew McNicol
 
BSides Philly Finding a Company's BreakPoint
BSides Philly Finding a Company's BreakPointBSides Philly Finding a Company's BreakPoint
BSides Philly Finding a Company's BreakPointAndrew McNicol
 
BSidesJXN 2016: Finding a Company's BreakPoint
BSidesJXN 2016: Finding a Company's BreakPointBSidesJXN 2016: Finding a Company's BreakPoint
BSidesJXN 2016: Finding a Company's BreakPointAndrew McNicol
 
BSidesDC 2016 Beyond Automated Testing
BSidesDC 2016 Beyond Automated TestingBSidesDC 2016 Beyond Automated Testing
BSidesDC 2016 Beyond Automated TestingAndrew McNicol
 
Beyond Automated Testing - RVAsec 2016
Beyond Automated Testing - RVAsec 2016Beyond Automated Testing - RVAsec 2016
Beyond Automated Testing - RVAsec 2016Andrew McNicol
 
Pentesting Tips: Beyond Automated Testing
Pentesting Tips: Beyond Automated TestingPentesting Tips: Beyond Automated Testing
Pentesting Tips: Beyond Automated TestingAndrew McNicol
 
How To Start Your InfoSec Career
How To Start Your InfoSec CareerHow To Start Your InfoSec Career
How To Start Your InfoSec CareerAndrew McNicol
 
BSides_Charm2015_Info sec hunters_gathers
BSides_Charm2015_Info sec hunters_gathersBSides_Charm2015_Info sec hunters_gathers
BSides_Charm2015_Info sec hunters_gathersAndrew McNicol
 
Introduction to Penetration Testing
Introduction to Penetration TestingIntroduction to Penetration Testing
Introduction to Penetration TestingAndrew McNicol
 
Introduction to Malware Analysis
Introduction to Malware AnalysisIntroduction to Malware Analysis
Introduction to Malware AnalysisAndrew McNicol
 
OSINT for Attack and Defense
OSINT for Attack and DefenseOSINT for Attack and Defense
OSINT for Attack and DefenseAndrew McNicol
 

More from Andrew McNicol (12)

BSidesJXN 2017 - Improving Vulnerability Management
BSidesJXN 2017 - Improving Vulnerability ManagementBSidesJXN 2017 - Improving Vulnerability Management
BSidesJXN 2017 - Improving Vulnerability Management
 
BSides Philly Finding a Company's BreakPoint
BSides Philly Finding a Company's BreakPointBSides Philly Finding a Company's BreakPoint
BSides Philly Finding a Company's BreakPoint
 
BSidesJXN 2016: Finding a Company's BreakPoint
BSidesJXN 2016: Finding a Company's BreakPointBSidesJXN 2016: Finding a Company's BreakPoint
BSidesJXN 2016: Finding a Company's BreakPoint
 
BSidesDC 2016 Beyond Automated Testing
BSidesDC 2016 Beyond Automated TestingBSidesDC 2016 Beyond Automated Testing
BSidesDC 2016 Beyond Automated Testing
 
Beyond Automated Testing - RVAsec 2016
Beyond Automated Testing - RVAsec 2016Beyond Automated Testing - RVAsec 2016
Beyond Automated Testing - RVAsec 2016
 
Pentesting Tips: Beyond Automated Testing
Pentesting Tips: Beyond Automated TestingPentesting Tips: Beyond Automated Testing
Pentesting Tips: Beyond Automated Testing
 
How To Start Your InfoSec Career
How To Start Your InfoSec CareerHow To Start Your InfoSec Career
How To Start Your InfoSec Career
 
BSides_Charm2015_Info sec hunters_gathers
BSides_Charm2015_Info sec hunters_gathersBSides_Charm2015_Info sec hunters_gathers
BSides_Charm2015_Info sec hunters_gathers
 
Introduction to Penetration Testing
Introduction to Penetration TestingIntroduction to Penetration Testing
Introduction to Penetration Testing
 
Introduction to Malware Analysis
Introduction to Malware AnalysisIntroduction to Malware Analysis
Introduction to Malware Analysis
 
Tcpdump hunter
Tcpdump hunterTcpdump hunter
Tcpdump hunter
 
OSINT for Attack and Defense
OSINT for Attack and DefenseOSINT for Attack and Defense
OSINT for Attack and Defense
 

Recently uploaded

Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxFIDO Alliance
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...FIDO Alliance
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!Memoori
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentationyogeshlabana357357
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxFIDO Alliance
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...panagenda
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGDSC PJATK
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewDianaGray10
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxFIDO Alliance
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxFIDO Alliance
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfFIDO Alliance
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingScyllaDB
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...FIDO Alliance
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuidePixlogix Infotech
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch TuesdayIvanti
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...FIDO Alliance
 

Recently uploaded (20)

Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 

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! 