package sales import ( "fmt" "net" "net/url" "strings" ) // checkMirrorURL refuses a mirror target that is not a public HTTP(S) URL. // // /mirror makes this server fetch a URL, so an unchecked target is an SSRF // primitive: it could reach loopback services, RFC1918 hosts, or link-local // metadata. allowPrivate exists only for local labs and tests. func checkMirrorURL(raw string, allowPrivate bool) error { u, err := url.Parse(raw) if err != nil { return fmt.Errorf("sales: mirror URL: %w", err) } if u.Scheme != "http" && u.Scheme != "https" { return fmt.Errorf("sales: mirror URL scheme %q is not http or https", u.Scheme) } host := u.Hostname() if host == "" { return fmt.Errorf("sales: mirror URL has no host") } if allowPrivate { return nil } if strings.EqualFold(host, "localhost") { return fmt.Errorf("sales: mirror URL targets localhost") } ips, err := net.LookupIP(host) if err != nil { // A literal public IP parses without a lookup; a name that cannot be // resolved cannot be fetched, and refusing it here is the safe answer. if ip := net.ParseIP(host); ip != nil { if isPrivateIP(ip) { return fmt.Errorf("sales: mirror URL targets a private address") } return nil } return fmt.Errorf("sales: mirror host %q does not resolve", host) } for _, ip := range ips { if isPrivateIP(ip) { return fmt.Errorf("sales: mirror host %q resolves to a private address", host) } } return nil } // isPrivateIP covers loopback, RFC1918, link-local, unique-local, and the // unspecified address. func isPrivateIP(ip net.IP) bool { return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsUnspecified() }