# Real-Time Protocols & Missing Framework Extensions (WebSocket/gRPC/SSE + .NET/Rails/Rust/Nest/Fastify)

> Bidirectional channels, persistent connections, streaming interfaces, and high-risk audit points for uncovered mainstream frameworks

## Core Risks
- Authentication missing or only at handshake stage -> privilege escalation after connection establishment for subscriptions/push
- Origin/Host not validated -> WebSocket cross-site hijacking (WS-CSRF)
- Message-level ACL missing -> subscribing to arbitrary rooms/topics, broadcast data leakage
- Input validation missing -> JSON deserialization, protobuf deserialization RCE/DoS
- Message size/rate limiting missing -> memory/CPU DoS
- Compression + reflection -> CRIME/BREACH-class compression side-channel
- gRPC reflection/health publicly exposed, Admin service exposed
- Security middleware not enabled in Nest/Fastify/.NET/Rails/Rust frameworks

## WebSocket/SSE/gRPC Detection Checklist
- [ ] Handshake authentication: Whether Cookie/Bearer/API Key is validated, and resource permissions are re-validated at the message layer
- [ ] Origin/Host whitelist: `Origin`/`Sec-WebSocket-Protocol`/`Sec-WebSocket-Version` validation
- [ ] Subscribe/publish authorization: Whether channels/topics are bound to users/tenants; whether IDs can be enumerated/guessed for subscription
- [ ] Message validation: Length limits, rate limiting, message signing/replay protection
- [ ] Deserialization: Whether protobuf/JSON parsing has polymorphic types, arbitrary class loading, or custom decoders
- [ ] Management/debug endpoints: Whether gRPC reflection, /metrics, /health, /debug are exposed
- [ ] Compression: Whether `permessage-deflate` is enabled without isolating sensitive data (consider disabling or separating traffic)

## Dangerous Patterns
```js
// NestJS WebSocket Gateway - No authentication, no rate limiting
@WebSocketGateway()
export class ChatGateway {
  @SubscribeMessage('join')
  handleJoin(@MessageBody() data) {
    // data.room is controllable, not bound to user/tenant
    this.server.to(data.room).emit('joined', data.user);
  }
}
```

```go
// gRPC without interceptors, no limits
server := grpc.NewServer() // No auth/interceptor/limits added
pb.RegisterAdminService(server, &Admin{}) // Admin interface exposed
```

```ruby
# Rails ActionCable - User not validated against stream
stream_from params[:room] # room is controllable, privilege escalation for subscriptions
```

## Detection Commands
```bash
# WebSocket/SSE entry points
rg -n "WebSocket|ActionCable|SockJS|socketio|socket.io|ServerSentEvent|EventSource" --glob "*.{js,ts,go,rb,py,java,cs,rs}"
rg -n "@SubscribeMessage|@WebSocketGateway|@OnMessage|@ServerEndpoint" --glob "*.{js,ts,java,cs}"

# gRPC
rg -n "grpc\\.NewServer|grpc::ServerBuilder|AddGrpc" --glob "*.{go,cc,cpp,rs,cs,java}"
rg -n "reflection\\.Register|EnableReflection" --glob "*.{go,cc,cpp,rs,cs,java}"

# Rate limiting/size limits
rg -n "MaxReceiveMessageSize|MaxSendMessageSize|permessage-deflate|compression" --glob "*.{go,js,ts,java,cs,rs}"
```

## Framework-Specific Audit Points
- **.NET/ASP.NET Core**: Whether `AddAuthentication`/`AddAuthorization` is effective for SignalR/Minimal APIs; `UseCors` Origin restrictions; `MaxHubConnectionCount`, `MaximumReceiveMessageSize`; `IHubFilter` for permission/audit.
- **Rails/ActionCable**: `identified_by` user binding; whether `stream_from` parameters are whitelisted; whether Redis channel naming includes tenant isolation; disable unused channels.
- **Rust (Actix/axum/Tonic)**: Whether middleware authentication applies to WebSocket/stream routes; `max_frame_size`, `initial_window_size`; whether unsafe/cgo or other external bindings exist.
- **NestJS**: Whether `@UseGuards` is used for Gateways; whether `WsThrottlerGuard`/`ThrottlerGuard` is enabled; `forRoutes({ path: 'events', method: ALL })` covers SSE.
- **Fastify**: Whether `fastify-websocket`/`@fastify/websocket` performs Origin validation; whether `@fastify/rate-limit` is applied to Upgrade/WS; `trustProxy` configuration coordination with Host/Origin validation.

## Security Baseline
- Unified authentication: Dual authentication at handshake + message layer; channels/resources bound to users/tenants
- Origin whitelist: Strict matching of domain/protocol/port; reject empty Origin
- Rate limiting: Message size, concurrent connections, frequency; enable backpressure; disable compression if necessary
- Isolation: Management/debug interfaces only on internal network; disable gRPC reflection/health from external access
- Logging and audit: Record subscription targets, senders, rate limit violations, abnormal disconnects
- Configuration examples:
  - gRPC: `grpc.max_receive_message_length`, `keepalive_time_ms`, disable reflection
  - SignalR: `MaximumReceiveMessageSize`, `MaximumParallelInvocationsPerClient`
  - SSE: Explicit authentication middleware, disable sensitive event caching, limit concurrent connections

## Verification Steps
- Use forged Origin/Host for WebSocket/SSE connections, verify if rejected
- Connect without authentication or with a low-privilege token, verify if subscribing/pushing to sensitive channels is possible
- Enumerate channel/room IDs, confirm whether privilege escalation data leakage exists
- Use gRPC reflection to list services/methods, attempt to call admin interfaces or unbounded streaming for DoS

## Minimal PoC Examples
```bash
# WebSocket Origin forgery
websocat -H="Origin: https://evil.com" wss://victim/ws

# SSE without authentication
curl -H "Authorization: Bearer invalid" https://victim/events

# gRPC reflection list services (python grpcurl equivalent)
grpcurl -plaintext victim:50051 list
grpcurl -plaintext victim:50051 describe admin.AdminService
```
