|
| 1 | +package net |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "net" |
| 7 | + "net/http" |
| 8 | + "time" |
| 9 | +) |
| 10 | + |
| 11 | +var ( |
| 12 | + linkLocalV4 = net.IPNet{ |
| 13 | + IP: net.IP{169, 254, 0, 0}, |
| 14 | + Mask: net.CIDRMask(16, 32), |
| 15 | + } |
| 16 | + linkLocalV6 = net.IPNet{ |
| 17 | + IP: net.ParseIP("fe80::"), |
| 18 | + Mask: net.CIDRMask(10, 128), |
| 19 | + } |
| 20 | +) |
| 21 | + |
| 22 | +// isLinkLocal returns true if the given IP is in the IPv4 link-local range |
| 23 | +// (169.254.0.0/16) or the IPv6 link-local range (fe80::/10). |
| 24 | +func isLinkLocal(ip net.IP) bool { |
| 25 | + return linkLocalV4.Contains(ip) || linkLocalV6.Contains(ip) |
| 26 | +} |
| 27 | + |
| 28 | +// SafeDialContext returns a DialContext function that blocks connections to |
| 29 | +// link-local IP addresses (169.254.0.0/16 and fe80::/10). This prevents SSRF |
| 30 | +// attacks targeting cloud instance metadata endpoints (e.g. 169.254.169.254). |
| 31 | +// |
| 32 | +// The returned function resolves the hostname before connecting and rejects the |
| 33 | +// connection if all resolved addresses are link-local. |
| 34 | +func SafeDialContext(dialer *net.Dialer) func( |
| 35 | + ctx context.Context, |
| 36 | + network string, |
| 37 | + addr string, |
| 38 | +) (net.Conn, error) { |
| 39 | + return func(ctx context.Context, network, addr string) (net.Conn, error) { |
| 40 | + host, port, err := net.SplitHostPort(addr) |
| 41 | + if err != nil { |
| 42 | + return nil, fmt.Errorf("failed to parse address %q: %w", addr, err) |
| 43 | + } |
| 44 | + |
| 45 | + // Resolve the hostname to IP addresses. |
| 46 | + ips, err := net.DefaultResolver.LookupIPAddr(ctx, host) |
| 47 | + if err != nil { |
| 48 | + return nil, fmt.Errorf("failed to resolve host %q: %w", host, err) |
| 49 | + } |
| 50 | + |
| 51 | + // Filter out link-local addresses. |
| 52 | + var safe []net.IPAddr |
| 53 | + for _, ip := range ips { |
| 54 | + if !isLinkLocal(ip.IP) { |
| 55 | + safe = append(safe, ip) |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + if len(safe) == 0 { |
| 60 | + return nil, fmt.Errorf( |
| 61 | + "connections to link-local addresses are not permitted "+ |
| 62 | + "(host %q resolved to link-local IPs only)", |
| 63 | + host, |
| 64 | + ) |
| 65 | + } |
| 66 | + |
| 67 | + // Dial using the first safe address. |
| 68 | + safeAddr := net.JoinHostPort(safe[0].IP.String(), port) |
| 69 | + return dialer.DialContext(ctx, network, safeAddr) |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +// SafeTransport wraps the given transport's DialContext to block connections to |
| 74 | +// link-local IP addresses. |
| 75 | +func SafeTransport(t *http.Transport) *http.Transport { |
| 76 | + dialer := &net.Dialer{ |
| 77 | + Timeout: 30 * time.Second, |
| 78 | + KeepAlive: 30 * time.Second, |
| 79 | + } |
| 80 | + t.DialContext = SafeDialContext(dialer) |
| 81 | + return t |
| 82 | +} |
0 commit comments