forked from timewasted/go-check-certs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check-certs.go
282 lines (254 loc) · 7.53 KB
/
check-certs.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
// Copyright 2013 Ryan Rogers. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
const defaultConcurrency = 8
var (
columnNames = "Hostname -- Common Name -- S/N -- Time to expire -- Expiration date"
errExpiringShortly = "%s: ** '%s' (S/N %X) expires in %d hours ** at %s!"
errExpiringSoon = "%s: '%s' (S/N %X) expires in roughly %d days on %s"
errSunsetAlg = "%s: '%s' (S/N %X) expires after the sunset date for its signature algorithm '%s' on %s."
)
type sigAlgSunset struct {
name string // Human readable name of signature algorithm
sunsetsAt time.Time // Time the algorithm will be sunset
}
// sunsetSigAlgs is an algorithm to string mapping for signature algorithms
// which have been or are being deprecated. See the following links to learn
// more about SHA1's inclusion on this list.
//
// - https://technet.microsoft.com/en-us/library/security/2880823.aspx
// - http://googleonlinesecurity.blogspot.com/2014/09/gradually-sunsetting-sha-1.html
var sunsetSigAlgs = map[x509.SignatureAlgorithm]sigAlgSunset{
x509.MD2WithRSA: sigAlgSunset{
name: "MD2 with RSA",
sunsetsAt: time.Now(),
},
x509.MD5WithRSA: sigAlgSunset{
name: "MD5 with RSA",
sunsetsAt: time.Now(),
},
x509.SHA1WithRSA: sigAlgSunset{
name: "SHA1 with RSA",
sunsetsAt: time.Date(2017, 1, 1, 0, 0, 0, 0, time.UTC),
},
x509.DSAWithSHA1: sigAlgSunset{
name: "DSA with SHA1",
sunsetsAt: time.Date(2017, 1, 1, 0, 0, 0, 0, time.UTC),
},
x509.ECDSAWithSHA1: sigAlgSunset{
name: "ECDSA with SHA1",
sunsetsAt: time.Date(2017, 1, 1, 0, 0, 0, 0, time.UTC),
},
}
var (
appDir, appDirErr = filepath.Abs(filepath.Dir(os.Args[0]))
hostsFile = flag.String("hosts", appDir+"/hosts.txt", "The path to the file containing a list of hosts to check.")
resultsDir = flag.String("results", appDir+"/results", "Absolute path of where you want to store the results")
warnYears = flag.Int("years", 0, "Warn if the certificate will expire within this many years.")
warnMonths = flag.Int("months", 0, "Warn if the certificate will expire within this many months.")
warnDays = flag.Int("days", 0, "Warn if the certificate will expire within this many days.")
checkSigAlg = flag.Bool("check-sig-alg", true, "Verify that non-root certificates are using a good signature algorithm.")
concurrency = flag.Int("concurrency", defaultConcurrency, "Maximum number of hosts to check at once.")
outPutToFile = flag.Bool("output", false, "Output results to csv") // create output file results.csv for results
serveFile = flag.Bool("serve", false, "Serve output csv on port 8080") // create outputfile and serve results.csv on port 8080
)
type certErrors struct {
commonName string
errs []error
}
type hostResult struct {
host string
err error
certs []certErrors
}
func main() {
flag.Parse()
if *warnYears < 0 {
*warnYears = 0
}
if *warnMonths < 0 {
*warnMonths = 0
}
if *warnDays < 0 {
*warnDays = 0
}
if *warnYears == 0 && *warnMonths == 0 && *warnDays == 0 {
*warnDays = 30
}
if *concurrency < 0 {
*concurrency = defaultConcurrency
}
if *outPutToFile {
changeToCSV()
// create output file for results, the writing occurs in processHosts
createOutPutFile()
}
if *serveFile {
*outPutToFile = true // set this so that writing occurs in processHosts
changeToCSV()
createOutPutFile()
processHosts()
serveHTTP()
}
//check hosts
processHosts()
}
func processHosts() {
done := make(chan struct{})
defer close(done)
hosts := queueHosts(done)
results := make(chan hostResult)
var wg sync.WaitGroup
wg.Add(*concurrency)
for i := 0; i < *concurrency; i++ {
go func() {
processQueue(done, hosts, results)
wg.Done()
}()
}
go func() {
wg.Wait()
close(results)
}()
for r := range results {
if r.err != nil {
fmt.Printf("%s: %v", r.host, r.err)
if *outPutToFile {
outputProblemCert(r.host, r.err.Error())
}
continue
}
fmt.Println(columnNames)
for _, cert := range r.certs {
for _, err := range cert.errs {
fmt.Println(err)
// write output file
if *outPutToFile {
outputCert(err)
}
}
}
}
}
func queueHosts(done <-chan struct{}) <-chan string {
hosts := make(chan string)
go func() {
defer close(hosts)
fileContents, err := ioutil.ReadFile(*hostsFile)
if err != nil {
return
}
lines := strings.Split(string(fileContents), "\n")
for _, line := range lines {
host := strings.TrimSpace(line)
if len(host) == 0 || host[0] == '#' {
continue
}
select {
case hosts <- host:
case <-done:
return
}
}
}()
return hosts
}
func processQueue(done <-chan struct{}, hosts <-chan string, results chan<- hostResult) {
for host := range hosts {
select {
case results <- checkHost(host):
case <-done:
return
}
}
}
func checkHost(host string) hostResult {
if len(host) >= 2 && host[0:2] == "i " {
return checkUnverifiedHost(host[2:])
} else {
return checkVerifiedHost(host)
}
}
func checkVerifiedHost(host string) (result hostResult) {
result = hostResult{
host: host,
certs: []certErrors{},
}
conn, err := tls.Dial("tcp", host, nil)
if err != nil {
result.err = err
return
}
defer conn.Close()
checkedCerts := make(map[string]struct{})
for _, chain := range conn.ConnectionState().VerifiedChains {
for certNum, cert := range chain {
if _, checked := checkedCerts[string(cert.Signature)]; checked {
continue
}
checkedCerts[string(cert.Signature)] = struct{}{}
result.certs = append(result.certs, checkCert(host, certNum, chain))
}
}
return
}
func checkUnverifiedHost(host string) (result hostResult) {
result = hostResult{
host: host,
certs: []certErrors{},
}
conn, err := tls.Dial("tcp", host, &tls.Config{InsecureSkipVerify: true})
if err != nil {
result.err = err
return
}
defer conn.Close()
certs := conn.ConnectionState().PeerCertificates
for certNum := range certs {
result.certs = append(result.certs, checkCert(host, certNum, certs))
}
return
}
func checkCert(host string, certNum int, certs []*x509.Certificate) certErrors {
cert := certs[certNum]
cErrs := []error{}
timeNow := time.Now()
// Check the expiration.
if timeNow.AddDate(*warnYears, *warnMonths, *warnDays).After(cert.NotAfter) {
expiresIn := int64(cert.NotAfter.Sub(timeNow).Hours())
if expiresIn <= 48 {
cErrs = append(cErrs, fmt.Errorf(errExpiringShortly, host, cert.Subject.CommonName, cert.SerialNumber, expiresIn, cert.NotAfter))
} else {
cErrs = append(cErrs, fmt.Errorf(errExpiringSoon, host, cert.Subject.CommonName, cert.SerialNumber, expiresIn/24, cert.NotAfter))
}
}
// Check the signature algorithm, ignoring the root certificate.
if alg, exists := sunsetSigAlgs[cert.SignatureAlgorithm]; *checkSigAlg && exists && certNum != len(certs)-1 {
if cert.NotAfter.Equal(alg.sunsetsAt) || cert.NotAfter.After(alg.sunsetsAt) {
cErrs = append(cErrs, fmt.Errorf(errSunsetAlg, host, cert.Subject.CommonName, cert.SerialNumber, alg.name))
}
}
return certErrors{
commonName: cert.Subject.CommonName,
errs: cErrs,
}
}
func changeToCSV() {
columnNames = "hostname, Common Name, S/N, time to expire, expiration date"
errExpiringShortly = "%s, ** '%s', (S/N %X), %d hours **, %s"
errExpiringSoon = "%s, '%s', (S/N %X), %d days, %s"
errSunsetAlg = "%s, '%s', (S/N %X), expires after the sunset date for its signature algorithm '%s'., %s"
}