Debian Codegraph @

command/ca/revoke.go

raw symbols SCIP
1 package ca
2
3 import (
4 "crypto/tls"
5 "crypto/x509"
6 "encoding/pem"
7 "io/ioutil"
8 "net/http"
9 "os"
10 "strconv"
11 "strings"
12 "time"
13
14 "github.com/pkg/errors"
15 "github.com/smallstep/certificates/api"
16 "github.com/smallstep/certificates/authority/provisioner"
17 "github.com/smallstep/certificates/ca"
18 "github.com/smallstep/certificates/pki"
19 "github.com/smallstep/cli/command"
20 "github.com/smallstep/cli/crypto/pemutil"
21 "github.com/smallstep/cli/crypto/x509util"
22 "github.com/smallstep/cli/errs"
23 "github.com/smallstep/cli/flags"
24 "github.com/smallstep/cli/jose"
25 "github.com/smallstep/cli/ui"
26 "github.com/smallstep/cli/utils/cautils"
27 "github.com/urfave/cli"
28 "golang.org/x/crypto/ocsp"
29 )
30
31 /*
32 NOTE: This command currently only supports passive revocation. Passive revocation
33 means preventing a certificate from being renewed and letting it expire.
34
35 TODO: Add support for CRL and OCSP.
36 */
37
38 func revokeCertificateCommand() cli.Command {
39 return cli.Command{
40 Name: "revoke",
41 Action: command.ActionFunc(revokeCertificateAction),
42 Usage: "revoke a certificate",
43 UsageText: `**step ca revoke** <serial-number>
44 [**--cert**=<path>] [**--key**=<path>] [**--token**=<ott>]
45 [**--ca-url**=<uri>] [**--root**=<path>] [**--reason**=<string>]
46 [**--reasonCode**=<code>] [**-offline**]`,
47 Description: `
48 **step ca revoke** command revokes a certificate with the given serial
49 number.
50
51 **Active Revocation**: A certificate is no longer valid from the moment it has
52 been actively revoked. Clients are required to check against centralized
53 sources of certificate validity information (e.g. by using CRLs (Certificate
54 Revocation Lists) or OCSP (Online Certificate Status Protocol)) to
55 verify that certificates have not been revoked. Active Revocation requires
56 clients to take an active role in certificate validation for the benefit of
57 real time revocation.
58
59 **Passive Revocation**: A certificate that has been passively revoked can no
60 longer be renewed. It will still be valid for the remainder of it's validity period,
61 but cannot be prolonged. The benefit of passive revocation is that clients
62 can verify certificates in a simple, decentralized manner without relying on
63 centralized 3rd parties. Passive revocation works best with short
64 certificate lifetimes.
65
66 **step ca revoke** currently only supports passive revocation. Active revocation
67 is on our roadmap.
68
69 ## POSITIONAL ARGUMENTS
70
71 <serial-number>
72 : The serial number of the certificate that should be revoked. Can be left blank
73 either to be supplied by prompt or when using --cert and --key flags for
74 revocation over mTLS.
75
76 ## EXAMPLES
77
78 Revoke a certificate using a transparently generated API token and the default
79 'unspecified' reason:
80 '''
81 $ step ca revoke 308893286343609293989051180431574390766
82 '''
83
84 Revoke a certificate using a transparently generated token and configured reason
85 and reasonCode:
86 '''
87 $ step ca revoke --reason "laptop compromised" --reasonCode 1 308893286343609293989051180431574390766
88 '''
89
90 Revoke a certificate using a transparently generated token and configured reason
91 and stringified reasonCode:
92 '''
93 $ step ca revoke --reason "laptop compromised" --reasonCode "key compromise" 308893286343609293989051180431574390766
94 '''
95
96 Revoke a certificate using that same certificate to validate and authorize the
97 request (rather than a token) over mTLS:
98 '''
99 $ step ca revoke --cert mike.cert --key mike.key
100 '''
101
102 Revoke a certificate using a token, generated by a provisioner, to authorize
103 the request with the CA:
104 '''
105 $ TOKEN=$(step ca token --revoke 308893286343609293989051180431574390766)
106 $ step ca revoke --token $TOKEN 308893286343609293989051180431574390766
107 '''
108
109 Revoke a certificate in offline mode:
110 '''
111 $ step ca revoke --offline 308893286343609293989051180431574390766
112 '''
113
114 Revoke a certificate in offline mode using --cert and --key (the cert/key pair
115 will be validated against the root and intermediate certifcates configured in
116 the step CA):
117 '''
118 $ step ca revoke --offline --cert foo.crt --key foo.key
119 '''`,
120 Flags: []cli.Flag{
121 cli.StringFlag{
122 Name: "cert",
123 Usage: `The path to the <cert> that should be revoked.`,
124 },
125 cli.StringFlag{
126 Name: "key",
127 Usage: `The <path> to the key corresponding to the cert that should be revoked.`,
128 },
129 cli.StringFlag{
130 Name: "reason",
131 Usage: `The <string> representing the reason for which the cert is being revoked.`,
132 },
133 cli.StringFlag{
134 Name: "reasonCode",
135 Value: "",
136 Usage: `The <reasonCode> specifies the reason for revocation - chose from a list of
137 common revocation reasons. If unset, the default is Unspecified.
138
139 : <reasonCode> can be a number from 0-9 or a case insensitive string matching
140 one of the following options:
141
142 **Unspecified**
143 : No reason given (Default -- reasonCode=0).
144
145 **KeyCompromise**
146 : The key is believed to have been compromised (reasonCode=1).
147
148 **CACompromise**
149 : The issuing Certificate Authority itself has been compromised (reasonCode=2).
150
151 **AffiliationChanged**
152 : The certificate contained affiliation information, for example, it may
153 have been an EV certificate and the associated business is no longer owned by
154 the same entity (reasonCode=3).
155
156 **Superseded**
157 : The certificate is being replaced (reasonCode=4).
158
159 **CessationOfOperation**
160 : If a CA is decommissioned, no longer to be used, the CA's certificate
161 should be revoked with this reason code. Do not revoke the CA's certificate if
162 the CA no longer issues new certificates, yet still publishes CRLs for the
163 currently issued certificates (reasonCode=5).
164
165 **CertificateHold**
166 : A temporary revocation that indicates that a CA will not vouch for a
167 certificate at a specific point in time. Once a certificate is revoked with a
168 CertificateHold reason code, the certificate can then be revoked with another
169 Reason Code, or unrevoked and returned to use (reasonCode=6).
170
171 **RemoveFromCRL**
172 : If a certificate is revoked with the CertificateHold reason code, it is
173 possible to "unrevoke" a certificate. The unrevoking process still lists the
174 certificate in the CRL, but with the reason code set to RemoveFromCRL.
175 Note: This is specific to the CertificateHold reason and is only used in DeltaCRLs
176 (reasonCode=8).
177
178 **PrivilegeWithdrawn**
179 : The right to represent the given entity was revoked for some reason
180 (reasonCode=9).
181
182 **AACompromise**
183 : It is known or suspected that aspects of the AA validated in the
184 attribute certificate have been compromised (reasonCode=10).
185 `,
186 },
187 flags.CaConfig,
188 flags.CaURL,
189 flags.Offline,
190 flags.Root,
191 flags.Token,
192 },
193 }
194 }
195
196 func revokeCertificateAction(ctx *cli.Context) error {
197 args := ctx.Args()
198 serial := args.Get(0)
199 certFile, keyFile := ctx.String("cert"), ctx.String("key")
200 token := ctx.String("token")
201 offline := ctx.Bool("offline")
202
203 // Validate the reasonCode arg early in the flow.
204 if _, err := ReasonCodeToNum(ctx.String("reasonCode")); err != nil {
205 return err
206 }
207
208 // offline and token are incompatible because the token is generated before
209 // the start of the offline CA.
210 if offline && len(token) != 0 {
211 return errs.IncompatibleFlagWithFlag(ctx, "offline", "token")
212 }
213
214 // revokeFlow unifies online and offline flows on a single api.
215 flow, err := newRevokeFlow(ctx, certFile, keyFile)
216 if err != nil {
217 return err
218 }
219
220 // If cert and key are passed then infer the serial number and certificate
221 // that should be revoked.
222 if len(certFile) > 0 || len(keyFile) > 0 {
223 // Must be using cert/key flags for mTLS revoke so should be 0 cmd line args.
224 if ctx.NArg() > 0 {
225 return errors.Errorf("'%s %s --cert <certificate> --key <key>' expects no additional positional arguments", ctx.App.Name, ctx.Command.Name)
226 }
227 if len(certFile) == 0 {
228 return errs.RequiredWithFlag(ctx, "key", "cert")
229 }
230 if len(keyFile) == 0 {
231 return errs.RequiredWithFlag(ctx, "cert", "key")
232 }
233 if len(token) > 0 {
234 errs.IncompatibleFlagWithFlag(ctx, "cert", "token")
235 }
236 if len(serial) > 0 {
237 errs.IncompatibleFlagWithFlag(ctx, "cert", "serial")
238 }
239 var cert []*x509.Certificate
240 cert, err = pemutil.ReadCertificateBundle(certFile)
241 if err != nil {
242 return err
243 }
244 serial = cert[0].SerialNumber.String()
245 } else {
246 // Must be using serial number so verify that only 1 command line args was given.
247 if err = errs.NumberOfArguments(ctx, 1); err != nil {
248 return err
249 }
250 if len(token) == 0 {
251 // No token and no cert/key pair - so generate a token.
252 token, err = flow.GenerateToken(ctx, &serial)
253 if err != nil {
254 return err
255 }
256 }
257 }
258
259 if err := flow.Revoke(ctx, serial, token); err != nil {
260 return err
261 }
262
263 ui.Printf("Certificate with Serial Number %s has been revoked.\n", serial)
264 return nil
265 }
266
267 type revokeTokenClaims struct {
268 SHA string `json:"sha"`
269 jose.Claims
270 }
271
272 type revokeFlow struct {
273 offlineCA *cautils.OfflineCA
274 offline bool
275 }
276
277 func newRevokeFlow(ctx *cli.Context, certFile, keyFile string) (*revokeFlow, error) {
278 var err error
279 var offlineClient *cautils.OfflineCA
280
281 offline := ctx.Bool("offline")
282 if offline {
283 caConfig := ctx.String("ca-config")
284 if caConfig == "" {
285 return nil, errs.InvalidFlagValue(ctx, "ca-config", "", "")
286 }
287 offlineClient, err = cautils.NewOfflineCA(caConfig)
288 if err != nil {
289 return nil, err
290 }
291 if len(certFile) > 0 || len(keyFile) > 0 {
292 if err = offlineClient.VerifyClientCert(certFile, keyFile); err != nil {
293 return nil, err
294 }
295 }
296 }
297
298 return &revokeFlow{
299 offlineCA: offlineClient,
300 offline: offline,
301 }, nil
302 }
303
304 func (f *revokeFlow) getClient(ctx *cli.Context, serial, token string) (cautils.CaClient, error) {
305 if f.offline {
306 return f.offlineCA, nil
307 }
308
309 // Create online client
310 caURL, err := flags.ParseCaURLIfExists(ctx)
311 if err != nil {
312 return nil, err
313 }
314 rootFile := ctx.String("root")
315 var options []ca.ClientOption
316
317 if len(token) > 0 {
318 tok, err := jose.ParseSigned(token)
319 if err != nil {
320 return nil, errors.Wrap(err, "error parsing flag '--token'")
321 }
322 var claims revokeTokenClaims
323 if err := tok.UnsafeClaimsWithoutVerification(&claims); err != nil {
324 return nil, errors.Wrap(err, "error parsing flag '--token'")
325 }
326 if !strings.EqualFold(claims.Subject, serial) {
327 return nil, errors.Errorf("token subject '%s' and serial number '%s' do not match", claims.Subject, serial)
328 }
329
330 // Prepare client for bootstrap or provisioning tokens
331 if len(claims.SHA) > 0 && len(claims.Audience) > 0 && strings.HasPrefix(strings.ToLower(claims.Audience[0]), "http") {
332 if len(caURL) == 0 {
333 caURL = claims.Audience[0]
334 }
335 options = append(options, ca.WithRootSHA256(claims.SHA))
336 ui.PrintSelected("CA", caURL)
337 return ca.NewClient(caURL, options...)
338 }
339 } else {
340 // If there is no token then caURL is required.
341 if len(caURL) == 0 {
342 return nil, errs.RequiredFlag(ctx, "ca-url")
343 }
344 }
345
346 if len(rootFile) == 0 {
347 rootFile = pki.GetRootCAPath()
348 if _, err := os.Stat(rootFile); err != nil {
349 return nil, errs.RequiredFlag(ctx, "root")
350 }
351 }
352 options = append(options, ca.WithRootFile(rootFile))
353
354 ui.PrintSelected("CA", caURL)
355 return ca.NewClient(caURL, options...)
356 }
357
358 func (f *revokeFlow) GenerateToken(ctx *cli.Context, subject *string) (string, error) {
359 // For offline just generate the token
360 if f.offline {
361 return f.offlineCA.GenerateToken(ctx, cautils.RevokeType, *subject, nil, time.Time{}, time.Time{}, provisioner.TimeDuration{}, provisioner.TimeDuration{})
362 }
363
364 // Use online CA to get the provisioners and generate the token
365 caURL, err := flags.ParseCaURLIfExists(ctx)
366 if err != nil {
367 return "", err
368 } else if len(caURL) == 0 {
369 return "", errs.RequiredUnlessFlag(ctx, "ca-url", "token")
370 }
371
372 root := ctx.String("root")
373 if len(root) == 0 {
374 root = pki.GetRootCAPath()
375 if _, err := os.Stat(root); err != nil {
376 return "", errs.RequiredUnlessFlag(ctx, "root", "token")
377 }
378 }
379
380 if *subject == "" {
381 *subject, err = ui.Prompt("What is the Serial Number of the certificate you would like to revoke? (`step certificate inspect foo.cert`)", ui.WithValidateNotEmpty())
382 if err != nil {
383 return "", err
384 }
385 }
386
387 return cautils.NewTokenFlow(ctx, cautils.RevokeType, *subject, nil, caURL, root, time.Time{}, time.Time{}, provisioner.TimeDuration{}, provisioner.TimeDuration{})
388 }
389
390 func (f *revokeFlow) Revoke(ctx *cli.Context, serial, token string) error {
391 client, err := f.getClient(ctx, serial, token)
392 if err != nil {
393 return err
394 }
395
396 reason := ctx.String("reason")
397 // Convert the reasonCode flag to an OCSP revocation code.
398 reasonCode, err := ReasonCodeToNum(ctx.String("reasonCode"))
399 if err != nil {
400 return err
401 }
402
403 var tr http.RoundTripper
404
405 // If token is not provided then set up mTLS client with expected cert and key.
406 if len(token) == 0 {
407 certFile, keyFile := ctx.String("cert"), ctx.String("key")
408
409 certPEMBytes, err := ioutil.ReadFile(certFile)
410 if err != nil {
411 return errors.Wrap(err, "error reading certificate")
412 }
413 key, err := pemutil.Read(keyFile)
414 if err != nil {
415 return errors.Wrap(err, "error parsing key")
416 }
417 keyBlock, err := pemutil.Serialize(key)
418 if err != nil {
419 return errors.Wrap(err, "error serializing key")
420 }
421
422 cert, err := tls.X509KeyPair(certPEMBytes, pem.EncodeToMemory(keyBlock))
423 if err != nil {
424 return errors.Wrap(err, "error loading certificate key pair")
425 }
426 if len(cert.Certificate) == 0 {
427 return errors.New("error loading certificate: certificate chain is empty")
428 }
429 root := ctx.String("root")
430 if len(root) == 0 {
431 root = pki.GetRootCAPath()
432 if _, err = os.Stat(root); err != nil {
433 return errs.RequiredUnlessFlag(ctx, "root", "token")
434 }
435 }
436 var rootCAs *x509.CertPool
437 rootCAs, err = x509util.ReadCertPool(root)
438 if err != nil {
439 return err
440 }
441 tr = &http.Transport{
442 Proxy: http.ProxyFromEnvironment,
443 TLSClientConfig: &tls.Config{
444 RootCAs: rootCAs,
445 PreferServerCipherSuites: true,
446 Certificates: []tls.Certificate{cert},
447 },
448 }
449 }
450
451 req := &api.RevokeRequest{
452 Serial: serial,
453 Reason: reason,
454 ReasonCode: reasonCode,
455 OTT: token,
456 Passive: true,
457 }
458 if _, err = client.Revoke(req, tr); err != nil {
459 return err
460 }
461 return nil
462 }
463
464 // RevocationReasonCodes is a map between string reason codes
465 // to integers as defined in RFC 5280
466 var RevocationReasonCodes = map[string]int{
467 "unspecified": ocsp.Unspecified,
468 "keycompromise": ocsp.KeyCompromise,
469 "cacompromise": ocsp.CACompromise,
470 "affiliationchanged": ocsp.AffiliationChanged,
471 "superseded": ocsp.Superseded,
472 "cessationofoperation": ocsp.CessationOfOperation,
473 "certificatehold": ocsp.CertificateHold,
474 "removefromcrl": ocsp.RemoveFromCRL,
475 "privilegewithdrawn": ocsp.PrivilegeWithdrawn,
476 "aacompromise": ocsp.AACompromise,
477 }
478
479 // ReasonCodeToNum converts a string encoded code to a number.
480 // 1) "4" -> 4
481 // 2) "key compromise" -> 1
482 // 3) "keYComPromIse" -> 1
483 func ReasonCodeToNum(rc string) (int, error) {
484 // default to 0
485 if rc == "" {
486 return 0, nil
487 }
488
489 if code, err := strconv.Atoi(rc); err == nil {
490 if code < ocsp.Unspecified || code > ocsp.AACompromise {
491 return -1, errors.Errorf("reasonCode out of bounds. Got %d, but want value between %d and %d",
492 code, ocsp.Unspecified, ocsp.AACompromise)
493 }
494 return code, nil
495 }
496
497 code, found := RevocationReasonCodes[strings.ToLower(strings.Replace(rc, " ", "", -1))]
498 if !found {
499 return 0, errors.Errorf("unrecognized revocation reason code '%s'", rc)
500 }
501
502 return code, nil
503 }