Debian Codegraph @

utils/cautils/offline.go

raw symbols SCIP
1 package cautils
2
3 import (
4 "context"
5 "crypto/tls"
6 "crypto/x509"
7 "encoding/json"
8 "encoding/pem"
9 "fmt"
10 "net/http"
11 "time"
12
13 "github.com/pkg/errors"
14 "github.com/smallstep/certificates/api"
15 "github.com/smallstep/certificates/authority"
16 "github.com/smallstep/certificates/authority/provisioner"
17 "github.com/smallstep/cli/crypto/pemutil"
18 "github.com/smallstep/cli/crypto/x509util"
19 "github.com/smallstep/cli/utils"
20 "github.com/urfave/cli"
21 "golang.org/x/crypto/ssh"
22 )
23
24 // OfflineCA is a wrapper on top of the certificates authority methods that is
25 // used to sign certificates without an online CA.
26 type OfflineCA struct {
27 authority *authority.Authority
28 config authority.Config
29 configFile string
30 }
31
32 // offlineInstance is a singleton used for OfflineCA. The use of a singleton is
33 // necessary to avoid double initialization. Double initializations are
34 // sometimes not possible due to locks - as seen in badgerDB
35 var offlineInstance *OfflineCA
36
37 // NewOfflineCA initializes an offlineCA.
38 func NewOfflineCA(configFile string) (*OfflineCA, error) {
39 if offlineInstance != nil {
40 return offlineInstance, nil
41 }
42
43 b, err := utils.ReadFile(configFile)
44 if err != nil {
45 return nil, err
46 }
47
48 var config authority.Config
49 if err = json.Unmarshal(b, &config); err != nil {
50 return nil, errors.Wrapf(err, "error reading %s", configFile)
51 }
52
53 if config.AuthorityConfig == nil || len(config.AuthorityConfig.Provisioners) == 0 {
54 return nil, errors.Errorf("error parsing %s: no provisioners found", configFile)
55 }
56
57 auth, err := authority.New(&config)
58 if err != nil {
59 return nil, err
60 }
61
62 offlineInstance = &OfflineCA{
63 authority: auth,
64 config: config,
65 configFile: configFile,
66 }
67 return offlineInstance, nil
68 }
69
70 // GetRootCAs return the cert pool for the ca, as it's an offline ca, a pool is
71 // not required and it always returns nil.
72 func (c *OfflineCA) GetRootCAs() *x509.CertPool {
73 return nil
74 }
75
76 // VerifyClientCert verifies and validates the client cert/key pair
77 // using the offline CA root and intermediate certificates.
78 func (c *OfflineCA) VerifyClientCert(certFile, keyFile string) error {
79 cert, err := pemutil.ReadCertificate(certFile, pemutil.WithFirstBlock())
80 if err != nil {
81 return err
82 }
83 key, err := pemutil.Read(keyFile)
84 if err != nil {
85 return err
86 }
87
88 certPem, err := pemutil.Serialize(cert)
89 if err != nil {
90 return err
91 }
92 keyPem, err := pemutil.Serialize(key)
93 if err != nil {
94 return err
95 }
96 // Validate that the certificate and key match
97 if _, err = tls.X509KeyPair(pem.EncodeToMemory(certPem), pem.EncodeToMemory(keyPem)); err != nil {
98 return errors.Wrap(err, "error loading x509 key pair")
99 }
100
101 rootPool, err := x509util.ReadCertPool(c.Root())
102 if err != nil {
103 return err
104 }
105 intermediatePool, err := x509util.ReadCertPool(c.config.IntermediateCert)
106 if err != nil {
107 return err
108 }
109
110 opts := x509.VerifyOptions{
111 Roots: rootPool,
112 Intermediates: intermediatePool,
113 }
114
115 if _, err = cert.Verify(opts); err != nil {
116 return errors.Wrapf(err, "failed to verify certificate")
117 }
118
119 return nil
120 }
121
122 // Audience returns the token audience.
123 func (c *OfflineCA) Audience(tokType int) string {
124 switch tokType {
125 case RevokeType:
126 return fmt.Sprintf("https://%s/revoke", c.config.DNSNames[0])
127 case SSHUserSignType, SSHHostSignType:
128 return fmt.Sprintf("https://%s/ssh/sign", c.config.DNSNames[0])
129 case SSHRenewType:
130 return fmt.Sprintf("https://%s/ssh/renew", c.config.DNSNames[0])
131 case SSHRevokeType:
132 return fmt.Sprintf("https://%s/ssh/revoke", c.config.DNSNames[0])
133 case SSHRekeyType:
134 return fmt.Sprintf("https://%s/ssh/rekey", c.config.DNSNames[0])
135 default:
136 return fmt.Sprintf("https://%s/sign", c.config.DNSNames[0])
137 }
138 }
139
140 // CaURL returns the CA URL using the first DNS entry.
141 func (c *OfflineCA) CaURL() string {
142 return fmt.Sprintf("https://%s", c.config.DNSNames[0])
143 }
144
145 // Root returns the path of the file used as root certificate.
146 func (c *OfflineCA) Root() string {
147 return c.config.Root.First()
148 }
149
150 // Provisioners returns the list of configured provisioners.
151 func (c *OfflineCA) Provisioners() provisioner.List {
152 return c.config.AuthorityConfig.Provisioners
153 }
154
155 func certChainToPEM(certChain []*x509.Certificate) []api.Certificate {
156 certChainPEM := make([]api.Certificate, 0, len(certChain))
157 for _, c := range certChain {
158 certChainPEM = append(certChainPEM, api.Certificate{Certificate: c})
159 }
160 return certChainPEM
161 }
162
163 // Version is a wrapper on top of the Version method. It returns
164 // an api.VersionResponse.
165 func (c *OfflineCA) Version() (*api.VersionResponse, error) {
166 v := c.authority.Version()
167 return &api.VersionResponse{
168 Version: v.Version,
169 RequireClientAuthentication: v.RequireClientAuthentication,
170 }, nil
171 }
172
173 // Sign is a wrapper on top of certificates Authorize and Sign methods. It
174 // returns an api.SignResponse with the requested certificate and the
175 // intermediate.
176 func (c *OfflineCA) Sign(req *api.SignRequest) (*api.SignResponse, error) {
177 ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SignMethod)
178 opts, err := c.authority.Authorize(ctx, req.OTT)
179 if err != nil {
180 return nil, err
181 }
182 signOpts := provisioner.SignOptions{
183 NotBefore: req.NotBefore,
184 NotAfter: req.NotAfter,
185 }
186 certChain, err := c.authority.Sign(req.CsrPEM.CertificateRequest, signOpts, opts...)
187 if err != nil {
188 return nil, err
189 }
190 certChainPEM := certChainToPEM(certChain)
191 var caPEM api.Certificate
192 if len(certChainPEM) > 1 {
193 caPEM = certChainPEM[1]
194 }
195 return &api.SignResponse{
196 ServerPEM: certChainPEM[0],
197 CaPEM: caPEM,
198 CertChainPEM: certChainPEM,
199 TLSOptions: c.authority.GetTLSOptions(),
200 }, nil
201 }
202
203 // Renew is a wrapper on top of certificates Renew method. It returns an
204 // api.SignResponse with the requested certificate and the intermediate.
205 func (c *OfflineCA) Renew(rt http.RoundTripper) (*api.SignResponse, error) {
206 // it should not panic as this is always internal code
207 tr := rt.(*http.Transport)
208 asn1Data := tr.TLSClientConfig.Certificates[0].Certificate[0]
209 peer, err := x509.ParseCertificate(asn1Data)
210 if err != nil {
211 return nil, errors.Wrap(err, "error parsing certificate")
212 }
213 // renew cert using authority
214 certChain, err := c.authority.Renew(peer)
215 if err != nil {
216 return nil, err
217 }
218 certChainPEM := certChainToPEM(certChain)
219 var caPEM api.Certificate
220 if len(certChainPEM) > 1 {
221 caPEM = certChainPEM[1]
222 }
223 return &api.SignResponse{
224 ServerPEM: certChainPEM[0],
225 CaPEM: caPEM,
226 CertChainPEM: certChainPEM,
227 TLSOptions: c.authority.GetTLSOptions(),
228 }, nil
229 }
230
231 // Revoke is a wrapper on top of certificates Revoke method. It returns an
232 // api.RevokeResponse.
233 func (c *OfflineCA) Revoke(req *api.RevokeRequest, rt http.RoundTripper) (*api.RevokeResponse, error) {
234 var (
235 opts = authority.RevokeOptions{
236 Serial: req.Serial,
237 Reason: req.Reason,
238 ReasonCode: req.ReasonCode,
239 PassiveOnly: req.Passive,
240 }
241 ctx = provisioner.NewContextWithMethod(context.Background(), provisioner.RevokeMethod)
242 err error
243 )
244 if len(req.OTT) > 0 {
245 opts.OTT = req.OTT
246 opts.MTLS = false
247 if _, err = c.authority.Authorize(ctx, opts.OTT); err != nil {
248 return nil, err
249 }
250 } else {
251 // it should not panic as this is always internal code
252 tr := rt.(*http.Transport)
253 asn1Data := tr.TLSClientConfig.Certificates[0].Certificate[0]
254 opts.Crt, err = x509.ParseCertificate(asn1Data)
255 if err != nil {
256 return nil, errors.Wrap(err, "error parsing certificate")
257 }
258 opts.MTLS = true
259 }
260
261 // revoke cert using authority
262 if err := c.authority.Revoke(ctx, &opts); err != nil {
263 return nil, err
264 }
265
266 return &api.RevokeResponse{Status: "ok"}, nil
267 }
268
269 // SSHSign is a wrapper on top of certificate Authorize and SignSSH methods. It
270 // returns an api.SSHSignResponse with the signed certificate.
271 func (c *OfflineCA) SSHSign(req *api.SSHSignRequest) (*api.SSHSignResponse, error) {
272 publicKey, err := ssh.ParsePublicKey(req.PublicKey)
273 if err != nil {
274 return nil, errors.Wrap(err, "error parsing publicKey")
275 }
276 ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SSHSignMethod)
277 opts, err := c.authority.Authorize(ctx, req.OTT)
278 if err != nil {
279 return nil, err
280 }
281 signOpts := provisioner.SignSSHOptions{
282 CertType: req.CertType,
283 KeyID: req.KeyID,
284 Principals: req.Principals,
285 ValidAfter: req.ValidAfter,
286 ValidBefore: req.ValidBefore,
287 TemplateData: req.TemplateData,
288 }
289 cert, err := c.authority.SignSSH(context.Background(), publicKey, signOpts, opts...)
290 if err != nil {
291 return nil, err
292 }
293 return &api.SSHSignResponse{
294 Certificate: api.SSHCertificate{
295 Certificate: cert,
296 },
297 }, nil
298 }
299
300 // SSHRevoke is a wrapper on top of certificates SSHRevoke method. It returns an
301 // api.SSHRevokeResponse.
302 func (c *OfflineCA) SSHRevoke(req *api.SSHRevokeRequest) (*api.SSHRevokeResponse, error) {
303 opts := authority.RevokeOptions{
304 Serial: req.Serial,
305 Reason: req.Reason,
306 ReasonCode: req.ReasonCode,
307 PassiveOnly: req.Passive,
308 OTT: req.OTT,
309 MTLS: false,
310 }
311
312 ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SSHRevokeMethod)
313 if _, err := c.authority.Authorize(ctx, opts.OTT); err != nil {
314 return nil, err
315 }
316 if err := c.authority.Revoke(ctx, &opts); err != nil {
317 return nil, err
318 }
319
320 return &api.SSHRevokeResponse{Status: "ok"}, nil
321 }
322
323 // SSHRenew is a wrapper on top of certificates SSHRenew method. It returns an
324 // api.SSHRenewResponse.
325 func (c *OfflineCA) SSHRenew(req *api.SSHRenewRequest) (*api.SSHRenewResponse, error) {
326 ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SSHRenewMethod)
327 _, err := c.authority.Authorize(ctx, req.OTT)
328 if err != nil {
329 return nil, err
330 }
331 oldCert, _, err := provisioner.ExtractSSHPOPCert(req.OTT)
332 if err != nil {
333 return nil, err
334 }
335 cert, err := c.authority.RenewSSH(context.Background(), oldCert)
336 if err != nil {
337 return nil, err
338 }
339
340 return &api.SSHRenewResponse{Certificate: api.SSHCertificate{Certificate: cert}}, nil
341 }
342
343 // SSHRekey is a wrapper on top of certificates SSHRekey method. It returns an
344 // api.SSHRekeyResponse.
345 func (c *OfflineCA) SSHRekey(req *api.SSHRekeyRequest) (*api.SSHRekeyResponse, error) {
346 ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SSHRekeyMethod)
347 signOpts, err := c.authority.Authorize(ctx, req.OTT)
348 if err != nil {
349 return nil, err
350 }
351 oldCert, _, err := provisioner.ExtractSSHPOPCert(req.OTT)
352 if err != nil {
353 return nil, err
354 }
355 sshPub, err := ssh.ParsePublicKey(req.PublicKey)
356 if err != nil {
357 return nil, err
358 }
359
360 cert, err := c.authority.RekeySSH(context.Background(), oldCert, sshPub, signOpts...)
361 if err != nil {
362 return nil, err
363 }
364
365 return &api.SSHRekeyResponse{Certificate: api.SSHCertificate{Certificate: cert}}, nil
366 }
367
368 // SSHRoots is a wrapper on top of the GetSSHRoots method. It returns an
369 // api.SSHRootsResponse.
370 func (c *OfflineCA) SSHRoots() (*api.SSHRootsResponse, error) {
371 keys, err := c.authority.GetSSHRoots(context.Background())
372 if err != nil {
373 return nil, err
374 }
375
376 resp := new(api.SSHRootsResponse)
377 for _, k := range keys.HostKeys {
378 resp.HostKeys = append(resp.HostKeys, api.SSHPublicKey{PublicKey: k})
379 }
380 for _, k := range keys.UserKeys {
381 resp.UserKeys = append(resp.UserKeys, api.SSHPublicKey{PublicKey: k})
382 }
383
384 return resp, nil
385 }
386
387 // SSHFederation is a wrapper on top of the GetSSHFederation method. It returns
388 // an api.SSHRootsResponse.
389 func (c *OfflineCA) SSHFederation() (*api.SSHRootsResponse, error) {
390 keys, err := c.authority.GetSSHFederation(context.Background())
391 if err != nil {
392 return nil, err
393 }
394
395 resp := new(api.SSHRootsResponse)
396 for _, k := range keys.HostKeys {
397 resp.HostKeys = append(resp.HostKeys, api.SSHPublicKey{PublicKey: k})
398 }
399 for _, k := range keys.UserKeys {
400 resp.UserKeys = append(resp.UserKeys, api.SSHPublicKey{PublicKey: k})
401 }
402
403 return resp, nil
404 }
405
406 // SSHConfig is a wrapper on top of the GetSSHConfig method. It returns an
407 // api.SSHConfigResponse.
408 func (c *OfflineCA) SSHConfig(req *api.SSHConfigRequest) (*api.SSHConfigResponse, error) {
409 ts, err := c.authority.GetSSHConfig(context.Background(), req.Type, req.Data)
410 if err != nil {
411 return nil, err
412 }
413
414 var config api.SSHConfigResponse
415 switch req.Type {
416 case provisioner.SSHUserCert:
417 config.UserTemplates = ts
418 case provisioner.SSHHostCert:
419 config.UserTemplates = ts
420 default:
421 return nil, errors.New("it should hot get here")
422 }
423
424 return &config, nil
425 }
426
427 // SSHCheckHost is a wrapper on top of the CheckSSHHost method. It returns an
428 // api.SSHCheckPrincipalResponse.
429 func (c *OfflineCA) SSHCheckHost(principal string, tok string) (*api.SSHCheckPrincipalResponse, error) {
430 exists, err := c.authority.CheckSSHHost(context.Background(), principal, tok)
431 if err != nil {
432 return nil, err
433 }
434 return &api.SSHCheckPrincipalResponse{
435 Exists: exists,
436 }, nil
437 }
438
439 // SSHGetHosts is a wrapper on top of the CheckSSHHost method. It returns an
440 // api.SSHCheckPrincipalResponse.
441 func (c *OfflineCA) SSHGetHosts() (*api.SSHGetHostsResponse, error) {
442 hosts, err := c.authority.GetSSHHosts(context.Background(), nil)
443 if err != nil {
444 return nil, err
445 }
446 return &api.SSHGetHostsResponse{
447 Hosts: hosts,
448 }, nil
449 }
450
451 // SSHBastion is a wrapper on top of the GetSSHBastion method. It returns an
452 // api.SSHBastionResponse.
453 func (c *OfflineCA) SSHBastion(req *api.SSHBastionRequest) (*api.SSHBastionResponse, error) {
454 bastion, err := c.authority.GetSSHBastion(context.Background(), req.User, req.Hostname)
455 if err != nil {
456 return nil, err
457 }
458 return &api.SSHBastionResponse{
459 Hostname: req.Hostname,
460 Bastion: bastion,
461 }, nil
462 }
463
464 // GenerateToken creates the token used by the authority to authorize requests.
465 func (c *OfflineCA) GenerateToken(ctx *cli.Context, tokType int, subject string, sans []string, notBefore, notAfter time.Time, certNotBefore, certNotAfter provisioner.TimeDuration) (string, error) {
466 // Use ca.json configuration for the root and audience
467 root := c.Root()
468 audience := c.Audience(tokType)
469
470 // Get provisioner to use
471 provisioners := c.Provisioners()
472 p, err := provisionerPrompt(ctx, provisioners)
473 if err != nil {
474 return "", err
475 }
476
477 tokAttrs := tokenAttrs{
478 subject: subject,
479 root: root,
480 caURL: c.CaURL(),
481 audience: audience,
482 sans: sans,
483 notBefore: notBefore,
484 notAfter: notAfter,
485 certNotBefore: certNotBefore,
486 certNotAfter: certNotAfter,
487 }
488
489 switch p := p.(type) {
490 case *provisioner.OIDC: // Run step oauth.
491 return generateOIDCToken(ctx, p)
492 case *provisioner.X5C: // Get a JWT with an X5C header and signature.
493 return generateX5CToken(ctx, p, tokType, tokAttrs)
494 case *provisioner.SSHPOP: // Generate an SSHPOP token using ssh cert + key.
495 return generateSSHPOPToken(ctx, p, tokType, tokAttrs)
496 case *provisioner.K8sSA: // Get the Kubernetes service account token.
497 return generateK8sSAToken(ctx, p)
498 case *provisioner.GCP: // Do the identity request to get the token.
499 sharedContext.DisableCustomSANs = p.DisableCustomSANs
500 return p.GetIdentityToken(subject, c.CaURL())
501 case *provisioner.AWS: // Do the identity request to get the token.
502 sharedContext.DisableCustomSANs = p.DisableCustomSANs
503 return p.GetIdentityToken(subject, c.CaURL())
504 case *provisioner.Azure: // Do the identity request to get the token.
505 sharedContext.DisableCustomSANs = p.DisableCustomSANs
506 return p.GetIdentityToken(subject, c.CaURL())
507 case *provisioner.ACME: // Return an error with the provisioner ID.
508 return "", &ErrACMEToken{p.GetName()}
509 default: // Default is assumed to be a standard JWT.
510 jwkP, ok := p.(*provisioner.JWK)
511 if !ok {
512 return "", errors.Errorf("unknown provisioner type %T", p)
513 }
514 return generateJWKToken(ctx, jwkP, tokType, tokAttrs)
515 }
516 }