1. Understand the Goal: The user wants a "Service Worker security audit plan." The plan needs to specifically cover three main areas:
* XSS (Cross-Site Scripting) threat modeling.
* Cache Poisoning.
* Update Race Conditions.
Target Audience: Likely a web developer, security engineer, or penetration tester. The tone should be technical, structured, and actionable.
Scope Definition: A Service Worker (SW) sits between the browser and the network. It acts as a programmable proxy. Therefore, the audit must focus on how this proxy handles requests, responses, and its own lifecycle.
Structure of the Audit Plan:
Phase 1: Reconnaissance & Setup: Getting the lay of the land (files, scope).
Phase 2: XSS Threat Modeling (The "Logic" layer): How does the SW handle data?
Phase 3: Cache Poisoning (The "Storage" layer): How does the SW store data?
Phase 4: Update Race Conditions (The "Lifecycle" layer): How does the SW change?
Phase 5: Reporting: Synthesizing findings.
Drafting Content - Section by Section:
Phase 1: Recon:
Need to find the SW file (service-worker.js).
Check registration scope (critical!).
Identify libraries used (Workbox?).
Phase 2: XSS Threat Modeling:
Concept: If an attacker controls the input to the SW or the cached response, does it lead to XSS?
Scenario A: postMessage handling. If the SW accepts messages from the main thread and does something dangerous (like eval or dynamic imports), that's bad.
Scenario B: Response Hijacking. If the SW fetches content and returns it, is it sanitizing? (Usually, SWs pass through, but if they modify headers or inject scripts, that's a risk).
Scenario C: Scope. If the scope is too broad, a vulnerable page can affect more than it should.
Phase 3: Cache Poisoning:
Concept: Tricking the SW into caching a malicious response, serving it to all future visitors (persistent XSS).
Vector 1: Unvalidated Responses. Caching responses from untrusted CDNs or APIs without checking integrity.
Vector 2: Man-in-the-Middle (MitM). If the site uses HTTP (mixed content) or weak headers, an attacker injects malicious code during the caching phase.
Vector 3: Query Parameter Confusion. If the SW caches index.html?v=1 and index.html?v=2 differently or identical, can an attacker poison one?
Phase 4: Update Race Conditions:
Concept: What happens during the transition from SW v1 to SW v2?
Vector 1: The "Skip Waiting" issue. If self.skipWaiting() is used improperly, a new SW takes over immediately. If the page expects old logic/assets, it breaks (State corruption) or security controls are bypassed.
Vector 2: Clients.claim(). Force-controlling pages without a reload.
Vector 3: Atomic Updates. Does the update process leave the site in an inconsistent state (e.g., old HTML + new JS API calls)? This is often a functional bug but can have security implications (data leakage).
Phase 5: Additional Headers & Permissions:
Content-Security-Policy (CSP) applies to SW?
Cross-Origin-Resource-Policy (CORP) / CORS checks.
Refining and Polishing:
Organization: Use headers, bullet points, and code snippets for clarity.
Specifics: Instead of "check for XSS," say "Analyze fetch event listeners for dynamic response generation."
Critique: I initially thought about just "XSS," but I need to link it specifically to the Service Worker context. A standard DOM XSS on the page isn't an SW issue unless the SW facilitates it (e.g., via caching).
Critique: Cache poisoning needs to highlight persistence. The danger is that even after the attacker leaves, the victim serves the malware from disk.
Critique: Update race conditions are subtle. I need to explain why they are a security risk (integrity/availability).
Final Output Generation: (This aligns with the provided good response). I will structure it logically:
Preparation (Recon).
XSS Deep Dive.
Cache Poisoning Deep Dive.
Update Race Condition Deep Dive.
Tooling & Checklist.
(Self-Correction during output generation): Make sure to mention importScripts(). This is a huge vector for XSS and supply chain attacks in SWs.
Final Polish: Check for clarity and tone. Ensure the "Plan" format is easy to follow for an auditor.
This is a comprehensive security audit plan for a Service Worker (sw.js). Because Service Workers act as a network proxy, control of one is equivalent to controlling the user's connection to your origin.
The audit is structured into three phases based on your requirements: XSS & Logic Flaws, Cache Integrity, and Lifecycle Race Conditions.
Prerequisites & Reconnaissance
Before testing specific vectors, map the attack surface:
Locate the Registration: Find where navigator.serviceWorker.register is called in the main application code.
Determine Scope: Check the scope parameter. If the scope is broad (e.g., /), a compromise affects the entire site.
Identify Libraries: Check if the SW uses helper libraries like workbox or sw-precache (which may have known CVEs) or if it is custom vanilla JS.
Phase 1: XSS Threat Modeling (The Persistent Proxy)
The goal here is to determine if an attacker can execute arbitrary code within the context of the Service Worker. Since the SW runs on every page load in scope, an XSS in a Service Worker is a "Forever XSS"—it persists even after the browser is closed and reopened, until the cache is cleared.
1. postMessage Handlers
Service Workers listen for messages from the main thread (via self.addEventListener('message', ...)).
The Vulnerability: Does the SW accept messages that trigger sensitive actions without validating the origin?
Test:
Identify the message protocol (e.g., {action: 'skipWaiting'} or {action: 'clearCache'}).
From a different origin (attacker site) or a vulnerable subdomain, attempt to send a message to the SW using controller.postMessage.
Goal: Trigger a cache flush, a force update, or the injection of a malicious URL into the cache list.
Code Smell:
javascript
// BAD: No event.origin check
self.addEventListener('message', (event) => {
if (event.data.type === 'LOAD_URL') {
fetch(event.data.url); // Potential for SSRF or caching malicious content
}
});
2. importScripts Impurities
SWs can import external scripts.
The Vulnerability: If importScripts() pulls from a third-party CDN or an HTTP (insecure) endpoint, a Man-in-the-Middle (MitM) or compromised CDN grants total control.
Test: Verify all imports use SRI (Subresource Integrity) hashes and use https://.
3. Template Injection in Responses
Some SWs generate HTML/JSON dynamically based on request parameters to create offline fallbacks.
The Vulnerability: Reflecting user input into a cached response creates a persistent XSS.
Test: Intercept a request handled by the SW and modify URL parameters. Check if the response served by the SW reflects these parameters unsanitized.
Phase 2: Cache Poisoning
The goal is to trick the Service Worker into storing a malicious resource and serving it to the user instead of the legitimate one.
1. "Golden" Cache Pollution
The Vulnerability: The SW caches a response that contains malicious code. Because SWs act as a "sticky" cache, the browser will serve this malicious code indefinitely.
Test:
Man-in-the-Middle the connection (if testing on HTTP/local) or utilize a temporary XSS on the origin.
Force the SW to fetch a legitimate resource (e.g., app.js).
Intercept the response and replace the body with malicious JavaScript.
Verify that the SW caches the malicious version.
Result: Even after the network XSS is fixed, the user executes the malicious code from the SW cache.
2. Third-Party Integrity
The Vulnerability: If the SW caches resources from https://cdn.jquery.com or similar.
Test: Check if the SW validates the content or headers before caching.
Mitigation Check: Ensure the application uses Subresource Integrity (SRI) in the HTML and that the Service Worker respects or enforces hash checks, or that it only caches same-origin resources.
3. Header Manipulation
The Vulnerability: Does the SW logic rely on headers to decide what to cache? (e.g., "Only cache if Content-Type is text/html").
Test: Can an attacker craft a URL that returns malicious JS but spoofs the Content-Type header to trick the SW logic?
Phase 3: Update Race Conditions
Service Workers have a complex lifecycle. This phase focuses on exploiting the transition period between an old SW and a new one.
1. The skipWaiting() Dilemma
The Vulnerability: If a new SW calls self.skipWaiting(), it activates immediately, potentially before all tabs are closed.
The Risk: "Version Mismatch." The HTML loaded in the current tab might expect API endpoints or data structures from version 1, but the active SW is now serving logic from version 2.
Test:
Open the application.
Trigger an update to the SW (modify sw.js).
Observe behavior in the console. Does the new SW take over immediately?
Security Implication: Does this version mismatch cause the app to crash, leak data, or fallback to insecure error handling?
2. The "Tab Orphaning" Race
The Vulnerability: When a new SW activates, clients.claim() allows it to control open pages immediately.
Test:
Load a page with SW v1.
Deploy SW v2 (which uses clients.claim()).
Refresh the page.
Goal: Does the hybrid state (v1 HTML logic + v2 SW network logic) allow for authentication bypasses or logic errors?
3. The "Update" Loop DoS
The Vulnerability: If the SW file is byte-for-byte identical, the browser skips the update. However, if the server returns a 200 OK for a 404 page (Soft 404) when requesting sw.js, the browser might try to re-install.
Test: Delete sw.js from the server but ensure the server returns a generic HTML page with a 200 status code.
Result: The browser installs the HTML page as the Service Worker. This effectively breaks the application (DoS) because the HTML cannot parse as valid JS, and the browser retains the broken SW until the user manually clears site data.
Audit Checklist Summary
Category
Test Case
Risk
XSS
Check message event listener for event.origin validation.
Cross-Origin Control
XSS
Inspect importScripts() sources.
Supply Chain Attack
XSS
Analyze dynamic Response creation for unsafe inputs.
Reflected/Stored XSS
Cache
Attempt to cache a resource with a spoofed MIME type.
Logic Bypass
Cache
Test if SRI is enforced for cached 3rd party scripts.
Integrity Violation
Update
Verify behavior when sw.js returns HTML/404.
Denial of Service
Update
Test skipWaiting for state corruption between versions.
Logic Flaws / DoS
Recommended Tools
Chrome DevTools: Application Tab > Service Workers. (Check "Update on reload" and "Bypass for network" for testing).
Burp Suite: Intercept the registration call and the sw.js file itself to modify logic on the fly.
Manual Code Review: The most effective way to find logic errors in the fetch and install events.