package alertwebhook import ( "context" "fmt" "net" "net/http" "syscall" "time" ) // PublicClient reaches public addresses only and follows no redirect. It // carries a webhook an org chose: the daemon sends from inside the instance's // network, so the org must not aim it at the daemon's own host or LAN. func PublicClient() *http.Client { dialer := &net.Dialer{ Timeout: timeout, Control: func(_, address string, _ syscall.RawConn) error { host, _, err := net.SplitHostPort(address) if err != nil { return err } if ip := net.ParseIP(host); ip == nil || !public(ip) { return fmt.Errorf("webhook address %s is not public", host) } return nil }, } return &http.Client{ Timeout: 15 * time.Second, Transport: &http.Transport{DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { return dialer.DialContext(ctx, network, addr) }}, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, } } func public(ip net.IP) bool { switch { case ip.IsLoopback(), ip.IsPrivate(), ip.IsUnspecified(), ip.IsLinkLocalUnicast(), ip.IsLinkLocalMulticast(), ip.IsInterfaceLocalMulticast(), ip.IsMulticast(): return false } for _, block := range reserved { if block.Contains(ip) { return false } } return true } // reserved are ranges that are not the public internet: carrier-grade NAT, // benchmarking, IETF protocol assignments and the NAT64 prefix, which can map // to private IPv4 hosts. var reserved = []*net.IPNet{ mustCIDR("100.64.0.0/10"), mustCIDR("198.18.0.0/15"), mustCIDR("192.0.0.0/24"), mustCIDR("64:ff9b::/96"), } func mustCIDR(text string) *net.IPNet { _, block, err := net.ParseCIDR(text) if err != nil { panic(err) } return block }