All About HackingBlackhat Hacking ToolsFree CoursesHacking

Hacking Tools with Python 2023

In this article we will learn about Hacking Tools with Python.

Overview [Hacking Tools with Python]:

Starting with the very basics of Python, we headed into loops, if else conditions, lists, pip and easy_install concepts, taking arguments from the user, reading and writing to files, handling exceptions, and sending basic requests to web servers.

Ok, so in this tutorial we will cover:

  • Taking input from the user in a more controlled manner.
  • Sending POST requests and handling the session.
  • Running a basic Click-Jacking test.


Let’s get started. There are two options for taking an argument from the user. Either we write our code using sys.argv[] and handle all exceptions and edge cases. Otherwise, we already have libraries like optparse and argparse to solve it for us and save us time. These libraries allow you to take multiple arguments from the user using switches. The best part is that even if no argument is passed, you don’t have to handle the same manually.

For now we will use optparse. Here is a sample code snippet for using Optparse.

import optparse
parser = optparse.OptionParser()
parser.add_option(‘-a’, ‘–firsttest’, action=”store”, dest=”first”, help=”Checks for first argument”, default=”spam”)
parser.add_option(‘-b’, ‘–secondtest’, action=”store”, dest=”second”, help=”Checks for second argument”, default=”spam”)
parser.add_option(‘-c’, ‘–thirdtest’, action=”store”, dest=”third”, help=”Checks for third argument”, default=”spam”)
options, args = parser.parse_args()
print “Hi, %s is out first argument” % (options.first)
print “Hi, %s is out second argument” % (options.second)
print “Hi, %s is out third argument” % (options.third)

First we imported the library; then we added some radio buttons through which we would like to receive input from the user. Since there are different attributes that we used in defining these switches, let’s go over them all.

The first argument i.e. “-a” can be accessed either by passing “-a” after the python name or it can be accessed by saying “- -firsttest”. Another important point here is the dest attribute. The value passed in this attribute contains the value passed by the user and we can access it later in our program. Help contains text that you would like to show your users so they understand what needs to be conveyed. This text appears when the user uses the –help or –h option after the filename.

Another important thing here is the default value. What if the user does not pass anything. Should the program be terminated? Well, of course not. Otparse remembers this and provides you with this default value option. You define a value that will be treated as the passed value if the user did not pass anything. You can do the same thing in a program by using if else stuff.

When you’re done, pass all of this to a variable called options. Not options.XXX will contain the value of your arguments, where XXX is the value you passed for the dest attribute in parser.add_option.

For example, if you want to read the value passed in argument – argument, options.first will give you the same.

Here is the output of using –h:

Figure 1: Arguments which are accepted by the program

Let’s run the program with switches. I am going to pass values to switch a and switch c and here is the output.

Figure 2: Sample run for OptParse

If you’d notice, since I didn’t pass the value of b, it automatically selected “spam” from the default attribute and printed the same thing.

Using if else conditions, we can further check this default behavior before printing it.

import optparse

parser = optparse.OptionParser()

parser.add_option(‘-a’, ‘–firsttest’, action=”store”, dest=”first”, help=”Checks for first argument”, default=”spam”)

parser.add_option(‘-b’, ‘–secondtest’, action=”store”, dest=”second”, help=”Checks for second argument”, default=”spam”)

parser.add_option(‘-c’, ‘–thirdtest’, action=”store”, dest=”third”, help=”Checks for third argument”, default=”spam”)

options, args = parser.parse_args()

#checking for first param

if (options.first != “spam”):

    print “Hi, %s is out first argument” % (options.first)

else:

    print “Please pass something in First Test”

#checking for second param

if (options.second != “spam”):

    print “Hi, %s is out second argument” % (options.second)

else:

    print “Please pass something in Second Test”

#checking for third param

if (options.third != “spam”):

    print “Hi, %s is out third argument” % (options.third)

else:

    print “Please pass something in Third Test”

Pretty simple, huh? Just check if the default value is spam or not, if the default value is spam, it means that nothing has been forwarded and allows the user to forward something. Please make sure you understand this part well because we’ll be using this optparse thing in most of our other programs (anywhere where user input is required).

Moving forward, let’s ask the user for the hostname and port number, then use a regular expression to validate the arguments passed. If everything is fine, we’ll run a basic ClickJacking check on the URL, and if something goes wrong, we’ll let the program freak out and display its own error message.

Division of the entire challenge into sub-challenges:

Take the hostname and port number from the user and verify the hostname.

import optparse

import re

parser = optparse.OptionParser()

parser.add_option(‘-t’, ‘–target’, action=”store”, dest=”hostname”, help=”Host where you want to check for common files.”, default=”spam”)

parser.add_option(‘-p’, ‘–port’, action=”store”, dest=”port”, help=”Port number to be used while hitting the host”, default=”80″)

#parser.add_option(‘-‘, ‘–search’, action=”store”, dest=”search”, help=”Define any search pattern, string / regex to be highlighted in the response pages.”, default=”spam”)

options, args = parser.parse_args()

hostregex = re.compile(“^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]).)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$”)

ipregex = re.compile(“^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$”)

host = options.hostname

port = options.port

if hostregex.match(host):

    print “n[+] Valid host – %sn” % (host)

elif ipregex.match(options.hostname):

    print “n[+] Valid host – %sn” % (host)

else:

    print “n[-] Invalid Hostname / IP Addressn”

Here we got the hostname from the user using the “-t” switch and the port number using the “–p” switch. Later we passed these values ​​to the host and port variables.

Since we have already imported the re library, we can use the re.match function to check whether a string matches a given regular expression or not. So we selected two variables, hostregex and iprexex, and passed the respective regexes to both. Note that these regex are converted to patterns using re.compile function, these patterns will help us to check whether the given value matches the pattern or not.

The regexes I used may not be perfect, but there are plenty of websites that allow you to create and validate regexes (we’re not too complex with this). If you are too lazy, use this link: http://lmgtfy.com/?q=online+regex+generator. Feel free to use other, more valid and precise regular expression patterns.

Once we have these regular expressions done, we used the regexpattern.match function and passed our string to it. It returns True if this matches, and False if not. We then use an if else condition that checks to see if True was returned when the host pattern was matched. If not, we tried the same with ipredex where we checked for a valid IP address. If this didn’t match either, our user probably entered some junk value, so let’s show them the error message in the Else block.

Here is the output for this program:

As you can see, when we passed www.facebook.com which is a valid domain name, it matched the regular expression and therefore a valid host is printed. The same happens for facebook.com (without www) and 10.0.1.2. All of these values ​​matched regular expression patterns and worked smoothly.

However, faceboo/34.com was clearly not a valid domain name and therefore did not match the pattern that resulted in the error message.

This brings us to the end of the first sub-challenge. Now that we can distinguish between a valid host and an invalid host, let’s check the ClickJacking vulnerability whenever we have a valid host. But before that, let’s quickly understand what ClickJacking is.

Imagine a web page, say target.com, that can be loaded into an iframe. If a website has a page, let’s say sendmoney.php, that contains a Send Money button, and hypothetically you click that button to send 1000 rupees to the email address listed in the text box next to it. (Now forget the hype of this statement, we’ve seen this stupid thing happen on many sites while testing pen apps)

Now, since this site can be loaded in an iframe, we as an attacker can host a page on our malicious site, say playtestgames.com. This page fetched the URL http://target.com/sendmoney.php in an iframe. Now we make this iframe transparent and create another div tag layer with fascinating objects (say Play Now and Click Here buttons/images) and place it right above the ‘Send Money’ button.

Now, when a normal user (already logged in on the same browser) comes to our site, they might think it’s a game and actually click the “play now” button, which ultimately clicks the “Send Money” button in the backend. If the user was already logged into their account, it would result in a deduction of 1000 rupees from their account.

ClickJacking is very popular and has affected a large number of websites, including major Internet giants, by making them vulnerable to such malicious activities.

An example would be this little google search: https://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=hackerone%20clickjacking

There are two main options for mitigation.

X-Frame-Options: This is a server response header and controls whether the browser should be allowed to render the page in a ,

import optparse

import requests

import re

parser = optparse.OptionParser()

parser.add_option(‘-t’, ‘–target’, action=”store”, dest=”hostname”, help=”Host where you want to check for common files.”, default=”spam”)

parser.add_option(‘-p’, ‘–port’, action=”store”, dest=”port”, help=”Port number to be used while hitting the host”, default=”80″)

#parser.add_option(‘-‘, ‘–search’, action=”store”, dest=”search”, help=”Define any search pattern, string / regex to be highlighted in the response pages.”, default=”spam”)

options, args = parser.parse_args()

hostregex = re.compile(“^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]).)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$”)

ipregex = re.compile(“^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$”)

host = options.hostname

port = options.port

if hostregex.match(host):

    print “Checking clickjacking on %s:%s” % (host,port)

    if (port == 443):

        req = requests.get(“https://” + host)

    else:

        req = requests.get(“http://” + host + “:” + port)

    try:

        print “[-] Not vulnerable to ClickJnX-Frame-Options response header present, Contains value %sn” % (req.headers[‘X-Frame-Options’])

    except:

        print “[+] Vulnerable to ClickJacking, but check framebusting.n”

elif ipregex.match(host):

    print “Checking clickjacking on %s:%s” % (host,port)

    if (port == 443):

        req = requests.get(“https://” + host)

    else:

        req = requests.get(“http://” + host + “:” + port)

    try:

        print “[-] Not vulnerable to ClickJnX-Frame-Options response header present, Contains value %sn” % (req.headers[‘X-Frame-Options’])

    except:

        print “[+] Vulnerable to ClickJacking, but check framebusting.n”

else:

    print “Please enter valid Hostname / IP Address”

As you may have noticed, we used the previous program to get the hostname and port from the user. Once we have the same and check that the hostname is valid, we send a simple GET request to the HTTP instance of the site, by default (since the default is set to port 80 in the optparse switch), or HTTPS if the port is 443 or hostname:portnumber , if none of the above conditions are met.

Once the response is returned, if the X-Frame option is present in the req.headers, display the value of the same X-Frame-Options and indicate that the site is not vulnerable. If it is not present, it indicates that the site is vulnerable to ClickJacking and may miss frames.

Note that we control this using the req.headers[‘X-Frame-Options’] variable.

With this we have successfully created a small tool that checks for ClickJacking vulnerability for a given host / IP. This is what the output looks like when passing different hostnames as arguments.

As you may have noticed, we used the previous program to get the hostname and port from the user. Once we have the same and check that the hostname is valid, we send a simple GET request to the HTTP instance of the site, by default (since the default is set to port 80 in the optparse switch), or HTTPS if the port is 443 or hostname:portnumber , if none of the above conditions are met.

RELATED ARTICLE:Everything you need to know about Ethical Hacking as a Career by Blackhat Pakistan 2023

Once the response is returned, if the X-Frame option is present in the req.headers, display the value of the same X-Frame-Options and indicate that the site is not vulnerable. If it is not present, it indicates that the site is vulnerable to ClickJacking and may miss frames.

Note that we control this using the req.headers[‘X-Frame-Options’] variable.

With this we have successfully created a small tool that checks for ClickJacking vulnerability for a given host / IP. This is what the output looks like when passing different hostnames as arguments.

I hope this tutorial was clear and you wrote the tool too. For more fun, you can try a few things:

  • Once you have identified the clickjacking vulnerability, create an HTML PoC for ClickJacking.
  • Read the list of hostnames from the file (as mentioned in the last blog in this series) and then check for clickjacking on all of them.
  • Write a crawler module.


In the upcoming posts, we will cover a bit more testing of such vulnerabilities along with some cryptographic stuff and android pen testing.

Leave a Reply

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