websocket-security
Skill2 starsChanged 4 months agoMITView on GitHub
SAST detection methodology for WebSocket security (CWE-346), centred on Cross-Site WebSocket Hijacking (CSWSH) — handshakes authenticated by cookies with no Origin validation — plus missing authN/authZ on WS messages (CWE-862), injection through WS payloads into downstream sinks, ws:// cleartext, and message flooding / resource exhaustion. Use when reviewing WebSocket handshake handlers and message routers (ws, socket.io, Spring, Django Channels, ASP.NET SignalR). Writes confirmed findings to findings/41-websocket-security.md.
6 other projects use a version of this.
Adopted by
Most recently taken up by
- awarexone/AXguardtheir own version, first seen Sep 15, 2026
- conjure-3301/skillstheir own version, first seen Aug 17, 2026
- Kur1sulab/blackboxtheir own version, first seen Aug 12, 2026
- jgamaraalv/delivery-looptheir own version, first seen Jul 4, 2026
- JustineDevs/premortemtheir own version, first seen Jun 9, 2026
- yaklang/hack-skillstheir own version, first seen Apr 29, 2026
Other versions6 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 6
- yaklang/hack-skills★ 2.4ksame name
- awarexone/AXguard★ 17same name
- Kur1sulab/blackbox★ 3same name
- JustineDevs/premortem★ 2same name
- conjure-3301/skills★ 0same name
- jgamaraalv/delivery-loop★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository49 other files it gives its agents.
- authentication-flawsSkill
- broken-access-control-idorSkill
- business-logic-flawsSkill
- cicd-and-pipeline-injectionSkill
- code-injectionSkill
- command-injectionSkill
- cors-misconfigurationSkill
- crlf-and-header-injectionSkill
- cross-site-scriptingSkill
- csrfSkill
- dependency-and-supply-chainSkill
- dom-clobbering-and-postmessageSkill
- graphql-injection-and-abuseSkill
- hardcoded-secretsSkill
- http-request-smugglingSkill
- iac-misconfigurationSkill
- information-disclosureSkill
- insecure-deserializationSkill
- insecure-randomnessSkill
- jwt-vulnerabilitiesSkill
- ldap-injectionSkill
- llm-and-ai-application-securitySkill
- mass-assignmentSkill
- memory-safetySkill
- mobile-android-securitySkill
- mobile-ios-securitySkill
- nosql-injectionSkill
- oauth-oidc-saml-flawsSkill
- open-redirectSkill
- path-traversal-and-file-inclusionSkill
- prototype-pollutionSkill
- race-conditions-and-toctouSkill
- redosSkill
- sast-final-reportSkill
- sast-finding-validationSkill
- sast-methodologySkill
- security-logging-and-monitoring-failuresSkill
- security-misconfiguration-and-headersSkill
- server-side-template-injectionSkill
- session-managementSkill
- smart-contract-securitySkill
- sql-injectionSkill
- ssrfSkill
- unrestricted-file-uploadSkill
- unsafe-parsers-and-yamlSkill
- weak-cryptographySkill
- web-cache-poisoning-and-deceptionSkill
- xpath-and-xml-injectionSkill
- xxeSkill
The file
We split this skill into the rules it gives an agent
3 rules. 0 are common, 2 are distinctive, and 1 is very specific to this project.
0
Common
Most of the 5 edited versions we read keep these.
2
Distinctive
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 97
Treat each message payload as untrusted: parameterize/validate before any SQL, command, template, or broadcast sink (cross-ref the relevant …
- Very specific: line 99
Use wss:// only; enforce connection/message rate limits and max frame size.
- Distinctive: line 166
Read-only public feed with no cookies, no sensitive data, and no message-driven sinks.
“Common” is measured: kept by at least 6 in 10 of the 5 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
WebSocket Security — SAST Methodology
Class: WebSocket Security · CWE-346 (and CWE-1385, CWE-862) · OWASP: A01 / A05
Findings file: findings/41-websocket-security.md
1. Overview
WebSockets upgrade an HTTP request into a full-duplex channel, but they inherit
none of the same-origin protections HTTP clients rely on: the browser attaches
cookies to the handshake yet does not enforce CORS or SameSite on it. If the
server authenticates the WebSocket solely from those ambient cookies and never
validates the Origin header, any attacker page can open an authenticated socket
for the victim — Cross-Site WebSocket Hijacking (CSWSH) — and read/write on
their behalf. Beyond CSWSH, WS channels frequently skip per-message authZ, tunnel
untrusted payloads into SQL/command/other sinks, and run over cleartext ws://.
The core test: is the handshake's Origin validated against an allowlist, and is
every message authenticated and authorized as strictly as the equivalent HTTP API?
2. Where it lives
- Handshake/upgrade handlers:
ws/websocketverifyClient/handleUpgrade,socket.ioio.on('connection')+allowRequest, SpringWebSocketHandler/setAllowedOrigins, Django ChannelsAllowedHostsOriginValidator/consumerconnect, ASP.NET SignalR hubs / rawWebSocketMiddleware, Gogorilla/websocketUpgrader.CheckOrigin. - Message routers: the
on('message')/receive/OnMessageReceivedhandlers that dispatch by atype/actionfield, and any downstream sink they call. - Transport/config:
ws://vswss://, reverse-proxy upgrade config, and connection/rate limits.
3. Sources (tainted input)
Two sources. (1) The handshake request itself — attacker-controlled Origin,
Sec-WebSocket-Protocol, cookies, and query string; a cross-site page fully
controls everything except the auto-attached cookies, which is exactly what makes
CSWSH work. (2) Each inbound WS message payload — fully attacker-controlled
bytes/JSON that flow into message handlers and any sink (DB, shell, template,
broadcast) with the same taint status as an HTTP body.
4. Sinks (dangerous operations)
// Node ws — dangerous: no Origin check, cookie-authenticated handshake
const wss = new WebSocket.Server({ server }); // no verifyClient → any origin
wss.on('connection', (ws, req) => {
const user = sessionFromCookie(req.headers.cookie); // trusts ambient cookie
ws.on('message', m => db.query(`SELECT * FROM msg WHERE room='${JSON.parse(m).room}'`)); // WS→SQLi
});// socket.io — dangerous: origin wide open
const io = new Server(server, { cors: { origin: '*', credentials: true } }); // reflects/any origin
io.on('connection', s => s.on('cmd', d => exec(d.shell))); // WS payload → command sink, no authz// Spring — dangerous: all origins allowed
registry.addHandler(handler, "/ws").setAllowedOrigins("*"); // CSWSH
// no per-message principal/authority check in handleTextMessage(...)# Django Channels — dangerous: no origin validator, accept-all
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.accept() # no self.scope origin/authz check
def receive(self, text_data):
run_command(json.loads(text_data)['q']) # payload → sink
# routing without AllowedHostsOriginValidator wrapper → cross-origin handshakes accepted// gorilla/websocket — dangerous: CheckOrigin always true
var up = websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true } } // CSWSH5. Sanitizers / safe patterns
Safe:
- Validate
Originon the handshake against a strict allowlist of full origins (SpringsetAllowedOrigins(exact), gorillaCheckOriginexact-match, ChannelsAllowedHostsOriginValidator, socket.io exactcors.origin) and reject others. - Bind the socket to a CSRF-style token passed in the handshake (query/subprotocol) that is verified server-side, not just the cookie — so a cross-site page cannot supply it.
- Re-check authentication and authorization on every message (the principal and their permission for the specific action/resource), not only at connect time.
- Treat each message payload as untrusted: parameterize/validate before any SQL, command, template, or broadcast sink (cross-ref the relevant injection skill).
- Use
wss://only; enforce connection/message rate limits and max frame size.
Fails / not a real sanitizer:
- No
CheckOrigin/setAllowedOrigins(or returningtrue/*) — the default in several libraries is to accept any origin, so CSWSH works out of the box. - Validating
Originbut also accepting a missing/nullOrigin (non-browser clients, sandboxed iframes) — attacker strips or forges it from a non-browser context. - Authenticating only at the handshake and then trusting the connection for the whole session — no per-message authZ lets a low-priv user invoke admin actions.
- Relying on cookies alone (no handshake token): cookies are auto-attached cross-site, which is the CSWSH precondition, not a defense.
- Substring/suffix
Originmatching (endsWith('.trusted.com'),origin.includes('trusted')) — same bypasses as CORS (cross-refcors-misconfiguration). - "It's JSON so it's safe" — a
JSON.parse'd field still flows unescaped into SQL/ shell/HTML sinks.
6. Detection methodology
- Find handshake/upgrade handlers and their origin check:
rg -n 'WebSocket\.Server|new Server\(|socket\.io|handleUpgrade|verifyClient|allowRequest|Upgrader|CheckOrigin|setAllowedOrigins|WebsocketConsumer|AddSignalR|MapHub' rg -n 'CheckOrigin|setAllowedOrigins|AllowedHostsOriginValidator|allowRequest|verifyClient' # is one present? - Flag missing/permissive origin validation: no
CheckOrigin,return true,"*",origin: true, or missingAllowedHostsOriginValidatorwrapper = CSWSH candidate. - Confirm the handshake is cookie-authenticated (session pulled from
req.headers.cookie/scope) with no separate handshake token — required for CSWSH to yield the victim's identity. - Audit message handlers for authZ and sinks:
For each, check: is the acting principal re-authorized? Does the payload reach a SQL/command/template/broadcast sink unsanitized?rg -n "on\(['\"]message|onmessage|handleTextMessage|def receive|OnMessageReceived|socket\.on\(" - Check transport & limits:
ws://in code/config, absence of rate/size limits. - Confirm reachability: the upgrade endpoint is an HTTP
GET— reachable over Web by any client.
7. Modern & niche variants
- CSWSH exfiltration: attacker page opens
new WebSocket('wss://target/ws'); the browser attaches the victim's cookies, the server accepts (noOrigincheck), and the attacker's JS reads every message the victim's socket receives — providesDATA_READ(private messages, tokens) and can send actions (FORCED_REQUEST/AUTHZ_BYPASS). - Sub-protocol abuse:
Sec-WebSocket-Protocolused to carry auth/role hints that the server trusts, or protocol negotiation that selects a less-authenticated code path. - Lack of per-message authZ: connect-time auth only; a user's socket can emit
type:"admin:deleteUser"and it is executed because the router never checks the action against the principal —AUTHZ_BYPASS/ BFLA over the socket. - JSON-in-WS injection: message fields flow into SQL/command/NoSQL/HTML sinks
exactly like an HTTP body — a CSWSH or an authenticated client thereby reaches
those sinks (chain with
sql-injection/command-injection/cross-site-scripting). - Tunneling past controls: routing sensitive actions over WS to dodge HTTP-layer WAF/CSRF/authz filters that only inspect REST endpoints.
- Resource exhaustion: unbounded message size/rate or connection count → DoS; amplified when each message triggers expensive backend work.
8. Common false positives
- Handshake authenticated by a bearer/handshake token (not just cookies) that a cross-site page cannot supply — not CSWSH-able.
Originexact-matched against an allowlist andnull/missing rejected.- Read-only public feed with no cookies, no sensitive data, and no message-driven sinks.
- Per-message authZ enforced and payloads parameterized before every sink.
wss://enforced end-to-end with rate/size limits in place.
9. Severity & exploitability
Base High for CSWSH on an authenticated socket that exposes or mutates
sensitive data (cross-origin DATA_READ + FORCED_REQUEST with the victim's
identity, no user interaction beyond visiting a page). Critical if a WS payload
reaches an RCE/SQL sink (CODE_EXEC/DATA_WRITE) or if missing per-message authZ
grants admin actions. Medium/Low for ws:// cleartext or DoS-only issues with
no data exposure. Raise when the handshake is pre-auth/default-vulnerable. See
references/severity-model.md.
10. Remediation
Validate the handshake Origin against a strict allowlist and reject
missing/null; additionally bind the socket to a server-verified CSRF/handshake
token rather than trusting cookies alone. Enforce authentication and
per-message authorization for every action/resource. Treat every message payload
as untrusted and parameterize/encode before any downstream sink. Serve only over
wss://. Apply connection, message-rate, and frame-size limits.
11. Output
Append each confirmed finding to findings/41-websocket-security.md using
references/finding-template.md. Set Class: WebSocket Security, the specific
CWE (CWE-346 CSWSH/origin, CWE-862 missing per-message authZ, CWE-1385
cross-site WS request forgery), and Reachable over: Web. Because the WS
handshake is an HTTP GET, include a Burp-pasteable raw HTTP request per
references/burp-request-format.md — the upgrade request with a cross-site
Origin — for example:
GET /ws HTTP/1.1
Host: TARGET_HOST
Upgrade: websocket
Connection: Upgrade
Origin: https://attacker.example
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: <BASE64-16-BYTES>
Cookie: session=<SESSION_TOKEN>Mark the injection point (the forged Origin; for payload-injection variants, the
message field), and state the expected indicator (101 Switching Protocols from a
foreign origin = CSWSH; sink signal for injection).
Primitives (controlled): provides AUTHZ_BYPASS(act without/beyond
authorization over the socket), DATA_READ(read the victim's channel via CSWSH),
FORCED_REQUEST(drive authenticated actions from a cross-site page); consumes none.
References
- CWE-346, CWE-1385, CWE-862; OWASP A01:2021 / A05:2021; OWASP Testing Guide (WebSockets); PortSwigger Cross-Site WebSocket Hijacking research; RFC 6455 §4/§10 (handshake & security considerations).
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

