mirror of
https://github.com/J3vb/OwnCord.git
synced 2026-09-03 03:50:00 +03:00
Applies fixes for 20 adversarially-verified findings from a whole-codebase security review (server side). All Go build-tag variants build, `go vet` is clean, and the suite passes (the sole failing test, ws TestEmitEvents, is a pre-existing nil-harness failure unrelated to these changes). High severity: - auth: close TOCTOU in TOTP verify rate-limit by recording each attempt atomically up-front (was Check-then-Allow), restoring the per-user brute-force cap. - plugin: enforce the CPU/time budget on every WASM guest call via a WithTimeout context (WithCloseOnContextDone interrupts runaways); the configured budget was previously parsed but never applied. - api/waf: inspect request bodies for chunked (ContentLength==-1) requests so the SQLi/XSS/RCE body rules can no longer be bypassed. - ws: rate-limit voice_join/voice_leave and voice_e2ee announce/offer, which fan out to every participant and could force mass disconnects. Medium severity: - api: run bcrypt on the unknown-user login path (no || short-circuit) to remove the timing-based username-enumeration oracle. - ws: verify LiveKit webhooks via the SDK receiver so the signature is bound to the body hash (kills forgery/replay). - authz: require READ_MESSAGES for reactions and for plugin-command broadcasts; route the latter through RequireChannelAccess. - api: cache the client-update signature fetch and rate-limit the endpoint. - service: propagate DeleteOtherSessions failure from ChangePassword instead of silently reporting success. - api: trust the rightmost non-proxy X-Forwarded-For entry, not the client-controllable leftmost one. - plugin: route auto-registered commands through the conflict-checked RegisterCommand; pin the DNS-validated IP for host_http dials (DNS-rebinding TOCTOU). - api: mark access-controlled downloads private/no-cache + Vary: Origin. Low severity: - auth: fail closed when a fully-shaped TOTP ciphertext fails GCM auth (was returning the ciphertext as plaintext). - api: apply the livekit-proxy path allowlist to WebSocket upgrades too. - service: verify attachment ownership before linking (IDOR). - admin: bound the bootstrap setup invite (5 uses / 24h); re-verify the update binary hash immediately before rename+spawn (TOCTOU). - service: require BanMembers + role hierarchy for moderation ban/unban. chore: stop tracking the stray Server/owncord-server.exe build artifact. Test infra: add uploader_id to the hand-rolled ws test attachment schemas and make MemStore.GetAttachmentByID a no-op lookup, matching production/DB behavior. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
137 lines
4.7 KiB
Go
137 lines
4.7 KiB
Go
// Package api provides the HTTP router and handlers for the OwnCord server.
|
|
//
|
|
// waf.go implements Coraza WAF middleware for OWASP CRS protection.
|
|
// Toggle via config: server.waf_enabled (default: false).
|
|
package api
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
|
|
"github.com/corazawaf/coraza/v3"
|
|
"github.com/corazawaf/coraza/v3/types"
|
|
)
|
|
|
|
// NewWAFMiddleware creates a Coraza WAF middleware with OWASP CRS rules.
|
|
// paranoiaLevel controls rule sensitivity (1=low, 2=default, 3=strict, 4=paranoid).
|
|
// Returns nil middleware if WAF creation fails (logged as error, server continues).
|
|
func NewWAFMiddleware(paranoiaLevel int) func(http.Handler) http.Handler {
|
|
if paranoiaLevel < 1 || paranoiaLevel > 4 {
|
|
paranoiaLevel = 2
|
|
}
|
|
|
|
waf, err := coraza.NewWAF(
|
|
coraza.NewWAFConfig().
|
|
WithDirectives(fmt.Sprintf(`
|
|
SecRuleEngine On
|
|
SecRequestBodyAccess On
|
|
SecResponseBodyAccess Off
|
|
SecRequestBodyLimit 1048576
|
|
|
|
# Paranoia level
|
|
SecAction "id:900000,phase:1,pass,t:none,nolog,setvar:tx.blocking_paranoia_level=%d"
|
|
|
|
# Core rules — SQL injection
|
|
SecRule ARGS|ARGS_NAMES|REQUEST_BODY "@detectSQLi" \
|
|
"id:942100,phase:2,deny,status:403,log,msg:'SQL Injection detected',tag:'OWASP_CRS',tag:'attack-sqli'"
|
|
|
|
# Core rules — XSS
|
|
SecRule ARGS|ARGS_NAMES|REQUEST_BODY "@detectXSS" \
|
|
"id:941100,phase:2,deny,status:403,log,msg:'XSS detected',tag:'OWASP_CRS',tag:'attack-xss'"
|
|
|
|
# Path traversal
|
|
SecRule ARGS|REQUEST_URI "@contains ../" \
|
|
"id:930100,phase:2,deny,status:403,log,msg:'Path traversal detected',tag:'OWASP_CRS',tag:'attack-lfi'"
|
|
|
|
# Command injection patterns
|
|
SecRule ARGS|REQUEST_BODY "@rx (?:;|\||\x60|&&|\$\()" \
|
|
"id:932100,phase:2,deny,status:403,log,msg:'Command injection detected',tag:'OWASP_CRS',tag:'attack-rce'"
|
|
|
|
# Block common scanners
|
|
SecRule REQUEST_HEADERS:User-Agent "@rx (?:nikto|sqlmap|nmap|masscan|dirbuster)" \
|
|
"id:913100,phase:1,deny,status:403,log,msg:'Scanner blocked',tag:'OWASP_CRS',tag:'automation'"
|
|
|
|
# Exclude WebSocket upgrade and health endpoints from body inspection
|
|
SecRule REQUEST_URI "@streq /ws" "id:900001,phase:1,pass,nolog,ctl:ruleRemoveById=942100;941100;932100"
|
|
SecRule REQUEST_URI "@streq /api/v1/health" "id:900002,phase:1,pass,nolog,ctl:ruleRemoveById=942100;941100;932100"
|
|
|
|
# Exclude file upload endpoint from body inspection (binary content)
|
|
SecRule REQUEST_URI "@beginsWith /api/v1/uploads" "id:900003,phase:1,pass,nolog,ctl:requestBodyAccess=Off"
|
|
`, paranoiaLevel)),
|
|
)
|
|
if err != nil {
|
|
slog.Error("waf: failed to create WAF engine, continuing without WAF", "error", err)
|
|
return func(next http.Handler) http.Handler { return next }
|
|
}
|
|
|
|
slog.Info("waf: Coraza WAF enabled", "paranoia_level", paranoiaLevel)
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
tx := waf.NewTransaction()
|
|
defer func() {
|
|
tx.ProcessLogging()
|
|
if err := tx.Close(); err != nil {
|
|
slog.Debug("waf: error closing transaction", "error", err)
|
|
}
|
|
}()
|
|
|
|
// Process request headers
|
|
tx.ProcessConnection(r.RemoteAddr, 0, "", 0)
|
|
tx.ProcessURI(r.URL.String(), r.Method, r.Proto)
|
|
for name, values := range r.Header {
|
|
for _, value := range values {
|
|
tx.AddRequestHeader(name, value)
|
|
}
|
|
}
|
|
|
|
if it := tx.ProcessRequestHeaders(); it != nil {
|
|
handleWAFInterruption(w, it)
|
|
return
|
|
}
|
|
|
|
// Process request body (if applicable). Use ContentLength != 0 so
|
|
// chunked requests (Transfer-Encoding: chunked → ContentLength == -1)
|
|
// are inspected too; otherwise the SQLi/XSS/RCE body rules are silently
|
|
// skipped for them. The read is bounded by SecRequestBodyLimit inside
|
|
// Coraza. ContentLength == 0 (no body) still skips inspection.
|
|
if r.Body != nil && r.ContentLength != 0 {
|
|
if it, _, err := tx.ReadRequestBodyFrom(r.Body); it != nil {
|
|
handleWAFInterruption(w, it)
|
|
return
|
|
} else if err != nil {
|
|
slog.Debug("waf: error reading request body", "error", err)
|
|
}
|
|
|
|
if it, err := tx.ProcessRequestBody(); it != nil {
|
|
handleWAFInterruption(w, it)
|
|
return
|
|
} else if err != nil {
|
|
slog.Debug("waf: error processing request body", "error", err)
|
|
}
|
|
|
|
// Replace body with buffered version so downstream handlers can read it
|
|
reader, err := tx.RequestBodyReader()
|
|
if err == nil && reader != nil {
|
|
r.Body = io.NopCloser(reader)
|
|
}
|
|
}
|
|
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|
|
|
|
func handleWAFInterruption(w http.ResponseWriter, it *types.Interruption) {
|
|
slog.Warn("waf: request blocked",
|
|
"status", it.Status,
|
|
"action", it.Action,
|
|
"rule_id", it.RuleID,
|
|
)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(it.Status)
|
|
_, _ = fmt.Fprintf(w, `{"error":"request blocked by security rules"}`)
|
|
}
|