| 1 | package guard |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "compress/gzip" |
| 6 | "context" |
| 7 | "crypto/tls" |
| 8 | "crypto/x509" |
| 9 | "errors" |
| 10 | "io" |
| 11 | "net" |
| 12 | "net/http" |
| 13 | "net/http/httptrace" |
| 14 | "net/netip" |
| 15 | "net/url" |
| 16 | "strings" |
| 17 | "sync/atomic" |
| 18 | "syscall" |
| 19 | |
| 20 | "amadan.net/oficina/equipo/internal/websource" |
| 21 | ) |
| 22 | |
| 23 | // allowedHeaders are the headers a caller may set, by policy; the guard |
| 24 | // sets User-Agent, Accept and Accept-Encoding itself, and a search's |
| 25 | // credential. |
| 26 | var allowedHeaders = map[Policy][]string{ |
| 27 | PolicyLookupPage: {}, |
| 28 | PolicySearch: {"Content-Type"}, |
| 29 | PolicyService: {"Authorization", "Content-Type", "Accept"}, |
| 30 | } |
| 31 | |
| 32 | // checkPolicy refuses a request outside the client's policy, before |
| 33 | // anything is resolved or dialled. |
| 34 | func (c *Client) checkPolicy(req *http.Request) error { |
| 35 | switch c.cfg.Policy { |
| 36 | case PolicyLookupPage: |
| 37 | if req.Method != http.MethodGet || req.Body != nil && req.Body != http.NoBody { |
| 38 | return Refusal{Rule: RulePolicy} |
| 39 | } |
| 40 | case PolicySearch, PolicyService: |
| 41 | if req.Method != http.MethodGet && req.Method != http.MethodPost { |
| 42 | return Refusal{Rule: RulePolicy} |
| 43 | } |
| 44 | } |
| 45 | for k := range req.Header { |
| 46 | ok := false |
| 47 | for _, a := range allowedHeaders[c.cfg.Policy] { |
| 48 | ok = ok || http.CanonicalHeaderKey(a) == http.CanonicalHeaderKey(k) |
| 49 | } |
| 50 | if !ok { |
| 51 | return Refusal{Rule: RulePolicy} |
| 52 | } |
| 53 | } |
| 54 | return nil |
| 55 | } |
| 56 | |
| 57 | // Do makes req through every check, hop by hop, and reads the answer |
| 58 | // within the limits. A refusal is a Refusal by rule; nothing returned |
| 59 | // ever holds the URL, the query or a credential. |
| 60 | func (c *Client) Do(ctx context.Context, req *http.Request) (*Response, error) { |
| 61 | if c.test && c.cfg.TestDial == nil { |
| 62 | // A test binary never dials the world. |
| 63 | return nil, Refusal{Rule: RuleUnavailable} |
| 64 | } |
| 65 | if err := c.checkPolicy(req); err != nil { |
| 66 | return nil, err |
| 67 | } |
| 68 | var body []byte |
| 69 | if req.Body != nil && req.Body != http.NoBody { |
| 70 | raw, err := io.ReadAll(io.LimitReader(req.Body, MaxBody+1)) |
| 71 | if err != nil || len(raw) > MaxBody { |
| 72 | return nil, Refusal{Rule: RulePolicy} |
| 73 | } |
| 74 | body = raw |
| 75 | } |
| 76 | ctx, cancel := context.WithTimeout(ctx, c.cfg.Timeouts.Overall) |
| 77 | defer cancel() |
| 78 | u := *req.URL |
| 79 | method := req.Method |
| 80 | for hop := 0; ; hop++ { |
| 81 | if hop > c.cfg.Redirects { |
| 82 | return nil, c.refuse(RuleTooManyRedirect, u.Hostname()) |
| 83 | } |
| 84 | if u.Scheme == "http" { |
| 85 | // An http address the person typed is tried once as https; |
| 86 | // a redirect down to http never. |
| 87 | if hop > 0 { |
| 88 | return nil, c.refuse(RuleDowngrade, u.Hostname()) |
| 89 | } |
| 90 | u.Scheme = "https" |
| 91 | } |
| 92 | host, addrs, err := c.check(ctx, &u) |
| 93 | if err != nil { |
| 94 | return nil, err |
| 95 | } |
| 96 | if f := beforeHopOf(ctx); f != nil { |
| 97 | if err := f(ctx, host); err != nil { |
| 98 | return nil, err |
| 99 | } |
| 100 | // The hop may have waited (its pace): the inventory is |
| 101 | // checked again right before the dial. |
| 102 | if c.cfg.Inventory.Ready(ctx) != nil { |
| 103 | return nil, c.refuse(RuleUnconfirmed, host) |
| 104 | } |
| 105 | } |
| 106 | res, err := c.send(ctx, method, u, body, req.Header, host, addrs) |
| 107 | if err != nil { |
| 108 | return nil, err |
| 109 | } |
| 110 | if res.Status < 300 || res.Status > 399 || res.Status == http.StatusNotModified { |
| 111 | res.FinalURL = u.String() |
| 112 | return res, nil |
| 113 | } |
| 114 | if c.cfg.Redirects == 0 { |
| 115 | return nil, c.refuse(RuleRedirect, host) |
| 116 | } |
| 117 | next, err := u.Parse(res.Header.Get("Location")) |
| 118 | if err != nil || res.Header.Get("Location") == "" { |
| 119 | return nil, c.refuse(RuleURL, host) |
| 120 | } |
| 121 | u, method, body = *next, http.MethodGet, nil |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | // check applies the per-hop checks to u, and resolves its host: every |
| 126 | // answer must be public and outside the inventory. |
| 127 | func (c *Client) check(ctx context.Context, u *url.URL) (string, []netip.Addr, error) { |
| 128 | host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") |
| 129 | switch { |
| 130 | case u.Scheme != "https": |
| 131 | return "", nil, c.refuse(RuleScheme, host) |
| 132 | case u.Port() != "" && u.Port() != "443": |
| 133 | return "", nil, c.refuse(RulePort, host) |
| 134 | case u.User != nil || u.Opaque != "" || len(u.String()) > MaxURL: |
| 135 | return "", nil, c.refuse(RuleURL, host) |
| 136 | } |
| 137 | if strings.HasPrefix(u.Host, "[") { |
| 138 | return "", nil, c.refuse(RuleIPLiteral, host) |
| 139 | } |
| 140 | if err := websource.CheckHost(host); err != nil { |
| 141 | if errors.Is(err, websource.ErrIPLiteral) { |
| 142 | return "", nil, c.refuse(RuleIPLiteral, host) |
| 143 | } |
| 144 | return "", nil, c.refuse(RuleHost, host) |
| 145 | } |
| 146 | for _, d := range append(append([]string(nil), c.cfg.Deny...), denyOf(ctx)...) { |
| 147 | d = strings.TrimSuffix(strings.ToLower(d), ".") |
| 148 | if d != "" && (host == d || strings.HasSuffix(host, "."+d)) { |
| 149 | return "", nil, c.refuse(RuleDenied, host) |
| 150 | } |
| 151 | } |
| 152 | if c.cfg.Inventory == nil || c.cfg.Inventory.Ready(ctx) != nil { |
| 153 | return "", nil, c.refuse(RuleUnconfirmed, host) |
| 154 | } |
| 155 | resolve := c.cfg.Resolve |
| 156 | if resolve == nil { |
| 157 | resolve = func(ctx context.Context, h string) ([]netip.Addr, error) { |
| 158 | return net.DefaultResolver.LookupNetIP(ctx, "ip", h) |
| 159 | } |
| 160 | } |
| 161 | addrs, err := resolve(ctx, host) |
| 162 | if err != nil || len(addrs) == 0 { |
| 163 | if ctx.Err() != nil { |
| 164 | return "", nil, c.refuse(RuleTimeout, host) |
| 165 | } |
| 166 | return "", nil, c.refuse(RuleUnavailable, host) |
| 167 | } |
| 168 | for _, a := range addrs { |
| 169 | if !websource.PublicAddress(a) { |
| 170 | return "", nil, c.refuse(RulePrivate, host) |
| 171 | } |
| 172 | if c.cfg.Inventory.Inside(a.Unmap()) { |
| 173 | return "", nil, c.refuse(RuleInventory, host) |
| 174 | } |
| 175 | } |
| 176 | return host, addrs, nil |
| 177 | } |
| 178 | |
| 179 | // send makes one hop: a fresh connection to the checked address (the |
| 180 | // socket's address checked again as it connects), TLS to host, no proxy, |
| 181 | // no cookies, no keep-alive, the policy's headers, and the credential |
| 182 | // only on its own origin. A 3xx comes back unread. |
| 183 | func (c *Client) send(ctx context.Context, method string, u url.URL, body []byte, given http.Header, host string, addrs []netip.Addr) (*Response, error) { |
| 184 | target := netip.AddrPortFrom(addrs[0].Unmap(), 443).String() |
| 185 | var roots *x509.CertPool |
| 186 | if c.test { |
| 187 | target, roots = c.cfg.TestDial(host) |
| 188 | } |
| 189 | dialer := &net.Dialer{Timeout: c.cfg.Timeouts.Connect, Control: func(_, address string, _ syscall.RawConn) error { |
| 190 | if c.test { |
| 191 | return nil |
| 192 | } |
| 193 | ap, err := netip.ParseAddrPort(address) |
| 194 | if err != nil || !websource.PublicAddress(ap.Addr()) { |
| 195 | return Refusal{Rule: RulePrivate} |
| 196 | } |
| 197 | if c.cfg.Inventory.Inside(ap.Addr().Unmap()) { |
| 198 | return Refusal{Rule: RuleInventory} |
| 199 | } |
| 200 | return nil |
| 201 | }} |
| 202 | tr := &http.Transport{ |
| 203 | Proxy: nil, |
| 204 | DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| 205 | return dialer.DialContext(ctx, "tcp", target) |
| 206 | }, |
| 207 | TLSClientConfig: &tls.Config{ServerName: host, RootCAs: roots, MinVersion: tls.VersionTLS12}, |
| 208 | TLSHandshakeTimeout: c.cfg.Timeouts.Connect, |
| 209 | ResponseHeaderTimeout: c.cfg.Timeouts.FirstByte, |
| 210 | MaxResponseHeaderBytes: MaxHeaderBytes, |
| 211 | DisableKeepAlives: true, |
| 212 | DisableCompression: true, |
| 213 | } |
| 214 | defer tr.CloseIdleConnections() |
| 215 | client := &http.Client{Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| 216 | rctx, cancel := context.WithTimeout(ctx, c.cfg.Timeouts.Request) |
| 217 | defer cancel() |
| 218 | out := u |
| 219 | if cr := c.cfg.Credential; cr != nil && cr.Param != "" && origin(u) == cr.Origin { |
| 220 | q := out.Query() |
| 221 | q.Set(cr.Param, cr.Value) |
| 222 | out.RawQuery = q.Encode() |
| 223 | } |
| 224 | var rd io.Reader |
| 225 | if body != nil { |
| 226 | rd = bytes.NewReader(body) |
| 227 | } |
| 228 | req, err := http.NewRequestWithContext(rctx, method, out.String(), rd) |
| 229 | if err != nil { |
| 230 | return nil, c.refuse(RuleURL, host) |
| 231 | } |
| 232 | for _, k := range allowedHeaders[c.cfg.Policy] { |
| 233 | if v := given.Get(k); v != "" { |
| 234 | req.Header.Set(k, v) |
| 235 | } |
| 236 | } |
| 237 | req.Header.Set("User-Agent", c.cfg.UserAgent) |
| 238 | if c.cfg.Policy != PolicyService || req.Header.Get("Accept") == "" { |
| 239 | req.Header.Set("Accept", "text/html,application/xhtml+xml,application/json,application/xml,text/plain;q=0.9,*/*;q=0.1") |
| 240 | } |
| 241 | req.Header.Set("Accept-Encoding", "gzip") |
| 242 | if cr := c.cfg.Credential; cr != nil && cr.Header != "" && origin(u) == cr.Origin { |
| 243 | req.Header.Set(cr.Header, cr.Value) |
| 244 | } |
| 245 | var wrote atomic.Bool |
| 246 | req = req.WithContext(httptrace.WithClientTrace(req.Context(), &httptrace.ClientTrace{WroteRequest: func(httptrace.WroteRequestInfo) { wrote.Store(true) }})) |
| 247 | res, err := client.Do(req) |
| 248 | if err != nil { |
| 249 | var r Refusal |
| 250 | rule := RuleUnavailable |
| 251 | switch { |
| 252 | case errors.As(err, &r): |
| 253 | rule = r.Rule |
| 254 | case rctx.Err() != nil || errors.Is(err, context.DeadlineExceeded): |
| 255 | rule = RuleTimeout |
| 256 | } |
| 257 | // Never err itself: a *url.Error prints the URL, and a search's |
| 258 | // key may ride in its query. |
| 259 | out := c.refuse(rule, host).(Refusal) |
| 260 | out.Sent = wrote.Load() |
| 261 | return nil, out |
| 262 | } |
| 263 | defer res.Body.Close() |
| 264 | resp := &Response{Status: res.StatusCode, Header: res.Header.Clone()} |
| 265 | if res.StatusCode >= 300 && res.StatusCode <= 399 { |
| 266 | return resp, nil |
| 267 | } |
| 268 | if res.ContentLength > c.cfg.Limit { |
| 269 | return nil, c.refuseSent(RuleTooLarge, host) |
| 270 | } |
| 271 | var rdr io.Reader = res.Body |
| 272 | if strings.EqualFold(res.Header.Get("Content-Encoding"), "gzip") { |
| 273 | gz, err := gzip.NewReader(res.Body) |
| 274 | if err != nil { |
| 275 | return nil, c.refuseSent(RuleUnavailable, host) |
| 276 | } |
| 277 | defer gz.Close() |
| 278 | rdr = gz |
| 279 | } |
| 280 | raw, err := io.ReadAll(io.LimitReader(rdr, c.cfg.Limit+1)) |
| 281 | if err != nil { |
| 282 | if rctx.Err() != nil { |
| 283 | return nil, c.refuseSent(RuleTimeout, host) |
| 284 | } |
| 285 | return nil, c.refuseSent(RuleUnavailable, host) |
| 286 | } |
| 287 | if int64(len(raw)) > c.cfg.Limit { |
| 288 | return nil, c.refuseSent(RuleTooLarge, host) |
| 289 | } |
| 290 | resp.Body, resp.Type = raw, sniff(raw, res.Header.Get("Content-Type")) |
| 291 | return resp, nil |
| 292 | } |
| 293 | |
| 294 | // refuseSent is refuse for a request already sent: its answer failed. |
| 295 | func (c *Client) refuseSent(rule, host string) error { |
| 296 | r := c.refuse(rule, host).(Refusal) |
| 297 | r.Sent = true |
| 298 | return r |
| 299 | } |
| 300 | |
| 301 | // origin is u's scheme and host. |
| 302 | func origin(u url.URL) string { return u.Scheme + "://" + strings.ToLower(u.Host) } |
| 303 | |
| 304 | // sniff is a body's type from its bytes (the header only breaks a tie |
| 305 | // between text kinds): html, text, json, xml, feed, or unsupported. |
| 306 | func sniff(body []byte, header string) string { |
| 307 | head := bytes.TrimSpace(body[:min(len(body), 512)]) |
| 308 | lower := bytes.ToLower(head) |
| 309 | switch { |
| 310 | case len(head) == 0: |
| 311 | return "text" |
| 312 | case bytes.HasPrefix(head, []byte("{")) || bytes.HasPrefix(head, []byte("[")): |
| 313 | return "json" |
| 314 | case bytes.Contains(lower, []byte("<rss")) || bytes.Contains(lower, []byte("<feed")): |
| 315 | return "feed" |
| 316 | case bytes.HasPrefix(lower, []byte("<?xml")): |
| 317 | if strings.Contains(header, "html") { |
| 318 | return "html" |
| 319 | } |
| 320 | return "xml" |
| 321 | } |
| 322 | switch kind := http.DetectContentType(body); { |
| 323 | case strings.HasPrefix(kind, "text/html"): |
| 324 | return "html" |
| 325 | case strings.HasPrefix(kind, "text/xml"): |
| 326 | return "xml" |
| 327 | case strings.HasPrefix(kind, "text/plain"): |
| 328 | if strings.Contains(header, "html") { |
| 329 | return "html" |
| 330 | } |
| 331 | return "text" |
| 332 | } |
| 333 | return "unsupported" |
| 334 | } |
| 335 | |