Plan a Service Worker security audit covering XSS threat modeling, cache poisoning, and…
- User
Plan a Service Worker security audit covering XSS threat modeling, cache poisoning, and update race conditions.
- Assistant
Service Worker Security Audit Plan
This plan outlines a comprehensive security audit for Service Workers (SWs) in a web application, with a focus on XSS threat modeling, cache poisoning, and update race conditions. The audit assumes access to the application's source code, production/staging environments, and developer tools. It follows a structured methodology inspired by OWASP Testing Guide and threat modeling best practices (e.g., STRIDE).
1. Objectives
- Identify vulnerabilities in SW lifecycle, caching, and request interception that could lead to XSS, persistent cache attacks, or inconsistent behavior.
- Prioritize high-impact issues (e.g., client-side execution of attacker-controlled content).
- Provide remediation recommendations with risk ratings (CVSS-inspired: Critical/High/Medium/Low).
- Ensure audit covers both development and production SW deployments.
2. Scope
- In Scope: All SW registration scripts (e.g.,
sw.js), fetch event handlers, cache APIs (caches.open(),caches.match()), postMessage handlers, update logic (self.skipWaiting(),clients.claim()), and related client-side code. - Out of Scope: General web app XSS (unless SW-amplified), server-side issues, non-SW caching (e.g., HTTP caches).
- Assumptions: Audit on HTTPS-only sites (SWs require secure contexts). Test on major browsers (Chrome, Firefox, Safari).
3. Audit Team and Timeline
- Roles: Security Engineer (lead), Developer (for code review), Tester (dynamic analysis).
- Timeline (2-4 weeks):
Phase Duration Deliverables Preparation 2 days Threat model, test env setup Static Analysis 3-5 days Code findings report Dynamic Testing 5-7 days PoC exploits Reporting 2 days Final report
4. Tools and Environment
- Static: ESLint (SW plugins), Snyk, Retire.js, custom regex for cache/fetch patterns.
- Dynamic: Browser DevTools (Lighthouse SW audits, Network tab), OWASP ZAP/ Burp Suite (SW interception), Playwright/Puppeteer for automation.
- Misc: Chrome's
chrome://serviceworker-internals/,lighthouse-cifor SW metrics, Wireshark for traffic. - Test Setup: Local HTTPS server (e.g.,
mkcert), staging env mirror, fuzzers likeffuffor cache params.
5. Audit Phases and Checklists
Phase 1: Reconnaissance and Documentation
- Map SW lifecycle: Registration, install, activate, fetch events.
- Inventory all caches (names, TTLs, matching strategies).
- Document update strategy (e.g.,
self.addEventListener('activate', ...)). - Review scope:
new Worker('/sw.js', {scope: '/'}).
Phase 2: XSS Threat Modeling
Use STRIDE (Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege) tailored to SWs.
Threats and Checks:
STRIDE Category Specific Threats Audit Steps Tools/Techniques Spoofing Malicious SW registration via open redirect or subdomain takeover. - Verify navigator.serviceWorker.register()uses HTTPS/strict scope.- Check for dynamic SW URLs from user input.Burp Repeater, subdomain enum (Sublist3r). Tampering SW intercepts/modifies responses to inject XSS payloads (e.g., via respondWith(fetch().then(r => r.text().replace(...)))).- Grep for respondWith,fetch(), string manipulation in SW.- Test injecting<script>alert(1)</script>via query params/body.- AuditpostMessagehandlers for origin validation (event.origin !== location.origin ? reject : handle).Playwright scripts to send tainted postMessages; XSS fuzzing. Information Disclosure Cache leaks sensitive data via XSS in SW-served content. - Enumerate caches via DevTools; dump contents.- Check if SW serves CSP-bypassing HTML/JS. caches.keys()PoC page.Elevation/DoS SW XSS enables persistent hooks (offline execution). - Model attacker controlling cache key (e.g., cache.put('/evil', new Response('<script>...'))).Simulate with custom SW. Mitigations to Verify CSP (script-src 'self'), SRI on SW script, Content-Security-Policy-Worker-Header. Output: Threat model diagram (Draw.io), STRIDE table with likelihood/impact scores.
Phase 3: Cache Poisoning Audit
Focus on SW as a client-side cache proxy vulnerable to poisoning (e.g., attacker poisons cache with malicious response for future requests).
Checklist:
- Cache Key Manipulation:
- Test query param poisoning:
fetch('/page?q=<script>')→ Does SW cache tainted variant? - Vary header bypass: Spoof
Vary: User-Agentto fragment cache.
- Test query param poisoning:
- Response Poisoning Vectors:
- Intercept 3xx redirects in
fetchhandler to cache malicious destinations. - Race: Multiple requests during install → poison shared cache.
- Third-party resources: SW caching CDNs with poisoned mirrors.
- Intercept 3xx redirects in
- Persistence Checks:
- Offline mode: Serve poisoned cache after network drop.
- Cache invalidation: Does
caches.delete()run on update? Test staleness.
- Fuzzing:
- 1000+ inputs via
ffuf: Params, headers (Cache-Control: public), bodies.
- 1000+ inputs via
- Mitigations:
- Cache only safe MIME (
text/htmlwith validation). - ETags/If-None-Match validation.
- Opacity checks:
new Response(data, {headers: { 'Content-Type': 'text/plain' }}).
- Cache only safe MIME (
PoC Template:
// Attacker page poisons /target via SW fetch('/target?xss=<svg onload=alert(1)>') caches.open('v1').then(c => c.put('/target', new Response('<h1>XSS</h1>')));Phase 4: Update Race Conditions Audit
SW updates create a "double caching" window (old/new SW active simultaneously).
Checklist:
- Race Scenarios:
- Client loads during update: Old SW serves stale/poisoned cache.
skipWaiting()+clients.claim()timing: Test desync with rapid navigations.- Parallel installs: Multiple tabs → inconsistent state.
- Testing:
- Deploy SW v1 → Load page → Deploy v2 → Navigate/refresh → Check
controllerchanges. - Simulate with DevTools: Throttle network, pause SW scripts.
- Automation: Puppeteer spawns tabs, monitors
navigator.serviceWorker.controller.
- Deploy SW v1 → Load page → Deploy v2 → Navigate/refresh → Check
- Vulnerable Patterns:
- Missing
waitingstate handling in clients. - Cache migration without
caches.delete()→ Orphaned poisoned caches.
- Missing
- Mitigations:
- Use
self.addEventListener('controllerchange', ...)on client. - Versioned cache names (e.g.,
cache-v${version}). installevent:self.skipWaiting()+ atomic updates.
- Use
PoC: Script triggering update during fetch → Verify old cache served post-update.
Phase 5: Dynamic Testing
- Run full app under proxy (ZAP/Burp) with SW enabled/disabled.
- Lighthouse audit: Check "Uses passive event listeners", SW efficiency.
- Fuzz postMessage from iframes/other origins.
6. Reporting and Remediation
- Structure:
- Executive Summary (risk heat map).
- Findings Table: Description, Severity, PoC, Remediation, References (e.g., MDN SW security, OWASP SW Cheat Sheet).
- Appendices: Threat model, full logs.
- Prioritization: Critical if exploitable remotely (e.g., XSS via cache).
- Follow-up: Retest after fixes; recommend SW security headers (e.g.,
Service-Worker-Allowed).
References
- MDN: Service Workers Security
- OWASP: Client-Side Cache Poisoning
- Research: "Service Worker Cache Poisoning" (PortSwigger), "SW Races" (Chrome Dev Blog)
This plan is executable and adaptable. If you provide code snippets or a repo, I can refine with specific PoCs.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.