ssrf.go raw
1 package sales
2
3 import (
4 "fmt"
5 "net"
6 "net/url"
7 "strings"
8 )
9
10 // checkMirrorURL refuses a mirror target that is not a public HTTP(S) URL.
11 //
12 // /mirror makes this server fetch a URL, so an unchecked target is an SSRF
13 // primitive: it could reach loopback services, RFC1918 hosts, or link-local
14 // metadata. allowPrivate exists only for local labs and tests.
15 func checkMirrorURL(raw string, allowPrivate bool) error {
16 u, err := url.Parse(raw)
17 if err != nil {
18 return fmt.Errorf("sales: mirror URL: %w", err)
19 }
20 if u.Scheme != "http" && u.Scheme != "https" {
21 return fmt.Errorf("sales: mirror URL scheme %q is not http or https", u.Scheme)
22 }
23 host := u.Hostname()
24 if host == "" {
25 return fmt.Errorf("sales: mirror URL has no host")
26 }
27 if allowPrivate {
28 return nil
29 }
30 if strings.EqualFold(host, "localhost") {
31 return fmt.Errorf("sales: mirror URL targets localhost")
32 }
33 ips, err := net.LookupIP(host)
34 if err != nil {
35 // A literal public IP parses without a lookup; a name that cannot be
36 // resolved cannot be fetched, and refusing it here is the safe answer.
37 if ip := net.ParseIP(host); ip != nil {
38 if isPrivateIP(ip) {
39 return fmt.Errorf("sales: mirror URL targets a private address")
40 }
41 return nil
42 }
43 return fmt.Errorf("sales: mirror host %q does not resolve", host)
44 }
45 for _, ip := range ips {
46 if isPrivateIP(ip) {
47 return fmt.Errorf("sales: mirror host %q resolves to a private address", host)
48 }
49 }
50 return nil
51 }
52
53 // isPrivateIP covers loopback, RFC1918, link-local, unique-local, and the
54 // unspecified address.
55 func isPrivateIP(ip net.IP) bool {
56 return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() ||
57 ip.IsLinkLocalMulticast() || ip.IsUnspecified()
58 }
59