-
Notifications
You must be signed in to change notification settings - Fork 243
/
inspect.go
552 lines (485 loc) 路 14.4 KB
/
inspect.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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
package crl
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"math/big"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"github.com/smallstep/cli/flags"
"github.com/smallstep/cli/utils"
"github.com/urfave/cli"
"go.step.sm/cli-utils/command"
"go.step.sm/cli-utils/errs"
"go.step.sm/crypto/pemutil"
"go.step.sm/crypto/x509util"
)
func inspectCommand() cli.Command {
return cli.Command{
Name: "inspect",
Action: command.ActionFunc(inspectAction),
Usage: "print certificate revocation list (CRL) details in human-readable format",
UsageText: `**step crl inspect** <file|url>`,
Description: `**step crl inspect** validates and prints the details of a certificate revocation list (CRL).
A CRL is considered valid if its signature is valid, the CA is not expired, and the next update time is in the future.
## POSITIONAL ARGUMENTS
<file|url>
: The file or URL where the CRL is. If <--from> is passed it will inspect
the certificate and extract the CRL distribution point from.
## EXAMPLES
Inspect a CRL:
'''
$ step crl inspect --insecure http://ca.example.com/crls/exampleca.crl
'''
Inspect and validate a CRL in a file:
'''
$ step crl inspect --ca ca.crt exampleca.crl
'''
Format the CRL in JSON:
'''
$ step crl inspect --insecure --format json exampleca.crl
'''
Inspect the CRL from the CRL distribution point of a given url:
'''
$ step crl inspect --from https://www.google.com
'''`,
Flags: []cli.Flag{
cli.StringFlag{
Name: "format",
Value: "text",
Usage: `The output format for printing the introspection details.
: <format> is a string and must be one of:
**text**
: Print output in unstructured text suitable for a human to read.
This is the default format.
**json**
: Print output in JSON format.
**pem**
: Print output in PEM format.`,
},
cli.StringFlag{
Name: "ca",
Usage: `The certificate <file> used to validate the CRL.`,
},
cli.BoolFlag{
Name: "from",
Usage: `Extract CRL and CA from the URL passed as argument.`,
},
cli.StringSliceFlag{
Name: "roots",
Usage: `Root certificate(s) that will be used to verify the
authenticity of the remote server.
: <roots> is a case-sensitive string and may be one of:
**file**
: Relative or full path to a file. All certificates in the file will be used for path validation.
**list of files**
: Comma-separated list of relative or full file paths. Every PEM encoded certificate from each file will be used for path validation.
**directory**
: Relative or full path to a directory. Every PEM encoded certificate from each file in the directory will be used for path validation.`,
},
flags.Insecure,
},
}
}
func inspectAction(ctx *cli.Context) error {
if err := errs.MinMaxNumberOfArguments(ctx, 0, 1); err != nil {
return err
}
isFrom := ctx.Bool("from")
// Require --insecure
if !isFrom && ctx.String("ca") == "" && !ctx.Bool("insecure") {
return errs.InsecureCommand(ctx)
}
var tlsConfig *tls.Config
httpClient := http.Client{}
if roots := ctx.String("roots"); roots != "" {
pool, err := x509util.ReadCertPool(roots)
if err != nil {
return err
}
tlsConfig = &tls.Config{
RootCAs: pool,
MinVersion: tls.VersionTLS12,
}
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.TLSClientConfig = tlsConfig
httpClient.Transport = tr
}
crlFile := ctx.Args().First()
if crlFile == "" {
crlFile = "-"
}
var isURL bool
for _, p := range []string{"http://", "https://"} {
if strings.HasPrefix(strings.ToLower(crlFile), p) {
isURL = true
break
}
}
var caCerts []*x509.Certificate
if filename := ctx.String("ca"); filename != "" {
var err error
if caCerts, err = pemutil.ReadCertificateBundle(filename); err != nil {
return err
}
}
if isFrom {
var bundle []*x509.Certificate
if isURL {
u, err := url.Parse(crlFile)
if err != nil {
return errors.Wrapf(err, "error parsing %s", crlFile)
}
if _, _, err := net.SplitHostPort(u.Host); err != nil {
u.Host = net.JoinHostPort(u.Host, "443")
}
conn, err := tls.Dial("tcp", u.Host, tlsConfig)
if err != nil {
return errors.Wrapf(err, "error connecting %s", crlFile)
}
bundle = conn.ConnectionState().PeerCertificates
} else {
var err error
if bundle, err = pemutil.ReadCertificateBundle(crlFile); err != nil {
return err
}
}
isURL = true
if len(bundle[0].CRLDistributionPoints) == 0 {
return errors.Errorf("failed to get CRL distribution points from %s", crlFile)
}
crlFile = bundle[0].CRLDistributionPoints[0]
if len(bundle) > 1 {
caCerts = append(caCerts, bundle[1:]...)
}
if len(caCerts) == 0 && !ctx.Bool("insecure") {
return errs.InsecureCommand(ctx)
}
}
var (
b []byte
err error
)
if isURL {
resp, err := httpClient.Get(crlFile)
if err != nil {
return errors.Wrap(err, "error downloading crl")
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return errors.Errorf("error downloading crl: status code %d", resp.StatusCode)
}
b, err = io.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, "error downloading crl")
}
} else {
b, err = utils.ReadFile(crlFile)
if err != nil {
return err
}
}
crl, err := ParseCRL(b)
if err != nil {
return errors.Wrap(err, "error parsing crl")
}
if len(caCerts) > 0 {
for _, crt := range caCerts {
if (crt.KeyUsage&x509.KeyUsageCRLSign) == 0 || len(crt.SubjectKeyId) == 0 {
continue
}
if crl.authorityKeyID == nil || bytes.Equal(crt.SubjectKeyId, crl.authorityKeyID) {
if crl.Verify(crt) {
crl.Signature.Valid = true
}
}
}
}
switch ctx.String("format") {
case "json":
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if err := enc.Encode(crl); err != nil {
return errors.Wrap(err, "error marshaling crl")
}
case "pem":
pem.Encode(os.Stdout, &pem.Block{
Type: "X509 CRL",
Bytes: b,
})
default:
printCRL(crl)
}
return nil
}
// CRL is the JSON representation of a certificate revocation list.
type CRL struct {
Version *big.Int `json:"version"`
SignatureAlgorithm SignatureAlgorithm `json:"signature_algorithm"`
Issuer DistinguishedName `json:"issuer"`
ThisUpdate time.Time `json:"this_update"`
NextUpdate time.Time `json:"next_update"`
RevokedCertificates []RevokedCertificate `json:"revoked_certificates"`
Extensions []Extension `json:"extensions,omitempty"`
Signature *Signature `json:"signature"`
authorityKeyID []byte
raw []byte
}
// pemCRLPrefix is the magic string that indicates that we have a PEM encoded
// CRL.
var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
// pemType is the type of a PEM encoded CRL.
var pemType = "X509 CRL"
func ParseCRL(b []byte) (*CRL, error) {
if bytes.HasPrefix(b, pemCRLPrefix) {
block, _ := pem.Decode(b)
if block != nil && block.Type == pemType {
b = block.Bytes
}
}
crl, err := x509.ParseRevocationList(b)
if err != nil {
return nil, errors.Wrap(err, "error parsing crl")
}
certs := make([]RevokedCertificate, len(crl.RevokedCertificates))
for i, c := range crl.RevokedCertificates {
certs[i] = newRevokedCertificate(c)
}
var issuerKeyID []byte
extensions := make([]Extension, len(crl.Extensions))
for i, e := range crl.Extensions {
extensions[i] = newExtension(e)
if e.Id.Equal(oidExtensionAuthorityKeyID) {
var v authorityKeyID
if _, err := asn1.Unmarshal(e.Value, &v); err == nil {
issuerKeyID = v.ID
}
}
}
sa := newSignatureAlgorithm(crl.SignatureAlgorithm)
return &CRL{
Version: crl.Number.Add(crl.Number, big.NewInt(1)),
SignatureAlgorithm: sa,
Issuer: newDistinguishedName(crl.Issuer),
ThisUpdate: crl.ThisUpdate,
NextUpdate: crl.NextUpdate,
RevokedCertificates: certs,
Extensions: extensions,
Signature: &Signature{
SignatureAlgorithm: sa,
Value: crl.Signature,
Valid: false,
Reason: "",
},
authorityKeyID: issuerKeyID,
raw: crl.RawTBSRevocationList,
}, nil
}
func (c *CRL) Verify(ca *x509.Certificate) bool {
now := time.Now()
if now.After(c.NextUpdate) {
c.Signature.Reason = "CRL has expired"
return false
}
if now.After(ca.NotAfter) {
c.Signature.Reason = "CA certificate has expired"
return false
}
if !c.VerifySignature(ca) {
c.Signature.Reason = "Signature does not match"
return false
}
return true
}
func (c *CRL) VerifySignature(ca *x509.Certificate) bool {
var sum []byte
var hash crypto.Hash
if hash = c.SignatureAlgorithm.hash; hash > 0 {
h := hash.New()
h.Write(c.raw)
sum = h.Sum(nil)
}
sig := c.Signature.Value
switch pub := ca.PublicKey.(type) {
case *ecdsa.PublicKey:
return ecdsa.VerifyASN1(pub, sum, sig)
case *rsa.PublicKey:
switch c.SignatureAlgorithm.algo {
case x509.SHA256WithRSAPSS, x509.SHA384WithRSAPSS, x509.SHA512WithRSAPSS:
return rsa.VerifyPSS(pub, hash, sum, sig, &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthAuto,
}) == nil
default:
return rsa.VerifyPKCS1v15(pub, hash, sum, sig) == nil
}
case ed25519.PublicKey:
return ed25519.Verify(pub, c.raw, sig)
default:
return false
}
}
func printCRL(crl *CRL) {
fmt.Println("Certificate Revocation List (CRL):")
fmt.Println(" Data:")
fmt.Printf(" Valid: %v\n", crl.Signature.Valid)
if crl.Signature.Reason != "" {
fmt.Printf(" Reason: %s\n", crl.Signature.Reason)
}
fmt.Printf(" Version: %d (0x%x)\n", crl.Version, crl.Version.Add(crl.Version, big.NewInt(-1)))
fmt.Println(" Signature algorithm:", crl.SignatureAlgorithm)
fmt.Println(" Issuer:", crl.Issuer)
fmt.Println(" Last Update:", crl.ThisUpdate.UTC())
fmt.Println(" Next Update:", crl.NextUpdate.UTC())
fmt.Println(" CRL Extensions:")
for _, e := range crl.Extensions {
fmt.Println(spacer(12) + e.Name)
for _, s := range e.Details {
fmt.Println(spacer(16) + s)
}
}
if len(crl.RevokedCertificates) == 0 {
fmt.Println(spacer(8) + "No Revoked Certificates.")
} else {
fmt.Println(spacer(8) + "Revoked Certificates:")
for _, crt := range crl.RevokedCertificates {
fmt.Printf(spacer(12)+"Serial Number: %s (0x%X)\n", crt.SerialNumber, crt.SerialNumberBytes)
fmt.Println(spacer(16)+"Revocation Date:", crt.RevocationTime.UTC())
if len(crt.Extensions) > 0 {
fmt.Println(spacer(16) + "CRL Entry Extensions:")
for _, e := range crt.Extensions {
fmt.Println(spacer(20) + e.Name)
for _, s := range e.Details {
fmt.Println(spacer(24) + s)
}
}
}
}
}
fmt.Println(" Signature Algorithm:", crl.Signature.SignatureAlgorithm)
printBytes(crl.Signature.Value, spacer(8))
}
// Signature is the JSON representation of a CRL signature.
type Signature struct {
SignatureAlgorithm SignatureAlgorithm `json:"signature_algorithm"`
Value []byte `json:"value"`
Valid bool `json:"valid"`
Reason string `json:"reason,omitempty"`
}
// DistinguishedName is the JSON representation of the CRL issuer.
type DistinguishedName struct {
Country []string `json:"country,omitempty"`
Organization []string `json:"organization,omitempty"`
OrganizationalUnit []string `json:"organizational_unit,omitempty"`
Locality []string `json:"locality,omitempty"`
Province []string `json:"province,omitempty"`
StreetAddress []string `json:"street_address,omitempty"`
PostalCode []string `json:"postal_code,omitempty"`
SerialNumber string `json:"serial_number,omitempty"`
CommonName string `json:"common_name,omitempty"`
ExtraNames map[string][]interface{} `json:"extra_names,omitempty"`
dn pkix.Name
}
// String returns the one line representation of the distinguished name.
func (d DistinguishedName) String() string {
return d.dn.String()
}
func newDistinguishedName(dn pkix.Name) DistinguishedName {
var extraNames map[string][]interface{}
if len(dn.ExtraNames) > 0 {
extraNames = make(map[string][]interface{})
for _, tv := range dn.ExtraNames {
oid := tv.Type.String()
if s, ok := tv.Value.(string); ok {
extraNames[oid] = append(extraNames[oid], s)
continue
}
if b, err := asn1.Marshal(tv.Value); err == nil {
extraNames[oid] = append(extraNames[oid], b)
continue
}
extraNames[oid] = append(extraNames[oid], escapeValue(tv.Value))
}
}
return DistinguishedName{
Country: dn.Country,
Organization: dn.Organization,
OrganizationalUnit: dn.OrganizationalUnit,
Locality: dn.Locality,
Province: dn.Province,
StreetAddress: dn.StreetAddress,
PostalCode: dn.PostalCode,
SerialNumber: dn.SerialNumber,
CommonName: dn.CommonName,
ExtraNames: extraNames,
}
}
// RevokedCertificate is the JSON representation of a certificate in a CRL.
type RevokedCertificate struct {
SerialNumber string `json:"serial_number"`
RevocationTime time.Time `json:"revocation_time"`
Extensions []Extension `json:"extensions,omitempty"`
SerialNumberBytes []byte `json:"-"`
}
func newRevokedCertificate(c pkix.RevokedCertificate) RevokedCertificate {
var extensions []Extension
return RevokedCertificate{
SerialNumber: c.SerialNumber.String(),
RevocationTime: c.RevocationTime.UTC(),
Extensions: extensions,
SerialNumberBytes: c.SerialNumber.Bytes(),
}
}
func spacer(i int) string {
return fmt.Sprintf("%"+strconv.Itoa(i)+"s", "")
}
func printBytes(bs []byte, prefix string) {
for i, b := range bs {
if i == 0 {
fmt.Print(prefix)
} else if (i % 16) == 0 {
fmt.Print("\n" + prefix)
}
fmt.Printf("%02x", b)
if i != len(bs)-1 {
fmt.Print(":")
}
}
fmt.Println()
}
func escapeValue(v interface{}) string {
s := fmt.Sprint(v)
escaped := make([]rune, 0, len(s))
for k, c := range s {
escape := false
switch c {
case ',', '+', '"', '\\', '<', '>', ';':
escape = true
case ' ':
escape = k == 0 || k == len(s)-1
case '#':
escape = k == 0
}
if escape {
escaped = append(escaped, '\\', c)
} else {
escaped = append(escaped, c)
}
}
return string(escaped)
}