Skip to content

Commit

Permalink
Fix using IP ranges in config.TrustedProxies (#1607)
Browse files Browse the repository at this point in the history
  • Loading branch information
hi019 committed Nov 8, 2021
1 parent 7b7dcf2 commit af19c71
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 17 deletions.
27 changes: 12 additions & 15 deletions app.go
Expand Up @@ -348,8 +348,9 @@ type Config struct {
// Read EnableTrustedProxyCheck doc.
//
// Default: []string
TrustedProxies []string `json:"trusted_proxies"`
trustedProxiesMap map[string]struct{}
TrustedProxies []string `json:"trusted_proxies"`
trustedProxiesMap map[string]struct{}
trustedProxyRangesMap []*net.IPNet
}

// Static defines configuration options when defining static assets.
Expand Down Expand Up @@ -479,8 +480,8 @@ func New(config ...Config) *App {
}

app.config.trustedProxiesMap = make(map[string]struct{}, len(app.config.TrustedProxies))
for _, ip := range app.config.TrustedProxies {
app.handleTrustedProxy(ip)
for _, ipAddress := range app.config.TrustedProxies {
app.handleTrustedProxy(ipAddress)
}

// Init app
Expand All @@ -490,23 +491,19 @@ func New(config ...Config) *App {
return app
}

// Checks if the given IP address is a range whether or not, adds it to the trustedProxiesMap
// Adds an ip address to trustedProxyRangesMap or trustedProxiesMap based on whether it is an IP range or not
func (app *App) handleTrustedProxy(ipAddress string) {
// Detects IP address is range whether or not
if strings.Contains(ipAddress, "/") {
// Parsing IP address
ip, ipnet, err := net.ParseCIDR(ipAddress)
_, ipNet, err := net.ParseCIDR(ipAddress)

if err != nil {
fmt.Printf("[Warning] IP range `%s` could not be parsed. \n", ipAddress)
return
}
// Iterates IP address which is between range
for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); utils.IncrementIPRange(ip) {
app.config.trustedProxiesMap[ip.String()] = struct{}{}
}
return

app.config.trustedProxyRangesMap = append(app.config.trustedProxyRangesMap, ipNet)
} else {
app.config.trustedProxiesMap[ipAddress] = struct{}{}
}
app.config.trustedProxiesMap[ipAddress] = struct{}{}
}

// Mount attaches another app instance as a sub-router along a routing path.
Expand Down
14 changes: 12 additions & 2 deletions ctx.go
Expand Up @@ -1286,6 +1286,16 @@ func (c *Ctx) IsProxyTrusted() bool {
return true
}

_, trustProxy := c.app.config.trustedProxiesMap[c.fasthttp.RemoteIP().String()]
return trustProxy
_, trusted := c.app.config.trustedProxiesMap[c.fasthttp.RemoteIP().String()]
if trusted {
return trusted
}

for _, ipNet := range c.app.config.trustedProxyRangesMap {
if ipNet.Contains(c.fasthttp.RemoteIP()) {
return true
}
}

return false
}

0 comments on commit af19c71

Please sign in to comment.