mirror of https://github.com/gin-gonic/gin.git
always trust xff headers from unix socket
This commit is contained in:
parent
78dad9d77d
commit
3b3d3bf6da
17
context.go
17
context.go
|
@ -779,14 +779,27 @@ func (c *Context) ClientIP() string {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
trusted bool
|
||||||
|
remoteIP net.IP
|
||||||
|
)
|
||||||
|
// If gin is listening a unix socket, always trust it.
|
||||||
|
localAddr, ok := c.Request.Context().Value(http.LocalAddrContextKey).(net.Addr)
|
||||||
|
if ok && strings.HasPrefix(localAddr.Network(), "unix") {
|
||||||
|
trusted = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback
|
||||||
|
if !trusted {
|
||||||
// It also checks if the remoteIP is a trusted proxy or not.
|
// It also checks if the remoteIP is a trusted proxy or not.
|
||||||
// In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks
|
// In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks
|
||||||
// defined by Engine.SetTrustedProxies()
|
// defined by Engine.SetTrustedProxies()
|
||||||
remoteIP := net.ParseIP(c.RemoteIP())
|
remoteIP = net.ParseIP(c.RemoteIP())
|
||||||
if remoteIP == nil {
|
if remoteIP == nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
trusted := c.engine.isTrustedProxy(remoteIP)
|
trusted = c.engine.isTrustedProxy(remoteIP)
|
||||||
|
}
|
||||||
|
|
||||||
if trusted && c.engine.ForwardedByClientIP && c.engine.RemoteIPHeaders != nil {
|
if trusted && c.engine.ForwardedByClientIP && c.engine.RemoteIPHeaders != nil {
|
||||||
for _, headerName := range c.engine.RemoteIPHeaders {
|
for _, headerName := range c.engine.RemoteIPHeaders {
|
||||||
|
|
|
@ -1437,6 +1437,16 @@ func TestContextClientIP(t *testing.T) {
|
||||||
c.engine.trustedCIDRs, _ = c.engine.prepareTrustedCIDRs()
|
c.engine.trustedCIDRs, _ = c.engine.prepareTrustedCIDRs()
|
||||||
resetContextForClientIPTests(c)
|
resetContextForClientIPTests(c)
|
||||||
|
|
||||||
|
// unix address
|
||||||
|
addr := &net.UnixAddr{Net: "unix", Name: "@"}
|
||||||
|
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), http.LocalAddrContextKey, addr))
|
||||||
|
c.Request.RemoteAddr = addr.String()
|
||||||
|
assert.Equal(t, "20.20.20.20", c.ClientIP())
|
||||||
|
|
||||||
|
// reset
|
||||||
|
c.Request = c.Request.WithContext(context.Background())
|
||||||
|
resetContextForClientIPTests(c)
|
||||||
|
|
||||||
// Legacy tests (validating that the defaults don't break the
|
// Legacy tests (validating that the defaults don't break the
|
||||||
// (insecure!) old behaviour)
|
// (insecure!) old behaviour)
|
||||||
assert.Equal(t, "20.20.20.20", c.ClientIP())
|
assert.Equal(t, "20.20.20.20", c.ClientIP())
|
||||||
|
|
Loading…
Reference in New Issue