Browser Security Features
Modern web browsers implement multiple security mechanisms to protect users from various attacks. Understanding these features is crucial for both developing secure web applications and performing security assessments. This lecture explores the most important browser security features and how they can be configured, bypassed, or exploited.
Same-Origin Policy (SOP)
The Same-Origin Policy (SOP) is the cornerstone of web security, preventing malicious scripts from one origin from accessing data from another origin. It's one of the oldest and most fundamental security mechanisms in web browsers.
What Defines an Origin?
An origin is determined by the combination of three components:
Protocol Scheme: The communication protocol (e.g.,
http,https)Host Name: The domain name or IP address (e.g.,
example.com)Port Number: The communication port (e.g.,
80for HTTP,443for HTTPS)
Two URLs have the same origin only if all three components are identical.
Example Origin Comparison:
Consider the base URL: http://normal-website.com/example/example.html
This uses scheme http, domain normal-website.com, and port 80.
URL accessed
Access permitted?
Reason
http://normal-website.com/example/
✅ Yes
Same scheme, domain, and port
http://normal-website.com/example2/
✅ 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 (subdomain)
http://www.normal-website.com/example/
❌ No
Different domain (subdomain)
http://normal-website.com:8080/example/
❌ No
Different port
http://normal-website.com:80/example/
✅ Yes
Port 80 is default for HTTP
Note: Internet Explorer does NOT consider port number when applying SOP, making it less secure.
SOP Policy Details
What SOP Restricts:
Reading Responses: Scripts from one origin cannot read responses from another origin
Prevents malicious site from reading your Gmail
XMLHttpRequest/Fetch API blocked for cross-origin reads
Accessing DOM: Cannot access DOM of documents from different origin
Cannot read
iframecontent from different originCannot access
windowobject properties from other origin
Cookies: Cookies set by origin only sent to that origin
example.comcannot read cookies frombank.comPrevents cookie theft across domains
What SOP Allows:
Sending Requests: Can send requests to any origin
Response is opaque (cannot read)
Useful for analytics, CDNs
Embedding Resources: Can embed cross-origin resources
Images:
<img src="https://other-site.com/image.jpg">Scripts:
<script src="https://cdn.com/library.js"></script>Stylesheets:
<link rel="stylesheet" href="https://cdn.com/style.css">Fonts:
@font-facedeclarationsMedia:
<video>,<audio>tagsIframes:
<iframe>(but cannot access content)
Navigation: Can navigate to different origins
Links:
<a href="https://other-site.com">Form submissions:
<form action="https://other-site.com">window.location = "https://other-site.com"
SOP Implementation Details
Cross-Domain Object Access:
Some objects are writable but not readable cross-domain:
locationobjectlocation.hrefproperty from iframes or new windows
Some objects are readable but not writable cross-domain:
window.length(number of frames)window.closed(whether window is closed)
Allowed Cross-Domain Functions:
window.close()window.blur()window.focus()window.postMessage()(for secure cross-origin communication)location.replace()
SOP Relaxation Mechanisms
1. document.domain
Legacy mechanism to relax SOP for subdomains:
Security Implications:
Allows subdomain to access parent domain
Can be exploited if attacker controls any subdomain
Modern browsers restrict to valid suffixes
Deprecated in modern web security
Exploitation Example: If attacker compromises evil.example.com, they can set document.domain to example.com and access main site data.
2. postMessage API
Secure way for cross-origin communication:
Sender:
Receiver:
Security Best Practices:
Always validate
event.originValidate
event.datacontentUse specific target origin, not
*Be cautious with
event.source
Insecure postMessage Example:
Attacker can exploit:
SOP and Cookies
Cookies follow a more relaxed policy than SOP:
Cookie Scope:
Can be set for entire domain and subdomains
Domain=.example.comincludes all subdomainsPath attribute controls URL path scope
Cookie Access Example:
Security Implications:
Subdomain can set cookies for parent domain
Subdomain compromise = full domain compromise
Use specific domains when possible
Mitigation:
Use
HttpOnlyflag (prevents JavaScript access)Use
Secureflag (HTTPS only)Use
SameSiteattributeDon't rely on subdomains for security isolation
Cross-Origin Resource Sharing (CORS)
CORS is a mechanism that allows servers to relax SOP for specific origins, enabling legitimate cross-origin requests while maintaining security.
How CORS Works
Simple Requests:
For simple requests (GET, HEAD, POST with simple headers), browser sends:
Server responds with:
Preflight Requests:
For complex requests (PUT, DELETE, custom headers), browser sends OPTIONS preflight:
Server responds:
If preflight succeeds, browser sends actual request.
CORS Headers
Response Headers:
Access-Control-Allow-Origin: Which origins can access*(wildcard - allows all, cannot use with credentials)https://specific-origin.comnull(dangerous, can be exploited)
Access-Control-Allow-Credentials: Allow cookies/authtrueor omitted (false)
Access-Control-Allow-Methods: Allowed HTTP methodsGET, POST, PUT, DELETE
Access-Control-Allow-Headers: Allowed custom headersContent-Type, Authorization, X-Custom-Header
Access-Control-Max-Age: Preflight cache duration3600(seconds)
Access-Control-Expose-Headers: Headers accessible to JavaScriptX-Custom-Response-Header
Request Headers:
Origin: Request origin (set by browser, cannot be modified)Access-Control-Request-Method: Method for actual requestAccess-Control-Request-Headers: Headers for actual request
CORS Misconfigurations
1. Wildcard with Credentials
Vulnerable Configuration:
Issue: Browser rejects this! Cannot use wildcard with credentials.
Workaround Attempt (Still Vulnerable):
Exploitation:
2. Null Origin
Vulnerable Configuration:
Exploitation: Attacker can create null origin using sandboxed iframe or data URI:
3. Insufficient Origin Validation
Vulnerable Pattern:
Bypass:
https://example.com.attacker.com✅ Contains "example.com"https://attackerexample.com✅ Contains "example.com"
Secure Validation:
4. Pre-Domain Wildcard
Vulnerable:
Browsers don't support wildcards in origin! Server must dynamically set origin.
CORS Security Best Practices
Whitelist Specific Origins: Don't reflect arbitrary origins
Avoid Null Origin: Never allow
nullProper Validation: Use exact matching, not substring checks
Minimize Credentials: Only use
Access-Control-Allow-Credentialswhen necessaryLimit Methods: Only allow required HTTP methods
Limit Headers: Only allow necessary custom headers
Cache Safely: Use appropriate
Max-Agefor preflight
Content Security Policy (CSP)
CSP is a powerful security feature that mitigates XSS and other code injection attacks by controlling which resources can be loaded and executed.
How CSP Works
Server sends CSP header specifying allowed resource sources:
Browser enforces policy, blocking violations and optionally reporting them.
CSP Directives
Fetch Directives (Control resource loading):
default-src: Fallback for other directivesscript-src: JavaScript sourcesstyle-src: CSS sourcesimg-src: Image sourcesfont-src: Font sourcesconnect-src: XMLHttpRequest, WebSocket, fetch()media-src:<audio>,<video>sourcesobject-src:<object>,<embed>,<applet>frame-src:<iframe>sourcesworker-src: Worker, SharedWorker, ServiceWorkermanifest-src: Manifest sources
Document Directives:
base-uri: Restricts<base>element URLssandbox: Applies sandbox restrictions (like iframe sandbox)
Navigation Directives:
form-action: Restricts form submission targetsframe-ancestors: Restricts who can embed this page (replaces X-Frame-Options)
Reporting Directives:
report-uri: Deprecated, use report-toreport-to: Endpoint for violation reports
Other Directives:
upgrade-insecure-requests: Upgrades HTTP to HTTPSblock-all-mixed-content: Blocks mixed content
CSP Source Values
Keywords:
'none': Block all'self': Same origin'unsafe-inline': Allow inline scripts/styles (dangerous!)'unsafe-eval': Alloweval()(dangerous!)'unsafe-hashes': Allow specific inline event handlers'strict-dynamic': Trust dynamically added scripts'report-sample': Include code sample in violation report
Hosts:
https://example.com: Specific domainhttps://*.example.com: Subdomain wildcardhttps:: Any HTTPS sourcedata:: Data URIsblob:: Blob URIs
Nonces:
'nonce-random123': Cryptographic nonce for inline scripts
Hashes:
'sha256-base64hash': Hash of inline script/style
CSP Examples
Strict CSP (Recommended):
Moderate CSP:
Report-Only Mode (Testing):**
CSP with Nonces
Server generates random nonce:
HTML includes nonce:
CSP Bypasses
1. unsafe-inline
Vulnerable Policy:
Any inline script works:
2. unsafe-eval
Vulnerable Policy:
Allows eval-like functions:
3. JSONP Endpoints
Vulnerable Policy:
If trusted-site.com has JSONP endpoint:
4. AngularJS CDN
Vulnerable Policy:
Exploit using AngularJS:
5. base-uri Not Set
Vulnerable - No base-uri restriction:
6. Wildcard Subdomains
Vulnerable Policy:
If attacker compromises any subdomain or finds user-content subdomain:
CSP Best Practices
Use Nonces or Hashes: Avoid
'unsafe-inline'Avoid 'unsafe-eval': Rewrite code to not use eval
Whitelist Carefully: Each whitelisted domain increases attack surface
Set base-uri:
base-uri 'none'orbase-uri 'self'Set object-src:
object-src 'none'(blocks Flash, Java)Use strict-dynamic: With nonces for better security
Set frame-ancestors: Prevent clickjacking
Test with Report-Only: Before enforcing
Monitor Reports: Track violations
Upgrade Insecure Requests: Use
upgrade-insecure-requests
Other Security Headers
X-Frame-Options
Prevents clickjacking by controlling iframe embedding.
Values:
Cannot be embedded in any iframe.
Can only be embedded on same origin.
Can be embedded on specified origin (deprecated, not widely supported).
Modern Alternative: CSP frame-ancestors
X-Content-Type-Options
Prevents MIME sniffing attacks.
Purpose:
Prevents browser from interpreting files as different type
Forces browser to respect declared
Content-TypePrevents XSS via uploaded files
Without nosniff:
With nosniff: Browser strictly follows Content-Type header.
X-XSS-Protection
Legacy XSS filter (deprecated).
Values:
0: Disable filter1: Enable filter, sanitize1; mode=block: Enable filter, block page
Issue:
Can introduce vulnerabilities
Bypassed easily
Deprecated in favor of CSP
Recommendation:
Disable it, use CSP instead.
Strict-Transport-Security (HSTS)
Forces HTTPS usage.
Directives:
max-age: Duration in secondsincludeSubDomains: Apply to all subdomainspreload: Include in browser's preload list
Benefits:
Prevents SSL stripping attacks
Prevents accidental HTTP access
Improves SEO
Preload List: Submit to https://hstspreload.org/ for browser-level enforcement.
Referrer-Policy
Controls Referer header sent with requests.
Values:
no-referrer: Never sendno-referrer-when-downgrade: Don't send on HTTPS→HTTPorigin: Send only originorigin-when-cross-origin: Full URL same-origin, origin cross-originsame-origin: Only send for same-originstrict-origin: Origin only, not on HTTPS→HTTPstrict-origin-when-cross-origin: Recommended defaultunsafe-url: Always send full URL (don't use!)
Permissions-Policy (Feature-Policy)
Controls which browser features can be used.
Features:
geolocation: Location APImicrophone: Microphone accesscamera: Camera accesspayment: Payment Request APIusb: WebUSB APIfullscreen: Fullscreen API
Values:
(): Blocked for all(self): Allowed for same origin(self "https://trusted.com"): Allowed for specific origins*: Allowed for all (not recommended)
Subresource Integrity (SRI)
Ensures third-party resources haven't been tampered with.
Usage:
Generate Hash:
Browser Behavior:
Downloads resource
Computes hash
Compares with
integrityattributeBlocks if mismatch
Benefits:
Protects against compromised CDNs
Detects tampering
Ensures resource authenticity
Requirements:
Must use
crossoriginattributeCORS headers must be configured
Hash must match exactly
Cookies Security Deep Dive
Cookie Attributes Security
Secure:
Only sent over HTTPS, never HTTP.
HttpOnly:
Not accessible via JavaScript document.cookie.
SameSite:
Strict: Never sent on cross-site requestsLax: Sent on top-level GET navigationsNone: Always sent (requires Secure)
SameSite Comparison:
Link from external site
❌
✅
✅
Form POST from external
❌
❌
✅
AJAX from external
❌
❌
✅
Iframe from external
❌
❌
✅
Complete Secure Cookie:
Cookie Prefixes
__Secure- Prefix:
Must have Secure attribute
Must be set over HTTPS
__Host- Prefix:
Must have Secure attribute
Must be set over HTTPS
Must NOT have Domain attribute
Path must be
/
Benefits:
Prevents subdomain override attacks
Ensures HTTPS-only
Stronger security guarantees
Key Takeaways
SOP is the foundation of web security, isolating origins
CORS relaxes SOP but must be configured carefully
CSP mitigates XSS through content restrictions
Security headers provide defense-in-depth
Cookie attributes are critical for session security
Each security feature has potential misconfigurations
Multiple layers of security are essential
Always validate inputs even with security features
Test security configurations thoroughly
Modern browsers provide powerful security mechanisms
Resources
Same-Origin Policy
MDN - Same-Origin Policy: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
PortSwigger - SOP: https://portswigger.net/web-security/cors/same-origin-policy
CORS
PortSwigger - CORS: https://portswigger.net/web-security/cors
CORS Misconfigurations: https://portswigger.net/research/exploiting-cors-misconfigurations-for-bitcoins-and-bounties
Content Security Policy
Google CSP Evaluator: https://csp-evaluator.withgoogle.com/
CSP Quick Reference: https://content-security-policy.com/
Security Headers
Security Headers Checker: https://securityheaders.com/
OWASP Secure Headers Project: https://owasp.org/www-project-secure-headers/
MDN - HTTP Security: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers#security
Cookie Security
MDN - Cookies: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
OWASP - Session Management: https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html
Tools
Burp Suite: Test security configurations
OWASP ZAP: Automated security testing
Browser DevTools: Inspect headers and cookies
CSP Evaluator: Validate CSP policies
SecurityHeaders.com: Check security header implementation
Last updated