Debian Codegraph @

utils/cautils/token_generator.go

raw symbols SCIP
1 package cautils
2
3 import (
4 "crypto"
5 "encoding/base64"
6 "encoding/json"
7 "fmt"
8 "io/ioutil"
9 "strings"
10 "time"
11
12 "github.com/pkg/errors"
13 "github.com/smallstep/certificates/authority/provisioner"
14 "github.com/smallstep/certificates/pki"
15 "github.com/smallstep/cli/crypto/randutil"
16 "github.com/smallstep/cli/errs"
17 "github.com/smallstep/cli/exec"
18 "github.com/smallstep/cli/jose"
19 "github.com/smallstep/cli/token"
20 "github.com/smallstep/cli/token/provision"
21 "github.com/smallstep/cli/ui"
22 "github.com/urfave/cli"
23 )
24
25 // TokenGenerator is a helper used to generate different types of tokens used in
26 // the CA.
27 type TokenGenerator struct {
28 kid, iss, aud string
29 root string
30 notBefore, notAfter time.Time
31 jwk *jose.JSONWebKey
32 }
33
34 // NewTokenGenerator initializes a new token generator with the common fields.
35 func NewTokenGenerator(kid, iss, aud, root string, notBefore, notAfter time.Time, jwk *jose.JSONWebKey) *TokenGenerator {
36 return &TokenGenerator{
37 kid: kid,
38 iss: iss,
39 aud: aud,
40 root: root,
41 notBefore: notBefore,
42 notAfter: notAfter,
43 jwk: jwk,
44 }
45 }
46
47 // Token generates a generic token with the given subject and options.
48 func (t *TokenGenerator) Token(sub string, opts ...token.Options) (string, error) {
49 // A random jwt id will be used to identify duplicated tokens
50 jwtID, err := randutil.Hex(64) // 256 bits
51 if err != nil {
52 return "", err
53 }
54
55 tokOptions := []token.Options{
56 token.WithJWTID(jwtID),
57 token.WithKid(t.kid),
58 token.WithIssuer(t.iss),
59 token.WithAudience(t.aud),
60 }
61 if len(t.root) > 0 {
62 tokOptions = append(tokOptions, token.WithRootCA(t.root))
63 }
64
65 // Add custom options
66 tokOptions = append(tokOptions, opts...)
67
68 // Add token validity
69 notBefore, notAfter := t.notBefore, t.notAfter
70 if !notBefore.IsZero() || !notAfter.IsZero() {
71 if notBefore.IsZero() {
72 notBefore = time.Now()
73 }
74 if notAfter.IsZero() {
75 notAfter = notBefore.Add(token.DefaultValidity)
76 }
77 tokOptions = append(tokOptions, token.WithValidity(notBefore, notAfter))
78 }
79
80 tok, err := provision.New(sub, tokOptions...)
81 if err != nil {
82 return "", err
83 }
84
85 return tok.SignedString(t.jwk.Algorithm, t.jwk.Key)
86 }
87
88 // SignToken generates a X.509 certificate signing token. If sans is empty, we
89 // will use the subject (common name) as the only SAN.
90 func (t *TokenGenerator) SignToken(sub string, sans []string, opts ...token.Options) (string, error) {
91 if len(sans) == 0 {
92 sans = []string{sub}
93 }
94 opts = append(opts, token.WithSANS(sans))
95 return t.Token(sub, opts...)
96 }
97
98 // RevokeToken generates a X.509 certificate revoke token.
99 func (t *TokenGenerator) RevokeToken(sub string, opts ...token.Options) (string, error) {
100 return t.Token(sub, opts...)
101 }
102
103 // SignSSHToken generates a SSH certificate signing token.
104 func (t *TokenGenerator) SignSSHToken(sub, certType string, principals []string, notBefore, notAfter provisioner.TimeDuration, opts ...token.Options) (string, error) {
105 opts = append([]token.Options{token.WithSSH(provisioner.SignSSHOptions{
106 CertType: certType,
107 KeyID: sub,
108 Principals: principals,
109 ValidAfter: notBefore,
110 ValidBefore: notAfter,
111 })}, opts...)
112 return t.Token(sub, opts...)
113 }
114
115 // generateOIDCToken performs the necessary protocol to retrieve an OIDC token
116 // using a configured provisioner.
117 func generateOIDCToken(ctx *cli.Context, p *provisioner.OIDC) (string, error) {
118 args := []string{"oauth", "--oidc", "--bare",
119 "--provider", p.ConfigurationEndpoint,
120 "--client-id", p.ClientID, "--client-secret", p.ClientSecret}
121 if ctx.Bool("console") {
122 args = append(args, "--console")
123 }
124 if p.ListenAddress != "" {
125 args = append(args, "--listen", p.ListenAddress)
126 }
127 out, err := exec.Step(args...)
128 if err != nil {
129 return "", err
130 }
131 return strings.TrimSpace(string(out)), nil
132 }
133
134 type tokenAttrs struct {
135 subject string
136 root string
137 caURL string
138 audience string
139 issuer string
140 kid string
141 sans []string
142 notBefore, notAfter time.Time
143 certNotBefore, certNotAfter provisioner.TimeDuration
144 }
145
146 func generateK8sSAToken(ctx *cli.Context, p *provisioner.K8sSA) (string, error) {
147 path := ctx.String("k8ssa-token-path")
148 if len(path) == 0 {
149 path = "/var/run/secrets/kubernetes.io/serviceaccount/token"
150 }
151 tokBytes, err := ioutil.ReadFile(path)
152 if err != nil {
153 return "", errors.Wrap(err, "error reading kubernetes service account token")
154 }
155 return string(tokBytes), nil
156 }
157
158 func generateX5CToken(ctx *cli.Context, p *provisioner.X5C, tokType int, tokAttrs tokenAttrs) (string, error) {
159 x5cCertFile := ctx.String("x5c-cert")
160 x5cKeyFile := ctx.String("x5c-key")
161 if len(x5cCertFile) == 0 {
162 return "", errs.RequiredWithProvisionerTypeFlag(ctx, "X5C", "x5c-cert")
163 }
164 if len(x5cKeyFile) == 0 {
165 return "", errs.RequiredWithProvisionerTypeFlag(ctx, "X5C", "x5c-key")
166 }
167
168 // Get private key from given key file
169 var opts []jose.Option
170 if passwordFile := ctx.String("password-file"); len(passwordFile) != 0 {
171 opts = append(opts, jose.WithPasswordFile(passwordFile))
172 }
173 jwk, err := jose.ParseKey(x5cKeyFile, opts...)
174 if err != nil {
175 return "", err
176 }
177 tokenGen := NewTokenGenerator(jwk.KeyID, p.Name,
178 fmt.Sprintf("%s#%s", tokAttrs.audience, p.GetID()), tokAttrs.root,
179 tokAttrs.notBefore, tokAttrs.notAfter, jwk)
180 switch tokType {
181 case SignType:
182 return tokenGen.SignToken(tokAttrs.subject, tokAttrs.sans, token.WithX5CFile(x5cCertFile, jwk.Key))
183 case RevokeType:
184 return tokenGen.RevokeToken(tokAttrs.subject, token.WithX5CFile(x5cCertFile, jwk.Key))
185 case SSHUserSignType:
186 return tokenGen.SignSSHToken(tokAttrs.subject, provisioner.SSHUserCert, tokAttrs.sans,
187 tokAttrs.certNotBefore, tokAttrs.certNotAfter, token.WithX5CFile(x5cCertFile, jwk.Key))
188 case SSHHostSignType:
189 return tokenGen.SignSSHToken(tokAttrs.subject, provisioner.SSHHostCert, tokAttrs.sans,
190 tokAttrs.certNotBefore, tokAttrs.certNotAfter, token.WithX5CFile(x5cCertFile, jwk.Key))
191 default:
192 return tokenGen.Token(tokAttrs.subject, token.WithX5CFile(x5cCertFile, jwk.Key))
193 }
194 }
195
196 func generateSSHPOPToken(ctx *cli.Context, p *provisioner.SSHPOP, tokType int, tokAttrs tokenAttrs) (string, error) {
197 sshPOPCertFile := ctx.String("sshpop-cert")
198 sshPOPKeyFile := ctx.String("sshpop-key")
199 if len(sshPOPCertFile) == 0 {
200 return "", errs.RequiredWithProvisionerTypeFlag(ctx, "SSHPOP", "sshpop-cert")
201 }
202 if len(sshPOPKeyFile) == 0 {
203 return "", errs.RequiredWithProvisionerTypeFlag(ctx, "SSHPOP", "sshpop-key")
204 }
205
206 // Get private key from given key file
207 var opts []jose.Option
208 if passwordFile := ctx.String("password-file"); len(passwordFile) != 0 {
209 opts = append(opts, jose.WithPasswordFile(passwordFile))
210 }
211 jwk, err := jose.ParseKey(sshPOPKeyFile, opts...)
212 if err != nil {
213 return "", err
214 }
215 tokenGen := NewTokenGenerator(jwk.KeyID, p.Name,
216 fmt.Sprintf("%s#%s", tokAttrs.audience, p.GetID()), tokAttrs.root,
217 tokAttrs.notBefore, tokAttrs.notAfter, jwk)
218 switch tokType {
219 case SSHRevokeType:
220 return tokenGen.Token(tokAttrs.subject, token.WithSSHPOPFile(sshPOPCertFile, jwk.Key))
221 case SSHRenewType:
222 return tokenGen.Token(tokAttrs.subject, token.WithSSHPOPFile(sshPOPCertFile, jwk.Key))
223 case SSHRekeyType:
224 return tokenGen.Token(tokAttrs.subject, token.WithSSHPOPFile(sshPOPCertFile, jwk.Key))
225 default:
226 return "", errors.Errorf("unexpected requested token type for SSHPOP token: %d", tokType)
227 }
228 }
229
230 // loadJWK loads a JWK based on the following system:
231 // 1. If a private key is specified on the command line, then load the JWK from
232 // that private key.
233 // 2. No private key was given on the command line. We'll need to use the
234 // provided provisioner to load a signing key.
235 // a) Offline-mode: load the JWK directly from the provisioner in the CA-config.
236 // b) Online-mode: get the provisioner private key from the CA.
237 func loadJWK(ctx *cli.Context, p *provisioner.JWK, tokAttrs tokenAttrs) (jwk *jose.JSONWebKey, kid string, err error) {
238 var opts []jose.Option
239 switch {
240 case ctx.String("provisioner-password-file") != "":
241 opts = append(opts, jose.WithPasswordFile(ctx.String("provisioner-password-file")))
242 case ctx.String("password-file") != "":
243 opts = append(opts, jose.WithPasswordFile(ctx.String("password-file")))
244 }
245
246 if keyFile := ctx.String("key"); len(keyFile) == 0 {
247 if p == nil {
248 return nil, "", errors.New("no provisioner selected")
249 }
250 kid = p.Key.KeyID
251 // If provisioner is not nil then we must be using the offlineCA.
252 var encryptedKey string
253 if ctx.IsSet("offline") {
254 encryptedKey = p.EncryptedKey
255 if len(encryptedKey) == 0 {
256 return nil, "", errors.Errorf("provisioner '%s' does not have an 'encryptedKey' property", kid)
257 }
258 } else {
259 // Get private key from CA.
260 encryptedKey, err = pki.GetProvisionerKey(tokAttrs.caURL, tokAttrs.root, kid)
261 if err != nil {
262 return nil, "", err
263 }
264 }
265
266 // Add template with check mark
267 opts = append(opts, jose.WithUIOptions(
268 ui.WithPromptTemplates(ui.PromptTemplates()),
269 ))
270
271 decrypted, err := jose.Decrypt("Please enter the password to decrypt the provisioner key", []byte(encryptedKey), opts...)
272 if err != nil {
273 return nil, "", err
274 }
275
276 jwk = new(jose.JSONWebKey)
277 if err := json.Unmarshal(decrypted, jwk); err != nil {
278 return nil, "", errors.Wrap(err, "error unmarshalling provisioning key")
279 }
280 } else {
281 // Get private key from given key file
282 jwk, err = jose.ParseKey(keyFile, opts...)
283 if err != nil {
284 return nil, "", err
285 }
286
287 if p != nil {
288 kid = p.Key.KeyID
289 } else if len(tokAttrs.kid) > 0 {
290 kid = tokAttrs.kid
291 } else {
292 hash, err := jwk.Thumbprint(crypto.SHA256)
293 if err != nil {
294 return nil, "", errors.Wrap(err, "error generating JWK thumbprint")
295 }
296 kid = base64.RawURLEncoding.EncodeToString(hash)
297 }
298 }
299 return
300 }
301
302 func generateJWKToken(ctx *cli.Context, p *provisioner.JWK, tokType int, tokAttrs tokenAttrs) (string, error) {
303 jwk, kid, err := loadJWK(ctx, p, tokAttrs)
304 if err != nil {
305 return "", err
306 }
307
308 issuer := tokAttrs.issuer
309 if p != nil {
310 issuer = p.Name
311 }
312 // Generate token
313 tokenGen := NewTokenGenerator(kid, issuer, tokAttrs.audience, tokAttrs.root,
314 tokAttrs.notBefore, tokAttrs.notAfter, jwk)
315 switch tokType {
316 case SignType:
317 return tokenGen.SignToken(tokAttrs.subject, tokAttrs.sans)
318 case RevokeType:
319 return tokenGen.RevokeToken(tokAttrs.subject)
320 case SSHUserSignType:
321 return tokenGen.SignSSHToken(tokAttrs.subject, provisioner.SSHUserCert,
322 tokAttrs.sans, tokAttrs.certNotBefore, tokAttrs.certNotAfter)
323 case SSHHostSignType:
324 return tokenGen.SignSSHToken(tokAttrs.subject, provisioner.SSHHostCert,
325 tokAttrs.sans, tokAttrs.certNotBefore, tokAttrs.certNotAfter)
326 default:
327 return tokenGen.Token(tokAttrs.subject)
328 }
329 }