Debian Codegraph @

command/crypto/jwt/verify.go

raw symbols SCIP
1 package jwt
2
3 import (
4 "fmt"
5 "os"
6 "strings"
7 "time"
8
9 "github.com/pkg/errors"
10 "github.com/smallstep/cli/errs"
11 "github.com/smallstep/cli/jose"
12 "github.com/smallstep/cli/utils"
13 "github.com/urfave/cli"
14 )
15
16 func verifyCommand() cli.Command {
17 return cli.Command{
18 Name: "verify",
19 Action: cli.ActionFunc(verifyAction),
20 Usage: "verify a signed JWT data structure and return the payload",
21 UsageText: `**step crypto jwt verify**
22 [**--aud**=<audience>] [**--iss**=<issuer>] [**--alg**=<algorithm>]
23 [**--key**=<path>] [**--jwks**=<jwks>] [**--kid**=<kid>]`,
24 Description: `**step crypto jwt verify** reads a JWT data structure from STDIN; checks that
25 the audience, issuer, and algorithm are in agreement with expectations;
26 verifies the digital signature or message authentication code as appropriate;
27 and outputs the decoded payload of the JWT on STDOUT. If verification fails a
28 non-zero failure code is returned. If verification succeeds the command
29 returns 0.
30
31 For a JWT to be verified successfully:
32
33 * The JWT must be well formed (no errors during deserialization)
34 * The <algorithm> must match the **"alg"** member in the JWT header
35 * The <issuer> and <audience> must match the **"iss"** and **"aud"** claims in the JWT,
36 respectively
37 * The <kid> must match the **"kid"** member in the JWT header (if both are
38 present) and must match the **"kid"** in the JWK or the **"kid"** of one of the
39 JWKs in JWKS
40 * The JWT signature must be successfully verified
41 * The JWT must not be expired
42
43 For examples, see **step help crypto jwt**.`,
44 Flags: []cli.Flag{
45 cli.StringFlag{
46 Name: "iss, issuer",
47 Usage: `The issuer of this JWT. The <issuer> must match the value of the **"iss"** claim in
48 the JWT. <issuer> is a case-sensitive string. Required unless disabled with the **--subtle** flag.`,
49 },
50 cli.StringFlag{
51 Name: "aud, audience",
52 Usage: `The identity of the principal running this command. The <audience> specified
53 must match one of the values in the **"aud"** claim, indicating the intended
54 recipient(s) of the JWT. <audience> is a case-sensitive string. Required unless disabled with the
55 **--subtle** flag.`,
56 },
57 cli.StringFlag{
58 Name: "alg, algorithm",
59 Usage: `The signature or MAC <algorithm> to use. Algorithms are case-sensitive strings
60 defined in RFC7518. If the key used do verify the JWT is not a JWK, or if it
61 is a JWK but does not have an **"alg"** member indicating its the intended
62 algorithm for use with the key, then the **--alg** flag is required to prevent
63 algorithm downgrade attacks. To disable this protection you can pass the
64 **--insecure** flag and omit the **--alg** flag.`,
65 },
66 cli.StringFlag{
67 Name: "key",
68 Usage: `The <path> to the key to use to verify the JWT.
69 The contents of the file can be a public or private JWK (or a JWK
70 encrypted as a JWE payload) or a public or private PEM (or a private key
71 encrypted using the modes described on RFC 1423 or with PBES2+PBKDF2 described
72 in RFC 2898).`,
73 },
74 cli.StringFlag{
75 Name: "jwks",
76 Usage: `The JWK Set containing the key to use to verify the JWS. The <jwks> argument
77 should be the name of a file. The file contents should be a JWK Set or a JWE
78 with a JWK Set payload. The JWS being verified should have a "kid" member that
79 matches the "kid" of one of the JWKs in the JWK Set. If the JWS does not have
80 a "kid" member the '--kid' flag can be used.`,
81 },
82 cli.StringFlag{
83 Name: "kid",
84 Usage: `The ID of the key used to sign the JWK, used to select a JWK from a JWK Set.
85 The KID argument is a case-sensitive string. If the input JWS has a "kid"
86 member its value must match <kid> or verification will fail.`,
87 },
88 cli.StringFlag{
89 Name: "password-file",
90 Usage: `The path to the <file> containing the password to decrypt the key.`,
91 },
92 cli.BoolFlag{
93 Name: "subtle",
94 Hidden: true,
95 },
96 cli.BoolFlag{
97 Name: "no-exp-check",
98 Hidden: true,
99 },
100 cli.BoolFlag{
101 Name: "insecure",
102 Hidden: true,
103 },
104 },
105 }
106 }
107
108 type timeClaims struct {
109 Expiry *int64 `json:"exp,omitempty"`
110 NotBefore *int64 `json:"nbf,omitempty"`
111 }
112
113 // Get the public key for a JWK.
114 func publicKey(jwk *jose.JSONWebKey) interface{} {
115 if jose.IsSymmetric(jwk) {
116 return jwk.Key
117 }
118 return jwk.Public().Key
119 }
120
121 func verifyAction(ctx *cli.Context) error {
122 token, err := utils.ReadString(os.Stdin)
123 if err != nil {
124 return errors.Wrap(err, "error reading token")
125 }
126
127 tok, err := jose.ParseSigned(token)
128 if err != nil {
129 return errors.Errorf("error parsing token: %s", strings.TrimPrefix(err.Error(), "square/go-jose: "))
130 }
131
132 // Validate key, jwks and kid
133 key := ctx.String("key")
134 jwks := ctx.String("jwks")
135 kid := ctx.String("kid")
136 alg := ctx.String("alg")
137 switch {
138 case key == "" && jwks == "":
139 return errs.RequiredOrFlag(ctx, "key", "jwks")
140 case key != "" && jwks != "":
141 return errs.MutuallyExclusiveFlags(ctx, "key", "jwks")
142 case jwks != "" && kid == "":
143 if tok.Headers[0].KeyID == "" {
144 return errs.RequiredWithFlag(ctx, "kid", "jwks")
145 }
146 kid = tok.Headers[0].KeyID
147 }
148
149 // Validate subtled
150 isSubtle := ctx.Bool("subtle")
151 iss := ctx.String("iss")
152 aud := ctx.String("aud")
153 if !isSubtle {
154 switch {
155 case len(iss) == 0:
156 return errs.RequiredUnlessSubtleFlag(ctx, "iss")
157 case len(aud) == 0:
158 return errs.RequiredUnlessSubtleFlag(ctx, "aud")
159 }
160 }
161
162 // Validate no-exp-check with insecure
163 if ctx.Bool("no-exp-check") && !ctx.Bool("insecure") {
164 return errs.RequiredInsecureFlag(ctx, "no-exp-check")
165 }
166
167 // Add parse options
168 var options []jose.Option
169 options = append(options, jose.WithUse("sig"))
170 if len(alg) > 0 {
171 options = append(options, jose.WithAlg(alg))
172 }
173 if len(kid) > 0 {
174 options = append(options, jose.WithKid(kid))
175 }
176 if isSubtle {
177 options = append(options, jose.WithSubtle(true))
178 }
179 if !ctx.Bool("insecure") {
180 options = append(options, jose.WithNoDefaults(true))
181 }
182 if passwordFile := ctx.String("password-file"); len(passwordFile) > 0 {
183 options = append(options, jose.WithPasswordFile(passwordFile))
184 }
185
186 // Read key from --key or --jwks
187 var jwk *jose.JSONWebKey
188 switch {
189 case key != "":
190 jwk, err = jose.ParseKey(key, options...)
191 case jwks != "":
192 jwk, err = jose.ParseKeySet(jwks, options...)
193 default:
194 return errs.RequiredOrFlag(ctx, "key", "jwks")
195 }
196 if err != nil {
197 return err
198 }
199
200 // At this moment jwk.Algorithm should have an alg from:
201 // * alg parameter
202 // * jwk or jwkset
203 // * guessed for ecdsa and ed25519 keys
204 if jwk.Algorithm == "" {
205 return errors.New("flag '--alg' is required with the given key")
206 }
207 if err := jose.ValidateJWK(jwk); err != nil {
208 return err
209 }
210
211 // We don't support multiple signatures or any critical headers
212 if len(tok.Headers) > 1 {
213 return errors.New("validation failed: multiple signatures are not supported")
214 }
215 if _, ok := tok.Headers[0].ExtraHeaders["crit"]; ok {
216 return errors.New("validation failed: unrecognized critical headers (crit)")
217 }
218 if !isSubtle && alg != "" && tok.Headers[0].Algorithm != "" && alg != tok.Headers[0].Algorithm {
219 return errors.Errorf("alg %s does not match the alg on JWT (%s)", alg, tok.Headers[0].Algorithm)
220 }
221
222 claims := jose.Claims{}
223 if err := tok.Claims(publicKey(jwk), &claims); err != nil {
224 switch err {
225 case jose.ErrCryptoFailure:
226 return errors.New("validation failed: invalid signature")
227 default:
228 return errors.Wrap(err, "claim verify failed")
229 }
230 }
231
232 // Check exp and nbf presence
233 // There's no need to do the verification again.
234 var tClaims timeClaims
235 if err := tok.UnsafeClaimsWithoutVerification(&tClaims); err != nil {
236 switch err {
237 case jose.ErrCryptoFailure:
238 return errors.New("validation failed: invalid signature")
239 default:
240 return errors.Wrap(err, "claim verify failed")
241 }
242 }
243
244 expected := jose.Expected{Issuer: iss}
245 if aud != "" {
246 expected.Audience = jose.Audience{aud}
247 }
248 if tClaims.Expiry != nil || tClaims.NotBefore != nil {
249 expected.Time = time.Now()
250 }
251
252 if err := validateClaimsWithLeeway(ctx, claims, expected, tClaims, 0); err != nil {
253 return err
254 }
255
256 return printToken(token)
257 }
258
259 // validateClaimsWithLeeway is a custom implementation of go-jose
260 // jwt.Claims.ValidateWithLeeway that returns all the errors found.
261 func validateClaimsWithLeeway(ctx *cli.Context, c jose.Claims, e jose.Expected, t timeClaims, leeway time.Duration) error {
262 var errs []string
263
264 if e.Issuer != "" && e.Issuer != c.Issuer {
265 errs = append(errs, "invalid issuer claim (iss)")
266 }
267
268 // we're not currently checking the subject
269 if e.Subject != "" && e.Subject != c.Subject {
270 errs = append(errs, "invalid subject subject (sub)")
271 }
272
273 // we're not currently checking the id
274 if e.ID != "" && e.ID != c.ID {
275 errs = append(errs, "invalid ID claim (jti)")
276 }
277
278 if len(e.Audience) != 0 {
279 for _, v := range e.Audience {
280 if !c.Audience.Contains(v) {
281 errs = append(errs, "invalid audience claim (aud)")
282 break
283 }
284 }
285 }
286
287 // Only if nbf is defined, just in case is tested in time <0 :)
288 if t.NotBefore != nil {
289 if !e.Time.IsZero() && e.Time.Add(leeway).Before(c.NotBefore.Time()) {
290 errs = append(errs, "token not valid yet (nbf)")
291 }
292 }
293
294 // Only if exp is defined and no-exp-check is not used
295 if t.Expiry != nil && !ctx.Bool("no-exp-check") {
296 if !e.Time.IsZero() && e.Time.Add(-leeway).After(c.Expiry.Time()) {
297 errs = append(errs, fmt.Sprintf("token is expired by %s (exp)", e.Time.Sub(c.Expiry.Time()).Round(time.Millisecond)))
298 }
299 }
300
301 if len(errs) > 0 {
302 return errors.Errorf("validation failed: %s", strings.Join(errs, ", "))
303 }
304
305 return nil
306 }