1. Test Environment
Hacking is influenced by the testing environment, and therefore, if an example does not work properly, please refer to the following table. For Windows, you must install the 32-bit version, and you must also install Python version 2.7.6.
Table of the Test Environment
Table of the Test Environment
Program
|
Version
|
URL
|
Windows
|
7
professional 32 bits
|
http://www.microsoft.com
|
Python
|
2.7.6
|
http://www.python.org/download
|
PaiMei
|
1.1
REV122
|
http://www.openrce.org/downloads/details/208/PaiMei
|
VirtualBox
|
4.3.10
r93012
|
https://www.virtualbox.org/wiki/Downloads
|
APM
|
Apache
2.4.9
MySQL
5.6.17
PHP
5.5.12
PHPMyAdmin
4.1.14
|
http://www.wampserver.com/en/
|
WordPress
|
3.8.1
|
https://wordpress.org/download/release-archive/
|
HTTP Analyzer
|
Stand-alone
V7.1.1.445
|
http://www.ieinspector.com/download.html
|
NMap
|
6.46
|
http://nmap.org/download.html
|
Python-nmap
|
0.3.3
|
http://xael.org/norman/python/python-nmap/
|
Wireshark
|
1.10.7
|
https://www.wireshark.org/download.html
|
Linux
|
Ubuntu
12.04.4 LTS Pricise Pangolin
|
http://releases.ubuntu.com/precise/
|
pyloris
|
3.2
|
http://sourceforge.net/projects/pyloris/
|
py2exe
|
py2exe-0.6.9.win32-py2.7.exe
|
http://www.py2exe.org/
|
BlazeDVD
|
5.2.0.1
|
http://www.exploit-db.com/exploits/26889
|
adrenalin
|
2.2.5.3
|
http://www.exploit-db.com/exploits/26525/
|
2. Starting Python
2.1 Selecting a Python Version
The latest version of Python is 3.3.4. As of November 30, 2014, the 3.3.4 and 2.7.6 versions are published together on the official website for Python. Usually, other web sites only link to the latest version. If this is not the latest version, then it is possible to download it from as a previous release. However, on the Python home page, both versions are treated equally because Python version 2.7.6 is used extensively.
Figure 1-1 Python Home Page
To hack using Python, you must learn to effectively use external libraries (third party libraries). One of the greatest strengths of using the Python language is that there are many powerful external libraries. Python version 3.x does not provide backward compatibility, so it is not possible to use a number of libraries that have been developed over time. Therefore, it is preferable to use the 2.7.6 version of Python for efficient hacking.
This book is written using Python 2.7.6 as the basis. Of course, external libraries will continue to be developed for 3.x from now on, but those who have studied this book to the end will be able to easily adopt a higher version of Python. If you study the basics of Python once, the syntax will not be a big problem.
2.2 Python Installation
First, connect to the download site on the Python home page (http://www.python.org/download). The Python 2.7.6 Windows Installer can be confirmed at the bottom of the screen. Click and download it to the PC.
Figure 1-2 Python Download Website
When you click on the link, the installation begins. The PC installation is automatically completed, and when all installation processes are complete, it is possible to confirm that the program is present by noticing the following icons.
Figure 1-3 Python Run Icon
3. Basic Grammar
3.1 Python Language Structure
#story of "hong gil dong" #(1)
name = "Hong
Gil Dong" #(2)
age = 18
weight = 69.3
skill = ["sword","spear","bow","axe"] #(3)
power = [98.5, 89.2, 100, 79.2]
querySkill = raw_input("select
weapon: ") #(4)
print "\n"
print "----------------------------------------"
print "1.name:", name #(5)
print "2.age:", age
print "3.weight:", weight
i=0
for each_item in skill: # (6)
if(each_item ==
querySkill): #(7)
print "4.armed
weapon:",each_item, "[ power", power[i],"]"
print ">>>i
am ready to fight"
i = i+1 #(8)
print "----------------------------------------"
print "\n"
|
The “IDLE” (Python application) can be used to develop, run and debug a program. The “Ctrl+S” key stores the program and “F5” key run it. Let's now look at an example that has been developed in IDLE.
(1) Comments: The lines starting with “#” are treated as comments in a program, and these are not executed. To comment out an entire paragraph, it must be enclosed in the [‘’’] symbol.
(2) Variable Declaration: The types of variables are not specified, and for Python only the name is declared.
(3) List: A list is enclosed in square brackets "[" and may be used as an “array”. The reference number starts from 0. The type is not specified, and it is possible to store strings and numbers together.
(4) Using the Built-in Functions: The built-in function “raw_input” is used here. This function receives user input and stores it in the variable “querySkill”
(5) Combining the String and Variable Value: A comma “,” makes it possible to combine the string and the Variable value.
(6) Loop: The “for” statement is a loop. The number of items in the “skill” list are repeated, and the start of the loop is represented by a colon “:”. There is no indication for the end of the loop, and the subroutines for the loop are separated by the indentation.
(7) Comparison and Branch Statement: It is possible to use an “if” statement to determine a “true” or “false” condition. The colon “:” specifies the start of the branch statement block, and in a manner similar to C and Java, a comparison uses the “==” symbol.
(8) Operator: Similar to C and Java, Python uses the “+” operator. Python also uses the following reserved words, and these reserved words cannot be used as variable names.
List 1-1 Reserved Words
And
|
del
|
for
|
is
|
raise
|
assert
|
elif
|
form
|
lambda
|
return
|
break
|
else
|
global
|
not
|
try
|
class
|
except
|
if
|
or
|
while
|
continue
|
exec
|
import
|
pass
|
yield
|
def
|
finally
|
in
|
print
|
Python is a language that dynamically determines the type for a variable. When the variable name is first declared, the type of variable is not specified, and Python will automatically recognize the type when you assign the value of the variable and store it in memory. There are some drawbacks in terms of performance, but this provides a high level of convenience to the programmer. Python supports data types, such as the following.
List 1-2 Frequently Used Data types
Numerics
|
int
|
Integer
|
1024, 768
|
float
|
Floating-point
|
3.14, 1234.45
|
|
complex
|
Complex
|
3+4j
|
|
Sequence
|
str
|
Strings, Immutable objects
|
“Hello World”
|
list
|
List, Mutable objects
|
[“a”,’’b”,1,2]
|
|
tuple
|
Tuple, Immutable objects
|
(“a”,”b”,1,2)
|
|
Mapping
|
dict
|
Key viewable list, Mutable
objects
|
{“a”:”hi”, “b”:”go”}
|
3.2 Branch Statements and Loop
In addition to Java and C, Python supports branch statements and loops. The usage is similar, but there are some differences in the detailed syntax. First, let's learn the basic structure and usage of the branch statement.
if <Conditions comparison 1>:
Execution syntax 1
elif <Conditions comparison 2>:
Execution syntax 2
else:
Execution syntax 3
|
Python uses a structure that is similar to that of other languages, but it has a difference in that it uses “elif" instead of “else if”.
Next, let's look at the loop. There are two kinds of loops: “while” and “for”. The function is similar, but there are some differences in terms of implementation. The most significant difference from other languages is that the “else” statement is used at the end.
while
|
for
|
while <Execution syntax>:
Execution syntax
else:
Execution syntax
|
for <Variable> in <Object>:
Execution syntax
else:
Execution syntax
|
The “for” statement is used to repeatedly assigns an item to a variable for only the number of items contained in the object. It runs a statement every time that an item is assigned, one by one. When the allocation of the item is completed, the loop ends after executing the commands defined in the “else” statement.
4. Functions
4.1 Built-in Functions
As with other languages, Python uses functions to improve the program structurally and to remove duplicate code. Python supports a variety of built-in functions that can be used by including a function call or importing a module. The “print” function is used most frequently and can be used without import statements, but mathematical functions can only be used after importing the “math” module.
import math
print “value of cos 30:”, math.cos(30)
>>>>>cos value of 30: 0.154251449888
|
4.2 User-defined Functions
It is possible to define functions to improve the program structure at the user level. The most typical grammar to use as a reserved word is “def”. “def” explicitly defines functions, and the function name and arguments then follow. It is therefore possible to specify the default values behind an argument.
def function(argument 1, argument 2=default value)
|
Let's change the Example 1-1 by using the user-defined function.
#story of "hong gil dong"
skill = ["sword","spear","bow","axe"]
power = [98.5, 89.2, 100, 79.2]
#start of function
def printItem(inSkill, idx=0): #(1)
name = "Hong
Gil Dong"
age = 18
weight = 69.3
print "\n"
print "----------------------------------------"
print "1.name:", name
print "2.age:", age
print "3.weight:", weight
print "4.armed
weapon:",inSkill, "[ power",
power[idx],"]"
print ">>>i
am ready to fight"
#end of function
querySkill = raw_input("select
weapon: ")
i=0
for each_item in skill:
if(each_item ==
querySkill):
printItem(querySkill, i) #(2)
i = i+1
print "----------------------------------------"
print "\n"
|
(1) Function declaration: Declare the “printItem” function that prints the value of the “power” list at a position corresponding to “inSkill” and “idx” received as an argument
(2) Calling User-Defined Functions: To perform a function, an index value for the “querySkill” value is passed, and the “skill” list that is received on the user input matches as the function of an argument
Since the default value is declared in the second argument “idx” of the “printItem” function, the function can be called without error even when passing only one argument at the time of the function call.
printItem(“sword”, 1)
printItem(“sword”)
printItem(“sword”, i=0)
|
5. Class and Object
5.1 Basis of Class
It is possible to develop all programs with Python both in a procedural way and in an object-oriented way. To develop simple hacking programs, it is convenient to use a procedural manner. However, to develop complex programs that are needed for operation in an enterprise environment, it is necessary to structure the program. An object-oriented language can be used to improve productivity during development by allowing for reusability and inheritance. If you use an object-oriented language, it is possible to develop a program that is logically constructed.
The basic structure to declare a class is as follows.
class name: #(1)
def __init__(self, argument): #(2)
def functioin(argument): #(3)
class name(inherited class ame): #(4)
def functioin (argument):
|
(1) Create a Class: If you specify a class name after using the reserved word “class”, the class is declared.
(2) Constructor: The “__ init__” function is a constructor that is called by default when the class is created. The “self” pointing to the class itself is always entered as an argument into the constructor. In particular, the constructor may be omitted when there is no need to initialize.
(3) Function: It is possible to declare a function in the class. An instance is then generated to call the function.
(4) Inheritance: In order inherit from another class, the name of the inherited class must be used as an argument when the class is declared. Inheritance supports the use of member variables and functions of the upper class as is.
5.2 Creating a Class
Through this example, let us find out use for the class declaration, initialization, and inheritance by replacing Example 4-2 with a class.
class Hero: #(1)
def __init__(self, name, age, weight): #(2)
self.name = name #(3)
self.age = age
self.weight = weight
def printHero(self): #(4)
print "\n"
print "--------------------------------------"
print "1.name:" , self.name #(5)
print "2.age:" , self.age
print "3.weight:" , self.weight
class MyHero(Hero): #(6)
def __init__(self, inSkill, inPower, idx):
Hero.__init__(self, "hong gil
dong", 18, 69.3) #(7)
self.skill = inSkill
self.power = inPower
self.idx = idx
def printSkill(self):
print "4.armed
weapon:" , self.skill + "[ power:" , self.power[self.idx], "]"
skill = ["sword","spear","bow","axe"]
power = [98.5, 89.2, 100, 79.2]
querySkill = raw_input("select weapon: ")
i=0
for each_item in skill:
if(each_item == querySkill):
myHero = MyHero(querySkill, power, i) #(8)
myHero.printHero() #(9)
myHero.printSkill()
i = i+1
print "--------------------------------------"
print "\n"
|
(1) Class Declaration: Declare the class “Hero”.
(2) Constructor Declaration: Declare the constructor that takes three arguments and the “self” representing the class itself.
(3) Variable Initialization: Initialize the class variables by assigning the arguments.
(4) Function Declaration: Declare the “printHero” function in the class.
(5) Using Variables: Use class variables in the format of “self.variable name”.
(6) Class Inheritance: Declare the “MyHero” class that inherits the “Hero” class.
(7) Calling the Constructor: Generate and initialize the object by calling the constructor of the upper class.
(8) Creating a Class: Generate a “MyHero” class. Pass along the arguments required to the constructor.
(9) Calling Class Function: The tasks are run by calling the functions that are declared for the “myHero” object.
6. Exception Handling
6.1 Basis for Exception Handling
Even if you create a program that has no errors in syntax, errors can occur during execution. Errors that occur during the execution of a program are called “exceptions”. Since it is not possible to take into account all of the circumstances that might occur during the execution, even when errors occur, the program must have special equipment to be able to operate normally. It is possible to make a program operate safely with exception handling.
The basic structure for exception handling is as follows.
try: #(1)
Program with Errors #(2)
except Exception type: #(3)
Exception Handling
else: #(4)
Normal Processing
finally: #(5)
Unconditionally executed, irrespective of the occurrence of the exception
|
(1) Start: Exception handling is started by using the reserved word “try”.
(2) Program with Errors: An error may occur during program execution.
(3) Exception Handling: Specify the type of exception that is to be handled. Multiple exception types can be specified, and when it is not clear what kind of exception can occur, it can be omitted.
(4) Normal Processing: If an exception does not occur, the “else” statement can be omitted.
(5) Unconditional Execution: This will be executed unconditionally, irrespective of the occurrence of the exception. The “finally” statement can be omitted.
6.2 Exception Handling
This simple example can be used to learn about the behavior to handle exceptions. Here, a division operation is used to divide by 0 in an attempt to intentionally generate errors. Let's then make a program for normal operation using the “try except’ statement.
try:
a = 10 / 0
#(1)
except:
#(2)
print "1.[exception]
divided by zero "
print "\n"
try:
a = 10 / 0
print "value
of a: ", a
except ZeroDivisionError: #(3)
print "2.[exception]
divided by zero "
print "\n"
try:
a = 10
b = "a"
c = a / b
except (TypeError, ZeroDivisionError): #(4)
print "3.[exception]
type error occurred"
else:
print "4.type
is proper" #(5)
finally:
print "5.end
of test program" #(6)
>>>
1.[exception] divided by zero
2.[exception] divided by zero
3.[exception] type error occurred
5.end of test program
|
(1) An Exception Occurs: In the middle of executing the division, an exception is generated by using 0 as the dividend.
(2) Exception Handling: Exception handling starts without specifying the type of exception, and an error message is printed.
(3) Indicating the Type of Exception: Start the exception handling by specifying the type of exception (ZeroDivisionError)
(4) Explicit Multiple Exceptions: It is possible to explicitly process multiple exceptions.
(5) Normal Processing: If no exception occurs, normal processing prints a message.
(6) Unconditional Execution: Regardless of whether or not an exception occurs, the program prints this message.
7. Module
7.1 Basis of Module
A module in Python is a kind of file that serves as a collection of functions that are frequently used. If you use a module, a complex function is separated into a separate file. Therefore, it is possible to create a simple program structure.
The basic syntax of the module is as follows.
import module #(1)
import module, module #(2)
from module import function/attribute #(3)
import module as alias #(4)
|
(2) A Plurality of Modules: It is possible to use multiple modules with a comma.
(3) Specifying Function: Specify the module name with “from”. Using “import” after that, specify the name of the function that is to be used.
(4) Using the Alias: It is possible to rename the module using a name that is appropriate for the program features.
You can check the module path that Python recognizes as follows. To save the module to another path, it is necessary to add the path by yourself.
import sys #(1)
print sys.path #(2)
sys.path.append("D:\Python27\Lib\myModule") #(3)
|
(1) Import sys Module: The “sys” module provides information and functions that are related to the interpreter.
(2) sys.path: Provides the path information that can be used to locate the referenced module.
(3) Add the Path: It is possible to add the path of new module by using the “path.append” function.
7.2 Custom Module
In addition to the basic modules that are provided in Python, modules can also be defined by the user. Here, we can learn how to create a custom module through a simple example. For convenience, let’s save the user-defined module in the same directory as the example. The prefix "mod" is used to distinguish it from a general program.
skill = ["sword","spear","bow","axe"]
#(1)
power = [98.5, 89.2, 100, 79.2]
def printItem(inSkill, idx=0): #(2)
name = "Hong Gil
Dong"
age = 18
weight = 69.3
print "\n"
print "----------------------------------------"
print "1.name:", name
print "2.age:", age
print "3.weight:", weight
print "4.armed
weapon:",inSkill, "[ power", power[idx],"]"
print ">>>i
am ready to fight"
|
(0) Creating a Module: Save it in the same directory as the program that calls the “modHero.py” module.
(1) Declaring Variable: Declare a variable that can be used internally or externally
(2) Declaring Function: Define a function according to the feature that the module provides.
To import a previously declared module, let's create a program that uses the functions in the module.
import modHero #(1)
querySkill = raw_input("select weapon: ")
i=0
for each_item in modHero.skill: #(2)
if(each_item == querySkill):
modHero.printItem(querySkill, i) #(3)
i = i+1
print "----------------------------------------"
print "\n"
|
(1) Import Module: Explicitly import the “modHero” module
(2) Module Variables: Use the “skill” variable that has been declared in the module “modHero”.
(3) Module Function: Use the “printItem” function that has been declared in the module “modHero”.
“sys” module supports the program to recognize the module in a different manner. It can be used in the same way as “sys.path.append(directory)”.
8. File Handling
8.1 Basis of File Input and Output
In the examples that have been developed so far, all of the data are lost when the program is finished, and when a new program is started, it is then necessary to enter the data again. Therefore, Python also has the ability to save and use data easily by accessing files.
The basic syntax for file input and output is as follows.
File object = open(file name, open mode) #(1)
File object.close() #(2)
Open mode
r read: Open for read
w write: Open for write
a append: Open for append
|
(1) Creating Object: Open the file object to handle files with a specified name. Depending on the open mode, it is possible to deal with file objects in different ways.
(2) Closing Object: After the use of the file object has finished, you must close the object. Python automatically closes all file objects at the end of the program, but if you try to use the file opened in the “w” mode, an error will occur.
8.2 File Handling
The following example can be used to learn how to create and read a file and add content. If you do not specify the location at the time of the file creation, the file is created in the same location as the program. After the “fileFirst.txt” and “fileSecond.txt” files have been created, let's create a simple program that print out each file.
import os
def makeFile(fileName, message, mode): #(1)
a=open(fileName,
mode)
#(2)
a.write(message) #(3)
a.close()
#(4)
def openFile(fileName): #(5)
b=open(fileName, "r") #(6)
lines = b.readlines() #(7)
for line in lines: #(8)
print(line)
b.close()
makeFile("fileFirst.txt","This is my
first file1\n","w") #(9)
makeFile("fileFirst.txt","This is my
first file2\n","w")
makeFile("fileFirst.txt","This is my
first file3\n","w")
makeFile("fileSecond.txt","This is my
second file 1\n","a") #(10)
makeFile("fileSecond.txt","This is my
second file 2\n","a")
makeFile("fileSecond.txt","This is my
second file 3\n","a")
print("write
fileFirst.txt")
print("-----------------------------")
openFile("fileFirst.txt") #(11)
print("-----------------------------")
print("\n")
print("write
secondFirst.txt")
print("-----------------------------")
openFile("fileSecond.txt") #(12)
print("-----------------------------")
>>>
write fileFirst.txt
-----------------------------
This is my first file3
-----------------------------
write secondFirst.txt
-----------------------------
This is my second file 1
This is my second file 2
This is my second file 3
-----------------------------
|
(1) Creating a Function: To handle a file, a function is declared to receive the file name, message, an open mode as an argument.
(2) Opening File: Creates a file object with the specified file name and open mode.
(3) Writing File: Records the message received in the file depending on the mode.
(4) Closing Object: After the use of the file object is finished, the object is closed. To create a more efficient program, it is preferable to place “open()” before and “close()” after the user-defined function. To provide for a simple explanation, place it inside the user-defined function.
(5) Creating a Function: Declare a function that receives the file name as an argument.
(6) Opening File: Create a file object that opens the file in the “r” mode.
(7) Reading the Content: Read all of the content contained in the file and save it to the list variable "lines".
(8) Loop: Repeat as many times as the number stored in the list.
(9) Creating a Write Mode File: Create a file named "fileFirst.txt" in the write mode. While this is repeated three times to record the content, in the write mode, only one piece of content that is recorded at last remains.
(10) Creating an Append Mode File: Create a file named "fileSecond.txt" in the append mode. All content that was repeatedly recorded three times is stored in the file.
(11) Opening the File: Open the file named “fileFirst.txt” for which you want to print the content. Only one row is printed.
(12) Opening the file: Open the file named “fileSecond.txt” for which you want to print the content. All three lines are printed.
You can copy and delete the files using a variety of modules, and it is is possible to move and copy by using the “shutil” module, and to delete the file by using the “os” module.
9. String Format
9.1 Basis of the String Format
The string format is a technique that can be used to insert a specific value into the string that you want to print out. The type of value inserted is determined by a string format code. The string format is used in the following manner.
print(“output string1 %s output string2” % inserted string)
|
Insert the string format code in the middle of the output string. Place the characters that you want to insert with the “%” code after the string.
List 1-3 String Format Code
%s
|
String
|
%c
|
Character
|
%d
|
Integer
|
%f
|
Floating Pointer
|
%o
|
Octal Number
|
%x
|
Hexadecimal Number
|
9.2 String Formatting
Let's learn how to use the string format through a simple example.
print("print string: [%s]" % "test")
print("print string: [%10s]" % "test") #(1)
print("print character: [%c]" % "t")
print("print character: [%5c]" % "t") #(2)
print("print Integer: [%d]" % 17)
print("print Float: [%f]" % 17) #(3)
print("print Octal: [%o]" % 17) #(4)
print("print Hexadecimal: [%x]" % 17) #(5)
>>>
print string: [test]
print string: [ test]
print character: [t]
print character: [ t]
print Integer: [17]
print Float: [17.000000]
print Octal: [21]
print Hexadecimal: [11]
|
If you use the string formatting codes and the numbers together, the characters can be used to secure a space according to the size of the numbers that are printed on the screen.
(1) Printing a Fixed Length Character String: If “%s” is used with a number, it secures space by an amount corresponding to the number. In the example, “test” is printed using 4 digits, and spaces are printed for the remaining six digits, so all 10 characters are printed.
(2) Printing a Fixed Character Containing Spaces of a Certaiin Length: If “%c” is used with a number, the amount corresponding to the number that is same a “%s” is printed. Therefore, one character and four blanks are printed.
(3) The string is the same as that used with the number "% c", which can be output only as a long number. The character of you, 4-digit blank is output
(3) Real Number: “17” is converted into a real number.
(4) Octal: “17” is converted into an octal number, and “21” is printed.
(5) Hex: “17” is converted into a hex number, and “11” is printed.
No comments:
Post a Comment