add additional allowed hosts

This commit is contained in:
Jeffrey Morgan 2024-03-08 23:23:59 -08:00
parent 6c0af2599e
commit 5c143af726

View file

@ -915,9 +915,9 @@ func allowedHost(host string) bool {
} }
var tlds = []string{ var tlds = []string{
".localhost", "localhost",
".local", "local",
".internal", "internal",
} }
for _, tld := range tlds { for _, tld := range tlds {
@ -929,6 +929,27 @@ func allowedHost(host string) bool {
return false return false
} }
func ips() []string {
var ips []string
if interfaces, err := net.Interfaces(); err == nil {
for _, iface := range interfaces {
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, a := range addrs {
if ip, _, err := net.ParseCIDR(a.String()); err == nil {
ips = append(ips, ip.String())
}
}
}
}
return ips
}
func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc { func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
if addr == nil { if addr == nil {
@ -936,17 +957,8 @@ func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
return return
} }
if !netip.MustParseAddrPort(addr.String()).Addr().IsLoopback() { addr, err := netip.ParseAddrPort(addr.String())
c.Next() if err == nil && !addr.Addr().IsLoopback() {
return
}
if addrPort, _ := netip.ParseAddrPort(c.Request.Host); addrPort.Addr().IsLoopback() {
c.Next()
return
}
if addr, _ := netip.ParseAddr(c.Request.Host); addr.IsLoopback() {
c.Next() c.Next()
return return
} }
@ -956,6 +968,13 @@ func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
host = c.Request.Host host = c.Request.Host
} }
if addr, err := netip.ParseAddr(host); err == nil {
if addr.IsLoopback() || addr.IsPrivate() || slices.Contains(ips(), host) || addr.String() == "0.0.0.0" {
c.Next()
return
}
}
if allowedHost(host) { if allowedHost(host) {
c.Next() c.Next()
return return