/
tokens.go
1125 lines (998 loc) · 31.9 KB
/
tokens.go
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package topdown
import (
"crypto"
"crypto/ecdsa"
"crypto/hmac"
"crypto/rsa"
"crypto/sha256"
"crypto/sha512"
"crypto/x509"
"encoding/hex"
"encoding/json"
"encoding/pem"
"fmt"
"hash"
"math/big"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/topdown/builtins"
"github.com/open-policy-agent/opa/topdown/internal/jwx/jwk"
"github.com/open-policy-agent/opa/topdown/internal/jwx/jws"
)
var (
jwtEncKey = ast.StringTerm("enc")
jwtCtyKey = ast.StringTerm("cty")
jwtAlgKey = ast.StringTerm("alg")
jwtIssKey = ast.StringTerm("iss")
jwtExpKey = ast.StringTerm("exp")
jwtNbfKey = ast.StringTerm("nbf")
jwtAudKey = ast.StringTerm("aud")
)
// JSONWebToken represent the 3 parts (header, payload & signature) of
// a JWT in Base64.
type JSONWebToken struct {
header string
payload string
signature string
decodedHeader ast.Object
}
// decodeHeader populates the decodedHeader field.
func (token *JSONWebToken) decodeHeader() (err error) {
var h ast.Value
if h, err = builtinBase64UrlDecode(ast.String(token.header)); err != nil {
return fmt.Errorf("JWT header had invalid encoding: %v", err)
}
if token.decodedHeader, err = validateJWTHeader(string(h.(ast.String))); err != nil {
return err
}
return
}
// Implements JWT decoding/validation based on RFC 7519 Section 7.2:
// https://tools.ietf.org/html/rfc7519#section-7.2
// It does no data validation, it merely checks that the given string
// represents a structurally valid JWT. It supports JWTs using JWS compact
// serialization.
func builtinJWTDecode(a ast.Value) (ast.Value, error) {
token, err := decodeJWT(a)
if err != nil {
return nil, err
}
if err = token.decodeHeader(); err != nil {
return nil, err
}
p, err := builtinBase64UrlDecode(ast.String(token.payload))
if err != nil {
return nil, fmt.Errorf("JWT payload had invalid encoding: %v", err)
}
if cty := token.decodedHeader.Get(jwtCtyKey); cty != nil {
ctyVal := string(cty.Value.(ast.String))
// It is possible for the contents of a token to be another
// token as a result of nested signing or encryption. To handle
// the case where we are given a token such as this, we check
// the content type and recurse on the payload if the content
// is "JWT".
// When the payload is itself another encoded JWT, then its
// contents are quoted (behavior of https://jwt.io/). To fix
// this, remove leading and trailing quotes.
if ctyVal == "JWT" {
p, err = builtinTrim(p, ast.String(`"'`))
if err != nil {
panic("not reached")
}
return builtinJWTDecode(p)
}
}
payload, err := extractJSONObject(string(p.(ast.String)))
if err != nil {
return nil, err
}
s, err := builtinBase64UrlDecode(ast.String(token.signature))
if err != nil {
return nil, fmt.Errorf("JWT signature had invalid encoding: %v", err)
}
sign := hex.EncodeToString([]byte(s.(ast.String)))
arr := make(ast.Array, 3)
arr[0] = ast.NewTerm(token.decodedHeader)
arr[1] = ast.NewTerm(payload)
arr[2] = ast.StringTerm(sign)
return arr, nil
}
// Implements RS256 JWT signature verification
func builtinJWTVerifyRS256(bctx BuiltinContext, args []*ast.Term, iter func(*ast.Term) error) error {
result, err := builtinJWTVerifyRSA(args[0].Value, args[1].Value, sha256.New, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error {
return rsa.VerifyPKCS1v15(
publicKey,
crypto.SHA256,
digest,
signature)
})
if err == nil {
return iter(ast.NewTerm(result))
}
return err
}
// Implements RS384 JWT signature verification
func builtinJWTVerifyRS384(bctx BuiltinContext, args []*ast.Term, iter func(*ast.Term) error) error {
result, err := builtinJWTVerifyRSA(args[0].Value, args[1].Value, sha512.New384, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error {
return rsa.VerifyPKCS1v15(
publicKey,
crypto.SHA384,
digest,
signature)
})
if err == nil {
return iter(ast.NewTerm(result))
}
return err
}
// Implements RS512 JWT signature verification
func builtinJWTVerifyRS512(bctx BuiltinContext, args []*ast.Term, iter func(*ast.Term) error) error {
result, err := builtinJWTVerifyRSA(args[0].Value, args[1].Value, sha512.New, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error {
return rsa.VerifyPKCS1v15(
publicKey,
crypto.SHA512,
digest,
signature)
})
if err == nil {
return iter(ast.NewTerm(result))
}
return err
}
// Implements PS256 JWT signature verification
func builtinJWTVerifyPS256(bctx BuiltinContext, args []*ast.Term, iter func(*ast.Term) error) error {
result, err := builtinJWTVerifyRSA(args[0].Value, args[1].Value, sha256.New, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error {
return rsa.VerifyPSS(
publicKey,
crypto.SHA256,
digest,
signature,
nil)
})
if err == nil {
return iter(ast.NewTerm(result))
}
return err
}
// Implements PS384 JWT signature verification
func builtinJWTVerifyPS384(bctx BuiltinContext, args []*ast.Term, iter func(*ast.Term) error) error {
result, err := builtinJWTVerifyRSA(args[0].Value, args[1].Value, sha512.New384, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error {
return rsa.VerifyPSS(
publicKey,
crypto.SHA384,
digest,
signature,
nil)
})
if err == nil {
return iter(ast.NewTerm(result))
}
return err
}
// Implements PS512 JWT signature verification
func builtinJWTVerifyPS512(bctx BuiltinContext, args []*ast.Term, iter func(*ast.Term) error) error {
result, err := builtinJWTVerifyRSA(args[0].Value, args[1].Value, sha512.New, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error {
return rsa.VerifyPSS(
publicKey,
crypto.SHA512,
digest,
signature,
nil)
})
if err == nil {
return iter(ast.NewTerm(result))
}
return err
}
// Implements RSA JWT signature verification.
func builtinJWTVerifyRSA(a ast.Value, b ast.Value, hasher func() hash.Hash, verify func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error) (ast.Value, error) {
return builtinJWTVerify(a, b, hasher, func(publicKey interface{}, digest []byte, signature []byte) error {
publicKeyRsa, ok := publicKey.(*rsa.PublicKey)
if !ok {
return fmt.Errorf("incorrect public key type")
}
return verify(publicKeyRsa, digest, signature)
})
}
// Implements ES256 JWT signature verification.
func builtinJWTVerifyES256(bctx BuiltinContext, args []*ast.Term, iter func(*ast.Term) error) error {
result, err := builtinJWTVerify(args[0].Value, args[1].Value, sha256.New, verifyES)
if err == nil {
return iter(ast.NewTerm(result))
}
return err
}
// Implements ES384 JWT signature verification
func builtinJWTVerifyES384(bctx BuiltinContext, args []*ast.Term, iter func(*ast.Term) error) error {
result, err := builtinJWTVerify(args[0].Value, args[1].Value, sha512.New384, verifyES)
if err == nil {
return iter(ast.NewTerm(result))
}
return err
}
// Implements ES512 JWT signature verification
func builtinJWTVerifyES512(bctx BuiltinContext, args []*ast.Term, iter func(*ast.Term) error) error {
result, err := builtinJWTVerify(args[0].Value, args[1].Value, sha512.New, verifyES)
if err == nil {
return iter(ast.NewTerm(result))
}
return err
}
func verifyES(publicKey interface{}, digest []byte, signature []byte) error {
publicKeyEcdsa, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
return fmt.Errorf("incorrect public key type")
}
r, s := &big.Int{}, &big.Int{}
n := len(signature) / 2
r.SetBytes(signature[:n])
s.SetBytes(signature[n:])
if ecdsa.Verify(publicKeyEcdsa, digest, r, s) {
return nil
}
return fmt.Errorf("ECDSA signature verification error")
}
// getKeyFromCertOrJWK returns the public key found in a X.509 certificate or JWK key(s).
// A valid PEM block is never valid JSON (and vice versa), hence can try parsing both.
func getKeyFromCertOrJWK(certificate string) ([]interface{}, error) {
if block, rest := pem.Decode([]byte(certificate)); block != nil {
if len(rest) > 0 {
return nil, fmt.Errorf("extra data after a PEM certificate block")
}
if block.Type == "CERTIFICATE" {
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, errors.Wrap(err, "failed to parse a PEM certificate")
}
return []interface{}{cert.PublicKey}, nil
}
if block.Type == "PUBLIC KEY" {
key, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, errors.Wrap(err, "failed to parse a PEM public key")
}
return []interface{}{key}, nil
}
return nil, fmt.Errorf("failed to extract a Key from the PEM certificate")
}
jwks, err := jwk.ParseString(certificate)
if err != nil {
return nil, errors.Wrap(err, "failed to parse a JWK key (set)")
}
var keys []interface{}
for _, k := range jwks.Keys {
key, err := k.Materialize()
if err != nil {
return nil, err
}
keys = append(keys, key)
}
return keys, nil
}
// Implements JWT signature verification.
func builtinJWTVerify(a ast.Value, b ast.Value, hasher func() hash.Hash, verify func(publicKey interface{}, digest []byte, signature []byte) error) (ast.Value, error) {
token, err := decodeJWT(a)
if err != nil {
return nil, err
}
s, err := builtins.StringOperand(b, 2)
if err != nil {
return nil, err
}
keys, err := getKeyFromCertOrJWK(string(s))
if err != nil {
return nil, err
}
signature, err := token.decodeSignature()
if err != nil {
return nil, err
}
// Validate the JWT signature
for _, key := range keys {
err = verify(key,
getInputSHA([]byte(token.header+"."+token.payload), hasher),
[]byte(signature))
if err == nil {
return ast.Boolean(true), nil
}
}
// None of the keys worked, return false
return ast.Boolean(false), nil
}
// Implements HS256 (secret) JWT signature verification
func builtinJWTVerifyHS256(bctx BuiltinContext, args []*ast.Term, iter func(*ast.Term) error) error {
// Decode the JSON Web Token
token, err := decodeJWT(args[0].Value)
if err != nil {
return err
}
// Process Secret input
astSecret, err := builtins.StringOperand(args[1].Value, 2)
if err != nil {
return err
}
secret := string(astSecret)
mac := hmac.New(sha256.New, []byte(secret))
_, err = mac.Write([]byte(token.header + "." + token.payload))
if err != nil {
return err
}
signature, err := token.decodeSignature()
if err != nil {
return err
}
return iter(ast.NewTerm(ast.Boolean(hmac.Equal([]byte(signature), mac.Sum(nil)))))
}
// Implements HS384 JWT signature verification
func builtinJWTVerifyHS384(bctx BuiltinContext, args []*ast.Term, iter func(*ast.Term) error) error {
// Decode the JSON Web Token
token, err := decodeJWT(args[0].Value)
if err != nil {
return err
}
// Process Secret input
astSecret, err := builtins.StringOperand(args[1].Value, 2)
if err != nil {
return err
}
secret := string(astSecret)
mac := hmac.New(sha512.New384, []byte(secret))
_, err = mac.Write([]byte(token.header + "." + token.payload))
if err != nil {
return err
}
signature, err := token.decodeSignature()
if err != nil {
return err
}
return iter(ast.NewTerm(ast.Boolean(hmac.Equal([]byte(signature), mac.Sum(nil)))))
}
// Implements HS512 JWT signature verification
func builtinJWTVerifyHS512(bctx BuiltinContext, args []*ast.Term, iter func(*ast.Term) error) error {
// Decode the JSON Web Token
token, err := decodeJWT(args[0].Value)
if err != nil {
return err
}
// Process Secret input
astSecret, err := builtins.StringOperand(args[1].Value, 2)
if err != nil {
return err
}
secret := string(astSecret)
mac := hmac.New(sha512.New, []byte(secret))
_, err = mac.Write([]byte(token.header + "." + token.payload))
if err != nil {
return err
}
signature, err := token.decodeSignature()
if err != nil {
return err
}
return iter(ast.NewTerm(ast.Boolean(hmac.Equal([]byte(signature), mac.Sum(nil)))))
}
// -- Full JWT verification and decoding --
// Verification constraints. See tokens_test.go for unit tests.
// tokenConstraints holds decoded JWT verification constraints.
type tokenConstraints struct {
// The set of asymmetric keys we can verify with.
keys []interface{}
// The single symmetric key we will verify with.
secret string
// The algorithm that must be used to verify.
// If "", any algorithm is acceptable.
alg string
// The required issuer.
// If "", any issuer is acceptable.
iss string
// The required audience.
// If "", no audience is acceptable.
aud string
// The time to validate against, or -1 if no constraint set.
// (If unset, the current time will be used.)
time int64
}
// tokenConstraintHandler is the handler type for JWT verification constraints.
type tokenConstraintHandler func(value ast.Value, parameters *tokenConstraints) (err error)
// tokenConstraintTypes maps known JWT verification constraints to handlers.
var tokenConstraintTypes = map[string]tokenConstraintHandler{
"cert": tokenConstraintCert,
"secret": func(value ast.Value, constraints *tokenConstraints) (err error) {
return tokenConstraintString("secret", value, &constraints.secret)
},
"alg": func(value ast.Value, constraints *tokenConstraints) (err error) {
return tokenConstraintString("alg", value, &constraints.alg)
},
"iss": func(value ast.Value, constraints *tokenConstraints) (err error) {
return tokenConstraintString("iss", value, &constraints.iss)
},
"aud": func(value ast.Value, constraints *tokenConstraints) (err error) {
return tokenConstraintString("aud", value, &constraints.aud)
},
"time": tokenConstraintTime,
}
// tokenConstraintCert handles the `cert` constraint.
func tokenConstraintCert(value ast.Value, constraints *tokenConstraints) (err error) {
var s ast.String
var ok bool
if s, ok = value.(ast.String); !ok {
return fmt.Errorf("cert constraint: must be a string")
}
constraints.keys, err = getKeyFromCertOrJWK(string(s))
return
}
// tokenConstraintTime handles the `time` constraint.
func tokenConstraintTime(value ast.Value, constraints *tokenConstraints) (err error) {
var time ast.Number
var ok bool
if time, ok = value.(ast.Number); !ok {
err = fmt.Errorf("token time constraint: must be a number")
return
}
var timeFloat float64
if timeFloat, err = strconv.ParseFloat(string(time), 64); err != nil {
err = fmt.Errorf("token time constraint: %v", err)
return
}
if timeFloat < 0 {
err = fmt.Errorf("token time constraint: must not be negative")
return
}
constraints.time = int64(timeFloat)
return
}
// tokenConstraintString handles string constraints.
func tokenConstraintString(name string, value ast.Value, where *string) (err error) {
var av ast.String
var ok bool
if av, ok = value.(ast.String); !ok {
err = fmt.Errorf("%s constraint: must be a string", name)
return
}
*where = string(av)
return
}
// parseTokenConstraints parses the constraints argument.
func parseTokenConstraints(a ast.Value) (constraints tokenConstraints, err error) {
constraints.time = -1
var o ast.Object
var ok bool
if o, ok = a.(ast.Object); !ok {
err = fmt.Errorf("token constraints must be object")
return
}
if err = o.Iter(func(k *ast.Term, v *ast.Term) (err error) {
var handler tokenConstraintHandler
var ok bool
name := string(k.Value.(ast.String))
if handler, ok = tokenConstraintTypes[name]; ok {
if err = handler(v.Value, &constraints); err != nil {
return
}
} else {
// Anything unknown is rejected.
err = fmt.Errorf("unknown token validation constraint: %s", name)
return
}
return
}); err != nil {
return
}
return
}
// validate validates the constraints argument.
func (constraints *tokenConstraints) validate() (err error) {
keys := 0
if constraints.keys != nil {
keys++
}
if constraints.secret != "" {
keys++
}
if keys > 1 {
err = fmt.Errorf("duplicate key constraints")
return
}
if keys < 1 {
err = fmt.Errorf("no key constraint")
return
}
return
}
// verify verifies a JWT using the constraints and the algorithm from the header
func (constraints *tokenConstraints) verify(kid, alg, header, payload, signature string) error {
// Construct the payload
plaintext := []byte(header)
plaintext = append(plaintext, []byte(".")...)
plaintext = append(plaintext, payload...)
// Look up the algorithm
var ok bool
var a tokenAlgorithm
a, ok = tokenAlgorithms[alg]
if !ok {
return fmt.Errorf("unknown JWS algorithm: %s", alg)
}
// If we're configured with asymmetric key(s) then only trust that
if constraints.keys != nil {
verified := false
for _, key := range constraints.keys {
err := a.verify(key, a.hash, plaintext, []byte(signature))
if err == nil {
verified = true
break
}
}
if !verified {
return errSignatureNotVerified
}
return nil
}
if constraints.secret != "" {
return a.verify([]byte(constraints.secret), a.hash, plaintext, []byte(signature))
}
// (*tokenConstraints)validate() should prevent this happening
return errors.New("unexpectedly found no keys to trust")
}
// validAudience checks the audience of the JWT.
// It returns true if it meets the constraints and false otherwise.
func (constraints *tokenConstraints) validAudience(aud ast.Value) (valid bool) {
var ok bool
var s ast.String
if s, ok = aud.(ast.String); ok {
return string(s) == constraints.aud
}
var a ast.Array
if a, ok = aud.(ast.Array); ok {
for _, t := range a {
if s, ok = t.Value.(ast.String); ok {
if string(s) == constraints.aud {
return true
}
} else {
// Ill-formed aud claim
return false
}
}
}
return false
}
// JWT algorithms
type tokenVerifyFunction func(key interface{}, hash crypto.Hash, payload []byte, signature []byte) (err error)
type tokenVerifyAsymmetricFunction func(key interface{}, hash crypto.Hash, digest []byte, signature []byte) (err error)
// jwtAlgorithm describes a JWS 'alg' value
type tokenAlgorithm struct {
hash crypto.Hash
verify tokenVerifyFunction
}
// tokenAlgorithms is the known JWT algorithms
var tokenAlgorithms = map[string]tokenAlgorithm{
"RS256": {crypto.SHA256, verifyAsymmetric(verifyRSAPKCS)},
"RS384": {crypto.SHA384, verifyAsymmetric(verifyRSAPKCS)},
"RS512": {crypto.SHA512, verifyAsymmetric(verifyRSAPKCS)},
"PS256": {crypto.SHA256, verifyAsymmetric(verifyRSAPSS)},
"PS384": {crypto.SHA384, verifyAsymmetric(verifyRSAPSS)},
"PS512": {crypto.SHA512, verifyAsymmetric(verifyRSAPSS)},
"ES256": {crypto.SHA256, verifyAsymmetric(verifyECDSA)},
"ES384": {crypto.SHA384, verifyAsymmetric(verifyECDSA)},
"ES512": {crypto.SHA512, verifyAsymmetric(verifyECDSA)},
"HS256": {crypto.SHA256, verifyHMAC},
"HS384": {crypto.SHA384, verifyHMAC},
"HS512": {crypto.SHA512, verifyHMAC},
}
// errSignatureNotVerified is returned when a signature cannot be verified.
var errSignatureNotVerified = errors.New("signature not verified")
func verifyHMAC(key interface{}, hash crypto.Hash, payload []byte, signature []byte) (err error) {
macKey, ok := key.([]byte)
if !ok {
return fmt.Errorf("incorrect symmetric key type")
}
mac := hmac.New(hash.New, macKey)
if _, err = mac.Write([]byte(payload)); err != nil {
return
}
if !hmac.Equal(signature, mac.Sum([]byte{})) {
err = errSignatureNotVerified
}
return
}
func verifyAsymmetric(verify tokenVerifyAsymmetricFunction) tokenVerifyFunction {
return func(key interface{}, hash crypto.Hash, payload []byte, signature []byte) (err error) {
h := hash.New()
h.Write(payload)
return verify(key, hash, h.Sum([]byte{}), signature)
}
}
func verifyRSAPKCS(key interface{}, hash crypto.Hash, digest []byte, signature []byte) (err error) {
publicKeyRsa, ok := key.(*rsa.PublicKey)
if !ok {
return fmt.Errorf("incorrect public key type")
}
if err = rsa.VerifyPKCS1v15(publicKeyRsa, hash, digest, signature); err != nil {
err = errSignatureNotVerified
}
return
}
func verifyRSAPSS(key interface{}, hash crypto.Hash, digest []byte, signature []byte) (err error) {
publicKeyRsa, ok := key.(*rsa.PublicKey)
if !ok {
return fmt.Errorf("incorrect public key type")
}
if err = rsa.VerifyPSS(publicKeyRsa, hash, digest, signature, nil); err != nil {
err = errSignatureNotVerified
}
return
}
func verifyECDSA(key interface{}, hash crypto.Hash, digest []byte, signature []byte) (err error) {
publicKeyEcdsa, ok := key.(*ecdsa.PublicKey)
if !ok {
return fmt.Errorf("incorrect public key type")
}
r, s := &big.Int{}, &big.Int{}
n := len(signature) / 2
r.SetBytes(signature[:n])
s.SetBytes(signature[n:])
if ecdsa.Verify(publicKeyEcdsa, digest, r, s) {
return nil
}
return errSignatureNotVerified
}
// JWT header parsing and parameters. See tokens_test.go for unit tests.
// tokenHeaderType represents a recognized JWT header field
// tokenHeader is a parsed JWT header
type tokenHeader struct {
alg string
kid string
typ string
cty string
crit map[string]bool
unknown []string
}
// tokenHeaderHandler handles a JWT header parameters
type tokenHeaderHandler func(header *tokenHeader, value ast.Value) (err error)
// tokenHeaderTypes maps known JWT header parameters to handlers
var tokenHeaderTypes = map[string]tokenHeaderHandler{
"alg": func(header *tokenHeader, value ast.Value) (err error) {
return tokenHeaderString("alg", &header.alg, value)
},
"kid": func(header *tokenHeader, value ast.Value) (err error) {
return tokenHeaderString("kid", &header.kid, value)
},
"typ": func(header *tokenHeader, value ast.Value) (err error) {
return tokenHeaderString("typ", &header.typ, value)
},
"cty": func(header *tokenHeader, value ast.Value) (err error) {
return tokenHeaderString("cty", &header.cty, value)
},
"crit": tokenHeaderCrit,
}
// tokenHeaderCrit handles the 'crit' header parameter
func tokenHeaderCrit(header *tokenHeader, value ast.Value) (err error) {
var ok bool
var v ast.Array
if v, ok = value.(ast.Array); !ok {
err = fmt.Errorf("crit: must be a list")
return
}
header.crit = map[string]bool{}
for _, t := range v {
var tv ast.String
if tv, ok = t.Value.(ast.String); !ok {
err = fmt.Errorf("crit: must be a list of strings")
return
}
header.crit[string(tv)] = true
}
if len(header.crit) == 0 {
err = fmt.Errorf("crit: must be a nonempty list") // 'MUST NOT' use the empty list
return
}
return
}
// tokenHeaderString handles string-format JWT header parameters
func tokenHeaderString(name string, where *string, value ast.Value) (err error) {
var ok bool
var v ast.String
if v, ok = value.(ast.String); !ok {
err = fmt.Errorf("%s: must be a string", name)
return
}
*where = string(v)
return
}
// parseTokenHeader parses the JWT header.
func parseTokenHeader(token *JSONWebToken) (header tokenHeader, err error) {
header.unknown = []string{}
if err = token.decodedHeader.Iter(func(k *ast.Term, v *ast.Term) (err error) {
ks := string(k.Value.(ast.String))
var ok bool
var handler tokenHeaderHandler
if handler, ok = tokenHeaderTypes[ks]; ok {
if err = handler(&header, v.Value); err != nil {
return
}
} else {
header.unknown = append(header.unknown, ks)
}
return
}); err != nil {
return
}
return
}
// validTokenHeader returns true if the JOSE header is valid, otherwise false.
func (header *tokenHeader) valid() bool {
// RFC7515 s4.1.1 alg MUST be present
if header.alg == "" {
return false
}
// RFC7515 4.1.11 JWS is invalid if there is a critical parameter that we did not recognize
for _, u := range header.unknown {
if header.crit[u] {
return false
}
}
return true
}
func commonBuiltinJWTEncodeSign(inputHeaders, jwsPayload, jwkSrc string) (v ast.Value, err error) {
keys, err := jwk.ParseString(jwkSrc)
if err != nil {
return nil, err
}
key, err := keys.Keys[0].Materialize()
if err != nil {
return nil, err
}
if jwk.GetKeyTypeFromKey(key) != keys.Keys[0].GetKeyType() {
return nil, fmt.Errorf("JWK derived key type and keyType parameter do not match")
}
standardHeaders := &jws.StandardHeaders{}
jwsHeaders := []byte(inputHeaders)
err = json.Unmarshal(jwsHeaders, standardHeaders)
if err != nil {
return nil, err
}
alg := standardHeaders.GetAlgorithm()
if (standardHeaders.Type == "" || standardHeaders.Type == "JWT") && !json.Valid([]byte(jwsPayload)) {
return nil, fmt.Errorf("type is JWT but payload is not JSON")
}
// process payload and sign
var jwsCompact []byte
jwsCompact, err = jws.SignLiteral([]byte(jwsPayload), alg, key, jwsHeaders)
if err != nil {
return nil, err
}
return ast.String(jwsCompact[:]), nil
}
func builtinJWTEncodeSign(a ast.Value, b ast.Value, c ast.Value) (v ast.Value, err error) {
jwkSrc := c.String()
inputHeaders := a.String()
jwsPayload := b.String()
return commonBuiltinJWTEncodeSign(inputHeaders, jwsPayload, jwkSrc)
}
func builtinJWTEncodeSignRaw(a ast.Value, b ast.Value, c ast.Value) (v ast.Value, err error) {
jwkSrc, err := builtins.StringOperand(c, 1)
if err != nil {
return nil, err
}
inputHeaders, err := builtins.StringOperand(a, 1)
if err != nil {
return nil, err
}
jwsPayload, err := builtins.StringOperand(b, 1)
if err != nil {
return nil, err
}
return commonBuiltinJWTEncodeSign(string(inputHeaders), string(jwsPayload), string(jwkSrc))
}
// Implements full JWT decoding, validation and verification.
func builtinJWTDecodeVerify(a ast.Value, b ast.Value) (v ast.Value, err error) {
// io.jwt.decode_verify(string, constraints, [valid, header, payload])
//
// If valid is true then the signature verifies and all constraints are met.
// If valid is false then either the signature did not verify or some constrain
// was not met.
//
// Decoding errors etc are returned as errors.
arr := make(ast.Array, 3)
arr[0] = ast.BooleanTerm(false) // by default, not verified
arr[1] = ast.NewTerm(ast.NewObject())
arr[2] = ast.NewTerm(ast.NewObject())
var constraints tokenConstraints
if constraints, err = parseTokenConstraints(b); err != nil {
return
}
if err = constraints.validate(); err != nil {
return
}
var token *JSONWebToken
var p ast.Value
for {
// RFC7519 7.2 #1-2 split into parts
if token, err = decodeJWT(a); err != nil {
return
}
// RFC7519 7.2 #3, #4, #6
if err = token.decodeHeader(); err != nil {
return
}
// RFC7159 7.2 #5 (and RFC7159 5.2 #5) validate header fields
var header tokenHeader
if header, err = parseTokenHeader(token); err != nil {
return
}
if !header.valid() {
return arr, nil
}
// Check constraints that impact signature verification.
if constraints.alg != "" && constraints.alg != header.alg {
return arr, nil
}
// RFC7159 7.2 #7 verify the signature
var signature string
if signature, err = token.decodeSignature(); err != nil {
return
}
if err = constraints.verify(header.kid, header.alg, token.header, token.payload, signature); err != nil {
if err == errSignatureNotVerified {
return arr, nil
}
return
}
// RFC7159 7.2 #9-10 decode the payload
if p, err = builtinBase64UrlDecode(ast.String(token.payload)); err != nil {
return nil, fmt.Errorf("JWT payload had invalid encoding: %v", err)
}
// RFC7159 7.2 #8 and 5.2 cty
if strings.ToUpper(header.cty) == "JWT" {
// Nested JWT, go round again
a = p
continue
} else {
// Non-nested JWT (or we've reached the bottom of the nesting).
break
}
}
var payload ast.Object
if payload, err = extractJSONObject(string(p.(ast.String))); err != nil {
return
}
// Check registered claim names against constraints or environment
// RFC7159 4.1.1 iss
if constraints.iss != "" {
if iss := payload.Get(jwtIssKey); iss != nil {
issVal := string(iss.Value.(ast.String))
if constraints.iss != issVal {
return arr, nil
}
}
}
// RFC7159 4.1.3 aud
if aud := payload.Get(jwtAudKey); aud != nil {
if !constraints.validAudience(aud.Value) {
return arr, nil
}
} else {
if constraints.aud != "" {
return arr, nil
}
}
// RFC7159 4.1.4 exp
if exp := payload.Get(jwtExpKey); exp != nil {
if constraints.time < 0 {
constraints.time = time.Now().UnixNano()
}
// constraints.time is in nanoseconds but exp Value is in seconds
compareTime := ast.Number(strconv.FormatFloat(float64(constraints.time)/1000000000, 'g', -1, 64))