Gameplay

3/Gameplay/grid-small

How to Make a Password Generator in Python

In this tutorial, we will make a command-line tool in Python for generating passwords. We will use the argparse module to make it easier to parse the command line arguments the user has provided. Let us get started.


Imports

Let us import some modules. For this program, we just need the ArgumentParser class from argparse and the random and secrets modules. We also get the string module which just has some collections of letters and numbers. We don't have to install any of these because they come with Python:

from argparse import ArgumentParser
import secrets
import random
import string

If you're not sure how the random and secrets modules works. Check this tutorial that covers generating random data with these modules.

Setting up the Argument Parser

Now we continue with setting up the argument parser. To do this, we create a new instance of the ArgumentParser class to our parser variable. We give the parser a name and a description. This information will appear if the user provides the -h argument when running our program, it will also tell them the available arguments:

# Setting up the Argument Parser
parser = ArgumentParser(
    prog='Password Generator.',
    description='Generate any number of passwords with this tool.'
)

We continue by adding arguments to the parser. The first four will be the number of each character type; numbers, lowercase, uppercase, and special characters, we also set the type of these arguments as int:

# Adding the arguments to the parser
parser.add_argument("-n", "--numbers", default=0, help="Number of digits in the PW", type=int)
parser.add_argument("-l", "--lowercase", default=0, help="Number of lowercase chars in the PW", type=int)
parser.add_argument("-u", "--uppercase", default=0, help="Number of uppercase chars in the PW", type=int)
parser.add_argument("-s", "--special-chars", default=0, help="Number of special chars in the PW", type=int

Next, if the user wants to instead pass the total number of characters of the password, and doesn't want to specify the exact number of each character type, then the -t or --total-length argument handles that:

# add total pw length argument
parser.add_argument("-t", "--total-length", type=int, 
                    help="The total password length. If passed, it will ignore -n, -l, -u and -s, " \
                    "and generate completely random passwords with the specified length")

The next two arguments are the output file where we store the passwords, and the number of passwords to generate. The amount will be an integer and the output file is a string (default):

# The amount is a number so we check it to be of type int.
parser.add_argument("-a", "--amount", default=1, type=int)
parser.add_argument("-o", "--output-file")

Last but not least, we parse the command line for these arguments with the parse_args() method of the ArgumentParser class. If we don't call this method the parser won't check for anything and won't raise any exceptions:

# Parsing the command line arguments.
args = parser.parse_args()

The Password Loop

We continue with the main part of the program: the password loop. Here we generate the number of passwords specified by the user.

We need to define the passwords list that will hold all the generated passwords:

# list of passwords
passwords = []
# Looping through the amount of passwords.
for _ in range(args.amount):

In the for loop, we first check whether total_length is passed. If so, then we directly generate the random password using the length specified:

    if args.total_length:
Read More »

 

How To Hack Websites Using RCE (Remote Code Execution) 



RCE (Remote Code Execution)

Remote Code Execution can be characterized as “In PC security, self-assertive code execution or remote code execution is utilized to portray an assailant’s capacity to execute any summons of the aggressor’s decision on an objective machine or in an objective procedure.

It is normally utilized as a part of subjective code execution weakness to depict a product bug that gives an aggressor an approach to execute discretionary code.

A program that is intended to adventure such defenselessness is called a self-assertive code execution abuse.

A large portion of these vulnerabilities permit the execution of machine code and most endeavors subsequently infuse and execute shell code to give an aggressor a simple approach to physically run subjective charges.

Remote code execution can be best depicted as an activity which includes an assailant executing code remotely utilizing framework vulnerabilities.

Such code can keep running from a remote server, which implies that the assault can start from anyplace around the globe giving the aggressor access to the PC.

Once a programmer accesses a framework, they’ll have the capacity to roll out improvements inside the objective PC.

The aggressor use the client’s administrator benefits to enable them to execute code and roll out further improvements to the PC.

It’s frequently the case that such client benefits wind up noticeably raised.

Aggressors generally hope .


RCE Attack Procedure 

Hardly any sites running vBulletin are powerless against Remote Code Execution, by misusing the defenselessness we can get our PHP secondary passage shell transferred on the site.

We’ll utilize a dork to locate the defenseless site.

Dork: inurl:faq.php and intext:”Warning: framework() [function.system]”

Presently, select any site of your decision from the query item, and go to its faq.php page.


Read More »

How to Build a SQL Injection Scanner in Python

How to Build a SQL Injection Scanner in Python



import requests
from bs4 import BeautifulSoup as bs
from urllib.parse import urljoin
from pprint import pprint

# initialize an HTTP session & set the browser
s = requests.Session()
s.headers["User-Agent"] =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like 




def get_all_forms(url):

    """Given a `url`, it returns all forms from the HTML content"""
    soup = bs(s.get(url).content, "html.parser")
    return soup.find_all("form")


def get_form_details(form):
    """
    This function extracts all possible useful information about an HTML `form`
    """
    details = {}
    # get the form action (target url)
    try:
        action = form.attrs.get("action").lower()
    except:
        action = None
    # get the form method (POST, GET, etc.)
    method = form.attrs.get("method", "get").lower()
    # get all the input details such as type and name
    inputs = []
    for input_tag in form.find_all("input"):
        input_type = input_tag.attrs.get("type", "text")
        input_name = input_tag.attrs.get("name")
        input_value = input_tag.attrs.get("value", "")
        inputs.append({"type": input_type, "name": input_name, "value": input_value})
    # put everything to the resulting dictionary
    details["action"] = action
    details["method"] = method
    details["inputs"] = inputs
    return details

get_all_forms() uses BeautifulSoup library to extract all form tags from HTML and returns them as a Python list, whereas get_form_details() function gets a single form tag object as an argument and parses useful information about the form, such as action (the target URL), method (GETPOST, etc) and all input field attributes (typename and value).

Next, we define a function that tells us whether a web page has SQL errors in it, this will be handy when checking for SQL injection vulnerability:

def is_vulnerable(response):
    """A simple boolean function that determines whether a page 
    is SQL Injection vulnerable from its `response`"""
    errors = {
        # MySQL
        "you have an error in your sql syntax;",
        "warning: mysql",
        # SQL Server
        "unclosed quotation mark after the character string",
        # Oracle
        "quoted string not properly terminated",
    }
    for error in errors:
        # if you find one of these errors, return True
        if error in response.content.decode().lower():
            return True
    # no error detected
    return False

Obviously, I can't define errors for all database servers. For more reliable checking, you need to use regular expressions to find error matches. Check this XML file which has many of them (used by the sqlmap utility).

Now that we have all the tools, let's define the main function that searches for all forms in the web page and tries to place quote and double quote characters in input fields:

def scan_sql_injection(url):
    # test on URL
    for c in "\"'":
        # add quote/double quote character to the URL
        new_url = f"{url}{c}"
        print("[!] Trying", new_url)
        # make the HTTP request
        res = s.get(new_url)
        if is_vulnerable(res):
            # SQL Injection detected on the URL itself, 
            # no need to preceed for extracting forms and submitting them
            print("[+] SQL Injection vulnerability detected, link:", new_url)
            return
    # test on HTML forms
    forms = get_all_forms(url)
    print(f"[+] Detected {len(forms)} forms on {url}.")
    for form in forms:
        form_details = get_form_details(form)
        for c in "\"'":
            # the data body we want to submit
            data = {}
            for input_tag in form_details["inputs"]:
                if input_tag["type"] == "hidden" or input_tag["value"]:
                    # any input form that is hidden or has some value,
                    # just use it in the form body
                    try:
                        data[input_tag["name"]] = input_tag["value"] + c
                    except:
                        pass
                elif input_tag["type"] != "submit":
                    # all others except submit, use some junk data with special character
                    data[input_tag["name"]] = f"test{c}"
            # join the url with the action (form request URL)
            url = urljoin(url, form_details["action"])
            if form_details["method"] == "post":
                res = s.post(url, data=data)
            elif form_details["method"] == "get":
                res = s.get(url, params=data)
            # test whether the resulting page is vulnerable
            if is_vulnerable(res):
                print("[+] SQL Injection vulnerability detected, link:", url)
                print("[+] Form:")
                pprint(form_details)
                break

Before extracting forms and submitting them, the above function checks for the vulnerability in the URL first, as the URL itself may be vulnerable. This is simply done by appending a quote character to the URL.

We then make the request using requests library and check whether the response content has the errors that we're searching for.

After that, we parse the forms and make submissions with quote characters on each form found, here is my run after testing on a known vulnerable web page:

if __name__ == "__main__":
    url = "http://testphp.vulnweb.com/artists.php?artist=1"
    scan_sql_injection(url)

Output:

[!] Trying http://testphp.vulnweb.com/artists.php?artist=1"
[+] SQL Injection vulnerability detected, link: http://testphp.vulnweb.com/artists.php?artist=1"

As you can see, this was vulnerable in the URL itself, but after I tested this on my local vulnerable server (DVWA), I got this output:

Read More »