From 313d3148d2525853526f9dfd167f6e0a60cce339 Mon Sep 17 00:00:00 2001 From: Tiago Silva Date: Fri, 5 Jan 2024 10:31:20 +0000 Subject: [PATCH] Fix incorrect audit log IP when using Kubernetes impersonation Audit logs for Kubernetes requests showed incorrect IP addresses when reverse tunnel was used to forward the request. Audit logs use 'req.RemoteAddr` which was never updated with the impersonated IP address. Changelog: Fixed incorrect report of user's IP address in Kubernetes Audit Logs Fixes #36288 Signed-off-by: Tiago Silva --- lib/auth/middleware.go | 7 ++++++- lib/auth/middleware_test.go | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/auth/middleware.go b/lib/auth/middleware.go index ea9d83afa7b90..3869ae5517a9a 100644 --- a/lib/auth/middleware.go +++ b/lib/auth/middleware.go @@ -693,7 +693,12 @@ func (a *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx = authz.ContextWithClientSrcAddr(ctx, clientSrcAddr) } ctx = authz.ContextWithUser(ctx, user) - a.Handler.ServeHTTP(w, r.WithContext(ctx)) + r = r.WithContext(ctx) + // set remote address to the one that was passed in the header + // this is needed because impersonation reuses the same connection + // and the remote address is not updated from 0.0.0.0:0 + r.RemoteAddr = remoteAddr + a.Handler.ServeHTTP(w, r) } // WrapContextWithUser enriches the provided context with the identity information diff --git a/lib/auth/middleware_test.go b/lib/auth/middleware_test.go index 531f2a37edda6..3b185cdd5933a 100644 --- a/lib/auth/middleware_test.go +++ b/lib/auth/middleware_test.go @@ -647,6 +647,7 @@ func (h *fakeHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { clientSrcAddr, err := authz.ClientSrcAddrFromContext(r.Context()) require.NoError(h.t, err) require.Equal(h.t, h.userIP, clientSrcAddr.String()) + require.Equal(h.t, h.userIP, r.RemoteAddr) // Ensure that the Teleport-Impersonate-User header is not set on the request // after the middleware has run. require.Empty(h.t, r.Header.Get(TeleportImpersonateUserHeader))