forked from sourcegraph/checkup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tlschecker.go
190 lines (169 loc) · 5.2 KB
/
tlschecker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package checkup
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net"
"time"
)
// TLSChecker implements a Checker for TLS endpoints.
//
// TODO: Implement more checks on the certificate and TLS configuration.
// - Cipher suites
// - Protocol versions
// - OCSP stapling
// - Multiple SNIs
// - Other things that you might see at SSL Labs or other TLS health checks
type TLSChecker struct {
// Name is the name of the endpoint.
Name string `json:"endpoint_name"`
// URL is the host:port of the remote endpoint to check.
URL string `json:"endpoint_url"`
// Timeout is the maximum time to wait for a
// TLS connection to be established.
Timeout time.Duration `json:"timeout,omitempty"`
// ThresholdRTT is the maximum round trip time to
// allow for a healthy endpoint. If non-zero and a
// request takes longer than ThresholdRTT, the
// endpoint will be considered unhealthy. Note that
// this duration includes any in-between network
// latency.
ThresholdRTT time.Duration `json:"threshold_rtt,omitempty"`
// Attempts is how many requests the client will
// make to the endpoint in a single check.
Attempts int `json:"attempts,omitempty"`
// CertExpiryThreshold is how close to expiration
// the TLS certificate must be before declaring
// a degraded status. Default is 14 days.
CertExpiryThreshold time.Duration `json:"cert_expiry_threshold,omitempty"`
// TrustedRoots is a list of PEM files to load as
// trusted root CAs when connecting to TLS remotes.
TrustedRoots []string `json:"trusted_roots,omitempty"`
// tlsConfig is the config to use when making a TLS
// connection. Values in this struct take precedence
// over values described from the JSON (exported)
// fields, where necessary.
tlsConfig *tls.Config
}
// Check performs checks using c according to its configuration.
// An error is only returned if there is a configuration error.
func (c TLSChecker) Check() (Result, error) {
if c.Attempts < 1 {
c.Attempts = 1
}
if c.CertExpiryThreshold == 0 {
c.CertExpiryThreshold = 24 * time.Hour * 14
}
if len(c.TrustedRoots) > 0 {
if c.tlsConfig == nil {
c.tlsConfig = new(tls.Config)
}
if c.tlsConfig.RootCAs == nil {
c.tlsConfig.RootCAs = x509.NewCertPool()
}
for _, fname := range c.TrustedRoots {
pemData, err := ioutil.ReadFile(fname)
if err != nil {
return Result{}, fmt.Errorf("error loading file: %v", err)
}
if !c.tlsConfig.RootCAs.AppendCertsFromPEM(pemData) {
return Result{}, fmt.Errorf("error appending certs from PEM %s: %v", fname, err)
}
}
}
attempts, conns := c.doChecks()
result := Result{
Title: c.Name,
Endpoint: c.URL,
Timestamp: Timestamp(),
Times: attempts,
ThresholdRTT: c.ThresholdRTT,
}
return c.conclude(conns, result), nil
}
// doChecks executes the checks and returns each attempt
// along with its associated TLS connection. These connections
// will be open, so it's vital that conclude() is called,
// passing in the connections, so that they will be inspected
// and closed properly.
func (c TLSChecker) doChecks() (Attempts, []*tls.Conn) {
checks := make(Attempts, c.Attempts)
conns := make([]*tls.Conn, c.Attempts)
for i := 0; i < c.Attempts; i++ {
dialer := &net.Dialer{Timeout: c.Timeout}
start := time.Now()
conn, err := tls.DialWithDialer(dialer, "tcp", c.URL, c.tlsConfig)
checks[i].RTT = time.Since(start)
conns[i] = conn
if err != nil {
checks[i].Error = err.Error()
continue
}
}
return checks, conns
}
// conclude takes the data in result from the attempts and
// computes remaining values needed to fill out the result.
// It detects less-than-ideal (degraded) connections and
// marks them as such. It closes the connections that are
// passed in.
func (c TLSChecker) conclude(conns []*tls.Conn, result Result) Result {
// close all connections when done
defer func() {
for _, conn := range conns {
if conn != nil {
conn.Close()
}
}
}()
// check errors (down)
for i := range result.Times {
if result.Times[i].Error != "" {
result.Down = true
return result
}
}
// check if certificates expired (down)
for i, conn := range conns {
if conn == nil {
continue
}
serverCerts := conn.ConnectionState().PeerCertificates
if len(serverCerts) == 0 {
result.Times[i].Error = "no certificates presented"
result.Down = true
return result
}
leaf := serverCerts[0]
if leaf.NotAfter.Before(time.Now()) {
result.Times[i].Error = fmt.Sprintf("certificate expired %s ago", time.Since(leaf.NotAfter))
result.Down = true
return result
}
}
// check certificates expiring soon (degraded)
for _, conn := range conns {
if conn == nil {
continue
}
serverCerts := conn.ConnectionState().PeerCertificates
leaf := serverCerts[0]
if until := time.Until(leaf.NotAfter); until < c.CertExpiryThreshold {
result.Notice = fmt.Sprintf("certificate expiring soon (%s)", until)
result.Degraded = true
return result
}
}
// check round trip time (degraded)
if c.ThresholdRTT > 0 {
stats := result.ComputeStats()
if stats.Median > c.ThresholdRTT {
result.Notice = fmt.Sprintf("median round trip time exceeded threshold (%s)", c.ThresholdRTT)
result.Degraded = true
return result
}
}
result.Healthy = true
return result
}