-
Notifications
You must be signed in to change notification settings - Fork 202
/
verify.go
576 lines (502 loc) · 14.4 KB
/
verify.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
package jwt
import (
"crypto"
"crypto/ecdsa"
"crypto/hmac"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"github.com/ohler55/ojg/jp"
"github.com/ohler55/ojg/oj"
"math/big"
"reflect"
"strings"
"time"
)
type jwtToken struct {
Token string
Header64 string
Claims64 string
Signature64 string
Header map[string]interface{}
Claims map[string]interface{}
Signature string
}
type signingMethod struct {
Name string
Hash crypto.Hash
KeySize int
CurveBits int
}
var (
errInvalidKey = errors.New("key is invalid")
errInvalidKeyType = errors.New("key is of invalid type")
errHashUnavailable = errors.New("the requested hash function is unavailable")
errSignatureInvalid = errors.New("signature is invalid")
errInvalidSigningMethod = errors.New("signing method is invalid")
errECDSAVerification = errors.New("crypto/ecdsa: verification error")
errKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key")
errNotRSAPublicKey = errors.New("Key is not a valid RSA public key")
errNotECPublicKey = errors.New("Key is not a valid ECDSA public key")
)
func newSigningMethod(name string) *signingMethod {
switch name {
case "HS256":
return &signingMethod{Name: name, Hash: crypto.SHA256}
case "HS384":
return &signingMethod{Name: name, Hash: crypto.SHA384}
case "HS512":
return &signingMethod{Name: name, Hash: crypto.SHA512}
case "RS256":
return &signingMethod{Name: name, Hash: crypto.SHA256}
case "RS384":
return &signingMethod{Name: name, Hash: crypto.SHA384}
case "RS512":
return &signingMethod{Name: name, Hash: crypto.SHA512}
case "ES256":
return &signingMethod{Name: name, Hash: crypto.SHA256, KeySize: 32, CurveBits: 256}
case "ES384":
return &signingMethod{Name: name, Hash: crypto.SHA384, KeySize: 48, CurveBits: 384}
case "ES512":
return &signingMethod{Name: name, Hash: crypto.SHA512, KeySize: 66, CurveBits: 512}
default:
return nil
}
}
func (m *signingMethod) Verify(signingString, signature string, key interface{}) error {
switch m.Name {
case "HS256", "HS384", "HS512":
{
// Verify the key is the right type
keyBytes, ok := key.([]byte)
if !ok {
return errInvalidKeyType
}
// Decode signature, for comparison
sig, err := decodeSegment(signature)
if err != nil {
return err
}
// Can we use the specified hashing method?
if !m.Hash.Available() {
return errHashUnavailable
}
// This signing method is symmetric, so we validate the signature
// by reproducing the signature from the signing string and key, then
// comparing that against the provided signature.
hasher := hmac.New(m.Hash.New, keyBytes)
hasher.Write([]byte(signingString))
if !hmac.Equal(sig, hasher.Sum(nil)) {
return errSignatureInvalid
}
// No validation errors. Signature is good.
return nil
}
case "RS256", "RS384", "RS512":
{
var err error
// Decode the signature
var sig []byte
if sig, err = decodeSegment(signature); err != nil {
return err
}
var rsaKey *rsa.PublicKey
var ok bool
if rsaKey, ok = key.(*rsa.PublicKey); !ok {
return errInvalidKeyType
}
// Create hasher
if !m.Hash.Available() {
return errHashUnavailable
}
hasher := m.Hash.New()
hasher.Write([]byte(signingString))
// Verify the signature
return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig)
}
case "ES256", "ES384", "ES512":
{
var err error
// Decode the signature
var sig []byte
if sig, err = decodeSegment(signature); err != nil {
return err
}
// GetEmployee the key
var ecdsaKey *ecdsa.PublicKey
switch k := key.(type) {
case *ecdsa.PublicKey:
ecdsaKey = k
default:
return errInvalidKeyType
}
if len(sig) != 2*m.KeySize {
return errECDSAVerification
}
r := big.NewInt(0).SetBytes(sig[:m.KeySize])
s := big.NewInt(0).SetBytes(sig[m.KeySize:])
// Create hasher
if !m.Hash.Available() {
return errHashUnavailable
}
hasher := m.Hash.New()
hasher.Write([]byte(signingString))
// Verify the signature
if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true {
return nil
}
return errECDSAVerification
}
default:
return errInvalidSigningMethod
}
}
func (m *signingMethod) Sign(signingString string, key interface{}) (string, error) {
switch m.Name {
case "HS256", "HS384", "HS512":
{
if keyBytes, ok := key.([]byte); ok {
if !m.Hash.Available() {
return "", errHashUnavailable
}
hasher := hmac.New(m.Hash.New, keyBytes)
hasher.Write([]byte(signingString))
return encodeSegment(hasher.Sum(nil)), nil
}
return "", errInvalidKeyType
}
case "RS256", "RS384", "RS512":
{
var rsaKey *rsa.PrivateKey
var ok bool
// Validate type of key
if rsaKey, ok = key.(*rsa.PrivateKey); !ok {
return "", errInvalidKey
}
// Create the hasher
if !m.Hash.Available() {
return "", errHashUnavailable
}
hasher := m.Hash.New()
hasher.Write([]byte(signingString))
// Sign the string and return the encoded bytes
if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil {
return encodeSegment(sigBytes), nil
} else {
return "", err
}
}
case "ES256", "ES384", "ES512":
{
// GetEmployee the key
var ecdsaKey *ecdsa.PrivateKey
switch k := key.(type) {
case *ecdsa.PrivateKey:
ecdsaKey = k
default:
return "", errInvalidKeyType
}
// Create the hasher
if !m.Hash.Available() {
return "", errHashUnavailable
}
hasher := m.Hash.New()
hasher.Write([]byte(signingString))
// Sign the string and return r, s
if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil {
curveBits := ecdsaKey.Curve.Params().BitSize
if m.CurveBits != curveBits {
return "", errInvalidKey
}
keyBytes := curveBits / 8
if curveBits%8 > 0 {
keyBytes++
}
// We serialize the outpus (r and s) into big-endian byte arrays and pad
// them with zeros on the left to make sure the sizes work out. Both arrays
// must be keyBytes long, and the output must be 2*keyBytes long.
rBytes := r.Bytes()
rBytesPadded := make([]byte, keyBytes)
copy(rBytesPadded[keyBytes-len(rBytes):], rBytes)
sBytes := s.Bytes()
sBytesPadded := make([]byte, keyBytes)
copy(sBytesPadded[keyBytes-len(sBytes):], sBytes)
out := append(rBytesPadded, sBytesPadded...)
return encodeSegment(out), nil
} else {
return "", err
}
}
default:
{
return "", errInvalidSigningMethod
}
}
}
func methodEnable(method string) bool {
if method == "HS256" || method == "HS384" || method == "HS512" || method == "RS256" || method == "RS384" || method == "RS512" || method == "ES256" || method == "ES384" || method == "ES512" {
return true
}
return false
}
// Decode JWT specific base64url encoding with padding stripped
func decodeSegment(seg string) ([]byte, error) {
if l := len(seg) % 4; l > 0 {
seg += strings.Repeat("=", 4-l)
}
return base64.URLEncoding.DecodeString(seg)
}
// encode JWT specific base64url encoding with padding stripped
func encodeSegment(seg []byte) string {
return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=")
}
//ParseRSAPublicKeyFromPEM parse PEM encoded PKCS1 or PKCS8 public key
func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
var err error
// parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, errKeyMustBePEMEncoded
}
// parse the key
var parsedKey interface{}
if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
parsedKey = cert.PublicKey
} else {
return nil, err
}
}
var pkey *rsa.PublicKey
var ok bool
if pkey, ok = parsedKey.(*rsa.PublicKey); !ok {
return nil, errNotRSAPublicKey
}
return pkey, nil
}
//ParseECPublicKeyFromPEM parse PEM encoded PKCS1 or PKCS8 public key
func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) {
var err error
// parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, errKeyMustBePEMEncoded
}
// parse the key
var parsedKey interface{}
if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
parsedKey = cert.PublicKey
} else {
return nil, err
}
}
var pkey *ecdsa.PublicKey
var ok bool
if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok {
return nil, errNotECPublicKey
}
return pkey, nil
}
// base64解密
func b64Decode(input string) (string, error) {
remainder := len(input) % 4
// base64编码需要为4的倍数,如果不是4的倍数,则填充"="号
if remainder > 0 {
padlen := 4 - remainder
input = input + strings.Repeat("=", padlen)
}
// 将原字符串中的"_","-"分别用"/"和"+"替换
input = strings.Replace(strings.Replace(input, "_", "/", -1), "-", "+", -1)
result, err := base64.StdEncoding.DecodeString(input)
return string(result), err
}
// 根据"."分割token字符串
func tokenize(token string) []string {
parts := strings.Split(token, ".")
if len(parts) == 3 {
return parts
}
return nil
}
// 解析token,将token信息解析为jwtToken对象
func decodeToken(token string) (*jwtToken, error) {
tokenParts := tokenize(token)
if tokenParts == nil {
return nil, errors.New("[jwt_auth] Invalid token")
}
header64 := tokenParts[0]
claims64 := tokenParts[1]
signature64 := tokenParts[2]
var header, claims map[string]interface{}
var signature string
headerD64, err := b64Decode(header64)
if err != nil {
return nil, errors.New("[jwt_auth] Invalid base64 encoded JSON")
}
if err = json.Unmarshal([]byte(headerD64), &header); err != nil {
return nil, errors.New("[jwt_auth] Invalid JSON")
}
claimsD64, err := b64Decode(claims64)
if err != nil {
return nil, errors.New("[jwt_auth] Invalid base64 encoded JSON")
}
if err = json.Unmarshal([]byte(claimsD64), &claims); err != nil {
return nil, errors.New("[jwt_auth] Invalid JSON")
}
signature, err = b64Decode(signature64)
if err != nil {
return nil, errors.New("[jwt_auth] Invalid base64 encoded JSON")
}
if _, ok := header["typ"]; !ok || strings.ToUpper(header["typ"].(string)) != "JWT" {
return nil, errors.New("[jwt_auth] Invalid typ")
}
if _, ok := header["alg"]; !ok || !methodEnable(header["alg"].(string)) {
return nil, errors.New("[jwt_auth] Invalid alg")
}
if len(claims) == 0 {
return nil, errors.New("[jwt_auth] Invalid claims")
}
if len(signature) == 0 {
return nil, errors.New("[jwt_auth] Invalid signature")
}
return &jwtToken{Token: token, Header64: header64, Claims64: claims64, Signature64: signature64, Header: header, Claims: claims, Signature: signature}, nil
}
//verifySignature 验证签名
func verifySignature(token *jwtToken, key string) error {
var k interface{}
switch token.Header["alg"].(string) {
case "HS256", "HS384", "HS512":
{
k = []byte(key)
}
case "RS256", "RS384", "RS512":
{
var err error
k, err = ParseRSAPublicKeyFromPEM([]byte(key))
if err != nil {
return err
}
}
case "ES256", "ES384", "ES512":
{
var err error
k, err = ParseECPublicKeyFromPEM([]byte(key))
if err != nil {
return err
}
}
default:
{
return errInvalidSigningMethod
}
}
return newSigningMethod(token.Header["alg"].(string)).Verify(token.Header64+"."+token.Claims64, token.Signature64, k)
}
//verifyRegisteredClaims 验证签发字段
func verifyRegisteredClaims(token *jwtToken, claimsToVerify []string) error {
if claimsToVerify == nil {
claimsToVerify = []string{}
}
for _, claimName := range claimsToVerify {
var claim int64 = 0
if _, ok := token.Claims[claimName]; ok {
if typeOfData(token.Claims[claimName]) == reflect.Float64 {
claimFloat64, success := token.Claims[claimName].(float64)
if success {
claim = int64(claimFloat64)
}
}
}
if claim < 1 {
return errors.New("[jwt_auth] " + claimName + " must be a number")
}
switch claimName {
case "nbf":
if claim > time.Now().Unix() {
return errors.New("[jwt_auth] token not valid yet")
}
case "exp":
if claim <= time.Now().Unix() {
return errors.New("[jwt_auth] token expired")
}
default:
return errors.New("[jwt_auth] Invalid claims")
}
}
return nil
}
//获取数据的类型
func typeOfData(data interface{}) reflect.Kind {
value := reflect.ValueOf(data)
valueType := value.Kind()
if valueType == reflect.Ptr {
valueType = value.Elem().Kind()
}
return valueType
}
//doJWTAuthentication 进行JWT鉴权
func (j *jwt) doJWTAuthentication(tokenStr string) (string, error) {
token, err := decodeToken(tokenStr)
if err != nil {
return "", errors.New("Bad token; " + err.Error())
}
key := ""
keyClaimName := "iss"
if _, ok := token.Claims[keyClaimName]; ok {
key = token.Claims[keyClaimName].(string)
} else if _, ok = token.Header[keyClaimName]; ok {
key = token.Header[keyClaimName].(string)
}
if key == "" {
return "", errors.New("no mandatory " + keyClaimName + " in claims")
}
algorithm := token.Header["alg"].(string)
if j.cfg.Algorithm != algorithm {
return "", fmt.Errorf("no match algorithm,need %s,now %s", j.cfg.Algorithm, algorithm)
}
jwtSecretValue := ""
if algorithm == "HS256" || algorithm == "HS384" || algorithm == "HS512" {
jwtSecretValue = j.cfg.Secret
if j.cfg.SignatureIsBase64 {
jwtSecretValue, err = b64Decode(jwtSecretValue)
if err != nil {
return "", errors.New("invalid key/secret")
}
}
} else {
jwtSecretValue = j.cfg.RsaPublicKey
}
if jwtSecretValue == "" {
return "", errors.New("invalid key/secret")
}
if err = verifySignature(token, jwtSecretValue); err != nil {
return "", errors.New("[jwt_auth] Invalid signature")
}
if err = verifyRegisteredClaims(token, j.cfg.ClaimsToVerify); err != nil {
return "", err
}
data, _ := json.Marshal(token.Claims)
return getUserByPath(data, j.cfg.Path)
}
func getUserByPath(data []byte, path string) (string, error) {
obj, err := oj.Parse(data)
x, err := jp.ParseString(path)
if err != nil {
return "", err
}
targets := x.Get(obj)
if len(targets) < 1 {
return "", errors.New("user not found")
}
v, ok := targets[0].(string)
if !ok {
return "", errors.New("invalid data type")
}
return v, nil
}