| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | "net" |
| 7 | "net/http" |
| 8 | "net/netip" |
| 9 | "syscall" |
| 10 | "time" |
| 11 | ) |
| 12 | |
| 13 | var errBlockedAddress = errors |
| 14 | |
| 15 | var ( |
| 16 | thisNetwork = netip. |
| 17 | sharedCGNAT = netip. |
| 18 | ) |
| 19 | |
| 20 | // blocked reports whether a webhook may not connect to a. Link-local covers |
| 21 | // the cloud metadata address 169.254.169.254 and stays blocked even when |
| 22 | // private networks are allowed. |
| 23 | func blocked(a netip |
| 24 | a = a. |
| 25 | if a.IsLinkLocalUnicast() |
| 26 | a.IsUnspecified() || |
| 27 | return true |
| 28 | } |
| 29 | if allowPrivate { |
| 30 | return false |
| 31 | } |
| 32 | return a.IsLoopback() |
| 33 | } |
| 34 | |
| 35 | // newWebhookClient returns a client that checks the IP it actually dials, |
| 36 | // after DNS, so a hostname that resolves or rebinds to an internal address |
| 37 | // is refused. It never uses a proxy (the check would see the proxy's IP) and |
| 38 | // never follows redirects (a redirect could point anywhere). |
| 39 | func newWebhookClient(allowPrivate bool |
| 40 | dialer := &net |
| 41 | Timeout: 5 * |
| 42 | Control: func(network |
| 43 | ap, err := |
| 44 | if err != nil |
| 45 | return err |
| 46 | } |
| 47 | if blocked(ap. |
| 48 | return fmt.Errorf( |
| 49 | } |
| 50 | return nil |
| 51 | }, |
| 52 | } |
| 53 | return &http.Client |
| 54 | Transport: &http |
| 55 | Proxy: nil, |
| 56 | DialContext: dialer.DialContext |
| 57 | TLSHandshakeTimeout: 5 * |
| 58 | MaxIdleConnsPerHost: 2, |
| 59 | IdleConnTimeout: 90 * |
| 60 | }, |
| 61 | CheckRedirect: func(*http |
| 62 | return http.ErrUseLastResponse |
| 63 | }, |
| 64 | } |
| 65 | } |