/
run.go
367 lines (310 loc) · 8.72 KB
/
run.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package check
import (
"bytes"
"context"
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"time"
"golang.org/x/crypto/ocsp"
)
// July 2012 is the CAB Forum deadline for when CAs must stop issuing certificates valid for more than 5 years.
var jul2012 = time.Date(2012, time.July, 1, 0, 0, 0, 0, time.UTC).Add(-1 * time.Nanosecond)
// April 2015 is the CAB Forum deadline for when CAs must stop issuing certificates valid for more than 39 months.
var apr2015 = time.Date(2015, time.April, 1, 0, 0, 0, 0, time.UTC).Add(-1 * time.Nanosecond)
// September 2020 is the Apple deadline for when CAs must stop issuing certificates valid for more than 13 months.
var sep2020 = time.Date(2020, time.September, 1, 0, 0, 0, 0, time.UTC).Add(-1 * time.Nanosecond)
// RunCheck executes checks and collects facts for provided host and port.
func RunCheck(collector Collector, host, port string, opts ...Option) error {
options := Options{
ctx: context.Background(),
collectTiming: false,
}
for _, opt := range opts {
opt(&options)
}
if options.collectTiming {
start := time.Now()
defer func() {
collector <- CollectedInfo{
Name: "time check",
Duration: time.Since(start),
}
}()
}
now := time.Now()
var err error
var ips []string
if options.nameserver == "" {
ips, err = defaultLookup(collector, host, options.collectTiming)
} else {
ips, err = externalLookup(collector, options.nameserver, host, options.collectTiming)
}
if err != nil {
return err
}
if len(ips) == 0 {
return fmt.Errorf("host must resolve to one or more IP address")
}
for _, ip := range ips {
collector <- CollectedInfo{
Name: "resolved",
Value: ip,
}
}
ipCerts, err := collectedResolvedCertificates(options.ctx, collector, host, port, ips, options.collectTiming)
if err != nil {
return err
}
if err = verifyCertificates(collector, ipCerts); err != nil {
return err
}
certificates := ipCerts[ips[0]]
if err := certificates[0].VerifyHostname(host); err != nil {
return err
}
if err := verifyServerCertificate(host, certificates); err != nil {
return err
}
if certificates[0].NotAfter.Before(now) {
return fmt.Errorf("certificate expired")
}
if len(certificates) == 1 {
collector <- CollectedInfo{
Name: "warning",
Value: "certificate chain has one certificate",
}
}
if certificates[0].IsCA {
collector <- CollectedInfo{
Name: "warning",
Value: "certificate authority",
}
}
if len(certificates) > 1 {
err = isCertificateRevokedByOCSP(options.ctx, collector, certificates[0], certificates[1], options.collectTiming)
if err != nil {
collector <- CollectedInfo{
Name: "warning",
Value: err.Error(),
}
}
}
if _, _, ok := isValidExpiry(certificates[0]); !ok {
return err
}
if certificates[0].NotAfter.Before(now.AddDate(0, 0, 1)) {
return fmt.Errorf("certificate expires tomorrow: %s", certificates[0].NotAfter.String())
}
if certificates[0].NotAfter.Before(now.AddDate(0, 0, 7)) {
collector <- CollectedInfo{
Name: "warning",
Value: fmt.Sprintf("certificate expires within 7 days: %s", certificates[0].NotAfter.String()),
}
} else if certificates[0].NotAfter.Before(now.AddDate(0, 0, 30)) {
collector <- CollectedInfo{
Name: "warning",
Value: fmt.Sprintf("certificate expires within 30 days: %s", certificates[0].NotAfter.String()),
}
}
if len(certificates[0].Subject.Names) == 0 {
collector <- CollectedInfo{
Name: "warning",
Value: "no subject",
}
} else {
if certificates[0].Subject.CommonName == "" {
collector <- CollectedInfo{
Name: "warning",
Value: "no common name",
}
}
}
for _, cert := range certificates {
switch cert.SignatureAlgorithm {
case x509.MD2WithRSA, x509.MD5WithRSA, x509.SHA1WithRSA, x509.DSAWithSHA1, x509.ECDSAWithSHA1:
return fmt.Errorf("bad signature algorithm: %s", cert.SignatureAlgorithm)
}
// fmt.Println("EXTRA", i, "sigalg", cert.SignatureAlgorithm)
// fmt.Println("EXTRA", i, "pubkeyalg", cert.PublicKeyAlgorithm)
}
uniqueNames := make(map[string]bool)
for _, certificate := range certificates {
for _, name := range certificate.DNSNames {
if name == host {
continue
}
uniqueNames[name] = true
}
}
for name := range uniqueNames {
collector <- CollectedInfo{
Name: "name",
Value: name,
}
}
return nil
}
func collectedResolvedCertificates(ctx context.Context, collector Collector, host, port string, ips []string, timing bool) (map[string][]*x509.Certificate, error) {
results := make(map[string][]*x509.Certificate)
dialer := tlsCheckerDialer{
Timeout: 15 * time.Second,
}
for _, ip := range ips {
var connStart time.Time
if timing {
connStart = time.Now()
}
conn, err := dialer.Dial(ctx, host, port, ip)
if err != nil {
return nil, err
}
state := conn.ConnectionState()
certificates := state.PeerCertificates
if err = conn.Close(); err != nil {
return nil, err
}
results[ip] = certificates
if timing {
collector <- CollectedInfo{
Name: "time collect",
Value: ip,
Duration: time.Since(connStart),
}
}
}
return results, nil
}
func verifyCertificates(collector Collector, certs map[string][]*x509.Certificate) error {
var firstFingerprints []string
for _, certificates := range certs {
if len(certs) == 0 {
return fmt.Errorf("no certificates found")
}
var fingerprints []string
for _, certificate := range certificates {
fingerprintHash := sha256.Sum256(certificate.Raw)
fingerprints = append(fingerprints, hex.EncodeToString(fingerprintHash[:]))
}
if firstFingerprints == nil {
firstFingerprints = fingerprints
continue
}
if firstFingerprints[0] != fingerprints[0] {
return fmt.Errorf("different certificates found")
}
}
if len(firstFingerprints) > 0 {
collector <- CollectedInfo{
Name: "fingerprint",
Value: firstFingerprints[0],
}
}
return nil
}
func isCertificateRevokedByOCSP(ctx context.Context, collector Collector, clientCert, issuerCert *x509.Certificate, timing bool) error {
if timing {
start := time.Now()
defer func() {
collector <- CollectedInfo{
Name: "time ocsp",
Duration: time.Since(start),
}
}()
}
if len(clientCert.OCSPServer) == 0 {
return nil
}
ocspURL, err := url.Parse(clientCert.OCSPServer[0])
if err != nil {
return err
}
opts := &ocsp.RequestOptions{Hash: crypto.SHA1}
buffer, err := ocsp.CreateRequest(clientCert, issuerCert, opts)
if err != nil {
return err
}
request, err := http.NewRequestWithContext(ctx, http.MethodPost, ocspURL.String(), bytes.NewBuffer(buffer))
if err != nil {
return err
}
request.Header.Add("Content-Type", "application/ocsp-request")
request.Header.Add("Accept", "application/ocsp-response")
request.Header.Add("host", ocspURL.Host)
request.Header.Add("User-Agent", "certdialer")
httpClient := &http.Client{
Timeout: 15 * time.Second,
}
httpResponse, err := httpClient.Do(request)
if err != nil {
return err
}
defer httpResponse.Body.Close()
output, err := ioutil.ReadAll(httpResponse.Body)
if err != nil {
return err
}
ocspResponse, err := ocsp.ParseResponse(output, issuerCert)
if err != nil {
return err
}
if ocspResponse.Status == ocsp.Revoked {
return fmt.Errorf("certificate is revoked")
}
return nil
}
// isValidExpiry determines if a certificate is valid for an acceptable
// length of time per the CA/Browser Forum baseline requirements.
// See https://cabforum.org/wp-content/uploads/CAB-Forum-BR-1.3.0.pdf
func isValidExpiry(c *x509.Certificate) (int, int, bool) {
mm := maxMonths(c.NotBefore)
mv := monthsValid(c.NotBefore, c.NotAfter)
return mm, mv, monthsValid(c.NotBefore, c.NotAfter) <= maxMonths(c.NotBefore)
}
func maxMonths(issued time.Time) int {
if issued.After(sep2020) {
return 13
} else if issued.After(apr2015) {
return 39
} else if issued.After(jul2012) {
return 60
}
return 120
}
func monthsValid(issued, expiry time.Time) int {
years := expiry.Year() - issued.Year()
months := years*12 + int(expiry.Month()) - int(issued.Month())
// Round up if valid for less than a full month
if expiry.Day() > issued.Day() {
months++
}
return months
}
func verifyServerCertificate(host string, certificates []*x509.Certificate) error {
opts := x509.VerifyOptions{
DNSName: host,
Intermediates: x509.NewCertPool(),
}
for _, cert := range certificates[1:] {
opts.Intermediates.AddCert(cert)
}
_, err := certificates[0].Verify(opts)
if err != nil {
return err
}
switch certificates[0].PublicKey.(type) {
case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
break
default:
return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certificates[0].PublicKey)
}
return err
}