Python For Security - Chapter 1
Python For Security - Chapter 1
Revision + Basics
WHAT IS CYBER SECURITY?
Cyber Security is the practice of defending and protecting computer
systems, mobile devices, data, networks, and servers from disruptive
malicious attacks.
• Cross-platform
• Free
• Interpreted: it runs directly from the source code
(no need to compile it)
• Often used in scripting roles
• Easily usable in conjunction with components
written in other languages
Why Python?
Python is friendly.
Prototyping in Python is quick.
Many security tools are written in Python
Adding modules is painless.
Widely used (Google, NASA, Yahoo, etc)
It is a multi-platform and open source language.
It is a simple, fast, robust, and powerful language.
Python allows penetration testers and programmers to save time
by creating scripts that accelerate a job or task performance.
Python is commonly used for:
Binary analysis
Forensics
Malware analysis
Network analysis
Exploring file formats
Vulnerability and exploit analysis
Binary Analysis - Tasks
Disassembling code
Binary to Assembly
Automating the analysis of code
Deobfuscating code
Full binary analysis frameworks have been written in Python
Forensics - Tasks
File and disk analysis.
Timelines
Parsing the registry.
Memory analysis.
Analyzing memory dumps
Malware Analysis- Tasks
Scanning files.
Extracting data.
Network Analysis- Tasks
Protocol and decoding analysis
PCAP parsing.
Decompressing files.
Fuzzing
Providing invalid, unexpected or random data as input to see if the data invokes exceptions
or crashes
Scripts.
• A comma at the end of the statement (print (‘hello’),) will not print a newline
character
• print(‘hello’, ‘there’)
Documentation
• The ‘#’ starts a line comment
• Can usually just use %s for everything, it will convert the object to its String
representation.
• There are many types of variables, such as integers, real numbers, Booleans, strings,
tuples or more complex data such as lists or dictionaries. .
• Create a variable named ‘x’ and assigns the value 10 to that variable.
The second statement creates a new variable y and assigns the string
“Hello”.
x = 10
• We do not need to declare the type of the variable.
y = “Hello”
Variables & Types
• The same variable could first refer to an integer value, and later be assigned a
different data type.
• Numbers
>>> num1=22
>>> num2=33.5
>>> sum= num1+num2
>>> print("Sum of two numbers is %s"%sum)
Sum of two numbers is 55.5
>>>
Variables & Types
• String types
• Strings are a sequence of characters, sentences, or words.
>>> my_first="Welcome to python strings ! "
>>> my_first
'Welcome to python strings ! '
>>>
• String Concatenation
>>> userName = “Mousa”
>>> domainName = “philadelphia.edu.jo”
>>> userEmail = userName + “@” + domainName
>>> userEmail
' Mousa @ philadelphia.edu.jo‘
Variables & Types
• Strings can be declared in many different ways.
Functions
a=0 evaluates to a=0
a +=1 evaluates to a = a + 1
a -= 1 evaluates to a = a + 1
a *= 2 evaluates to a = a * 2
a /= 5 evaluates to a = a / 5
a **= 3 evaluates to a = a ** 3
a //= 2 evaluates to a= a // 2 (floor division 2)
a %= 5 evaluates to a= a % 5
Input
• The raw_input(string) method returns a line of user input as a string
• The parameter is used as a prompt
• The string can be converted by using the conversion methods int(string),
float(string), etc.
• Or: True: If any of the two operands are non-zero, then the condition becomes true. For
example, (a or b) is true.
• Not: True: This is used to reverse the logical state of its operand.
For example, not (a and b) is false.
Functions Example
and a&b
or a|b
xor a^b
Logical operators:
Conditional statements
• The conditional statements supported by Python are as follows:
1. if condition
2. if...else condition
• If the if condition evaluates to a True value, the code block indented under if is
executed. Otherwise, the code block indented under the else block is executed.
• An if condition let's specify a condition alongside the else part of the code. Only if the
condition is true is the section proceeding the conditional statement executed.
a=44
b=66
if a > b:
print("a is Greater")
elif b > a:
print("B is either Greater or Equal")
else:
print("A and B are equal")
print("End")
Loops
Python offers two loops:
• while loop
• for loop
• As long as the condition is evaluated to True, the body of the while (statement_block) is
executed repeatedly.
• When the condition is evaluated to False, the while loop terminates, and the
post_while_statementswill be executed.
Loops
• while loop
• Unlike many other programming languages, in Python, the for loop does not
increment and test a variable against a condition on each iteration.
Loop Control Statements
x=1
~: python whileelse.py
while x < 3 :
1
print x
2
x=x+1
hello
else:
print 'hello'
Loops
• for loop
for x in range(5):
print x
break ~: python elseforloop.py
else : 1
print 'i got here'
Lists
• Python lists are similar to arrays in other programming languages; they are ordered
collections of any type of object.
• Lists are data structures that hold values separated by commas inside square brackets
([]) These values can either be strings or integers.
Lists
• In almost every programming language, indices start from 0; this
applies to Python as well.
0 first
1 2
2 els
3 4
Lists
• lists can contain objects of different types.
• We do not need to fix its size.
• Python gives you the ability to append values at the end of the list.
• You can also remove a value from the list.
• Where the element on the left of the of the colon is the key, and the
element on the right is its associated value.
• As much as lists, dictionaries can store objects of any type and values
are not implicitly ordered.
Dictionaries
• The above code shows some operations on dictionary elements.
• we can access an element like we did with lists, but now we have to use
keys instead of indices.
Functions
• A function is a group of statements that gets executed when it is called
(function call).
• The general form of a function definition is:
Where:
Functions are treated like any other variable in Python, the def
statement simply assigns a function to a variable
Functions
• In Python, each call to a function creates a new local scope as well as all the assigned
names within a function that are local to that function.
Functions
The variable scope
• Two variables x are used, but they have different values depending on their scope.
• The first x is local to the function and can be used only within my_sum. Each change
made to this variable has no effect outside the function.
• The second x is global and can be used in the entire program (within the single file).
Functions
• Parameters are usually passed by position; this means that when we call a function,
the parameters in the calling function are matched according to their order.
• So the number of parameters used by the caller and the called function must be the
same; otherwise, an exception will be raised.
Functions
• In Python, we can change this behavior passing variables by name;
this is possible by using the name of the corresponding parameter.
Modules
• A module is a file that contains source code. The main purpose of modules is to
group Python functions and objects in order to organize larger projects. Note that
in addition to Python code, we can also import C++ object files.
• To import any function or any object within the module, we can use the following
syntax:
• Moreover, if we want to import all functions and objects within the module, we
can also use the following syntax:
Modules
string, re
os, sys, socket
hashlib
httplib, urllib2
The OS Module
• Python OS module provides the facility to establish the interaction between the
user and the operating system.
• It offers many useful OS functions that are used to perform OS-based tasks and
get related information about operating system.
• The OS comes under Python's standard utility modules. This module offers a
portable way of using operating system dependent functionality.
• To work with the OS module, we need to import the OS module.
import os
The OS Module
• Running external programs are very essential in most programming languages,
especially the scripting.
>>> Import os
>>> print os.system("notepad.exe")
>>> import os
>>> os.getcwd()
'C:\\Python27'
>>>
The OS Module
• The os.mkdir() function is used to create new directory.
• It will create the new directory to the path in the string argument of the
function in the D drive named folder philadelphia.
>>> os.mkdir("d:\\ philadelphia")
>>>
>>> import os
>>> os.name
'nt'
The OS Module
• The os.startfile() method allows us to “start” a file with its associated program.
• In other words, we can open a file with it’s associated program, just like when
you double-click a PDF and it opens in Adobe Reader.
>>> os.startfile('D:\py1.pdf')
>>>
The sys Module
• The sys module provides system specific parameters and functions.
• To work with the SYS module, we need to import the SYS module.
import sys
• The sys.platform value is a platform identifier.
• Basically this tells Python what locations to look in when it tries to import a module.
>>>
The hashlib Module
• The hashlib module is an interface for hashing messages easily. This contains numerous
methods which will handle hashing any raw message in an encrypted format.
• The core purpose of this module is to use a hash function on a string, and encrypt it so
that it is very difficult to decrypt it.
The hashlib Module
• To work with the hashlib module, we need to import the hashlib module.
import hashlib
• Algorithms Guaranteed:
1. hashlib.md5(password) 2. hashlib.new('md5',password)
Mode Description
'r' Open for text file for reading text
'w' Open a text file for writing text
'a' Open a text file for appending text
Reading and Writing Files
Opening Files in Python
• Python has a built-in open() function to open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.
>>> f = open("D:\Test\First.txt","w")
>>> f.write("my first file\n")
>>> f.write(“This file\n\n")
>>> f.write(“contains three lines file\n")
>>>f.close()
Reading and Writing Files
The file object provides three methods for reading text from a text file:
>>> f = open("D:\Test\First.txt","a")
>>> f.write(“\npython for security is very importan\n")
>>> f.close()
>>> f = open("D:\Test\First.txt","r")
>>> f.readlines()
['my first file\n', 'my first file22222\n', 'my first file55555\n’,’python for security
is very importan\n’]
>>>f.close()
>>>