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
|
package cautils
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"net/http"
"time"
"github.com/pkg/errors"
"github.com/smallstep/certificates/api"
"github.com/smallstep/certificates/authority"
"github.com/smallstep/certificates/authority/provisioner"
"github.com/smallstep/cli/crypto/pemutil"
"github.com/smallstep/cli/crypto/x509util"
"github.com/smallstep/cli/utils"
"github.com/urfave/cli"
"golang.org/x/crypto/ssh"
)
// OfflineCA is a wrapper on top of the certificates authority methods that is
// used to sign certificates without an online CA.
type OfflineCA struct {
authority *authority.Authority
config authority.Config
configFile string
}
// offlineInstance is a singleton used for OfflineCA. The use of a singleton is
// necessary to avoid double initialization. Double initializations are
// sometimes not possible due to locks - as seen in badgerDB
var offlineInstance *OfflineCA
// NewOfflineCA initializes an offlineCA.
func NewOfflineCA(configFile string) (*OfflineCA, error) {
if offlineInstance != nil {
return offlineInstance, nil
}
b, err := utils.ReadFile(configFile)
if err != nil {
return nil, err
}
var config authority.Config
if err = json.Unmarshal(b, &config); err != nil {
return nil, errors.Wrapf(err, "error reading %s", configFile)
}
if config.AuthorityConfig == nil || len(config.AuthorityConfig.Provisioners) == 0 {
return nil, errors.Errorf("error parsing %s: no provisioners found", configFile)
}
auth, err := authority.New(&config)
if err != nil {
return nil, err
}
offlineInstance = &OfflineCA{
authority: auth,
config: config,
configFile: configFile,
}
return offlineInstance, nil
}
// GetRootCAs return the cert pool for the ca, as it's an offline ca, a pool is
// not required and it always returns nil.
func (c *OfflineCA) GetRootCAs() *x509.CertPool {
return nil
}
// VerifyClientCert verifies and validates the client cert/key pair
// using the offline CA root and intermediate certificates.
func (c *OfflineCA) VerifyClientCert(certFile, keyFile string) error {
cert, err := pemutil.ReadCertificate(certFile, pemutil.WithFirstBlock())
if err != nil {
return err
}
key, err := pemutil.Read(keyFile)
if err != nil {
return err
}
certPem, err := pemutil.Serialize(cert)
if err != nil {
return err
}
keyPem, err := pemutil.Serialize(key)
if err != nil {
return err
}
// Validate that the certificate and key match
if _, err = tls.X509KeyPair(pem.EncodeToMemory(certPem), pem.EncodeToMemory(keyPem)); err != nil {
return errors.Wrap(err, "error loading x509 key pair")
}
rootPool, err := x509util.ReadCertPool(c.Root())
if err != nil {
return err
}
intermediatePool, err := x509util.ReadCertPool(c.config.IntermediateCert)
if err != nil {
return err
}
opts := x509.VerifyOptions{
Roots: rootPool,
Intermediates: intermediatePool,
}
if _, err = cert.Verify(opts); err != nil {
return errors.Wrapf(err, "failed to verify certificate")
}
return nil
}
// Audience returns the token audience.
func (c *OfflineCA) Audience(tokType int) string {
switch tokType {
case RevokeType:
return fmt.Sprintf("https://%s/revoke", c.config.DNSNames[0])
case SSHUserSignType, SSHHostSignType:
return fmt.Sprintf("https://%s/ssh/sign", c.config.DNSNames[0])
case SSHRenewType:
return fmt.Sprintf("https://%s/ssh/renew", c.config.DNSNames[0])
case SSHRevokeType:
return fmt.Sprintf("https://%s/ssh/revoke", c.config.DNSNames[0])
case SSHRekeyType:
return fmt.Sprintf("https://%s/ssh/rekey", c.config.DNSNames[0])
default:
return fmt.Sprintf("https://%s/sign", c.config.DNSNames[0])
}
}
// CaURL returns the CA URL using the first DNS entry.
func (c *OfflineCA) CaURL() string {
return fmt.Sprintf("https://%s", c.config.DNSNames[0])
}
// Root returns the path of the file used as root certificate.
func (c *OfflineCA) Root() string {
return c.config.Root.First()
}
// Provisioners returns the list of configured provisioners.
func (c *OfflineCA) Provisioners() provisioner.List {
return c.config.AuthorityConfig.Provisioners
}
func certChainToPEM(certChain []*x509.Certificate) []api.Certificate {
certChainPEM := make([]api.Certificate, 0, len(certChain))
for _, c := range certChain {
certChainPEM = append(certChainPEM, api.Certificate{Certificate: c})
}
return certChainPEM
}
// Version is a wrapper on top of the Version method. It returns
// an api.VersionResponse.
func (c *OfflineCA) Version() (*api.VersionResponse, error) {
v := c.authority.Version()
return &api.VersionResponse{
Version: v.Version,
RequireClientAuthentication: v.RequireClientAuthentication,
}, nil
}
// Sign is a wrapper on top of certificates Authorize and Sign methods. It
// returns an api.SignResponse with the requested certificate and the
// intermediate.
func (c *OfflineCA) Sign(req *api.SignRequest) (*api.SignResponse, error) {
ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SignMethod)
opts, err := c.authority.Authorize(ctx, req.OTT)
if err != nil {
return nil, err
}
signOpts := provisioner.SignOptions{
NotBefore: req.NotBefore,
NotAfter: req.NotAfter,
}
certChain, err := c.authority.Sign(req.CsrPEM.CertificateRequest, signOpts, opts...)
if err != nil {
return nil, err
}
certChainPEM := certChainToPEM(certChain)
var caPEM api.Certificate
if len(certChainPEM) > 1 {
caPEM = certChainPEM[1]
}
return &api.SignResponse{
ServerPEM: certChainPEM[0],
CaPEM: caPEM,
CertChainPEM: certChainPEM,
TLSOptions: c.authority.GetTLSOptions(),
}, nil
}
// Renew is a wrapper on top of certificates Renew method. It returns an
// api.SignResponse with the requested certificate and the intermediate.
func (c *OfflineCA) Renew(rt http.RoundTripper) (*api.SignResponse, error) {
// it should not panic as this is always internal code
tr := rt.(*http.Transport)
asn1Data := tr.TLSClientConfig.Certificates[0].Certificate[0]
peer, err := x509.ParseCertificate(asn1Data)
if err != nil {
return nil, errors.Wrap(err, "error parsing certificate")
}
// renew cert using authority
certChain, err := c.authority.Renew(peer)
if err != nil {
return nil, err
}
certChainPEM := certChainToPEM(certChain)
var caPEM api.Certificate
if len(certChainPEM) > 1 {
caPEM = certChainPEM[1]
}
return &api.SignResponse{
ServerPEM: certChainPEM[0],
CaPEM: caPEM,
CertChainPEM: certChainPEM,
TLSOptions: c.authority.GetTLSOptions(),
}, nil
}
// Revoke is a wrapper on top of certificates Revoke method. It returns an
// api.RevokeResponse.
func (c *OfflineCA) Revoke(req *api.RevokeRequest, rt http.RoundTripper) (*api.RevokeResponse, error) {
var (
opts = authority.RevokeOptions{
Serial: req.Serial,
Reason: req.Reason,
ReasonCode: req.ReasonCode,
PassiveOnly: req.Passive,
}
ctx = provisioner.NewContextWithMethod(context.Background(), provisioner.RevokeMethod)
err error
)
if len(req.OTT) > 0 {
opts.OTT = req.OTT
opts.MTLS = false
if _, err = c.authority.Authorize(ctx, opts.OTT); err != nil {
return nil, err
}
} else {
// it should not panic as this is always internal code
tr := rt.(*http.Transport)
asn1Data := tr.TLSClientConfig.Certificates[0].Certificate[0]
opts.Crt, err = x509.ParseCertificate(asn1Data)
if err != nil {
return nil, errors.Wrap(err, "error parsing certificate")
}
opts.MTLS = true
}
// revoke cert using authority
if err := c.authority.Revoke(ctx, &opts); err != nil {
return nil, err
}
return &api.RevokeResponse{Status: "ok"}, nil
}
// SSHSign is a wrapper on top of certificate Authorize and SignSSH methods. It
// returns an api.SSHSignResponse with the signed certificate.
func (c *OfflineCA) SSHSign(req *api.SSHSignRequest) (*api.SSHSignResponse, error) {
publicKey, err := ssh.ParsePublicKey(req.PublicKey)
if err != nil {
return nil, errors.Wrap(err, "error parsing publicKey")
}
ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SSHSignMethod)
opts, err := c.authority.Authorize(ctx, req.OTT)
if err != nil {
return nil, err
}
signOpts := provisioner.SignSSHOptions{
CertType: req.CertType,
KeyID: req.KeyID,
Principals: req.Principals,
ValidAfter: req.ValidAfter,
ValidBefore: req.ValidBefore,
TemplateData: req.TemplateData,
}
cert, err := c.authority.SignSSH(context.Background(), publicKey, signOpts, opts...)
if err != nil {
return nil, err
}
return &api.SSHSignResponse{
Certificate: api.SSHCertificate{
Certificate: cert,
},
}, nil
}
// SSHRevoke is a wrapper on top of certificates SSHRevoke method. It returns an
// api.SSHRevokeResponse.
func (c *OfflineCA) SSHRevoke(req *api.SSHRevokeRequest) (*api.SSHRevokeResponse, error) {
opts := authority.RevokeOptions{
Serial: req.Serial,
Reason: req.Reason,
ReasonCode: req.ReasonCode,
PassiveOnly: req.Passive,
OTT: req.OTT,
MTLS: false,
}
ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SSHRevokeMethod)
if _, err := c.authority.Authorize(ctx, opts.OTT); err != nil {
return nil, err
}
if err := c.authority.Revoke(ctx, &opts); err != nil {
return nil, err
}
return &api.SSHRevokeResponse{Status: "ok"}, nil
}
// SSHRenew is a wrapper on top of certificates SSHRenew method. It returns an
// api.SSHRenewResponse.
func (c *OfflineCA) SSHRenew(req *api.SSHRenewRequest) (*api.SSHRenewResponse, error) {
ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SSHRenewMethod)
_, err := c.authority.Authorize(ctx, req.OTT)
if err != nil {
return nil, err
}
oldCert, _, err := provisioner.ExtractSSHPOPCert(req.OTT)
if err != nil {
return nil, err
}
cert, err := c.authority.RenewSSH(context.Background(), oldCert)
if err != nil {
return nil, err
}
return &api.SSHRenewResponse{Certificate: api.SSHCertificate{Certificate: cert}}, nil
}
// SSHRekey is a wrapper on top of certificates SSHRekey method. It returns an
// api.SSHRekeyResponse.
func (c *OfflineCA) SSHRekey(req *api.SSHRekeyRequest) (*api.SSHRekeyResponse, error) {
ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SSHRekeyMethod)
signOpts, err := c.authority.Authorize(ctx, req.OTT)
if err != nil {
return nil, err
}
oldCert, _, err := provisioner.ExtractSSHPOPCert(req.OTT)
if err != nil {
return nil, err
}
sshPub, err := ssh.ParsePublicKey(req.PublicKey)
if err != nil {
return nil, err
}
cert, err := c.authority.RekeySSH(context.Background(), oldCert, sshPub, signOpts...)
if err != nil {
return nil, err
}
return &api.SSHRekeyResponse{Certificate: api.SSHCertificate{Certificate: cert}}, nil
}
// SSHRoots is a wrapper on top of the GetSSHRoots method. It returns an
// api.SSHRootsResponse.
func (c *OfflineCA) SSHRoots() (*api.SSHRootsResponse, error) {
keys, err := c.authority.GetSSHRoots(context.Background())
if err != nil {
return nil, err
}
resp := new(api.SSHRootsResponse)
for _, k := range keys.HostKeys {
resp.HostKeys = append(resp.HostKeys, api.SSHPublicKey{PublicKey: k})
}
for _, k := range keys.UserKeys {
resp.UserKeys = append(resp.UserKeys, api.SSHPublicKey{PublicKey: k})
}
return resp, nil
}
// SSHFederation is a wrapper on top of the GetSSHFederation method. It returns
// an api.SSHRootsResponse.
func (c *OfflineCA) SSHFederation() (*api.SSHRootsResponse, error) {
keys, err := c.authority.GetSSHFederation(context.Background())
if err != nil {
return nil, err
}
resp := new(api.SSHRootsResponse)
for _, k := range keys.HostKeys {
resp.HostKeys = append(resp.HostKeys, api.SSHPublicKey{PublicKey: k})
}
for _, k := range keys.UserKeys {
resp.UserKeys = append(resp.UserKeys, api.SSHPublicKey{PublicKey: k})
}
return resp, nil
}
// SSHConfig is a wrapper on top of the GetSSHConfig method. It returns an
// api.SSHConfigResponse.
func (c *OfflineCA) SSHConfig(req *api.SSHConfigRequest) (*api.SSHConfigResponse, error) {
ts, err := c.authority.GetSSHConfig(context.Background(), req.Type, req.Data)
if err != nil {
return nil, err
}
var config api.SSHConfigResponse
switch req.Type {
case provisioner.SSHUserCert:
config.UserTemplates = ts
case provisioner.SSHHostCert:
config.UserTemplates = ts
default:
return nil, errors.New("it should hot get here")
}
return &config, nil
}
// SSHCheckHost is a wrapper on top of the CheckSSHHost method. It returns an
// api.SSHCheckPrincipalResponse.
func (c *OfflineCA) SSHCheckHost(principal string, tok string) (*api.SSHCheckPrincipalResponse, error) {
exists, err := c.authority.CheckSSHHost(context.Background(), principal, tok)
if err != nil {
return nil, err
}
return &api.SSHCheckPrincipalResponse{
Exists: exists,
}, nil
}
// SSHGetHosts is a wrapper on top of the CheckSSHHost method. It returns an
// api.SSHCheckPrincipalResponse.
func (c *OfflineCA) SSHGetHosts() (*api.SSHGetHostsResponse, error) {
hosts, err := c.authority.GetSSHHosts(context.Background(), nil)
if err != nil {
return nil, err
}
return &api.SSHGetHostsResponse{
Hosts: hosts,
}, nil
}
// SSHBastion is a wrapper on top of the GetSSHBastion method. It returns an
// api.SSHBastionResponse.
func (c *OfflineCA) SSHBastion(req *api.SSHBastionRequest) (*api.SSHBastionResponse, error) {
bastion, err := c.authority.GetSSHBastion(context.Background(), req.User, req.Hostname)
if err != nil {
return nil, err
}
return &api.SSHBastionResponse{
Hostname: req.Hostname,
Bastion: bastion,
}, nil
}
// GenerateToken creates the token used by the authority to authorize requests.
func (c *OfflineCA) GenerateToken(ctx *cli.Context, tokType int, subject string, sans []string, notBefore, notAfter time.Time, certNotBefore, certNotAfter provisioner.TimeDuration) (string, error) {
// Use ca.json configuration for the root and audience
root := c.Root()
audience := c.Audience(tokType)
// Get provisioner to use
provisioners := c.Provisioners()
p, err := provisionerPrompt(ctx, provisioners)
if err != nil {
return "", err
}
tokAttrs := tokenAttrs{
subject: subject,
root: root,
caURL: c.CaURL(),
audience: audience,
sans: sans,
notBefore: notBefore,
notAfter: notAfter,
certNotBefore: certNotBefore,
certNotAfter: certNotAfter,
}
switch p := p.(type) {
case *provisioner.OIDC: // Run step oauth.
return generateOIDCToken(ctx, p)
case *provisioner.X5C: // Get a JWT with an X5C header and signature.
return generateX5CToken(ctx, p, tokType, tokAttrs)
case *provisioner.SSHPOP: // Generate an SSHPOP token using ssh cert + key.
return generateSSHPOPToken(ctx, p, tokType, tokAttrs)
case *provisioner.K8sSA: // Get the Kubernetes service account token.
return generateK8sSAToken(ctx, p)
case *provisioner.GCP: // Do the identity request to get the token.
sharedContext.DisableCustomSANs = p.DisableCustomSANs
return p.GetIdentityToken(subject, c.CaURL())
case *provisioner.AWS: // Do the identity request to get the token.
sharedContext.DisableCustomSANs = p.DisableCustomSANs
return p.GetIdentityToken(subject, c.CaURL())
case *provisioner.Azure: // Do the identity request to get the token.
sharedContext.DisableCustomSANs = p.DisableCustomSANs
return p.GetIdentityToken(subject, c.CaURL())
case *provisioner.ACME: // Return an error with the provisioner ID.
return "", &ErrACMEToken{p.GetName()}
default: // Default is assumed to be a standard JWT.
jwkP, ok := p.(*provisioner.JWK)
if !ok {
return "", errors.Errorf("unknown provisioner type %T", p)
}
return generateJWKToken(ctx, jwkP, tokType, tokAttrs)
}
}
|