Skip to content

Commit 38609d7

Browse files
committed
Add the negative depth case
1 parent 5785956 commit 38609d7

2 files changed

Lines changed: 14 additions & 6 deletions

File tree

request/real_ip.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,17 +27,19 @@ func RealIP(r *http.Request) string {
2727
if fw := r.Header.Get(header.XForwardFor); fw != "" {
2828
xffs := strings.Split(fw, ",")
2929

30-
// If no IPs, return the first IP in the chain
31-
if len(xffs) == 0 {
32-
return ""
33-
}
34-
3530
// Get depth from config, default to 0 (first IP in chain)
3631
depth := 0
3732
if Global != nil {
3833
depth = Global().HttpServerOptions.XFFDepth
3934
}
4035

36+
// It's more secure to return empty if depth is invalid.
37+
// Returning the first IP in the case of an incorrect depth is a security risk.
38+
// and a buried failure.
39+
if depth < 0 {
40+
return ""
41+
}
42+
4143
// If depth exceeds available IPs, return empty
4244
if depth > len(xffs) {
4345
return ""

request/real_ip_test.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ func TestXFFDepth(t *testing.T) {
239239
name: "Depth -5 (Negative Depth uses same as NO depth)",
240240
xffValue: "10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1",
241241
depth: -5,
242-
expected: "10.0.0.1",
242+
expected: "",
243243
},
244244
{
245245
name: "Header with spaces",
@@ -253,6 +253,12 @@ func TestXFFDepth(t *testing.T) {
253253
depth: 3,
254254
expected: "11.0.0.1",
255255
},
256+
{
257+
name: "Empty header",
258+
xffValue: "",
259+
depth: 0,
260+
expected: "192.168.1.1", // Should fall back to RemoteAddr
261+
},
256262
{
257263
name: "Invalid IP at selected depth",
258264
xffValue: "10.0.0.1,invalid-ip,12.0.0.1,13.0.0.1",

0 commit comments

Comments
 (0)