[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79QNYXR7Q53T6390PDYDCFJ":3,"skill-same:01M79QNYXR7Q53T6390PDYDCFJ":43},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":13,"repositoryHtmlUrl":25,"repositoryHomepageUrl":6,"ownerHtmlUrl":26,"ownerBlogUrl":6,"ownerDescription":27,"updatedAt":28,"install":29,"resources":42},"01M79QNYXR7Q53T6390PDYDCFJ","websocket-security-cheat-sheet",null,"JunMystery\u002FAgent-Guidance","JunMystery","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F161468934?v=4","01M79MTMV8F0BY8NK1A92RA8A0","Jun","01M79MTMWCFBKPHN5B25E6V20B",0,"MIT","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fwebsocket-security-cheat-sheet\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"# WebSocket Security Cheat Sheet\n\n## Introduction\n\nWebSockets enable real-time, bidirectional communication between clients and servers, powering applications like chat systems, live trading platforms, and collaborative tools. Unlike traditional HTTP requests, WebSocket connections remain open and allow continuous data exchange.\n\nHowever, WebSockets introduce security challenges that differ from standard web application security:\n\n- **Cross-Site WebSocket Hijacking (CSWSH)**: Attackers hijack authenticated connections from malicious websites\n- **Authentication bypass**: No built-in authentication makes access control easy to forget\n- **Injection attacks**: WebSocket messages can carry XSS, SQL injection, and other malicious payloads\n- **Denial-of-service**: Persistent connections enable new DoS attack vectors like connection exhaustion\n- **Monitoring gaps**: Traditional HTTP logs only capture the initial upgrade request, missing all message traffic\n\n**Real-world vulnerabilities:**\n\n- **Gitpod CSWSH (2023)**: [Insufficient origin validation](https:\u002F\u002Fgithub.com\u002Fadvisories\u002FGHSA-f53g-frr2-jhpf) allowed full account takeover via hijacked WebSocket connections\n- **Spring RCE vulnerability**: [CVE-2018-1270](https:\u002F\u002Fspring.io\u002Fsecurity\u002Fcve-2018-1270) let attackers execute code through crafted STOMP messages\n\n## Primary Defenses\n\n### Transport Security\n\n#### Always Use WSS (WebSocket Secure)\n\nNever use unencrypted `ws:\u002F\u002F` connections in production. Unencrypted `ws:\u002F\u002F` connections allow eavesdropping and tampering.\n\n```javascript\n\u002F\u002F Secure - always use this\nconst socket = new WebSocket('wss:\u002F\u002Fapp.example.com\u002Fsocket');\n\n\u002F\u002F Insecure - never use in production\n\u002F\u002F const socket = new WebSocket('ws:\u002F\u002Fapp.example.com\u002Fsocket');\n```\n\nSee the [Transport Layer Security Cheat Sheet](Transport_Layer_Security_Cheat_Sheet.md) for more details.\n\n#### WebSocket Protocol Configuration\n\n**Use modern protocol versions:**\n\nOnly support [RFC 6455](https:\u002F\u002Fdatatracker.ietf.org\u002Fdoc\u002Fhtml\u002Frfc6455) (the current WebSocket standard). Drop backward compatibility for outdated versions like [Hixie-76](https:\u002F\u002Fdatatracker.ietf.org\u002Fdoc\u002Fhtml\u002Fdraft-hixie-thewebsocketprotocol-76) and [hybi-00](https:\u002F\u002Fdatatracker.ietf.org\u002Fdoc\u002Fhtml\u002Fdraft-ietf-hybi-thewebsocketprotocol-00) which have known security vulnerabilities.\n\n**Compression security:**\n\nDisable `permessage-deflate` compression unless specifically needed. Compression can introduce security vulnerabilities similar to CRIME\u002FBREACH attacks where compression combined with secret data can leak information.\n\n```javascript\n\u002F\u002F Node.js - disable compression for security\nconst wss = new WebSocket.Server({\n  perMessageDeflate: false\n});\n```\n\n#### Infrastructure Configuration\n\n**Proxy and load balancer support:**\n\nEnsure reverse proxies, load balancers, and CDNs are configured to handle WebSocket upgrades:\n\n- Configure proxy to support HTTP\u002F1.1 upgrade mechanism  \n- Pass `Upgrade` and `Connection: upgrade` headers correctly\n- Set proper read timeouts for long-lived connections\n- Ensure WebSocket traffic isn't blocked by security policies\n\n**WAF support:**\n\nCheck that your WAF supports WebSocket traffic inspection beyond the initial handshake. If not, rely on server-side validation and application logging.\n\n### Authentication and Authorization\n\nFor general identity and session controls, see the [Authentication Cheat Sheet](Authentication_Cheat_Sheet.md) and [Session Management Cheat Sheet](Session_Management_Cheat_Sheet.md).\n\nWebSockets don't have built-in authentication. Browsers include cookies in WebSocket handshake requests, making WebSocket applications vulnerable to Cross-Site WebSocket Hijacking (CSWSH).\n\nCSWSH allows attackers to hijack authenticated WebSocket connections from malicious websites:\n\n1. User logs into your application (session cookie established)\n2. User later visits a malicious website\n3. Malicious site opens WebSocket to your application, browser sends cookies automatically\n4. Server accepts the connection → attacker gets live, authenticated WebSocket access\n\n#### Origin Header Validation\n\nValidate the `Origin` header on every handshake. Always use an explicit allowlist of trusted origins. Browsers include this header and malicious JavaScript cannot override it.\n\nFor Node.js `ws`, validate the `Origin` header in the HTTP server's `upgrade` event before calling `handleUpgrade`; the library discourages `verifyClient` ([`ws` documentation](https:\u002F\u002Fgithub.com\u002Fwebsockets\u002Fws\u002Fblob\u002Fmaster\u002Fdoc\u002Fws.md#new-websocketserveroptions-callback)).\n\n**Important:** Use an allowlist, not a denylist. Avoid wildcards or substring matching which are error-prone.\n\n#### Additional CSWSH Protections\n\nFor applications already using CSRF protection, include **CSRF tokens** in WebSocket handshakes.\n\n#### Session Management\n\nWebSocket connections often outlive normal sessions, requiring special handling.\n\n**Use SameSite cookies** (`SameSite=Lax` or `Strict`) to prevent cross-site cookie transmission and strengthen CSWSH defenses.\n\n**Handle session expiration** by implementing server-side validation for long-running connections. Close WebSocket connections when sessions expire. Re-validate user sessions periodically (every 30 minutes is common) to ensure they remain valid.\n\n```javascript\n\u002F\u002F Example: Close WebSocket on session expiry\nfunction validateSession(ws, sessionId) {\n  if (!isSessionValid(sessionId)) {\n    ws.close(1008, 'Session expired');\n    return false;\n  }\n  return true;\n}\n```\n\n**When users log out**, close all their WebSocket connections immediately. Maintain a mapping of sessions to active connections so you can invalidate WebSocket access the moment logout occurs.\n\n**Token-based authentication:**\n\nFor browser clients using tokens, prefer sending the token in the first message over WSS. Avoid tokens in URL query strings because they can leak into access logs; see the [`websockets` authentication guidance](https:\u002F\u002Fwebsockets.readthedocs.io\u002Fen\u002Fstable\u002Ftopics\u002Fauthentication.html#sending-credentials).\n\nUntil token validation succeeds, accept only the authentication message and do not send protected data. Close the connection on authentication failure or timeout, and [limit unauthenticated connections](#denial-of-service-protection). Message-based authentication keeps tokens out of the handshake URL, but tokens must also be excluded from message logs.\n\n**Token refresh:**\n\nRotate tokens in long-lived connections to prevent hijacked sessions from persisting.\n\n#### Message-Level Authorization\n\nDon't assume WebSocket connection equals unlimited access. Check authorization for each action:\n\n```javascript\nws.on('message', (data) => {\n  const message = JSON.parse(data);\n  \n  \u002F\u002F Check authorization for each action\n  if (message.action === 'delete_user' && !user.hasRole('admin')) {\n    ws.send(JSON.stringify({type: 'error', message: 'Access denied'}));\n    return;\n  }\n  \n  handleAuthorizedMessage(ws, user, message);\n});\n```\n\n### Input Validation\n\nTreat all WebSocket messages as untrusted input. WebSocket messages can carry injection payloads such as SQLi, XSS, and command injection.\n\n**Validate message structure and content** using JSON schemas and allow-lists. Set reasonable size limits (typically 64KB or less) and implement rate limiting to prevent message flooding.\n\n**For binary data**, verify file types using magic numbers rather than trusting content-type headers. Scan uploads for malware when appropriate, and use safe deserialization for protocols like protobuf or MessagePack.\n\n```javascript\nws.on('message', (data, isBinary) => {\n  if (isBinary) {\n    \u002F\u002F Validate binary data\n    if (data.length > MAX_BINARY_SIZE) {\n      ws.close(1009, 'Message too large');\n      return;\n    }\n    \n    \u002F\u002F Check file type by magic numbers\n    if (!isValidFileType(data)) {\n      ws.close(1008, 'Invalid file type');\n      return;\n    }\n  }\n  \n  processBinaryData(data);\n});\n```\n\n**To prevent message replay attacks** include timestamps or nonces in messages and reject duplicates to ensure old messages cannot be maliciously resent.\n\n```javascript\nws.on('message', (data) => {\n  const message = JSON.parse(data);\n  \n  \u002F\u002F Check timestamp or nonce to prevent replay\n  if (!isValidNonce(message.nonce)) {\n    ws.close(1008, 'Replay detected');\n    return;\n  }\n\n  processMessage(message);\n});\n```\n\n**Always use `JSON.parse()` instead of `eval()`** for JSON processing - `eval()` enables code execution from untrusted input.\n\n```javascript\n\u002F\u002F Safe\nconst message = JSON.parse(data);\n\n\u002F\u002F Dangerous - enables code execution\n\u002F\u002F const message = eval('(' + data + ')');\n```\n\nSee the [Input Validation Cheat Sheet](Input_Validation_Cheat_Sheet.md), [Cross Site Scripting Prevention Cheat Sheet](Cross_Site_Scripting_Prevention_Cheat_Sheet.md), and [SQL Injection Prevention Cheat Sheet](SQL_Injection_Prevention_Cheat_Sheet.md) for more details.\n\n### Service Tunneling Risks\n\nWhile WebSockets can tunnel TCP services (VNC, FTP, SSH), this creates security risks. If your application has XSS vulnerabilities, attackers could access these services directly from victims' browsers. If tunneling is necessary, implement additional authentication and access controls beyond the WebSocket layer.\n\n### Denial-of-Service Protection\n\nPersistent WebSocket connections increase DoS risk.\n\n**Limit connections and resources** by restricting total connections and implementing per-user limits (preferred) or per-IP limits where user identification isn't available. Set **message size limits** (typically 64KB or less) and implement **rate limiting** to prevent message flooding - 100 messages per minute is a common starting point.\n\n**Handle idle and dead connections** by implementing idle timeouts to close inactive connections. Use **heartbeat monitoring** with ping\u002Fpong frames to detect and clean up dead connections.\n\n**Implement backpressure controls** to prevent memory exhaustion from fast message producers. Many WebSocket implementations lack proper flow control, allowing attackers to overwhelm server memory by sending messages faster than they can be processed.\n\n```javascript\nconst wss = new WebSocket.Server({\n  maxPayload: 64 * 1024\n});\n```\n\n### Security Monitoring and Logging\n\nTraditional HTTP access logs only capture the initial WebSocket upgrade request, not subsequent message traffic. You'll miss auth failures, injection attempts, rate-limit violations, and abuse.\n\n**Log WebSocket events** including connection establishment and termination (with user identity, IP, and origin), authentication and authorization events during handshake and message processing, security violations like rate limiting triggers and message validation failures, and abnormal disconnections and protocol errors.\n\n**Avoid logging sensitive data** - never log complete message contents, authentication tokens, session IDs, or personal information that could violate privacy regulations.\n\nSee the [Logging Cheat Sheet](Logging_Cheat_Sheet.md) for more details.\n\n### Testing WebSocket Security\n\n**Key security tests:**\n\n- **Origin validation**: Connect from unauthorized domains\n- **Authentication bypass**: Attempt connections without proper credentials\n- **Message injection**: Send XSS, SQL injection, and command injection payloads\n- **DoS resistance**: Test connection limits, message flooding, and oversized messages\n- **Session management**: Test session expiration and logout handling\n\n**Testing tools:**\n\n- Browser developer tools for manual testing\n- [wscat](https:\u002F\u002Fgithub.com\u002Fwebsockets\u002Fwscat) for command-line WebSocket connections\n- Custom scripts for automated vulnerability testing\n- OWASP ZAP (includes WebSocket security testing features)\n\n### Framework-Specific Best Practices\n\n**Node.js:** With `ws`, perform origin and authentication checks in the HTTP server's `upgrade` event; set `maxPayload` limits and disable `perMessageDeflate` compression unless needed.\n\n**Python:** With Django Channels, implement authentication middleware and origin validation. Use async exception handling to prevent application crashes from malformed WebSocket messages.\n\n**Java Spring:** Configure allowed origins explicitly and integrate Spring Security for authorization. Set message size limits in your WebSocket container configuration to prevent resource exhaustion.\n\n**Go:** When using Gorilla WebSocket, implement validation in your `CheckOrigin` function - don't just return `true`. Set read limits, implement timeouts, and use context cancellation for graceful connection cleanup.\n\n#### Keep Dependencies Updated\n\nRegularly update WebSocket libraries and monitor security advisories. Past versions of popular libraries (`ws`, Spring STOMP, Python `websockets`) have had critical security vulnerabilities including DoS and RCE issues.\n\n## References\n\n- [RFC 6455: The WebSocket Protocol](https:\u002F\u002Fdatatracker.ietf.org\u002Fdoc\u002Fhtml\u002Frfc6455)\n- [CWE-1385: Missing Origin Validation in WebSockets](https:\u002F\u002Fcwe.mitre.org\u002Fdata\u002Fdefinitions\u002F1385.html)\n",{},"main","5d0a87185c0e172c3901e2a6e5916b6d544b8b94","skills\u002Fwebsocket-security-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance","https:\u002F\u002Fgithub.com\u002FJunMystery","AI is the typist, I am the architect. Building efficient, secure, and user-centric products through disciplined AI prompt engineering.","2026-11-13 17:41:25",{"source":7,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add JunMystery\u002FAgent-Guidance --skill websocket-security-cheat-sheet",{"tool":35,"command":36},"bunx","bunx skills add JunMystery\u002FAgent-Guidance --skill websocket-security-cheat-sheet",{"tool":38,"command":39},"pnpm","pnpm dlx skills add JunMystery\u002FAgent-Guidance --skill websocket-security-cheat-sheet","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fwebsocket-security-cheat-sheet\u002FSKILL.md",true,[],[44,50,56,62,68,74],{"skillNo":45,"name":46,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":47,"categories":48,"keywords":49,"publishedAt":18},"01M79QR1E309VJ6CTQKB32AWWA","zero-trust-architecture-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-architecture-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":51,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M79QQV7GHYR02DYGN41S23WN","xss-filter-evasion-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxss-filter-evasion-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M79QQNSN7YB8XB61FFSCS3WH","xs-leaks-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxs-leaks-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M79QQHZZJKFDY9132G5A65C2","xpath-injection-prevention-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxpath-injection-prevention-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M79QQB9ZSD3DJG8658EHQXR1","xml-security-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxml-security-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M79QQ60WKV7PFMXWT9CW8PM6","xml-external-entity-prevention-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxml-external-entity-prevention-cheat-sheet\u002FSKILL.md",[],[]]