Introduction

The application layer is where most bugs live. Web applications and APIs are complex systems with enormous attack surfaces — every input field, every endpoint, every piece of user-controlled data is a potential vector. Effective testing requires more than probing isolated vulnerabilities; it demands reconnaissance that reveals the true shape of the target, chaining findings to understand real-world impact, and deep inspection of business logic and authorization.

Always obtain written, explicit authorization before testing any web application or API. Define the exact scope: domains, endpoints, user roles, and whether social engineering or source code review is allowed.

The attacker’s perspective: you are a user who wants to perform actions the developers never intended — injecting commands, forging requests, reading other users’ data, or subverting workflows. A thorough tester thinks in attack chains, not individual bugs, and starts with a hypothesis based on solid application-level recon.


Application Recon

Before sending a single payload, map the application’s visible surface and identify the underlying technology stack. This passive and semi‑passive recon feeds directly into targeted testing. Do not perform any active scanning that generates noisy traffic until you have authorization to do so; many of the techniques below can be performed without touching the target directly.

  • Technology fingerprinting
    Inspect HTTP response headers (Server, X-Powered-By, Set-Cookie format), HTML source comments, error pages, file extensions (.php, .aspx, .do), and default favicons. Identify the web server, application framework, and exact version where possible. This immediately points to known CVEs and framework‑specific vulnerabilities.

  • Endpoints and API surface discovery

    • Browser DevTools / proxy passive crawl: Browse the application normally while a proxy (Burp, ZAP) passively collects all URLs, JavaScript files, and API calls.
    • JavaScript static analysis: Download and beautify all .js files. Search for strings like api/, endpoint, url:, path:, fetch(, axios., hidden admin paths, internal hostnames, and comments left by developers.
    • Sitemap and robots.txt: Check /sitemap.xml, /robots.txt for intentionally exposed (and disallowed) directories.
    • Public archives: Use the Wayback Machine to see historical endpoints, parameters, and even old API keys that may still be valid.
    • Search engines: Use Google dorks (site:example.com inurl:admin, filetype:pdf site:example.com) to find exposed documents, login portals, and forgotten directories.
  • Parameters and input vectors
    Collect every parameter name from URLs, forms, and JSON bodies. Tools like Arjun (when permitted) can discover hidden parameters, but even manual inspection of JavaScript and intercepted requests yields a substantial list. Focus on parameters that influence state (id, user, role, price, redirect, url, callback, file, path).

  • API documentation and schema leaks
    Look for /graphql, /graphiql, /swagger.json, /api-docs, /openapi.json. Introspection queries on GraphQL endpoints can dump the entire schema if not disabled, exposing every query, mutation, and underlying data type. Overly verbose error messages (stack traces in JSON, database error details) reveal internal paths and frameworks.

  • User roles and multi‑tenancy
    Register accounts with different privilege levels (guest, user, admin) and note differences in responses, accessible endpoints, and data scoping. This sets the stage for vertical and horizontal privilege escalation tests.

Reducing Exposure During Recon

  • Use public datasets first: Wayback Machine, Common Crawl, Google/Bing caches, and certificate transparency logs (via crt.sh) reveal subdomains and historical endpoints without a single request to the target.
  • Rate‑limit all active requests: When you must send requests (e.g., fetching JavaScript files), add random delays between 3‑8 seconds and limit concurrent threads to 1. This mimics human browsing and reduces the chance of tripping rate‑based defenses.
  • Rotate User‑Agent and source IP: Use a pool of residential/mobile IPs or a VPN that exits from different geographic regions. Never use your corporate or personal IP directly for active recon.
  • Avoid aggressive spidering: Focus on directories that the application itself links to. Directory brute‑forcing (e.g., with a wordlist like raft-small-words) is noisy and often a last resort after other mapping has been exhausted.
  • Engineer your traffic to blend in: Accept cookies, load CSS/images, and follow normal navigation flows. Requests that drop connections without completing a full page load appear anomalous.
  • Never perform recon without authorization if testing a third‑party system. For bug bounty programs, read the program’s recon rules carefully. Some forbid brute‑forcing, subdomain scanning, or social engineering altogether.

Social Engineering

Social engineering tests the human layer. In an authorized engagement, it can demonstrate how an attacker might obtain credentials, deliver a payload, or manipulate an employee into performing a sensitive action. This section focuses on phishing and target selection; all activities must be explicitly scoped.

Who to Target in an Organization

  • Help desk / support: Holds password reset and account recovery power. Often willing to assist a “frustrated” employee.
  • Administrative assistants / executive assistants: Manage executive calendars and sensitive documents; likely to open attachments labeled “urgent contract” or “itinerary.”
  • Developers and DevOps: Have access to source code, CI/CD pipelines, and cloud consoles. May be more suspicious of unsolicited emails but also more curious about technical lures.
  • Accounting and HR: Handle wire transfers, payroll data, and W‑2 forms. Classic targets for fake invoices and tax‑themed phishing.
  • New hires: Less familiar with internal procedures; easy to impersonate IT onboarding.

Gather target emails and roles from LinkedIn, company “About Us” pages, press releases, and public WHOIS. Tools like Hunter.io can find email patterns, but only use them if authorized and within scope.

Crafting Realistic Phishing Emails

A realistic pretext considers the company’s current events (funding announcements, product launches, holiday schedules) and mimics internal tone.

  • Sender impersonation: Use a domain similar to the target’s (typosquatting) or spoof an internal address if the mail server lacks SPF/DKIM enforcement. In a controlled test, spoofing is often blocked; register a look‑alike domain and set appropriate DNS records so the email passes basic checks.
  • Lure types:
    • Urgent IT portal login: “Your password expires in 2 hours – click here to keep access.” Link to a fake login page that captures credentials and transparently proxies to the real login.
    • Shared document: Link to a cloud storage page (OneDrive, Google Drive) hosting a malicious file, or simply a credential‑harvesting page.
    • Invoice / payment: Well‑crafted fake invoices with a PDF that, when opened, says “This document has been encrypted – please sign in with your email to view.”
  • Language and tone: Scrape internal newsletters, job postings, and any public‑facing communication to mirror phrasing. Personalise using the recipient’s name, department, and manager’s name (often found on LinkedIn).
  • Avoid triggering spam filters: Use plain text instead of heavy HTML for initial lures, omit attachments on the first email, and avoid known‑bad TLDs (.xyz, .tk). Include a legitimate physical address and an unsubscribe link in the footer like a real commercial email.

Stealthy Phishing Delivery

  • Send emails during business hours from a warm, aged domain (registered months in advance if possible).
  • Limit volume: target a small, hand‑picked list rather than the whole organization.
  • Use a dedicated mail server with correct forward and reverse DNS, and warm up the IP beforehand with benign traffic.
  • Immediately destroy any captured credentials after the test in accordance with the data handling agreement.

Ethical Boundaries

  • Never collect personal credentials and reuse them outside the test’s scope.
  • Do not use real‑world malware or any technique that could permanently compromise a system.
  • Stop and report if a phished employee inadvertently shares information about another employee who is not part of the test.
  • Obtain explicit consent for social engineering; many compliance frameworks require it.

Whitebox

When access to source code is granted, use it to accelerate finding security‑relevant patterns. Do not send a single request without first reviewing the codebase for dangerous calls and authorization gaps.

  • Grep for dangerous functions: eval(, innerHTML, document.write, exec(, system(, shell_exec, raw SQL concatenation (+ with user input, $query = "SELECT ... $_GET[...]"), open() with user‑controlled paths, deserialization without type checks.
  • Trace authorization and ownership checks: Look for missing @PreAuthorize annotations (Spring), unprotected API routes that lack a middleware for object ownership, and any handler that uses a direct object reference from the request without verifying that the object belongs to the current user.
  • Review password reset and token generation: Verify that reset tokens are generated with a cryptographically secure random source, are single‑use, and expire quickly. Check for predictable token values (e.g., time‑based, sequential).
  • Map the ORM: If mass assignment is possible because a model binder automatically maps all JSON fields to a database entity, identify all sensitive columns (e.g., role, is_admin, credit_balance) that should never be user‑assignable.
  • Examine CSP generation logic: Ensure the CSP is not built by string‑concatenating user‑supplied values that could inject unsafe-inline or * sources.

Document findings as hypotheses and then validate them with crafted HTTP requests in the controlled test environment.


Chaining

Individual vulnerabilities rarely exist in isolation. The most impactful findings arise when flaws are combined. Always assess findings in the context of what an attacker can achieve by chaining them.

  • SSRF + internal service discovery: A server that can reach an internal Redis/Elasticsearch instance might allow session token extraction or remote code execution.
  • Reflected XSS + missing CSRF token on a sensitive action: An attacker can craft a single malicious page that both executes script and performs a state‑changing request, bypassing same‑origin protections.
  • Misconfigured CSP with unsafe-inline: The presence of the CSP header gives a false sense of security; if unsafe-inline is allowed, XSS still executes. The header itself becomes a finding when considered alongside any injection vector.
  • IDOR + rate limiting absence: An attacker can enumerate objects without detection, exfiltrating entire data sets.
  • Business logic flaw + insufficient logging: A coupon code that can be reused 100 times without alerting the fraud team becomes catastrophic over time.

When scoring, consider the combined CVSS and document the full attack chain in the report, not just the individual steps.


SQL Injection

SQL injection occurs when user‑supplied input is incorporated into a database query without proper sanitisation or parameterisation. An attacker can manipulate the query’s logic to extract data, bypass authentication, or – in severe configurations – execute operating system commands. Testing should be informed by prior application recon: the database type, framework, and characteristic error formats enable precise payload selection.

Impact

  • Unauthorised access to all stored data, including personally identifiable information (PII), financial records, and credentials.
  • Authentication bypass – login without valid credentials by subverting the query’s WHERE clause.
  • Full database compromise: exfiltration of table structures, stored procedures, and entire datasets.
  • In certain configurations, operating system command execution via xp_cmdshell (Microsoft SQL Server), LOAD_FILE / INTO OUTFILE (MySQL), or COPY ... PROGRAM (PostgreSQL).
  • When chained with other weaknesses (e.g., weak authentication or exposed internal services), SQLi can become the pivot point for internal network access.

Expected Outcomes

  • Positive finding:

    • Time‑based: A consistent response time increase of at least three seconds above baseline after injection of a benign sleep function (pg_sleep(3), SLEEP(3)).
    • Error‑based: Verbose database error messages revealing server version, internal paths, or table structure.
    • Boolean‑based: Differing page content or status codes when injecting ' AND 1=1-- versus ' AND 1=2--.
    • Out‑of‑band: DNS or HTTP callback from the database server to an attacker‑controlled listener.
  • Clean result:

    • All input sanitised consistently (type casting, whitelist validation).
    • Parameterised queries (prepared statements) used uniformly; no raw string concatenation.
    • Identical response times regardless of injected payloads.
    • No SQL error messages returned; custom, generic error pages displayed.

Ethical Considerations

  • Use blind, time‑based probes only in production engagements. Avoid UNION‑based data extraction until authorisation explicitly covers it.
  • Never use payloads that modify or delete data: DROP, DELETE, TRUNCATE, UPDATE, INSERT are forbidden unless explicitly agreed.
  • Test on staging first; confirm schema equivalence with the client before escalating to production.
  • Hard stop: If a response time exceeds ten times the established baseline, stop immediately – a denial of service or resource exhaustion may be occurring. Report the incident to the engagement lead.
  • Do not extract sensitive data beyond a minimal proof (e.g., a database version string). If UNION extraction is permitted in staging, redact all real data from findings.

Testing Flow

flowchart LR
    A["LLM ideation"]
    B["Human review"]
    C["Staging verification"]
    D["Production (if authorised and necessary)"]
    A --> B --> C --> D

During ideation, leverage recon data: the technology stack informs the specific database syntax (e.g., PostgreSQL pg_sleep vs. MySQL SLEEP), and the endpoint map narrows which parameters to test first.

Manual Testing Steps

  1. Correlate with recon: From the application map, list every input vector that interacts with a database – login forms, search fields, profile updates, URL parameters, JSON body fields, HTTP headers (User‑Agent, Referer, Cookie).
  2. Confirm scope: Ensure the target endpoint is explicitly in scope; attach the engagement‑tracking request header (e.g., X-Request-ID: AUTHORIZED-PENTEST-{id}).
  3. Baseline timing: Send three normal requests and measure the average response time (in milliseconds). Note network latency variability.
  4. Error probe: Submit a single quote ' in each input. Observe any change in response content, HTTP status code, or the appearance of database error messages.
  5. Sleep‑based probe: Inject ' OR pg_sleep(3)-- (PostgreSQL) or ' OR SLEEP(3)-- (MySQL). If the database type is unknown from recon, test both sequentially.
  6. Compare timing: If the response time increases by a consistent margin (e.g., > 3 seconds) over the baseline and the sleep value correlates with the delay, flag as a candidate finding.
  7. Boolean probe (optional): Inject ' AND 1=1-- and ' AND 1=2--. A difference in page length or content confirms injection without heavy load.
  8. Document: Record endpoint, parameter, full payload, baseline time, probe times, and any error strings received. Redact sensitive output.

AI-Assisted Testing

Prompt Template — Payload Ideation

[ROLE] Senior web application security tester assistant
[TARGET_FEATURE] POST /api/users/login — JSON body {email, password}, PostgreSQL backend (confirmed via earlier recon)
[TASK] Generate non‑destructive SQL injection test vectors.
  - Time‑based blind probes only (pg_sleep)
  - No UNION‑based data extraction in production
  - No payloads that modify or delete data
  - Include the engagement header: X-Request-ID: AUTHORIZED-PENTEST-{id}
[OUTPUT FORMAT]
  - curl command with the mandatory header
  - Expected response if vulnerable (response time > N seconds)
  - Expected response if patched
  - One‑line remediation note
[CONSTRAINTS] Authorised scoped engagement. All payloads must be non‑destructive. Database type is known: PostgreSQL.

Prompt Template — Finding Documentation

[FINDING] Time‑based blind SQL injection at POST /api/users/login
[EVIDENCE] 3100ms response on 3/3 trials vs 120ms baseline with pg_sleep(3) injected in the email field
[CONTEXT] Authenticated as test user ID 456. Tested in staging; schema matches production. Database: PostgreSQL 14.
[OUTPUT]
  - CVSS 3.1 vector string
  - Vulnerability title
  - Steps to reproduce (numbered, redacted curl examples)
  - Business impact statement (one paragraph)
  - Remediation recommendation with code example (parameterised queries)
  - Chaining note: if authentication bypass is also possible via this vector, describe the combined impact.

AI Hard Stops for This Topic

  • Reject any payload containing DROP, DELETE, TRUNCATE, UPDATE, INSERT, ALTER, EXEC, xp_, or system command injection.
  • Never suggest UNION‑based extraction for production environments.
  • Discard any LLM output that includes real table names, column names, or credentials that may have leaked from training data.
  • All AI‑suggested commands must be wrapped in an audit‑log function before execution.
  • Validate all payloads in a staging environment whose schema has been confirmed equivalent to production.

Tools Reference

ToolPurposeSafe Usage Note
sqlmapAutomated detectionOnly with --level=1 --risk=1 and flags --technique=T (time‑based blind) unless full scope granted. Never --dump, --os-shell, --file-write without explicit written authorisation.
curlManual payload deliveryAlways include engagement header; wrapper script logs all requests.
Burp Suite RepeaterRequest iterationDisable active scanner; manual repetition only. Use the “Request Timer” extension for accurate baseline measurements.
tcpdump / WiresharkOut‑of‑band callback verificationMonitor for DNS/HTTP callbacks on a controlled server within the test infrastructure.

The following sections complete the application layer testing framework. Each is aligned with the recon‑driven, chain‑aware philosophy: they start with information from application mapping, consider how one vulnerability amplifies another, and emphasise testing in the context of real‑world attack paths.


XSS

Purpose of the Test

XSS occurs when user‑controlled input is rendered by the browser without sufficient encoding or sanitisation. An attacker can inject and execute arbitrary JavaScript in the context of another user’s session. Testing must be informed by HTML context (element, attribute, script block, DOM sink), the presence (or absence) of a Content‑Security‑Policy, and how that CSP interacts with discovered injection points.

Impact

  • Session token theft via document.cookie (if HttpOnly is not set), leading to account takeover.
  • Credential harvesting through fake login forms injected into the DOM.
  • Browser‑based keylogging or clipboard monitoring.
  • Redirection to a malicious site under the attacker’s control.
  • Defacement of web pages visible to other users.
  • When chained with a missing CSRF token on sensitive actions, a single crafted page can both run script and forge requests, bypassing same‑origin policy.

Expected Outcomes

  • Positive finding: An alert box, console log entry, or controlled network request (e.g., fetch('https://testserver/id')) is triggered when the payload is rendered. DOM modification visible in the browser’s Elements panel.
  • Clean result: The payload appears encoded in the HTML source (<script>), input is stripped by a server‑side allowlist, or the Content‑Security‑Policy header blocks inline script execution (and the CSP itself has no bypass, e.g., unsafe-inline).

Ethical Considerations

  • Use only benign, detectable payloads that do not affect other users. Acceptable triggers: console.log, alert(1), document.title = "XSSFOUND", or a network request to a controlled endpoint that does not exfiltrate real data.
  • For reflected XSS, test exclusively in your own session. Never craft a payload intended to execute in another user’s browser in production.
  • For stored XSS: inject a unique, identifiable string (e.g., XSSTEST-[random]) so the test payload can be located and removed immediately after confirmation.
  • Hard stop: If your stored XSS payload executes for real users (e.g., appears in a publicly visible comment), stop, contact the engagement lead, and ensure the payload is purged.

Testing Flow

flowchart LR
    A["LLM ideation"]
    B["Human review"]
    C["Reflected test in own session"]
    D["Stored test in isolated test account"]
    E["Document, including CSP context"]
    A --> B --> C --> D --> E

Manual Testing Steps

  1. Retrace recon: from the application map, list all input vectors whose values appear anywhere in a subsequent HTTP response. Pay special attention to search boxes, profile fields, error messages, URL parameters, Referer header reflection, and User-Agent reflection.
  2. Reflect a unique test string (e.g., XSSTEST-abc123) in each vector and search the HTML source for that string. Note the exact context: inside a <div>, inside an attribute value, inside a <script> block, or inside an event handler.
  3. Based on context, generate a context‑appropriate payload:
  • HTML element context: <script>console.log('XSSTEST')</script>
  • Attribute context (double‑quoted): " autofocus onfocus="console.log('XSSTEST')
  • JavaScript context (inside <script>): '-console.log('XSSTEST')-'
  • DOM‑based: Look for innerHTML, outerHTML, document.write, eval, setTimeout/setInterval with string input, or jQuery .html() in client‑side code identified during recon.
  1. Deliver the payload in your own session; monitor the browser console and network tab for execution.
  2. Inspect the Content‑Security‑Policy header from the response. If it contains unsafe-inline or unsafe-eval, note that even a strict policy might be evaded. Test against the policy: try a script-src nonce bypass with existing nonces, or a dangling markup injection if applicable.
  3. For stored XSS, log out and access the page as an unauthenticated user to confirm the payload fires for other roles.
  4. Document the injection point, payload, HTML context, CSP header value, and whether a real‑world attack chain could follow.

AI‑Assisted Testing

Prompt Template — XSS Payload Generation

[ROLE] Web security testing assistant
[CONTEXT] Reflected XSS test. Input from the `search` parameter is reflected inside:
  <div class="search-result">INPUT</div>
  No special filtering observed so far.
[TASK] Generate benign XSS detection payloads for this HTML context.
  - Payloads that write to console.log or trigger a detectable DOM change only.
  - Include context‑specific bypass variations (tag close, attribute escape, event handlers).
  - No document.cookie, no fetch/XMLHttpRequest to external sites, no redirects.
[OUTPUT FORMAT]
  - Payload per context with explanation of where it will execute.
  - How to confirm the payload worked (DevTools steps).
[CONSTRAINTS] Benign detection payloads only. No data exfiltration. No impact on other users.

AI Hard Stops for This Topic

  • Never generate payloads that exfiltrate cookies, session tokens, or any real user data.
  • Do not test stored XSS without a dedicated, isolated test account.
  • Remove all stored XSS payloads immediately after confirming the finding.
  • Use console.log as the primary trigger – it is benign, detectable, and has no lasting impact.
  • Always test in your own browser session first; never send a payload to another user.

Tools Reference

ToolPurposeSafe Usage Note
Burp SuiteRequest interception and payload injectionDisable active scanner; use Repeater manually. Burp’s Collaborator can receive benign callbacks (non‑private data) for out‑of‑band confirmation.
Browser DevToolsPayload verificationLocal only; inspect console, network, and DOM. Prevent external calls by using a local test endpoint.
OWASP ZAPAutomated XSS detectionPassive scan mode only in production.

CSRF

Purpose of the Test

CSRF tricks a victim’s browser into sending an unintended, authenticated request to a web application. Without CSRF protection, an attacker can forge state‑changing requests (password change, fund transfer, account deletion) from a malicious page. The test verifies that every state‑changing endpoint is protected by an unpredictable anti‑CSRF token, validated server‑side, and that session cookies are restricted with the SameSite attribute.

Impact

  • Unauthorised state changes on behalf of an authenticated user.
  • Account takeover (email/password change) without user interaction beyond visiting a malicious page.
  • Financial transactions (transfers, purchases) performed silently.
  • Privilege escalation if administrative actions are unprotected.
  • In the context of a chain: a reflected XSS on the same origin can bypass CSRF entirely, but a missing CSRF token amplifies the exploitability of any XSS.

Expected Outcomes

  • Positive finding: A state‑changing request (e.g., change email) is accepted without a CSRF token, or the token is present but not validated (reusing an old token, altering it slightly), or the session cookie lacks SameSite=Lax/Strict.
  • Clean result: Every state‑changing endpoint requires an unpredictable, per‑session (or per‑request) CSRF token that is verified on the server; session cookies carry SameSite=Lax or Strict and no __Host- prefix misconfigurations exist.

Ethical Considerations

  • Test only against your own test account. Never forge requests on behalf of real users.
  • Use a PoC that demonstrates the vulnerability without causing irreversible damage. For example, change the test account’s “middle name” field rather than its password, or point the PoC to a non‑production endpoint.
  • Hard stop: If the only state‑changing action that lacks CSRF protection would cause irreversible harm (e.g., account deletion, money transfer), capture the raw request and describe the PoC without executing it fully. Note the risk in the report.

Testing Flow

flowchart LR
    A["LLM ideation"]
    B["Human review"]
    C["PoC construction"]
    D["Test in isolated test account"]
    E["Document, noting absence of token or same‑site cookie"]
    A --> B --> C --> D --> E

Manual Testing Steps

  1. Intercept a sensitive state‑changing request (e.g., POST /account/change-email) using Burp Suite. Use the test account’s session.
  2. Examine the request body and headers for a CSRF token (often a hidden form field named csrf_token, _token, authenticity_token or a custom header like X-CSRF-Token).
  3. If token exists:
  • Remove it entirely and resend.
  • Replace it with an expired token from an earlier session.
  • Change one character.
    In each case, if the action still succeeds, CSRF validation is flawed.
  1. If no token is present: construct a minimal HTML PoC form that submits the request cross‑origin.
  2. Check SameSite cookie attribute: inspect Set-Cookie response headers for session cookies. If SameSite=None (or missing) and the cookie lacks the Secure attribute, the risk is higher.
  3. Open the PoC in a different browser or incognito window while logged into the target application. Submitting the PoC should trigger the state change automatically.
  4. Document the vulnerable endpoint, the missing controls, the PoC HTML, and any potential chaining impact (e.g., “combined with stored XSS in the user forum”).

AI‑Assisted Testing

Prompt Template — CSRF PoC Generation

[ROLE] Web security testing assistant
[REQUEST] POST /api/account/change-email
  Headers: Cookie: session=TEST_TOKEN_ONLY
  Body: {"new_email": "test@example.com"}
[TASK] Generate a minimal HTML CSRF proof‑of‑concept for this request.
  - Target: test account only (not real users).
  - Use a clearly test email address.
  - Explain why this demonstrates a CSRF vulnerability.
[OUTPUT FORMAT]
  - Minimal HTML form with Auto‑Submit script.
  - How to test it safely.
  - CVSS score and remediation recommendation.
[CONSTRAINTS] PoC targets test account only. No real user impact.

AI Hard Stops for This Topic

  • Never test CSRF against real user accounts.
  • Do not execute a PoC that would delete or irreversibly alter a test account’s critical data.
  • Always clean up any modifications made during testing (restore original test account details).

SSRF

Purpose of the Test

SSRF occurs when an attacker can induce the server to make an HTTP request to an arbitrary destination. This can expose internal services, cloud metadata endpoints, and internal network infrastructure. Application recon often reveals URL‑accepting parameters (webhooks, file import, image proxy, OEmbed endpoints) that should be tested. If the server is hosted in a cloud environment, the focus is on Instance Metadata Service endpoints.

Impact

  • Access to cloud metadata services (AWS IMDSv1 at 169.254.169.254, GCP, Azure endpoints) – can expose short‑lived access tokens and IAM credentials.
  • Internal network scanning, allowing an attacker to discover and map internal services.
  • Interaction with internal APIs (Redis, Elasticsearch, Kubernetes etcd, internal admin panels) that are not directly reachable from the internet.
  • In extreme cases, remote code execution by chaining SSRF with vulnerabilities in internal services (e.g., Redis SLAVEOF to an attacker host, or gopher protocol exploitation).

Expected Outcomes

  • Positive finding: The server fetches an attacker‑controlled URL (confirmed via DNS lookup or HTTP callback to a collaborator service). The server returns internal service responses or headers that reveal internal infrastructure.
  • Clean result: URL scheme restricted to https:// only, private IP ranges (127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16) are blocked, no DNS rebinding possible, and a short allowlist of permitted external destinations is enforced.

Ethical Considerations

  • Never use SSRF to access or retrieve data beyond what is strictly necessary to demonstrate the vulnerability.
  • Do not probe internal services beyond confirming that an HTTP request was made. Stop at response headers – do not retrieve data from internal databases or APIs.
  • In cloud environments: stop at proving you can reach the metadata endpoint (e.g., receiving a 200 with a header that indicates the service) – do not retrieve or store IAM access keys, security credentials, or service account tokens.
  • Hard stop: If the metadata endpoint responds with credential material, do not download it. Document the reachable URL and the fact that token‑level access appears possible.

Testing Flow

flowchart LR
    A["LLM ideation"]
    B["Human review"]
    C["Callback‑only probes"]
    D["Confirm internal reachability (headers only)"]
    E["Document and stop before data retrieval"]
    A --> B --> C --> D --> E

Manual Testing Steps

  1. From recon data, identify all parameters that accept or appear to accept a URL: url=, webhook=, callback=, endpoint=, file_url=, path=, redirect_uri=. Also look for fields that import images (avatar_url, image=) or fetch remote content (OEmbed, link previews).
  2. Set up a controlled callback listener – Burp Collaborator, interactsh server, or a custom DNS/HTTP server under your control.
  3. Submit the callback URL in the parameter and observe that the target server makes an outbound DNS or HTTP request to your listener. This confirms basic SSRF.
  4. If callback confirmed: test for access to internal IPs. Use http://127.0.0.1/, http://localhost/, http://[::1]/, and cloud‑specific addresses: http://169.254.169.254/latest/meta-data/ (AWS), http://metadata.google.internal/computeMetadata/v1/ (GCP with header requirement).
  5. If an internal endpoint responds, inspect only the response status code and response headers (e.g., Server, Content-Type, Location). Do not read the body if it contains sensitive data.
  6. Test URI scheme bypasses: some applications only block http:// but allow file://, gopher://, or dict://. Test file:///etc/passwd cautiously in staging, never in production without explicit permission.
  7. Document the full request, the confirmed callbacks, any internal IP reachability, and explicitly state where the test stopped. Include a statement that no credentials or sensitive data were retrieved.

AI‑Assisted Testing

Prompt Template — SSRF Test Planning

[ROLE] Web security testing assistant
[TARGET] URL parameter in webhook registration: POST /api/webhooks {"url": "..."}
[TASK] Plan a non‑destructive SSRF test for this endpoint.
  - Callback‑based detection only (no internal data retrieval beyond headers).
  - Test vectors: localhost, internal IP ranges, cloud metadata endpoints.
  - Stop criteria: when vulnerability is confirmed – do not retrieve data.
[OUTPUT FORMAT]
  - Test sequence with exact curl commands (including engagement header).
  - Callback setup instructions.
  - What evidence to collect (status codes, response headers only).
  - Where to stop before overstepping scope.
[CONSTRAINTS] Callback confirmation only. No IAM credential retrieval. No internal service exploitation.

AI Hard Stops for This Topic

  • Stop at demonstrating SSRF – do not retrieve or display cloud credentials.
  • Do not use SSRF to scan or attack internal services beyond establishing reachability.
  • Never request AI assistance for exploiting internal services once SSRF is confirmed.
  • DNS/HTTP callback is sufficient to prove the vulnerability; stop there in most cases.
  • Document the internal URL only – not any token values.

Tools Reference

ToolPurposeSafe Usage Note
Burp CollaboratorDetect out‑of‑band callbacksUse a fresh payload per test; do not store sensitive data in the collaborator. Enable only DNS/HTTP interactions.
curl / httpieManual request craftingAlways include engagement header; wrapper script logs all requests.
InteractshCustomisable OOB serverDeploy on a trusted, isolated server within test infrastructure.

Security Headers

Purpose of the Test

HTTP security headers instruct the browser to enforce restrictions that reduce the application’s attack surface. A missing or misconfigured header represents a defence‑in‑depth failure that makes other attacks – particularly XSS, clickjacking, MIME confusion, and man‑in‑the‑middle downgrades – easier to execute. Testing headers is a passive, low‑risk activity that provides immediate hardening guidance and feeds into severity assessments of other vulnerabilities.

Impact

  • Missing Content-Security-Policy or one that includes 'unsafe-inline', 'unsafe-eval', or wildcard sources (*) – dramatically increases the exploitability of XSS, even if the injection point is otherwise well‑encoded.
  • Missing X-Frame-Options or CSP frame-ancestors – permits clickjacking attacks that overlay the application in a frame, tricking users.
  • Missing HTTP Strict Transport Security (Strict-Transport-Security) – enables protocol downgrade attacks (SSL stripping) over insecure networks.
  • Missing X-Content-Type-Options: nosniff – allows MIME confusion attacks, e.g., interpreting a text file as a script.
  • Leaking Server and X-Powered-By headers – aids attackers in fingerprinting the exact technology stack and version, accelerating targeted attacks.

Expected Outcomes

  • Positive finding: One or more of the key defensive headers are absent, or present but with dangerous values (e.g., CSP: default-src 'none'; script-src 'unsafe-inline', X-Frame-Options not set on a page with sensitive actions, HSTS max‑age less than one year or missing includeSubDomains/preload).
  • Clean result: All critical headers present with a restrictive configuration. CSP is strict (no unsafe-inline, no broad source whitelists), X‑Frame‑Options DENY (or CSP frame-ancestors 'none'), HSTS includes max-age=63072000; includeSubDomains; preload, X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin, Permissions-Policy restricting unnecessary APIs, and server banner information suppressed.

Ethical Considerations

  • Header analysis is completely passive – it only examines the response of a single legitimate request.
  • No risk of harm to the target system. Findings are purely informational and guide other tests.

Testing Flow

flowchart LR
    A["Single request"]
    B["Inspect response headers"]
    C["Analyse each header’s value"]
    D["Document misconfigurations and their interaction with other findings"]
    A --> B --> C --> D

Manual Testing Steps

  1. Fetch the target’s main page and a few important sub‑pages (login, account settings) using curl -I or a browser’s network panel.
  2. Verify the presence of each critical header:
  • Strict-Transport-Security
  • Content-Security-Policy
  • X-Frame-Options (or CSP frame-ancestors)
  • X-Content-Type-Options
  • Referrer-Policy
  • Permissions-Policy
  1. Evaluate the values:
  • HSTS: must have max-age >= 31536000 (one year) and include includeSubDomains. The preload flag is also highly desirable.
  • CSP: check for unsafe-inline, unsafe-eval, data: blob: sources, or broad * in script-src or object-src. If a CSP is present but lax, note that it fails to defend against the XSS vectors you might have found.
  • Frame control: X-Frame-Options: DENY is strongest. CSP frame-ancestors 'self' is acceptable; absence on a page containing sensitive widgets is a finding.
  • X-Content-Type-Options: should be nosniff.
  • Referrer-Policy: at least strict-origin-when-cross-origin to avoid leaking URL information.
  1. Verify that Server, X-Powered-By, X-AspNet-Version, and similar informational headers are removed or generic.
  2. Optionally, use securityheaders.com on a public‑facing service for a graded automated analysis, but be aware that the scan result may be cached publicly.
  3. Document each missing or weak header. When reporting, explicitly link these gaps to other findings: e.g., “The lack of CSP script-src integrity combined with the reflected XSS on the search page allows full script execution.”

AI‑Assisted Testing

Prompt Template — Header Analysis

[ROLE] Web security analyst
[HEADERS] HTTP response headers from https://example.com:
  [paste curl -I output]
[TASK] Analyse these HTTP security headers and generate a findings report.
  - Identify missing headers.
  - Identify misconfigured values.
  - For each issue, provide a CVSS score (usually low/medium) and the recommended header value.
  - Comment on the interaction with XSS or clickjacking if relevant.
[OUTPUT FORMAT]
  - Table: Header | Issue | Risk | Recommended Value
  - Example nginx/Apache configuration for all recommended headers.
[CONSTRAINTS] Header configuration recommendations only.

AI Hard Stops for This Topic

  • Header analysis is always safe; no hard stops apply.
  • Focus on providing precise, hardened configuration examples.

Tools Reference

ToolPurposeSafe Usage Note
curl -IHeader inspectionSingle request; completely safe.
securityheaders.comAutomated graded analysisPublic internet‑facing services only; results cached publicly.
Burp SuitePassive header captureSafe; only reviews traffic you already generated.

IDOR

Purpose & Impact

Insecure Direct Object References occur when an application exposes a reference to an internal object (e.g., file, database key, user ID) without verifying that the requesting user has permission to access it. Impact ranges from unauthorized reading of other users’ data to full account takeover.

Testing

  1. Examine requests that carry object identifiers: user_id, order_id, document_id, accountId, etc., either in the URL path, query string, or JSON body.
  2. As one authenticated user, change the identifier to that of another user’s resource (horizontal privilege escalation) or to a higher‑privilege resource (vertical).
  3. If the application returns the resource, the reference is insecure. Test with any numeric, UUID, or predictable pattern.
  4. Also test with GUIDs that are sequential. Sometimes developers believe UUIDs are unpredictable but use version‑1 UUIDs that embed timestamps and MAC addresses.

AI‑Assisted Prompt Template

[ROLE] Authorization testing assistant
[CONTEXT] Authenticated as user A (id: 12345) fetching /api/orders/98765
[TASK] Generate a list of object reference mutations to test horizontal and vertical access.
[OUTPUT] cURL commands with expected behavior if vulnerable vs secure.
[CONSTRAINTS] Use test accounts only; no real user data retrieval beyond minimal proof.

Mass Assignment

Purpose & Impact

Many frameworks automatically bind incoming JSON request fields to internal model attributes. An attacker can include additional fields (e.g., "role": "admin", "is_verified": true, "credit_limit": 99999) in a registration or profile‑update request, and the application may unintentionally update those fields. This can lead to privilege escalation, payment bypass, or other severe bypasses.

Testing

  1. Identify endpoints that accept a JSON body for create/update operations.
  2. Add extra fields that guess at sensitive column names: role, admin, isAdmin, account_balance, verified, group, permissions, is_internal.
  3. Observe if the response indicates the field was accepted or if the new field appears in a subsequent GET of that resource.
  4. Some frameworks only ignore unknown fields; others throw an error, but a third category silently accepts them.

AI‑Assisted Prompt

[ROLE] API security tester
[ENDPOINT] PATCH /api/users/me – accepts {"email", "name"}
[TASK] List potential mass assignment field names that could grant admin access or bypass verification.
[OUTPUT] JSON payloads with explanation.
[CONSTRAINTS] Test on staging only; do not modify production user roles.

Rate Limiting

Purpose & Impact

Missing or weak rate limiting enables credential brute‑forcing, OTP/token enumeration, and data scraping. Timing differences in login or password‑reset flows may reveal whether a username/email is valid, facilitating further targeted attacks.

Testing

  • Login endpoint: Submit 20 requests per second with invalid credentials for the same account; check if account lockout or 429 responses occur. Submit with valid credentials and inspect response time differences relative to a non‑existent user (look for consistent delays).
  • Password reset: Request reset tokens for a known existing account and a non‑existent account; compare response codes, messages, and timing.
  • API endpoint enumeration: Rapid sequential ID values without rate limits can dump the entire dataset. Introduce a modest request rate and observe if throttling kicks in.

Hard Stops

  • Do not perform brute‑forcing that could lock out legitimate users in production without explicit permission.
  • Stop as soon as you confirm enumeration, don’t harvest a full user list.

Business Logic

These are vulnerabilities in the intended workflow that automated scanners miss. They stem from incorrect assumptions about how users will interact with the application.

Examples:

  • Skipping steps in a multi‑step checkout (order without payment).
  • Applying a coupon multiple times, using negative quantities, or manipulating floating‑point rounding to reduce order total.
  • Subscribing to a premium feature, canceling, yet retaining access due to improper state handling.
  • Predictable invoice numbers that allow invoice forgery or viewing invoices of other organizations.

Testing Methodology

  1. Map the business workflow using sequence diagrams or state machines.
  2. Challenge every assumption: can a step be replayed? Can a sequence be reversed? Does concurrent execution bypass checks?
  3. Write a hypothesis: “If I apply coupon COUP100 twice, the total may underflow.” Then test with carefully crafted requests.
  4. Involve the product owner to understand the intended logic; the most interesting bugs live where the code meets policy.

API Issues

Modern APIs present unique attack surfaces beyond traditional web forms.

  • GraphQL introspection: If enabled, query {__schema{types{name,fields{name}}}} to discover all queries, mutations, and sensitive data fields.
  • Excessive error messages: Stack traces, database errors, or debugging output in JSON responses reveal internal architecture.
  • Unauthenticated admin endpoints: /graphql, /api/admin/, /swagger-ui.html might be exposed without authentication.
  • Batching attacks: If the API accepts an array of requests (e.g., [{"query":"...", ...}, ...]), an attacker can chain multiple malicious operations in a single call, bypassing per‑request controls.

Test: send an array where a single object is expected, check if each element is processed.


Auth Deep Dive

JWT Issues

  • alg=none: Change the header to "alg":"none" and remove the signature. Some libraries accept it.
  • RS256 to HS256 confusion: The public key may be known; re‑sign the token using the public key as an HMAC secret.
  • Key ID (kid) injection: If the server uses kid to fetch a key, inject a path traversal or SQLi in the kid header.

OAuth / OpenID Connect

  • Redirect_uri bypass: Use a whitelist‑parsing flaw (e.g., http://app.com.attacker.com or http://app.com%40attacker.com).
  • Missing state parameter: CSRF that links a victim’s account to an attacker’s OAuth identity.
  • Implicit flow flaws: Access tokens in URL fragments may be leaked through referrer headers.

Password Reset & Tokens

  • Check token randomness: time‑based tokens, predictable PRNG.
  • Test token reusability: use a used token again.
  • Test concurrency: request multiple resets at the same time; check if all tokens remain valid.

Session Fixation & Concurrent Sessions

  • Accept a session ID before logging in; after authentication, see if the same ID is used.
  • Test if multiple simultaneous sessions are allowed and under what conditions they invalidate each other.

Integration with Recon

All the above tests succeed faster when you have comprehensive recon. The technology fingerprint guides payload selection (e.g., knowing it’s a PostgreSQL backend immediately narrows SQLi probes). Endpoint lists from JS files point directly to API routes that may lack IDOR protection or expose mass assignment. Understanding user roles from recon allows precise testing of privilege escalation.

Before any testing, compile a unified map of:

  • The technology stack and exact versions.
  • Every discovered endpoint with required roles.
  • All parameters, including hidden ones.
  • Publicly documented APIs (Swagger, GraphQL schemas).

Then design test hypotheses based on the map.


Final Note on Stealth

While the engagement may be authorized, reducing noise protects the test from being inadvertently blocked and keeps the assessment focused. Use application‑layer recon techniques that blend in with normal traffic, and coordinate with the blue team so they are aware of the testing IPs. This document assumes a cooperative, authorized engagement; all stealth measures are for minimizing impact on production monitoring, not for evading law enforcement.


The original SQL Injection, XSS, CSRF, SSRF, and Security Headers sections remain as in the provided application.md and are considered integrated into this expanded version.