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
|
package cautils
import (
"fmt"
"net/url"
"strings"
"time"
"github.com/pkg/errors"
"github.com/smallstep/certificates/authority/provisioner"
"github.com/smallstep/certificates/pki"
"github.com/smallstep/cli/errs"
"github.com/smallstep/cli/flags"
"github.com/smallstep/cli/ui"
"github.com/smallstep/cli/utils"
"github.com/urfave/cli"
)
type provisionersSelect struct {
Name string
Provisioner provisioner.Interface
}
// Token signing types
const (
SignType = iota
RevokeType
SSHUserSignType
SSHHostSignType
SSHRevokeType
SSHRenewType
SSHRekeyType
)
// parseAudience creates the ca audience url from the ca-url
func parseAudience(ctx *cli.Context, tokType int) (string, error) {
caURL, err := flags.ParseCaURL(ctx)
if err != nil {
return "", err
}
audience, err := url.Parse(caURL)
if err != nil {
return "", errs.InvalidFlagValue(ctx, "ca-url", caURL, "")
}
switch strings.ToLower(audience.Scheme) {
case "https", "":
var path string
switch tokType {
// default
case SignType:
path = "/1.0/sign"
// revocation token
case RevokeType:
path = "/1.0/revoke"
case SSHUserSignType, SSHHostSignType:
path = "/1.0/ssh/sign"
case SSHRevokeType:
path = "/1.0/ssh/revoke"
case SSHRenewType:
path = "/1.0/ssh/renew"
case SSHRekeyType:
path = "/1.0/ssh/rekey"
default:
return "", errors.Errorf("unexpected token type: %d", tokType)
}
audience.Scheme = "https"
audience = audience.ResolveReference(&url.URL{Path: path})
return audience.String(), nil
default:
return "", errs.InvalidFlagValue(ctx, "ca-url", caURL, "")
}
}
// ErrACMEToken is the error type returned when the user attempts a Token Flow
// while using an ACME provisioner.
type ErrACMEToken struct {
Name string
}
// Error implements the error interface.
func (e *ErrACMEToken) Error() string {
return "step ACME provisioners do not support token auth flows"
}
// NewTokenFlow implements the common flow used to generate a token
func NewTokenFlow(ctx *cli.Context, tokType int, subject string, sans []string, caURL, root string, notBefore, notAfter time.Time, certNotBefore, certNotAfter provisioner.TimeDuration) (string, error) {
// Get audience from ca-url
audience, err := parseAudience(ctx, tokType)
if err != nil {
return "", err
}
provisioners, err := pki.GetProvisioners(caURL, root)
if err != nil {
return "", err
}
p, err := provisionerPrompt(ctx, provisioners)
if err != nil {
return "", err
}
tokAttrs := tokenAttrs{
subject: subject,
root: root,
caURL: caURL,
audience: audience,
sans: sans,
notBefore: notBefore,
notAfter: notAfter,
certNotBefore: certNotBefore,
certNotAfter: certNotAfter,
}
switch p := p.(type) {
case *provisioner.JWK: // Get the step standard JWT.
return generateJWKToken(ctx, p, tokType, tokAttrs)
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 a SSHPOP token using an 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, caURL)
case *provisioner.AWS: // Do the identity request to get the token.
sharedContext.DisableCustomSANs = p.DisableCustomSANs
return p.GetIdentityToken(subject, caURL)
case *provisioner.Azure: // Do the identity request to get the token.
sharedContext.DisableCustomSANs = p.DisableCustomSANs
return p.GetIdentityToken(subject, caURL)
case *provisioner.ACME: // Return an error with the provisioner ID.
return "", &ErrACMEToken{p.GetName()}
default:
return "", errors.Errorf("unknown provisioner type %T", p)
}
}
// NewIdentityTokenFlow implements the flow to generate a token using only an
// OIDC provisioner.
func NewIdentityTokenFlow(ctx *cli.Context, caURL, root string) (string, error) {
provisioners, err := pki.GetProvisioners(caURL, root)
if err != nil {
return "", err
}
provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool {
return p.GetType() == provisioner.TypeOIDC
})
p, err := provisionerPrompt(ctx, provisioners)
if err != nil {
return "", err
}
switch p := p.(type) {
case *provisioner.OIDC:
return generateOIDCToken(ctx, p)
default:
return "", errors.Errorf("bootstrap flow does not support the %s provisioner", p.GetType())
}
}
// OfflineTokenFlow generates a provisioning token using either
// 1. static configuration from ca.json (created with `step ca init`)
// 2. input from command line flags
// These two options are mutually exclusive and priority is given to ca.json.
func OfflineTokenFlow(ctx *cli.Context, typ int, subject string, sans []string, notBefore, notAfter time.Time, certNotBefore, certNotAfter provisioner.TimeDuration) (string, error) {
caConfig := ctx.String("ca-config")
if caConfig == "" {
return "", errs.InvalidFlagValue(ctx, "ca-config", "", "")
}
// Using the offline CA
if utils.FileExists(caConfig) {
offlineCA, err := NewOfflineCA(caConfig)
if err != nil {
return "", err
}
return offlineCA.GenerateToken(ctx, typ, subject, sans, notBefore, notAfter, certNotBefore, certNotAfter)
}
kid := ctx.String("kid")
issuer := ctx.String("issuer")
// Require issuer and keyFile if ca.json does not exists.
// kid can be passed or created using jwk.Thumbprint.
switch {
case len(issuer) == 0:
return "", errs.RequiredWithFlag(ctx, "offline", "issuer")
case len(ctx.String("key")) == 0:
return "", errs.RequiredWithFlag(ctx, "offline", "key")
}
// Get audience from ca-url
audience, err := parseAudience(ctx, typ)
if err != nil {
return "", err
}
// Get root from argument or default location
root := ctx.String("root")
if len(root) == 0 {
root = pki.GetRootCAPath()
if utils.FileExists(root) {
return "", errs.RequiredFlag(ctx, "root")
}
}
tokAttrs := tokenAttrs{
subject: subject,
root: root,
audience: audience,
issuer: issuer,
kid: kid,
sans: sans,
notBefore: notBefore,
notAfter: notAfter,
certNotBefore: certNotBefore,
certNotAfter: certNotAfter,
}
switch {
case ctx.IsSet("x5c-cert") || ctx.IsSet("x5c-key"):
return generateX5CToken(ctx, nil, typ, tokAttrs)
default:
return generateJWKToken(ctx, nil, typ, tokAttrs)
}
}
func allowX5CProvisionerFilter(p provisioner.Interface) bool {
return p.GetType() == provisioner.TypeX5C
}
func allowSSHPOPProvisionerFilter(p provisioner.Interface) bool {
return p.GetType() == provisioner.TypeSSHPOP
}
func allowK8sSAProvisionerFilter(p provisioner.Interface) bool {
return p.GetType() == provisioner.TypeK8sSA
}
func provisionerPrompt(ctx *cli.Context, provisioners provisioner.List) (provisioner.Interface, error) {
switch {
// If x5c flags then only list x5c provisioners.
case ctx.IsSet("x5c-cert") || ctx.IsSet("x5c-key"):
provisioners = provisionerFilter(provisioners, allowX5CProvisionerFilter)
// If sshpop flags then only list sshpop provisioners.
case ctx.IsSet("sshpop-cert") || ctx.IsSet("sshpop-key"):
provisioners = provisionerFilter(provisioners, allowSSHPOPProvisionerFilter)
// If k8ssa-token-path flag is set then we must be using the k8sSA provisioner.
case ctx.IsSet("k8ssa-token-path"):
provisioners = provisionerFilter(provisioners, allowK8sSAProvisionerFilter)
// List all available provisioners.
default:
provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool {
switch p.GetType() {
case provisioner.TypeJWK, provisioner.TypeX5C, provisioner.TypeOIDC,
provisioner.TypeACME, provisioner.TypeK8sSA, provisioner.TypeSSHPOP:
return true
case provisioner.TypeGCP, provisioner.TypeAWS, provisioner.TypeAzure:
return true
default:
return false
}
})
}
if len(provisioners) == 0 {
return nil, errors.New("cannot create a new token: the CA does not have any provisioner configured")
}
// Filter by kid
if kid := ctx.String("kid"); len(kid) != 0 {
provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool {
switch p := p.(type) {
case *provisioner.JWK:
return p.Key.KeyID == kid
case *provisioner.OIDC:
return p.ClientID == kid
default:
return false
}
})
if len(provisioners) == 0 {
return nil, errs.InvalidFlagValue(ctx, "kid", kid, "")
}
}
// Filter by issuer (provisioner name)
if issuer := ctx.String("issuer"); len(issuer) != 0 {
provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool {
return p.GetName() == issuer
})
if len(provisioners) == 0 {
return nil, errs.InvalidFlagValue(ctx, "issuer", issuer, "")
}
}
// Select provisioner
var items []*provisionersSelect
for _, prov := range provisioners {
switch p := prov.(type) {
case *provisioner.JWK:
items = append(items, &provisionersSelect{
Name: fmt.Sprintf("%s (%s) [kid: %s]", p.Name, p.GetType(), p.Key.KeyID),
Provisioner: p,
})
case *provisioner.OIDC:
items = append(items, &provisionersSelect{
Name: fmt.Sprintf("%s (%s) [client: %s]", p.Name, p.GetType(), p.ClientID),
Provisioner: p,
})
case *provisioner.Azure:
items = append(items, &provisionersSelect{
Name: fmt.Sprintf("%s (%s) [tenant: %s]", p.Name, p.GetType(), p.TenantID),
Provisioner: p,
})
case *provisioner.GCP, *provisioner.AWS, *provisioner.X5C, *provisioner.SSHPOP, *provisioner.ACME:
items = append(items, &provisionersSelect{
Name: fmt.Sprintf("%s (%s)", p.GetName(), p.GetType()),
Provisioner: p,
})
case *provisioner.K8sSA:
items = append(items, &provisionersSelect{
Name: fmt.Sprintf("%s (%s)", p.Name, p.GetType()),
Provisioner: p,
})
default:
continue
}
}
if len(items) == 1 {
if err := ui.PrintSelected("Provisioner", items[0].Name); err != nil {
return nil, err
}
return items[0].Provisioner, nil
}
i, _, err := ui.Select("What provisioner key do you want to use?", items, ui.WithSelectTemplates(ui.NamedSelectTemplates("Provisioner")))
if err != nil {
return nil, err
}
return items[i].Provisioner, nil
}
// provisionerFilter returns a slice of provisioners that pass the given filter.
func provisionerFilter(provisioners provisioner.List, f func(provisioner.Interface) bool) provisioner.List {
var result provisioner.List
for _, p := range provisioners {
if f(p) {
result = append(result, p)
}
}
return result
}
|