Debian Codegraph @

utils/cautils/token_flow.go

raw symbols SCIP
1 package cautils
2
3 import (
4 "fmt"
5 "net/url"
6 "strings"
7 "time"
8
9 "github.com/pkg/errors"
10 "github.com/smallstep/certificates/authority/provisioner"
11 "github.com/smallstep/certificates/pki"
12 "github.com/smallstep/cli/errs"
13 "github.com/smallstep/cli/flags"
14 "github.com/smallstep/cli/ui"
15 "github.com/smallstep/cli/utils"
16 "github.com/urfave/cli"
17 )
18
19 type provisionersSelect struct {
20 Name string
21 Provisioner provisioner.Interface
22 }
23
24 // Token signing types
25 const (
26 SignType = iota
27 RevokeType
28 SSHUserSignType
29 SSHHostSignType
30 SSHRevokeType
31 SSHRenewType
32 SSHRekeyType
33 )
34
35 // parseAudience creates the ca audience url from the ca-url
36 func parseAudience(ctx *cli.Context, tokType int) (string, error) {
37 caURL, err := flags.ParseCaURL(ctx)
38 if err != nil {
39 return "", err
40 }
41
42 audience, err := url.Parse(caURL)
43 if err != nil {
44 return "", errs.InvalidFlagValue(ctx, "ca-url", caURL, "")
45 }
46 switch strings.ToLower(audience.Scheme) {
47 case "https", "":
48 var path string
49 switch tokType {
50 // default
51 case SignType:
52 path = "/1.0/sign"
53 // revocation token
54 case RevokeType:
55 path = "/1.0/revoke"
56 case SSHUserSignType, SSHHostSignType:
57 path = "/1.0/ssh/sign"
58 case SSHRevokeType:
59 path = "/1.0/ssh/revoke"
60 case SSHRenewType:
61 path = "/1.0/ssh/renew"
62 case SSHRekeyType:
63 path = "/1.0/ssh/rekey"
64 default:
65 return "", errors.Errorf("unexpected token type: %d", tokType)
66 }
67 audience.Scheme = "https"
68 audience = audience.ResolveReference(&url.URL{Path: path})
69 return audience.String(), nil
70 default:
71 return "", errs.InvalidFlagValue(ctx, "ca-url", caURL, "")
72 }
73 }
74
75 // ErrACMEToken is the error type returned when the user attempts a Token Flow
76 // while using an ACME provisioner.
77 type ErrACMEToken struct {
78 Name string
79 }
80
81 // Error implements the error interface.
82 func (e *ErrACMEToken) Error() string {
83 return "step ACME provisioners do not support token auth flows"
84 }
85
86 // NewTokenFlow implements the common flow used to generate a token
87 func NewTokenFlow(ctx *cli.Context, tokType int, subject string, sans []string, caURL, root string, notBefore, notAfter time.Time, certNotBefore, certNotAfter provisioner.TimeDuration) (string, error) {
88 // Get audience from ca-url
89 audience, err := parseAudience(ctx, tokType)
90 if err != nil {
91 return "", err
92 }
93
94 provisioners, err := pki.GetProvisioners(caURL, root)
95 if err != nil {
96 return "", err
97 }
98 p, err := provisionerPrompt(ctx, provisioners)
99 if err != nil {
100 return "", err
101 }
102
103 tokAttrs := tokenAttrs{
104 subject: subject,
105 root: root,
106 caURL: caURL,
107 audience: audience,
108 sans: sans,
109 notBefore: notBefore,
110 notAfter: notAfter,
111 certNotBefore: certNotBefore,
112 certNotAfter: certNotAfter,
113 }
114
115 switch p := p.(type) {
116 case *provisioner.JWK: // Get the step standard JWT.
117 return generateJWKToken(ctx, p, tokType, tokAttrs)
118 case *provisioner.OIDC: // Run step oauth.
119 return generateOIDCToken(ctx, p)
120 case *provisioner.X5C: // Get a JWT with an X5C header and signature.
121 return generateX5CToken(ctx, p, tokType, tokAttrs)
122 case *provisioner.SSHPOP: // Generate a SSHPOP token using an ssh cert + key.
123 return generateSSHPOPToken(ctx, p, tokType, tokAttrs)
124 case *provisioner.K8sSA: // Get the Kubernetes service account token.
125 return generateK8sSAToken(ctx, p)
126 case *provisioner.GCP: // Do the identity request to get the token.
127 sharedContext.DisableCustomSANs = p.DisableCustomSANs
128 return p.GetIdentityToken(subject, caURL)
129 case *provisioner.AWS: // Do the identity request to get the token.
130 sharedContext.DisableCustomSANs = p.DisableCustomSANs
131 return p.GetIdentityToken(subject, caURL)
132 case *provisioner.Azure: // Do the identity request to get the token.
133 sharedContext.DisableCustomSANs = p.DisableCustomSANs
134 return p.GetIdentityToken(subject, caURL)
135 case *provisioner.ACME: // Return an error with the provisioner ID.
136 return "", &ErrACMEToken{p.GetName()}
137 default:
138 return "", errors.Errorf("unknown provisioner type %T", p)
139 }
140 }
141
142 // NewIdentityTokenFlow implements the flow to generate a token using only an
143 // OIDC provisioner.
144 func NewIdentityTokenFlow(ctx *cli.Context, caURL, root string) (string, error) {
145 provisioners, err := pki.GetProvisioners(caURL, root)
146 if err != nil {
147 return "", err
148 }
149 provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool {
150 return p.GetType() == provisioner.TypeOIDC
151 })
152 p, err := provisionerPrompt(ctx, provisioners)
153 if err != nil {
154 return "", err
155 }
156 switch p := p.(type) {
157 case *provisioner.OIDC:
158 return generateOIDCToken(ctx, p)
159 default:
160 return "", errors.Errorf("bootstrap flow does not support the %s provisioner", p.GetType())
161 }
162 }
163
164 // OfflineTokenFlow generates a provisioning token using either
165 // 1. static configuration from ca.json (created with `step ca init`)
166 // 2. input from command line flags
167 // These two options are mutually exclusive and priority is given to ca.json.
168 func OfflineTokenFlow(ctx *cli.Context, typ int, subject string, sans []string, notBefore, notAfter time.Time, certNotBefore, certNotAfter provisioner.TimeDuration) (string, error) {
169 caConfig := ctx.String("ca-config")
170 if caConfig == "" {
171 return "", errs.InvalidFlagValue(ctx, "ca-config", "", "")
172 }
173
174 // Using the offline CA
175 if utils.FileExists(caConfig) {
176 offlineCA, err := NewOfflineCA(caConfig)
177 if err != nil {
178 return "", err
179 }
180 return offlineCA.GenerateToken(ctx, typ, subject, sans, notBefore, notAfter, certNotBefore, certNotAfter)
181 }
182
183 kid := ctx.String("kid")
184 issuer := ctx.String("issuer")
185
186 // Require issuer and keyFile if ca.json does not exists.
187 // kid can be passed or created using jwk.Thumbprint.
188 switch {
189 case len(issuer) == 0:
190 return "", errs.RequiredWithFlag(ctx, "offline", "issuer")
191 case len(ctx.String("key")) == 0:
192 return "", errs.RequiredWithFlag(ctx, "offline", "key")
193 }
194
195 // Get audience from ca-url
196 audience, err := parseAudience(ctx, typ)
197 if err != nil {
198 return "", err
199 }
200
201 // Get root from argument or default location
202 root := ctx.String("root")
203 if len(root) == 0 {
204 root = pki.GetRootCAPath()
205 if utils.FileExists(root) {
206 return "", errs.RequiredFlag(ctx, "root")
207 }
208 }
209
210 tokAttrs := tokenAttrs{
211 subject: subject,
212 root: root,
213 audience: audience,
214 issuer: issuer,
215 kid: kid,
216 sans: sans,
217 notBefore: notBefore,
218 notAfter: notAfter,
219 certNotBefore: certNotBefore,
220 certNotAfter: certNotAfter,
221 }
222
223 switch {
224 case ctx.IsSet("x5c-cert") || ctx.IsSet("x5c-key"):
225 return generateX5CToken(ctx, nil, typ, tokAttrs)
226 default:
227 return generateJWKToken(ctx, nil, typ, tokAttrs)
228 }
229 }
230
231 func allowX5CProvisionerFilter(p provisioner.Interface) bool {
232 return p.GetType() == provisioner.TypeX5C
233 }
234
235 func allowSSHPOPProvisionerFilter(p provisioner.Interface) bool {
236 return p.GetType() == provisioner.TypeSSHPOP
237 }
238
239 func allowK8sSAProvisionerFilter(p provisioner.Interface) bool {
240 return p.GetType() == provisioner.TypeK8sSA
241 }
242
243 func provisionerPrompt(ctx *cli.Context, provisioners provisioner.List) (provisioner.Interface, error) {
244 switch {
245 // If x5c flags then only list x5c provisioners.
246 case ctx.IsSet("x5c-cert") || ctx.IsSet("x5c-key"):
247 provisioners = provisionerFilter(provisioners, allowX5CProvisionerFilter)
248 // If sshpop flags then only list sshpop provisioners.
249 case ctx.IsSet("sshpop-cert") || ctx.IsSet("sshpop-key"):
250 provisioners = provisionerFilter(provisioners, allowSSHPOPProvisionerFilter)
251 // If k8ssa-token-path flag is set then we must be using the k8sSA provisioner.
252 case ctx.IsSet("k8ssa-token-path"):
253 provisioners = provisionerFilter(provisioners, allowK8sSAProvisionerFilter)
254 // List all available provisioners.
255 default:
256 provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool {
257 switch p.GetType() {
258 case provisioner.TypeJWK, provisioner.TypeX5C, provisioner.TypeOIDC,
259 provisioner.TypeACME, provisioner.TypeK8sSA, provisioner.TypeSSHPOP:
260 return true
261 case provisioner.TypeGCP, provisioner.TypeAWS, provisioner.TypeAzure:
262 return true
263 default:
264 return false
265 }
266 })
267 }
268
269 if len(provisioners) == 0 {
270 return nil, errors.New("cannot create a new token: the CA does not have any provisioner configured")
271 }
272
273 // Filter by kid
274 if kid := ctx.String("kid"); len(kid) != 0 {
275 provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool {
276 switch p := p.(type) {
277 case *provisioner.JWK:
278 return p.Key.KeyID == kid
279 case *provisioner.OIDC:
280 return p.ClientID == kid
281 default:
282 return false
283 }
284 })
285 if len(provisioners) == 0 {
286 return nil, errs.InvalidFlagValue(ctx, "kid", kid, "")
287 }
288 }
289
290 // Filter by issuer (provisioner name)
291 if issuer := ctx.String("issuer"); len(issuer) != 0 {
292 provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool {
293 return p.GetName() == issuer
294 })
295 if len(provisioners) == 0 {
296 return nil, errs.InvalidFlagValue(ctx, "issuer", issuer, "")
297 }
298 }
299
300 // Select provisioner
301 var items []*provisionersSelect
302 for _, prov := range provisioners {
303 switch p := prov.(type) {
304 case *provisioner.JWK:
305 items = append(items, &provisionersSelect{
306 Name: fmt.Sprintf("%s (%s) [kid: %s]", p.Name, p.GetType(), p.Key.KeyID),
307 Provisioner: p,
308 })
309 case *provisioner.OIDC:
310 items = append(items, &provisionersSelect{
311 Name: fmt.Sprintf("%s (%s) [client: %s]", p.Name, p.GetType(), p.ClientID),
312 Provisioner: p,
313 })
314 case *provisioner.Azure:
315 items = append(items, &provisionersSelect{
316 Name: fmt.Sprintf("%s (%s) [tenant: %s]", p.Name, p.GetType(), p.TenantID),
317 Provisioner: p,
318 })
319 case *provisioner.GCP, *provisioner.AWS, *provisioner.X5C, *provisioner.SSHPOP, *provisioner.ACME:
320 items = append(items, &provisionersSelect{
321 Name: fmt.Sprintf("%s (%s)", p.GetName(), p.GetType()),
322 Provisioner: p,
323 })
324 case *provisioner.K8sSA:
325 items = append(items, &provisionersSelect{
326 Name: fmt.Sprintf("%s (%s)", p.Name, p.GetType()),
327 Provisioner: p,
328 })
329 default:
330 continue
331 }
332 }
333
334 if len(items) == 1 {
335 if err := ui.PrintSelected("Provisioner", items[0].Name); err != nil {
336 return nil, err
337 }
338 return items[0].Provisioner, nil
339 }
340
341 i, _, err := ui.Select("What provisioner key do you want to use?", items, ui.WithSelectTemplates(ui.NamedSelectTemplates("Provisioner")))
342 if err != nil {
343 return nil, err
344 }
345
346 return items[i].Provisioner, nil
347 }
348
349 // provisionerFilter returns a slice of provisioners that pass the given filter.
350 func provisionerFilter(provisioners provisioner.List, f func(provisioner.Interface) bool) provisioner.List {
351 var result provisioner.List
352 for _, p := range provisioners {
353 if f(p) {
354 result = append(result, p)
355 }
356 }
357 return result
358 }