Service Worker Registration and Hijacking
What you'll learn: How attackers can abuse service worker registration to intercept and control network traffic for legitimate web applications.
Understanding the Threat
Service workers are powerful JavaScript files that act as network proxies between your web app and the server. They register with a specific scope—essentially a path prefix that determines which pages and requests they control. This power creates a serious security risk: if an attacker can register a malicious service worker, they gain control over all network traffic within that scope.
Think of a service worker like a gatekeeper at a building entrance. A legitimate gatekeeper checks IDs and directs visitors properly. But if an imposter takes over that position, they can intercept all communications, redirect people to the wrong places, or steal information.
How Service Worker Hijacking Works
Malicious Registration: If an attacker finds an XSS vulnerability or injects script into a page, they can register their own service worker:
// Attacker's malicious registration
navigator.serviceWorker.register('/attacker-sw.js', { scope: '/' });
Scope Manipulation: Attackers target the broadest possible scope (/) to control the entire application. Once registered, their service worker persists even after the user closes the tab.
Traffic Interception: The malicious service worker can now intercept every request, steal credentials, modify responses, or serve phishing pages.
Prevention Techniques
Path Restrictions: Service workers can only control pages at or below their own path. Host service worker files in protected directories.
Service-Worker-Allowed Header: Servers can restrict registration scope explicitly.
Content Security Policy: Use CSP to limit where service workers can be registered from.
Regular Auditing: Monitor registered service workers and unregister suspicious ones.
Key Takeaway: Service worker hijacking turns network proxying against users—prevent it through strict path controls, CSP policies, and vigilant XSS prevention, since registration requires script execution within your origin.