forked from google/certificate-transparency-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
certcheck.go
251 lines (236 loc) · 8.09 KB
/
certcheck.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
// Copyright 2016 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// certcheck is a utility to show and check the contents of certificates.
package main
import (
"bytes"
"crypto/tls"
"flag"
"fmt"
"net/url"
"os"
"strings"
"github.com/golang/glog"
"github.com/ctylim/certificate-transparency-go-p192/x509"
"github.com/ctylim/certificate-transparency-go-p192/x509util"
)
var (
root = flag.String("root", "", "Root CA certificate file")
intermediate = flag.String("intermediate", "", "Intermediate CA certificate file")
useSystemRoots = flag.Bool("system_roots", false, "Use system roots")
verbose = flag.Bool("verbose", false, "Verbose output")
strict = flag.Bool("strict", true, "Set non-zero exit code for non-fatal errors in parsing")
validate = flag.Bool("validate", false, "Validate certificate signatures")
checkTime = flag.Bool("check_time", false, "Check current validity of certificate")
checkName = flag.Bool("check_name", true, "Check certificate name validity")
checkEKU = flag.Bool("check_eku", true, "Check EKU nesting validity")
checkPathLen = flag.Bool("check_path_len", true, "Check path len constraint validity")
checkNameConstraint = flag.Bool("check_name_constraint", true, "Check name constraints")
checkUnknownCriticalExts = flag.Bool("check_unknown_critical_exts", true, "Check for unknown critical extensions")
checkRevoked = flag.Bool("check_revocation", false, "Check revocation status of certificate")
)
func addCerts(filename string, pool *x509.CertPool) {
if filename != "" {
dataList, err := x509util.ReadPossiblePEMFile(filename, "CERTIFICATE")
if err != nil {
glog.Exitf("Failed to read certificate file: %v", err)
}
for _, data := range dataList {
certs, err := x509.ParseCertificates(data)
if err != nil {
glog.Exitf("Failed to parse certificate from %s: %v", filename, err)
}
for _, cert := range certs {
pool.AddCert(cert)
}
}
}
}
func main() {
flag.Parse()
failed := false
for _, target := range flag.Args() {
var err error
var chain []*x509.Certificate
if strings.HasPrefix(target, "https://") {
chain, err = chainFromSite(target)
} else {
chain, err = chainFromFile(target)
}
if err != nil {
glog.Errorf("%v", err)
}
if x509.IsFatal(err) {
failed = true
continue
} else if err != nil && *strict {
failed = true
}
for _, cert := range chain {
if *verbose {
fmt.Print(x509util.CertificateToString(cert))
}
if *checkRevoked {
if err := checkRevocation(cert, *verbose); err != nil {
glog.Errorf("%s: certificate is revoked: %v", target, err)
failed = true
}
}
}
if *validate && len(chain) > 0 {
opts := x509.VerifyOptions{
DisableTimeChecks: !*checkTime,
DisableCriticalExtensionChecks: !*checkUnknownCriticalExts,
DisableNameChecks: !*checkName,
DisableEKUChecks: !*checkEKU,
DisablePathLenChecks: !*checkPathLen,
DisableNameConstraintChecks: !*checkNameConstraint,
}
if err := validateChain(chain, opts, *root, *intermediate, *useSystemRoots); err != nil {
glog.Errorf("%s: verification error: %v", target, err)
failed = true
}
}
}
if failed {
os.Exit(1)
}
}
// chainFromSite retrieves the certificate chain from an https: URL.
// Note that both a chain and an error can be returned (in which case
// the error will be of type x509.NonFatalErrors).
func chainFromSite(target string) ([]*x509.Certificate, error) {
u, err := url.Parse(target)
if err != nil {
return nil, fmt.Errorf("%s: failed to parse URL: %v", target, err)
}
if u.Scheme != "https" {
return nil, fmt.Errorf("%s: non-https URL provided", target)
}
host := u.Host
if !strings.Contains(host, ":") {
host += ":443"
}
conn, err := tls.Dial("tcp", host, &tls.Config{InsecureSkipVerify: true})
if err != nil {
return nil, fmt.Errorf("%s: failed to dial %q: %v", target, host, err)
}
defer conn.Close()
// Convert base crypto/x509.Certificates to our forked x509.Certificate type.
goChain := conn.ConnectionState().PeerCertificates
var nfe *x509.NonFatalErrors
chain := make([]*x509.Certificate, len(goChain))
for i, goCert := range goChain {
cert, err := x509.ParseCertificate(goCert.Raw)
if x509.IsFatal(err) {
return nil, fmt.Errorf("%s: failed to convert Go Certificate [%d]: %v", target, i, err)
} else if errs, ok := err.(x509.NonFatalErrors); ok {
nfe = nfe.Append(&errs)
} else if err != nil {
return nil, fmt.Errorf("%s: failed to convert Go Certificate [%d]: %v", target, i, err)
}
chain[i] = cert
}
if nfe.HasError() {
return chain, *nfe
}
return chain, nil
}
// chainFromSite retrieves a certificate chain from a PEM file.
// Note that both a chain and an error can be returned (in which case
// the error will be of type x509.NonFatalErrors).
func chainFromFile(filename string) ([]*x509.Certificate, error) {
dataList, err := x509util.ReadPossiblePEMFile(filename, "CERTIFICATE")
if err != nil {
return nil, fmt.Errorf("%s: failed to read data: %v", filename, err)
}
var nfe *x509.NonFatalErrors
var chain []*x509.Certificate
for _, data := range dataList {
certs, err := x509.ParseCertificates(data)
if x509.IsFatal(err) {
return nil, fmt.Errorf("%s: failed to parse: %v", filename, err)
} else if errs, ok := err.(x509.NonFatalErrors); ok {
nfe = nfe.Append(&errs)
} else if err != nil {
return nil, fmt.Errorf("%s: failed to parse: %v", filename, err)
}
chain = append(chain, certs...)
}
if nfe.HasError() {
return chain, *nfe
}
return chain, nil
}
func validateChain(chain []*x509.Certificate, opts x509.VerifyOptions, rootsFile, intermediatesFile string, useSystemRoots bool) error {
roots := x509.NewCertPool()
if useSystemRoots {
systemRoots, err := x509.SystemCertPool()
if err != nil {
glog.Errorf("Failed to get system roots: %v", err)
}
roots = systemRoots
}
opts.KeyUsages = []x509.ExtKeyUsage{x509.ExtKeyUsageAny}
opts.Roots = roots
opts.Intermediates = x509.NewCertPool()
addCerts(rootsFile, opts.Roots)
addCerts(intermediatesFile, opts.Intermediates)
if !useSystemRoots && len(rootsFile) == 0 {
// No root CA certs provided, so assume the chain is self-contained.
if len(chain) > 1 {
last := chain[len(chain)-1]
if bytes.Equal(last.RawSubject, last.RawIssuer) {
opts.Roots.AddCert(last)
}
}
}
if len(intermediatesFile) == 0 {
// No intermediate CA certs provided, so assume later entries in the chain are intermediates.
for i := 1; i < len(chain); i++ {
opts.Intermediates.AddCert(chain[i])
}
}
_, err := chain[0].Verify(opts)
return err
}
func checkRevocation(cert *x509.Certificate, verbose bool) error {
for _, crldp := range cert.CRLDistributionPoints {
crlDataList, err := x509util.ReadPossiblePEMURL(crldp, "X509 CRL")
if err != nil {
glog.Errorf("failed to retrieve CRL from %q: %v", crldp, err)
continue
}
for _, crlData := range crlDataList {
crl, err := x509.ParseCertificateList(crlData)
if x509.IsFatal(err) {
glog.Errorf("failed to parse CRL from %q: %v", crldp, err)
continue
}
if err != nil {
glog.Errorf("non-fatal error parsing CRL from %q: %v", crldp, err)
}
if verbose {
fmt.Printf("\nRevocation data from %s:\n", crldp)
fmt.Print(x509util.CRLToString(crl))
}
for _, c := range crl.TBSCertList.RevokedCertificates {
if c.SerialNumber.Cmp(cert.SerialNumber) == 0 {
return fmt.Errorf("certificate is revoked since %v", c.RevocationTime)
}
}
}
}
return nil
}