Debian Codegraph @

command/crypto/jwt/sign.go

raw symbols SCIP
1 package jwt
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "io/ioutil"
9 "os"
10 "strings"
11 "time"
12
13 "github.com/pkg/errors"
14 "github.com/smallstep/cli/crypto/randutil"
15 "github.com/smallstep/cli/errs"
16 "github.com/smallstep/cli/flags"
17 "github.com/smallstep/cli/jose"
18 "github.com/urfave/cli"
19 )
20
21 func signCommand() cli.Command {
22 return cli.Command{
23 Name: "sign",
24 Action: cli.ActionFunc(signAction),
25 Usage: "create a signed JWT data structure",
26 UsageText: `**step crypto jwt sign** [- | <filename>]
27 [**--alg**=<algorithm>] [**--aud**=<audience>] [**--iss**=<issuer>] [**--sub**=<sub>]
28 [**--exp**=<expiration>] [**--iat**=<issued_at>] [**--nbf**=<not-before>]
29 [**--key**=<path>] [**--jwks**=<jwks>] [**--kid**=<kid>] [**--jti**=<jti>]
30 [**--header=<key=value>**] [**--password-file**=<path>]
31 [**--x5c-cert**=<path>] [**--x5c-key**=<path>] [**--x5t-cert**=<path>] [**--x5t-key**=<path>]`,
32 Description: `**step crypto jwt sign** command generates a signed JSON Web Token (JWT) by
33 computing a digital signature or message authentication code for a JSON
34 payload. By default, the payload to sign is read from STDIN and the JWT will
35 be written to STDOUT. The suggested pronunciation of JWT is the same as the
36 English word "jot".
37
38 A JWT is a compact data structure used to represent some JSON encoded "claims"
39 that are passed as the payload of a JWS or JWE structure, enabling the claims
40 to be digitally signed and/or encrypted. The "claims" (or "claim set") are
41 represented as an ordinary JSON object. JWTs are represented using a compact
42 format that's URL safe and can be used in space-constrained environments. JWTs
43 can be passed in HTTP Authorization headers and as URI query parameters.
44
45 A "claim" is a piece of information asserted about a subject, represented as a
46 key/value pair. Logically a verified JWT should be interpreted as "<issuer> says
47 to <audience> that <subject>'s <claim-name> is <claim-value>" for each claim.
48
49 Some optional arguments introduce subtle security considerations if omitted.
50 These considerations should be carefully analyzed. Therefore, omitting <subtle>
51 arguments requires the use of the **--subtle** flag as a misuse prevention
52 mechanism.
53
54 A JWT signed using JWS has three parts:
55
56 1. A base64 encoded JSON object representing the JOSE (JSON Object Signing
57 and Encryption) header that describes the cryptographic operations
58 applied to the JWT Claims Set
59 2. A base64 encoded JSON object representing the JWT Claims Set
60 3. A base64 encoded digital signature of message authentication code
61
62 For examples, see **step help crypto jwt**.`,
63 Flags: []cli.Flag{
64 cli.StringFlag{
65 Name: "alg, algorithm",
66 Usage: `The signature or MAC algorithm to use. Algorithms are case-sensitive strings
67 defined in RFC7518. The selected algorithm must be compatible with the key
68 type. This flag is optional. If not specified, the "alg" member of the JWK is
69 used. If the JWK has no "alg" member then a default is selected depending on
70 the JWK key type. If the JWK has an "alg" member and the "alg" flag is passed
71 the two options must match unless the '--subtle' flag is also passed.
72
73 : <algorithm> is a case-sensitive string and must be one of:
74
75 **HS256**
76 : HMAC using SHA-256 (default for "oct" key type)
77
78 **HS384**
79 : HMAC using SHA-384
80
81 **HS512**
82 : HMAC using SHA-512
83
84 **RS256**
85 : RSASSA-PKCS1-v1_5 using SHA-256 (default for "RSA" key type)
86
87 **RS384**
88 : RSASSA-PKCS1-v1_5 using SHA-384
89
90 **RS512**
91 : RSASSA-PKCS1-v1_5 using SHA-512
92
93 **ES256**
94 : ECDSA using P-256 and SHA-256 (default for "EC" key type)
95
96 **ES384**
97 : ECDSA using P-384 and SHA-384
98
99 **ES512**
100 : ECDSA using P-521 and SHA-512
101
102 **PS256**
103 : RSASSA-PSS using SHA-256 and MGF1 with SHA-256
104
105 **PS384**
106 : RSASSA-PSS using SHA-384 and MGF1 with SHA-384
107
108 **PS512**
109 : RSASSA-PSS using SHA-512 and MGF1 with SHA-512
110
111 **EdDSA**
112 : EdDSA signature algorithm`,
113 },
114 cli.StringFlag{
115 Name: "iss, issuer",
116 Usage: `The issuer of this JWT. The processing of this claim is generally
117 application specific. Typically, the issuer must match the name of some
118 trusted entity (e.g., an identity provider like "https://accounts.google.com")
119 and identify which key(s) to use for JWT verification and/or decryption (e.g.,
120 the keys at "https://www.googleapis.com/oauth2/v3/certs").
121
122 : <issuer> is a case-sensitive string.`,
123 },
124 cli.StringSliceFlag{
125 Name: "aud, audience",
126 Usage: `The intended recipient(s) of the JWT, encoded as the **"aud"** claim in the
127 JWT. Recipient(s) must identify themselves with one or more of the values in
128 the **"aud"** claim. The **"aud"** claim can be a string (indicating a single
129 recipient) or an array (indicating multiple potential recipients). This flag
130 can be used multiple times to generate a JWK with multiple intended
131 recipients.
132
133 : Each <audience> is a case-sensitive string.`,
134 },
135 cli.StringFlag{
136 Name: "sub, subject",
137 Usage: `The subject of this JWT. The "claims" are normally interpreted as statements
138 about this subject. The subject must either be locally unique in the context
139 of the issuer or globally unique. The processing of this claim is generally
140 application specific.
141
142 : <subject> is a case-sensitive string.`,
143 },
144 cli.Int64Flag{
145 Name: "exp, expiration",
146 Usage: `The expiration time on or after which the JWT must not be accepted.
147 <expiration> must be a numeric value representing a Unix timestamp.`,
148 },
149 cli.Int64Flag{
150 Name: "nbf, not-before",
151 Usage: `The time before which the JWT must not be accepted. <not-before> must be a
152 numeric value representing a Unix timestamp. If not provided, the current time
153 is used.`,
154 },
155 cli.Int64Flag{
156 Name: "iat, issued-at",
157 Usage: `The time at which the JWT was issued, used to determine the age of the JWT.
158 ISSUED_AT must be a numeric value representing a Unix timestamp. If not
159 provided, the current time is used.`,
160 },
161 cli.StringFlag{
162 Name: "jti, jwt-id",
163 Usage: `A unique identifier for the JWT. The identifier must be assigned in a manner
164 that ensures that there is a negligible probability that the same value will
165 be accidentally assigned to multiple JWTs. The JTI claim can be used to
166 prevent a JWT from being replayed (i.e., recipient(s) can use <jti> to make a
167 JWT one-time-use). The <jti> argument is a case-sensitive string. If the
168 **--jti** flag is used without an argument a <jti> will be generated randomly
169 with sufficient entropy to satisfy the collision-resistance criteria.`,
170 },
171 cli.StringSliceFlag{
172 Name: "header",
173 Usage: `The <key=value> used as a header in the JWT token. Use the flag multiple
174 times to set multiple headers.`,
175 },
176 cli.StringFlag{
177 Name: "key, x5c-key, x5t-key",
178 Usage: `The <path> to the key with which to sign the JWT.
179 JWTs can be signed using a private JWK (or a JWK encrypted as a JWE payload) or
180 a PEM encoded private key (or a private key encrypted using the modes described
181 on RFC 1423 or with PBES2+PBKDF2 described in RFC 2898).`,
182 },
183 cli.StringFlag{
184 Name: "jwks",
185 Usage: `The JWK Set containing the key to use to sign the JWT. The <jwks> argument
186 should be the name of a file. The file contents should be a JWK Set or a JWE
187 with a JWK Set payload. The **--jwks** flag requires the use of the **--kid**
188 flag to specify which key to use.`,
189 },
190 cli.StringFlag{
191 Name: "kid",
192 Usage: `The ID of the key used to sign the JWT. The <kid> argument is a case-sensitive
193 string. When used with '--jwk' the <kid> value must match the **"kid"** member
194 of the JWK. When used with **--jwks** (a JWK Set) the <kid> value must match
195 the **"kid"** member of one of the JWKs in the JWK Set.`,
196 },
197 cli.StringFlag{
198 Name: "password-file",
199 Usage: `The path to the <file> containing the password to decrypt the key.`,
200 },
201 cli.BoolFlag{
202 Name: "subtle",
203 Hidden: true,
204 },
205 cli.BoolFlag{
206 Name: "no-kid",
207 Hidden: true,
208 },
209 flags.X5cCert,
210 flags.X5tCert,
211 },
212 }
213 }
214
215 func signAction(ctx *cli.Context) error {
216 var err error
217 var payload interface{}
218
219 // Read payload if provided
220 args := ctx.Args()
221 switch len(args) {
222 case 0:
223 // read payload from stdin if there is data
224 if payload, err = readPayload(""); err != nil {
225 return err
226 }
227 case 1:
228 // read payload from file or stdin (-)
229 if payload, err = readPayload(args[0]); err != nil {
230 return err
231 }
232 default:
233 return errs.TooManyArguments(ctx)
234 }
235
236 x5cCertFile, x5cKeyFile := ctx.String("x5c-cert"), ctx.String("x5c-key")
237 x5tCertFile, x5tKeyFile := ctx.String("x5t-cert"), ctx.String("x5t-key")
238 key := ctx.String("key")
239 jwks := ctx.String("jwks")
240 kid := ctx.String("kid")
241 var isX5C bool
242 if len(x5cCertFile) > 0 {
243 if len(x5cKeyFile) == 0 {
244 return errs.RequiredWithOrFlag(ctx, "x5c-cert", "key", "x5c-key")
245 }
246 if len(x5tCertFile) > 0 {
247 return errs.MutuallyExclusiveFlags(ctx, "x5c-cert", "x5t-cert")
248 }
249 if ctx.IsSet("jwk") {
250 return errs.MutuallyExclusiveFlags(ctx, "x5c-cert", "jwk")
251 }
252 if len(jwks) > 0 {
253 return errs.MutuallyExclusiveFlags(ctx, "x5c-cert", "jwks")
254 }
255 isX5C = true
256 }
257
258 var isX5T bool
259 if len(x5tCertFile) > 0 {
260 if len(x5tKeyFile) == 0 {
261 return errs.RequiredWithOrFlag(ctx, "x5t-cert", "key", "x5t-key")
262 }
263 if len(x5cCertFile) > 0 {
264 return errs.MutuallyExclusiveFlags(ctx, "x5t-cert", "x5c-cert")
265 }
266 if ctx.IsSet("jwk") {
267 return errs.MutuallyExclusiveFlags(ctx, "x5t-cert", "jwk")
268 }
269 if len(jwks) > 0 {
270 return errs.MutuallyExclusiveFlags(ctx, "x5t-cert", "jwks")
271 }
272 isX5T = true
273 }
274
275 if !isX5C && !isX5T {
276 // Validate key, jwks and kid
277 switch {
278 case key == "" && jwks == "":
279 return errs.RequiredOrFlag(ctx, "key", "jwks")
280 case key != "" && jwks != "":
281 return errs.MutuallyExclusiveFlags(ctx, "key", "jwks")
282 case jwks != "" && kid == "":
283 return errs.RequiredWithFlag(ctx, "kid", "jwks")
284 }
285 }
286
287 alg := ctx.String("alg")
288 isSubtle := ctx.Bool("subtle")
289 // Add parse options
290 var options []jose.Option
291 options = append(options, jose.WithUse("sig"))
292 if len(alg) > 0 {
293 options = append(options, jose.WithAlg(alg))
294 }
295 if len(kid) > 0 {
296 options = append(options, jose.WithKid(kid))
297 }
298 if isSubtle {
299 options = append(options, jose.WithSubtle(true))
300 }
301 if passwordFile := ctx.String("password-file"); len(passwordFile) > 0 {
302 options = append(options, jose.WithPasswordFile(passwordFile))
303 }
304
305 // Read key from --key or --jwks or --x5c-key or --x5t-key
306 var jwk *jose.JSONWebKey
307 switch {
308 case isX5T:
309 jwk, err = jose.ParseKey(x5tKeyFile, options...)
310 case isX5C:
311 jwk, err = jose.ParseKey(x5cKeyFile, options...)
312 case key != "":
313 jwk, err = jose.ParseKey(key, options...)
314 case jwks != "":
315 jwk, err = jose.ParseKeySet(jwks, options...)
316 default:
317 return errs.RequiredOrFlag(ctx, "key", "jwks")
318 }
319 if err != nil {
320 return err
321 }
322
323 // Public keys cannot be used for signing
324 if jwk.IsPublic() {
325 return errors.New("cannot use a public key for signing")
326 }
327
328 // Key "use" must be "sig" to use for signing
329 if jwk.Use != "sig" && jwk.Use != "" {
330 return errors.Errorf("invalid jwk use: found '%s', expecting 'sig' (signature)", jwk.Use)
331 }
332
333 // At this moment jwk.Algorithm should have an alg from:
334 // * alg parameter
335 // * jwk or jwkset
336 // * guessed for ecdsa and Ed25519 keys
337 if jwk.Algorithm == "" {
338 return errors.New("flag '--alg' is required with the given key")
339 }
340 if err = jose.ValidateJWK(jwk); err != nil {
341 return err
342 }
343
344 // Validate exp
345 if !isSubtle && ctx.IsSet("exp") && jose.UnixNumericDate(ctx.Int64("exp")).Time().Before(time.Now()) {
346 return errors.New("flag '--exp' must be in the future unless the '--subtle' flag is provided")
347 }
348
349 jti := ctx.String("jti")
350 if !ctx.IsSet("jti") {
351 if jti, err = randutil.Hex(64); err != nil { // 256 bits
352 return errors.Wrap(err, "error generating random JWT ID")
353 }
354 }
355
356 headers := ctx.StringSlice("header")
357
358 // Add claims
359 c := &jose.Claims{
360 Issuer: ctx.String("iss"),
361 Subject: ctx.String("sub"),
362 Audience: ctx.StringSlice("aud"),
363 Expiry: jose.UnixNumericDate(ctx.Int64("exp")),
364 NotBefore: jose.UnixNumericDate(ctx.Int64("nbf")),
365 IssuedAt: jose.UnixNumericDate(ctx.Int64("iat")),
366 ID: jti,
367 }
368
369 now := time.Now()
370 if c.NotBefore == nil {
371 c.NotBefore = jose.NewNumericDate(now)
372 }
373 if c.IssuedAt == nil {
374 c.IssuedAt = jose.NewNumericDate(now)
375 }
376 if c.ID == "" && ctx.IsSet("jti") {
377 if c.ID, err = randutil.Hex(40); err != nil {
378 return errors.Wrap(err, "error creating random jti")
379 }
380 }
381
382 // Validate recommended claims
383 if !isSubtle {
384 switch {
385 case len(c.Issuer) == 0:
386 return errors.New("flag '--iss' is required unless '--subtle' is used")
387 case len(c.Audience) == 0:
388 return errors.New("flag '--aud' is required unless '--subtle' is used")
389 case len(c.Subject) == 0:
390 return errors.New("flag '--sub' is required unless '--subtle' is used")
391 case c.Expiry == nil:
392 return errors.New("flag '--exp' is required unless '--subtle' is used")
393 case c.Expiry.Time().Before(time.Now()):
394 return errors.New("flag '--exp' must be in the future unless '--subtle' is used")
395 }
396 }
397
398 // Sign
399 so := new(jose.SignerOptions)
400 so.WithType("JWT")
401 if !ctx.Bool("no-kid") && jwk.KeyID != "" {
402 so.WithHeader("kid", jwk.KeyID)
403 }
404
405 if len(headers) > 0 {
406 for _, s := range headers {
407 i := strings.Index(s, "=")
408 if i == -1 {
409 return errs.InvalidFlagValue(ctx, "set", s, "")
410 }
411 so.WithHeader(jose.HeaderKey(s[:i]), s[i+1:])
412 }
413 }
414
415 if isX5C {
416 certStrs, err := jose.ValidateX5C(x5cCertFile, jwk.Key)
417 if err != nil {
418 return errors.Wrap(err, "error validating x5c certificate chain and key for use in x5c header")
419 }
420 so.WithHeader("x5c", certStrs)
421 }
422
423 if isX5T {
424 fingerprint, err := jose.ValidateX5T(x5tCertFile, jwk.Key)
425 if err != nil {
426 return errors.Wrap(err, "error validating x5t certificate and key for use in x5t header")
427 }
428 so.WithHeader("x5t", fingerprint)
429 }
430
431 signer, err := jose.NewSigner(jose.SigningKey{
432 Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
433 Key: jwk.Key,
434 }, so)
435 if err != nil {
436 return errors.Wrapf(err, "error creating JWT signer")
437 }
438
439 // Some implementations only accept "aud" as a string.
440 // Using claim overwriting for this special case.
441 aud := make(map[string]interface{})
442 if len(c.Audience) == 1 {
443 aud["aud"] = c.Audience[0]
444 }
445
446 raw, err := jose.Signed(signer).Claims(c).Claims(aud).Claims(payload).CompactSerialize()
447 if err != nil {
448 return errors.Wrapf(err, "error serializing JWT")
449 }
450
451 fmt.Println(raw)
452 return nil
453 }
454
455 func readPayload(filename string) (interface{}, error) {
456 var r io.Reader
457 switch filename {
458 case "":
459 st, err := os.Stdin.Stat()
460 if err != nil {
461 return nil, errors.Wrap(err, "error reading data")
462 }
463 if st.Size() == 0 && st.Mode()&os.ModeNamedPipe == 0 {
464 return make(map[string]interface{}), nil
465 }
466 r = os.Stdin
467 case "-":
468 r = os.Stdin
469 default:
470 b, err := ioutil.ReadFile(filename)
471 if err != nil {
472 return nil, errs.FileError(err, filename)
473 }
474 r = bytes.NewReader(b)
475 }
476
477 v := make(map[string]interface{})
478 if err := json.NewDecoder(r).Decode(&v); err != nil {
479 if filename == "" || filename == "-" {
480 return nil, errors.Wrap(err, "error decoding JSON from STDIN")
481 }
482 return nil, errors.Wrapf(err, "error decoding JSON from %s", filename)
483 }
484 return v, nil
485 }