// Package netguard keeps customer-supplied addresses from reaching our own // infrastructure. Identity providers and monitored targets are configured by // customers; in the cloud edition they must not be able to probe private // networks through us. package netguard import ( "context" "errors" "net" "net/netip" "syscall" "time" ) // ErrForbiddenAddress is returned when a destination resolves to an address // the caller may not contact. var ErrForbiddenAddress = errors.New("netguard: destination resolves to a non-public address") var cgnat = netip.MustParsePrefix("100.64.0.0/10") // IsPublic reports whether a is a globally routable unicast address. func IsPublic(a netip.Addr) bool { a = a.Unmap() return a.IsGlobalUnicast() && !a.IsPrivate() && !cgnat.Contains(a) } // Dialer returns a dialer that, unless allowPrivate is set, refuses to // connect to non-public addresses. The check runs on the resolved address at // connect time, so DNS rebinding and redirects cannot bypass it. func Dialer(allowPrivate bool, timeout time.Duration) *net.Dialer { d := &net.Dialer{Timeout: timeout} if !allowPrivate { d.Control = func(_, address string, _ syscall.RawConn) error { ap, err := netip.ParseAddrPort(address) if err != nil || !IsPublic(ap.Addr()) { return ErrForbiddenAddress } return nil } } return d } // CheckHost resolves host and fails if any of its addresses is non-public. // Use it where no dialer is involved, such as ICMP. func CheckHost(ctx context.Context, host string) ([]netip.Addr, error) { addrs, err := net.DefaultResolver.LookupNetIP(ctx, "ip", host) if err != nil { return nil, err } for _, a := range addrs { if !IsPublic(a) { return nil, ErrForbiddenAddress } } return addrs, nil }