api/handler: fix X-Real-IP header validation

When trusted proxy headers are enabled, the code accepted `X-Real-IP`
without validating it. The attacker could simply set `X-Real-IP` to an
arbitrary and that IP would be recorded as is. We validate the IP format
and ensure it's not from a trusted proxy, and add test cases.


Signed-off-by: NotAShelf <raf@notashelf.dev>
Change-Id: Ic1e761ea623a69371a28ad15d465d6c66a6a6964
This commit is contained in:
raf 2026-03-10 09:10:43 +03:00
commit 98611ca452
Signed by: NotAShelf
GPG key ID: 29D95B64378DB4BF
2 changed files with 107 additions and 1 deletions

View file

@ -272,7 +272,12 @@ func (h *IngestionHandler) extractIP(r *http.Request) string {
// Check X-Real-IP header
if xri := r.Header.Get("X-Real-IP"); xri != "" {
return xri
// Validate the IP format and ensure it's not from a trusted proxy
if testIP := net.ParseIP(xri); testIP != nil {
if !h.ipInNetworks(xri, h.trustedNetworks) {
return xri
}
}
}
// Fall back to RemoteAddr