Successfully reported this slideshow.
Your SlideShare is downloading. ×

Introduction to Python for Security Professionals

Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Loading in …3
×

Check these out next

1 of 53 Ad

Introduction to Python for Security Professionals

Download to read offline

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.

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.

Advertisement
Advertisement

More Related Content

Viewers also liked (13)

Advertisement

Similar to Introduction to Python for Security Professionals (20)

Advertisement

Recently uploaded (20)

Introduction to Python for Security Professionals

  1. 1. Introduction to Python for Security Professionals
  2. 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. 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. 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. 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. 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. 7. Now for the boring stuff….syntax and some intro stuff
  8. 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. 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. 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. 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. 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. 13. Python Integers • Python Integers can not only be combined in print statements but they can also perform basic math functions:
  14. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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
  24. 24. Some Useful Python Modules
  25. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 42. Now For Fun Stuff: Use Cases
  43. 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. 44. Web Vulnerability Scanner Cont. • <!--Web Testing Framework (WTF) -->
  45. 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. 46. Sending Email • Yea you can send a lot 
  47. 47. Sending Email • Example pulled from python.org:
  48. 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
  49. 49. Reverse Shell
  50. 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. 51. Exploitation (Shellshock) Cont. • ShellShock Example:
  52. 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. 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! 

×