package check import ( "bytes" "context" "crypto/tls" "crypto/x509" "errors" "io" "math" "net/http" "net/http/httptrace" "strings" "sync" "time" "unicode/utf8" ) // Evidence is what a check saw of an HTTP exchange: every request and // response of the redirect chain, where the time went, the server's // certificate and the start of the final body. Secrets are redacted before // it leaves the checker. type Evidence struct { Steps []HTTPStep `json:"steps"` RemoteAddr string `json:"remote_addr,omitempty"` Timing Timing `json:"timing"` TLS *TLSInfo `json:"tls,omitempty"` // FailedAt names the stage a failed exchange stopped in: dns, // connect, tls, response or body. FailedAt string `json:"failed_at,omitempty"` ContentType string `json:"content_type,omitempty"` Body string `json:"body,omitempty"` BodyTruncated bool `json:"body_truncated,omitempty"` // BodyBinary is set for bodies that are not text; they are not kept. BodyBinary bool `json:"body_binary,omitempty"` } // HTTPStep is one request and its response. type HTTPStep struct { Method string `json:"method"` URL string `json:"url"` Status int `json:"status,omitempty"` Proto string `json:"proto,omitempty"` RequestHeaders map[string][]string `json:"request_headers,omitempty"` ResponseHeaders map[string][]string `json:"response_headers,omitempty"` } // Timing splits the duration of the last connection, in milliseconds. // Phases that did not happen, such as DNS for an IP target, are zero. type Timing struct { DNS float64 `json:"dns_ms"` Connect float64 `json:"connect_ms"` TLS float64 `json:"tls_ms"` Wait float64 `json:"wait_ms"` Download float64 `json:"download_ms"` Total float64 `json:"total_ms"` } // TLSInfo describes the negotiated connection and the leaf certificate. type TLSInfo struct { Version string `json:"version"` Cipher string `json:"cipher,omitempty"` Subject string `json:"subject"` Issuer string `json:"issuer"` DNSNames []string `json:"dns_names,omitempty"` NotBefore time.Time `json:"not_before"` NotAfter time.Time `json:"not_after"` } // maxEvidenceBody bounds the captured body. const maxEvidenceBody = 32 << 10 // redacted replaces secret header values. const redacted = "" type recorderKey struct{} // recorder collects evidence while a check runs. type recorder struct { mu sync.Mutex ev Evidence start time.Time stage string marks map[string]time.Time firstByte time.Time done time.Time body bytes.Buffer // secretHeaders are request headers configured by the customer; their // values often are credentials. secretHeaders map[string]bool } func newRecorder() *recorder { return &recorder{start: time.Now(), marks: map[string]time.Time{}, secretHeaders: map[string]bool{}} } func recorderFrom(ctx context.Context) *recorder { r, _ := ctx.Value(recorderKey{}).(*recorder) return r } func ms(d time.Duration) float64 { return math.Round(float64(d)/float64(time.Millisecond)*10) / 10 } func (r *recorder) mark(stage string) { r.mu.Lock() defer r.mu.Unlock() r.stage = stage r.marks[stage] = time.Now() } func (r *recorder) since(stage string) float64 { if t, ok := r.marks[stage]; ok { return ms(time.Since(t)) } return 0 } func (r *recorder) trace() *httptrace.ClientTrace { return &httptrace.ClientTrace{ DNSStart: func(httptrace.DNSStartInfo) { r.mark("dns") }, DNSDone: func(httptrace.DNSDoneInfo) { r.mu.Lock() r.ev.Timing.DNS = r.since("dns") r.mu.Unlock() }, ConnectStart: func(string, string) { r.mark("connect") }, ConnectDone: func(_, addr string, err error) { r.mu.Lock() r.ev.Timing.Connect = r.since("connect") if err == nil { r.ev.RemoteAddr = addr } r.mu.Unlock() }, TLSHandshakeStart: func() { r.mark("tls") }, TLSHandshakeDone: func(cs tls.ConnectionState, _ error) { r.mu.Lock() defer r.mu.Unlock() r.ev.Timing.TLS = r.since("tls") if r.ev.TLS != nil && cs.Version != 0 { r.ev.TLS.Version = tls.VersionName(cs.Version) r.ev.TLS.Cipher = tls.CipherSuiteName(cs.CipherSuite) } }, WroteRequest: func(httptrace.WroteRequestInfo) { r.mark("response") }, GotFirstResponseByte: func() { r.mu.Lock() r.ev.Timing.Wait = r.since("response") r.firstByte = time.Now() r.stage = "body" r.mu.Unlock() }, } } func tlsInfo(cs tls.ConnectionState, c *x509.Certificate) *TLSInfo { info := &TLSInfo{ Subject: c.Subject.String(), Issuer: c.Issuer.String(), DNSNames: c.DNSNames, NotBefore: c.NotBefore, NotAfter: c.NotAfter, } if cs.Version != 0 { info.Version = tls.VersionName(cs.Version) } if cs.CipherSuite != 0 { info.Cipher = tls.CipherSuiteName(cs.CipherSuite) } return info } // recordingTLS verifies certificates like crypto/tls does, but records the // server's certificate first: crypto/tls drops it when verification fails, // which is when it matters most. func recordingTLS(r *recorder, verify bool) *tls.Config { cfg := &tls.Config{InsecureSkipVerify: true} //nolint:gosec // verified in VerifyConnection unless the customer opted out cfg.VerifyConnection = func(cs tls.ConnectionState) error { if len(cs.PeerCertificates) == 0 { return errors.New("tls: server sent no certificate") } r.mu.Lock() r.ev.TLS = tlsInfo(cs, cs.PeerCertificates[0]) r.mu.Unlock() if !verify { return nil } opts := x509.VerifyOptions{DNSName: cs.ServerName, Roots: cfg.RootCAs, Intermediates: x509.NewCertPool()} for _, c := range cs.PeerCertificates[1:] { opts.Intermediates.AddCert(c) } if _, err := cs.PeerCertificates[0].Verify(opts); err != nil { return &tls.CertificateVerificationError{UnverifiedCertificates: cs.PeerCertificates, Err: err} } return nil } return cfg } // step records one exchange of the chain. func (r *recorder) step(req *http.Request, resp *http.Response) { s := HTTPStep{Method: req.Method, URL: req.URL.Redacted(), RequestHeaders: r.requestHeaders(req.Header)} if resp != nil { s.Status, s.Proto, s.ResponseHeaders = resp.StatusCode, resp.Proto, responseHeaders(resp.Header) } r.mu.Lock() r.ev.Steps = append(r.ev.Steps, s) r.mu.Unlock() } func (r *recorder) requestHeaders(h http.Header) map[string][]string { out := make(map[string][]string, len(h)) for k, vs := range h { if r.secretHeaders[http.CanonicalHeaderKey(k)] || sensitiveHeader(k) { out[k] = []string{redacted} continue } out[k] = vs } return out } func sensitiveHeader(k string) bool { switch http.CanonicalHeaderKey(k) { case "Authorization", "Proxy-Authorization", "Cookie": return true } return false } // responseHeaders keeps cookie names but not their values. func responseHeaders(h http.Header) map[string][]string { out := make(map[string][]string, len(h)) for k, vs := range h { switch { case http.CanonicalHeaderKey(k) == "Set-Cookie": names := make([]string, len(vs)) for i, v := range vs { name, _, _ := strings.Cut(v, "=") names[i] = name + "=" + redacted } out[k] = names case sensitiveHeader(k): out[k] = []string{redacted} default: out[k] = vs } } return out } // captureBody keeps the start of a response body. On Close it reads up to // the capture limit if the check stopped reading earlier. type captureBody struct { io.ReadCloser r *recorder } // Read implements io.Reader. func (b captureBody) Read(p []byte) (int, error) { n, err := b.ReadCloser.Read(p) b.r.mu.Lock() if room := maxEvidenceBody - b.r.body.Len(); room > 0 { b.r.body.Write(p[:min(n, room)]) } if n > 0 && b.r.body.Len() >= maxEvidenceBody { b.r.ev.BodyTruncated = true } b.r.mu.Unlock() return n, err } // Close implements io.Closer. func (b captureBody) Close() error { b.r.mu.Lock() room := maxEvidenceBody - b.r.body.Len() b.r.mu.Unlock() if room > 0 { _, _ = io.Copy(io.Discard, io.LimitReader(b, int64(room)+1)) } b.r.mu.Lock() b.r.done = time.Now() b.r.mu.Unlock() return b.ReadCloser.Close() } // evidence finishes the recording for an outcome. func (r *recorder) evidence(o Outcome) *Evidence { r.mu.Lock() defer r.mu.Unlock() ev := r.ev ev.Timing.Total = ms(time.Since(r.start)) if !r.firstByte.IsZero() && !r.done.IsZero() { ev.Timing.Download = ms(r.done.Sub(r.firstByte)) } if !o.OK && o.StatusCode == 0 { ev.FailedAt = r.stage } body := r.body.Bytes() switch { case len(body) == 0: case !utf8.Valid(body) && !utf8.Valid(trimPartialRune(body)), bytes.IndexByte(body, 0) >= 0: ev.BodyBinary = true default: ev.Body = string(trimPartialRune(body)) } if len(ev.Steps) == 0 && ev.TLS == nil && ev.RemoteAddr == "" { return nil } return &ev } // trimPartialRune drops a multi-byte character cut off by the capture limit. func trimPartialRune(b []byte) []byte { for i := 0; i < utf8.UTFMax && len(b) > 0; i++ { if utf8.Valid(b) { return b } b = b[:len(b)-1] } return b }