BlueGit

timfa bluegit

Files

bluegit / internal / ssrf / ssrf.go

ssrf.go

feat: nieuw-formulier, groepsoverzicht, logo's en talen
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
Failed d1203d3b History
ssrf.go 5.8 KiB Download Raw
1// Package ssrf keurt webhook-bestemmingen.
2// Privénetwerken zijn geblokkeerd. Een naam die naar een publiek IP
3// wijst mag wel, ook als een router dat verkeer daarna terug naar huis
4// stuurt. Het IP wordt bij het verbinden vastgezet, zodat een tweede
5// DNS-antwoord niet alsnog een privéadres kan worden.
6package ssrf
7
8import (
9 "context"
10 "net"
11 "net/http"
12 "net/url"
13 "strings"
14 "time"
15
16 "gitlab.com/Timfa/bluegit/internal/i18n"
17)
18
19// MaxRedirects is het aantal hops dat een webhook nog volgt.
20const MaxRedirects = 3
21
22var (
23 v4Blocked []*net.IPNet
24 v6Blocked []*net.IPNet
25)
26
27func init() {
28 // RFC1918, loopback, link-local (daar zit 169.254.169.254 bij),
29 // CGNAT, unspecified, multicast en gereserveerd.
30 v4Blocked = mustCIDR(
31 "0.0.0.0/8",
32 "10.0.0.0/8",
33 "100.64.0.0/10",
34 "127.0.0.0/8",
35 "169.254.0.0/16",
36 "172.16.0.0/12",
37 "192.168.0.0/16",
38 "224.0.0.0/4",
39 "240.0.0.0/4",
40 )
41 // Loopback, ULA, link-local, het oude site-local, multicast.
42 v6Blocked = mustCIDR(
43 "::1/128",
44 "fc00::/7",
45 "fe80::/10",
46 "fec0::/10",
47 "ff00::/8",
48 )
49}
50
51func mustCIDR(cidrs ...string) []*net.IPNet {
52 var out []*net.IPNet
53 for _, c := range cidrs {
54 _, n, err := net.ParseCIDR(c)
55 if err != nil {
56 panic(err)
57 }
58 out = append(out, n)
59 }
60 return out
61}
62
63// Private meldt of ip geen publiek unicast-adres is.
64// IPv4-mapped adressen, 6to4 en NAT64 (64:ff9b::/96) worden beoordeeld
65// op het ingebedde IPv4-adres.
66func Private(ip net.IP) bool {
67 if ip == nil {
68 return true
69 }
70 if v4 := embeddedV4(ip); v4 != nil {
71 return privateV4(v4)
72 }
73 if v4 := ip.To4(); v4 != nil {
74 return privateV4(v4)
75 }
76 v6 := ip.To16()
77 if v6 == nil {
78 return true
79 }
80 if v6.Equal(net.IPv6unspecified) {
81 return true
82 }
83 for _, n := range v6Blocked {
84 if n.Contains(v6) {
85 return true
86 }
87 }
88 return false
89}
90
91func privateV4(ip net.IP) bool {
92 ip = ip.To4()
93 if ip == nil {
94 return true
95 }
96 for _, n := range v4Blocked {
97 if n.Contains(ip) {
98 return true
99 }
100 }
101 return false
102}
103
104// embeddedV4 haalt een IPv4-adres uit 6to4 (2002::/16) of NAT64 (64:ff9b::/96).
105func embeddedV4(ip net.IP) net.IP {
106 v6 := ip.To16()
107 if v6 == nil || ip.To4() != nil {
108 return nil
109 }
110 if v6[0] == 0x20 && v6[1] == 0x02 {
111 return net.IPv4(v6[2], v6[3], v6[4], v6[5]).To4()
112 }
113 if v6[0] == 0x00 && v6[1] == 0x64 && v6[2] == 0xff && v6[3] == 0x9b && allZero(v6[4:12]) {
114 return net.IPv4(v6[12], v6[13], v6[14], v6[15]).To4()
115 }
116 return nil
117}
118
119func allZero(b []byte) bool {
120 for _, c := range b {
121 if c != 0 {
122 return false
123 }
124 }
125 return true
126}
127
128// Lookup zoekt de adressen van een hostnaam. Tests vullen een eigen functie in.
129type Lookup func(ctx context.Context, host string) ([]net.IP, error)
130
131func defaultLookup(ctx context.Context, host string) ([]net.IP, error) {
132 addrs, err := net.DefaultResolver.LookupIPAddr(ctx, host)
133 if err != nil {
134 return nil, err
135 }
136 out := make([]net.IP, 0, len(addrs))
137 for _, a := range addrs {
138 out = append(out, a.IP)
139 }
140 return out, nil
141}
142
143// Pin kiest het IP waarmee verbonden wordt.
144// Een letterlijk privéadres wordt geweigerd zonder DNS. Een naam waarvan
145// minstens één adres geblokkeerd is, wordt helemaal geweigerd: anders kan
146// het tweede antwoord alsnog naar het lokale net wijzen.
147func Pin(ctx context.Context, host string, lookup Lookup) (net.IP, error) {
148 host = strings.TrimSuffix(strings.TrimSpace(host), ".")
149 if host == "" {
150 return nil, i18n.E("err.whHost")
151 }
152 if ip := net.ParseIP(host); ip != nil {
153 if Private(ip) {
154 return nil, i18n.E("err.whBlockedIP", ip.String())
155 }
156 return ip, nil
157 }
158 if lookup == nil {
159 lookup = defaultLookup
160 }
161 ips, err := lookup(ctx, host)
162 if err != nil {
163 return nil, i18n.E("err.whDNS", host, err.Error())
164 }
165 if len(ips) == 0 {
166 return nil, i18n.E("err.whNoAddr", host)
167 }
168 for _, ip := range ips {
169 if Private(ip) {
170 return nil, i18n.E("err.whBlockedHost", host, ip.String())
171 }
172 }
173 return ips[0], nil
174}
175
176// ValidateURL keurt het schema, een userinfo en een letterlijk privéadres af.
177func ValidateURL(u *url.URL) error {
178 if u == nil || u.Hostname() == "" || u.User != nil {
179 return i18n.E("err.whURL")
180 }
181 if u.Scheme != "http" && u.Scheme != "https" {
182 return i18n.E("err.whScheme")
183 }
184 if ip := net.ParseIP(u.Hostname()); ip != nil && Private(ip) {
185 return i18n.E("err.whBlockedIP", ip.String())
186 }
187 return nil
188}
189
190func checkRedirect(req *http.Request, via []*http.Request) error {
191 if len(via) >= MaxRedirects {
192 return i18n.E("err.whRedirects")
193 }
194 if err := ValidateURL(req.URL); err != nil {
195 return err
196 }
197 if len(via) == 0 || via[0].URL == nil || sameHost(via[0].URL, req.URL) {
198 return nil
199 }
200 if req.Response != nil && (req.Response.StatusCode == http.StatusTemporaryRedirect || req.Response.StatusCode == http.StatusPermanentRedirect) {
201 return i18n.E("err.whRedirectHost")
202 }
203 for k := range req.Header {
204 if strings.EqualFold(k, "Content-Type") || strings.EqualFold(k, "User-Agent") {
205 continue
206 }
207 req.Header.Del(k)
208 }
209 return nil
210}
211
212func sameHost(a, b *url.URL) bool {
213 if a == nil || b == nil {
214 return false
215 }
216 return strings.EqualFold(a.Hostname(), b.Hostname())
217}
218
219// NewClient belt alleen publieke IP's en zet het gekozen adres vast.
220// Omgevingsproxies worden niet gebruikt.
221func NewClient(timeout time.Duration) *http.Client {
222 dialer := &net.Dialer{Timeout: 5 * time.Second, KeepAlive: 30 * time.Second}
223 transport := &http.Transport{
224 DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
225 host, port, err := net.SplitHostPort(addr)
226 if err != nil {
227 return nil, err
228 }
229 ip, err := Pin(ctx, host, nil)
230 if err != nil {
231 return nil, err
232 }
233 return dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port))
234 },
235 TLSHandshakeTimeout: 5 * time.Second,
236 ForceAttemptHTTP2: true,
237 }
238 if timeout <= 0 {
239 timeout = 10 * time.Second
240 }
241 return &http.Client{Timeout: timeout, Transport: transport, CheckRedirect: checkRedirect}
242}