-
Notifications
You must be signed in to change notification settings - Fork 8.6k
Non-standard X-Forwarded-For header content is not supported #4572
Description
Description
When a user accesses a Gin-based web application through a reverse proxy server, and the application uses c.GetClientIP() to obtain the client IP address, it currently only recognizes the following formats:
IPv4 addresses
IPv6 addresses without square brackets
For example, the following addresses can be correctly recognized:
192.168.8.39
240e:318:2f4a:de56::240
However, in real production environments, some reverse proxy servers do not provide IP addresses in this “plain” format. For example, IIS automatically adds square brackets around IPv6 addresses, which may result in the following X-Forwarded-For header:
X-Forwarded-For: [240e:318:2f4a:de56::240]
This format with square brackets cannot currently be recognized.
In addition, some scenarios include the client port in the X-Forwarded-For header. For example:
When IIS uses Application Request Routing (ARR) + URL Rewrite as a reverse proxy and the “Include TCP port from clientIP” option is enabled.
Some cloud load balancers also provide similar settings, such as
routing.http.xff_client_port.enabled.
In these cases, the X-Forwarded-For header may look like this:
X-Forwarded-For: 192.168.8.39:38792
X-Forwarded-For: [240e:318:2f4a:de56::240]:38792
These formats that include a port number are also not recognized.
Gin Version
v1.12.0
Can you reproduce the bug?
Yes
Source Code
// main.go
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.SetTrustedProxies([]string{"0.0.0.0/0", "::/0"})
r.GET("/ip", func(c *gin.Context) {
c.String(200, c.ClientIP())
})
r.Run(":8081")
}Execute the test in Windows CMD, Test results:
curl -H "X-Forwarded-For: 192.168.8.39" http://127.0.0.1:8080/ip
Response content: 192.168.8.39
curl -H "X-Forwarded-For: 240e:318:2f4a:de56::240" http://127.0.0.1:8080/ip
Response content: 240e:318:2f4a:de56::240
curl -H "X-Forwarded-For: [240e:318:2f4a:de56::240]" http://127.0.0.1:8080/ip
Response content: 127.0.0.1
curl -H "X-Forwarded-For: 192.168.8.39:38792" http://127.0.0.1:8080/ip
Response content: 127.0.0.1
curl -H "X-Forwarded-For: [240e:318:2f4a:de56::240]:38792" http://127.0.0.1:8080/ip
Response content: 127.0.0.1Go Version
1.25.7
Operating System
Windows 11 Build 26200