O SlideShare utiliza cookies para otimizar a funcionalidade e o desempenho do site, assim como para apresentar publicidade mais relevante aos nossos usuários. Se você continuar a navegar o site, você aceita o uso de cookies. Leia nosso Contrato do Usuário e nossa Política de Privacidade.
O SlideShare utiliza cookies para otimizar a funcionalidade e o desempenho do site, assim como para apresentar publicidade mais relevante aos nossos usuários. Se você continuar a utilizar o site, você aceita o uso de cookies. Leia nossa Política de Privacidade e nosso Contrato do Usuário para obter mais detalhes.
This webcast introduces Python for security professionals. The goal is to inspire others to push past the initial learning curve to harness the power of Python. This is just a quick glance at the power that awaits anyone willing to gain the skill. If you are looking for more resources check out DrapsTV's YouTube channel.
Introduction to Python for Security
• Knowing a scripting language can save loads of
time when dealing with manual, repetitive
• 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
• 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
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:
• 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.
• 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
• 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
• 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 can not only be combined in print statements but they
can also perform basic math functions:
• 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()”
Exploring a Function
• To further explore how to use a function you can revisit the
• The split() function is very useful for breaking up a string by a
• 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 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 in Python are very useful to performing some action if a
condition has occurred. The basic syntax for (if/elif/else) conditional logic is
• 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.
• 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
• 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
• 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 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
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
• 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
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
• 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
• 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
• Two useful functions are “headers” which will return the server response
headers, and “getcode” which will return the status code:
• Parsing HTML is a very common task to perform when doing web
• 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
• 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
• 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
• Good example of a bleeding edge vulnerability
that required tool development to check
• Couldn’t wait for a tool to have a check for it,
had to take action immediately
• 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!