Skip to content

Commit

Permalink
add proxy handlin
Browse files Browse the repository at this point in the history
  • Loading branch information
sagostin committed Oct 4, 2024
1 parent 0a2c832 commit 06b72fe
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 16 deletions.
64 changes: 64 additions & 0 deletions web/proxy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package web

import (
"github.com/kataras/iris/v12"
"net"
"strings"
)

var trustedProxies = []string{
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"fc00::/7",
}

func isPrivateIP(ip net.IP) bool {
for _, cidr := range trustedProxies {
_, network, err := net.ParseCIDR(cidr)
if err == nil && network.Contains(ip) {
return true
}
}
return false
}

func ProxyIPMiddleware(ctx iris.Context) {
remoteIP := net.ParseIP(ctx.RemoteAddr())
if remoteIP == nil {
ctx.Values().Set("client_ip", ctx.RemoteAddr())
ctx.Next()
return
}

if !isPrivateIP(remoteIP) {
ctx.Values().Set("client_ip", remoteIP.String())
ctx.Next()
return
}

if forwardedFor := ctx.GetHeader("X-Forwarded-For"); forwardedFor != "" {
ips := strings.Split(forwardedFor, ",")
for _, ip := range ips {
parsedIP := net.ParseIP(strings.TrimSpace(ip))
if parsedIP != nil && !isPrivateIP(parsedIP) {
ctx.Values().Set("client_ip", parsedIP.String())
ctx.Next()
return
}
}
}

if realIP := ctx.GetHeader("X-Real-IP"); realIP != "" {
parsedIP := net.ParseIP(realIP)
if parsedIP != nil && !isPrivateIP(parsedIP) {
ctx.Values().Set("client_ip", parsedIP.String())
ctx.Next()
return
}
}

// If we couldn't determine a public IP, fall back to the remote address
ctx.Values().Set("client_ip", ctx.RemoteAddr())
ctx.Next()
}
16 changes: 0 additions & 16 deletions web/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/mongo"
"nw-guardian/internal/agent"
"strings"
)

type Router struct {
Expand Down Expand Up @@ -112,18 +111,3 @@ func (r *Router) Listen(host string) {
return
}
}

func ProxyIPMiddleware(ctx iris.Context) {
ip := ctx.RemoteAddr()
if forwardedFor := ctx.GetHeader("X-Forwarded-For"); forwardedFor != "" {
ips := strings.Split(forwardedFor, ",")
if len(ips) > 0 {
ip = strings.TrimSpace(ips[0])
}
} else if realIP := ctx.GetHeader("X-Real-IP"); realIP != "" {
ip = realIP
}

ctx.Values().Set("client_ip", ip)
ctx.Next()
}

0 comments on commit 06b72fe

Please sign in to comment.