forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathauth.go
More file actions
1128 lines (979 loc) · 25.6 KB
/
auth.go
File metadata and controls
1128 lines (979 loc) · 25.6 KB
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
package uadmin
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"math/big"
"net"
"os"
"path"
"sync"
"crypto/hmac"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"math"
"net/http"
"strconv"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
)
// CookieTimeout is the timeout of a login cookie in seconds.
// If the value is -1, then the session cookie will not have
// an expiry date.
var CookieTimeout = -1
var defaultCookieTimeout = int((time.Hour * 24).Seconds()) // 24 hours in seconds
// Salt is added to password hashing
var Salt = ""
// JWT secret for signing tokens
var JWT = ""
// jwtIssuer is a URL to identify the application issuing JWT tokens.
// If left empty, a partial hash of JWT will be assigned. This is also
// used to identify the as JWT audience.
var JWTIssuer = ""
var JWTAlgo = "HS256" //"RS256"
// AcceptedJWTIssuers is a list of accepted JWT issuers. By default the
// local JWTIssuer is accepted. To accept other issuers, add them to
// this list
var AcceptedJWTIssuers = []string{}
// bcryptDiff
var bcryptDiff = 12
// cachedSessions is variable for keeping active sessions
var cachedSessions map[string]Session
// Need to have a lock to protect it from race conditions during concurrent writes.
var cachedSessionsMutex sync.RWMutex
// invalidAttempts keeps track of invalid password attempts
// per IP address
var invalidAttempts = map[string]int{}
var CustomJWT func(r *http.Request, s *Session, payload map[string]interface{}) map[string]interface{}
// GenerateBase64 generates a base64 string of length length
func GenerateBase64(length int) string {
base := new(big.Int)
base.SetString("64", 10)
base64 := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
tempKey := ""
for i := 0; i < length; i++ {
index, _ := rand.Int(rand.Reader, base)
tempKey += string(base64[int(index.Int64())])
}
return tempKey
}
// GenerateBase32 generates a base32 string of length length
func GenerateBase32(length int) string {
base := new(big.Int)
base.SetString("32", 10)
base32 := "234567abcdefghijklmnopqrstuvwxyz"
tempKey := ""
for i := 0; i < length; i++ {
index, _ := rand.Int(rand.Reader, base)
tempKey += string(base32[int(index.Int64())])
}
return tempKey
}
// saltPassword prepares password to use in bcrypt algorithms
func saltPassword(pass string) []byte {
password := []byte(pass + Salt)
if len(password) > 72 {
password = password[:72]
}
return password
}
// hashPass Generates a hash from a password and salt
func hashPass(pass string) string {
password := saltPassword(pass)
hash, err := bcrypt.GenerateFromPassword(password, bcryptDiff)
if err != nil {
Trail(ERROR, "uadmin.auth.hashPass.GenerateFromPassword: %s", err)
return ""
}
return string(hash)
}
// IsAuthenticated returns if the http.Request is authenticated or not
func IsAuthenticated(r *http.Request) *Session {
key := getSession(r)
if strings.HasPrefix(key, "nouser:") {
return nil
}
s := getSessionByKey(key)
if isValidSession(r, s) {
return s
}
return nil
}
// SetCookieTimeout checks if CookieTimeout should be set to a custom value,
// or to use the default value
func SetCookieTimeout() {
CookieTimeout = defaultCookieTimeout
if ct := os.Getenv("COOKIE_TIMEOUT_SECONDS"); ct != "" {
timeout, err := strconv.Atoi(ct)
if err == nil {
CookieTimeout = int(timeout)
}
}
}
// SetSessionCookie sets the session cookie value, The the value passed in
// session is nil, then the session assigned will be a no user session
func SetSessionCookie(w http.ResponseWriter, r *http.Request, s *Session) string {
if s == nil {
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: "nouser:" + GenerateBase64(124),
SameSite: http.SameSiteStrictMode,
Path: "/",
Expires: time.Now().AddDate(0, 0, 1),
})
} else {
sessionCookie := &http.Cookie{
Name: "session",
Value: s.Key,
SameSite: http.SameSiteStrictMode,
Path: "/",
}
if s.ExpiresOn != nil {
sessionCookie.Expires = *s.ExpiresOn
}
http.SetCookie(w, sessionCookie)
jwt := createJWT(r, s)
jwtCookie := &http.Cookie{
Name: "access-jwt",
Value: jwt,
SameSite: http.SameSiteStrictMode,
Path: "/",
}
if s.ExpiresOn != nil {
jwtCookie.Expires = *s.ExpiresOn
}
http.SetCookie(w, jwtCookie)
return jwt
}
return ""
}
func createJWT(r *http.Request, s *Session) string {
if s == nil {
return ""
}
if !isValidSession(r, s) {
return ""
}
alg := JWTAlgo
aud := JWTIssuer
SSO := false
if r.Context().Value(CKey("aud")) != nil {
aud = r.Context().Value(CKey("aud")).(string)
SSO = true
}
header := map[string]interface{}{
"alg": alg,
"typ": "JWT",
}
payload := map[string]interface{}{
"sub": s.User.Username,
"iat": s.LastLogin.Unix(),
"iss": JWTIssuer,
"aud": aud,
}
if s.ExpiresOn != nil {
payload["exp"] = s.ExpiresOn.Unix()
}
// Check for custom JWT handler
if CustomJWT != nil {
payload = CustomJWT(r, s, payload)
}
// TODO: Add custom handler to customize JWT
// This custom function show have parameters for:
// JWT Object
// SSO boolean
// Algorithm
// User
// *Session
if alg == "HS256" {
jHeader, _ := json.Marshal(header)
jPayload, _ := json.Marshal(payload)
b64Header := base64.RawURLEncoding.EncodeToString(jHeader)
b64Payload := base64.RawURLEncoding.EncodeToString(jPayload)
hash := hmac.New(sha256.New, []byte(JWT+s.Key))
hash.Write([]byte(b64Header + "." + b64Payload))
signature := hash.Sum(nil)
b64Signature := base64.RawURLEncoding.EncodeToString(signature)
return b64Header + "." + b64Payload + "." + b64Signature
} else if alg == "RS256" {
buf, err := os.ReadFile(".jwt-rsa-private.pem")
if err != nil {
return ""
}
key, err := jwt.ParseRSAPrivateKeyFromPEM(buf)
if err != nil {
return ""
}
// Customize JWT Data
header["kid"] = "1"
// Extra customization for SSO
if SSO {
payload["name"] = s.User.String()
payload["given_name"] = s.User.FirstName
payload["family_name"] = s.User.LastName
payload["email"] = s.User.Email
if s.User.Photo != "" {
payload["picture"] = JWTIssuer + strings.TrimSuffix(RootURL, "/") + s.User.Photo + "?token=" + strings.TrimPrefix(hashPass(s.User.Photo), "$2a$12$")
}
groups := []map[string]interface{}{}
if s.User.UserGroupID != 0 {
Preload(&s.User, "UserGroup")
groups = append(groups, map[string]interface{}{
"displayName": s.User.UserGroup.GroupName,
"id": s.User.UserGroupID,
})
}
if s.User.Admin {
groups = append(groups, map[string]interface{}{
"displayName": "$admin",
"id": 0,
})
}
payload["groups"] = groups
entitlements := []map[string]interface{}{}
for k := range models {
perm := s.User.GetAccess(k)
entitlements = append(entitlements, map[string]interface{}{
"modelName": k,
"read": perm.Read,
"add": perm.Add,
"edit": perm.Edit,
"delete": perm.Delete,
"approval": perm.Approval,
})
}
payload["entitlements"] = entitlements
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims(payload))
for k, v := range header {
token.Header[k] = v
}
tokenRaw, err := token.SignedString(key)
if err != nil {
return ""
}
return tokenRaw
} else {
Trail(ERROR, "Unknown algorithm for JWT (%s)", alg)
return ""
}
}
func isValidSession(r *http.Request, s *Session) bool {
valid, otpPending := isValidSessionOTP(r, s)
return valid && !otpPending
}
func isValidSessionOTP(r *http.Request, s *Session) (bool, bool) {
if s != nil && s.ID != 0 {
if s.Active && (s.ExpiresOn == nil || s.ExpiresOn.After(time.Now())) {
if s.User.ID != s.UserID {
Get(&s.User, "id = ?", s.UserID)
}
if s.User.Active && (s.User.ExpiresOn == nil || s.User.ExpiresOn.After(time.Now())) {
// Check for IP restricted session
if RestrictSessionIP {
ip := GetRemoteIP(r)
return ip == s.IP, s.PendingOTP
}
return true, s.PendingOTP
}
}
}
return false, false
}
// GetUserFromRequest returns a user from a request
func GetUserFromRequest(r *http.Request) *User {
s := getSessionFromRequest(r)
if s != nil {
if s.User.ID == 0 {
Get(&s.User, "id = ?", s.UserID)
}
if s.User.ID != 0 {
return &s.User
}
}
return nil
}
// getSessionFromRequest returns a session from a request
func getSessionFromRequest(r *http.Request) *Session {
key := getSession(r)
s := getSessionByKey(key)
if s != nil && s.ID != 0 {
return s
}
return nil
}
// Login return *User and a bool for Is OTP Required
func Login(r *http.Request, username string, password string) (*Session, bool) {
if PreLoginHandler != nil {
PreLoginHandler(r, username, password)
}
// Get the user from DB
user := User{}
Get(&user, "username = ?", username)
if user.ID == 0 {
IncrementMetric("uadmin/security/invalidlogin")
go func() {
log := &Log{}
if r.Form == nil {
r.ParseForm()
}
ctx := context.WithValue(r.Context(), CKey("login-status"), "invalid username")
r = r.WithContext(ctx)
log.SignIn(username, log.Action.LoginDenied(), r)
log.Save()
}()
incrementInvalidLogins(r)
return nil, false
}
s := user.Login(password, "")
if s != nil && s.ID != 0 {
s.IP = GetRemoteIP(r)
s.Save()
if s.Active && (s.ExpiresOn == nil || s.ExpiresOn.After(time.Now())) {
s.User = user
if s.User.Active && (s.User.ExpiresOn == nil || s.User.ExpiresOn.After(time.Now())) {
IncrementMetric("uadmin/security/validlogin")
// Store login successful to the user log
go func() {
log := &Log{}
if r.Form == nil {
r.ParseForm()
}
log.SignIn(user.Username, log.Action.LoginSuccessful(), r)
log.Save()
}()
return s, s.User.OTPRequired
}
}
} else {
go func() {
log := &Log{}
if r.Form == nil {
r.ParseForm()
}
ctx := context.WithValue(r.Context(), CKey("login-status"), "invalid password or inactive user")
r = r.WithContext(ctx)
log.SignIn(username, log.Action.LoginDenied(), r)
log.Save()
}()
}
incrementInvalidLogins(r)
// Record metrics
IncrementMetric("uadmin/security/invalidlogin")
return nil, false
}
// Login2FA login using username, password and otp for users with OTPRequired = true
func Login2FA(r *http.Request, username string, password string, otpPass string) *Session {
s, otpRequired := Login(r, username, password)
if s != nil {
if otpRequired && s.User.VerifyOTP(otpPass) {
s.PendingOTP = false
s.Save()
} else if otpRequired && !s.User.VerifyOTP(otpPass) && otpPass != "" {
incrementInvalidLogins(r)
}
return s
}
return nil
}
func incrementInvalidLogins(r *http.Request) {
// Increment password attempts and check if it reached
// the maximum invalid password attempts
ip := GetRemoteIP(r)
invalidAttempts[ip]++
if invalidAttempts[ip] >= PasswordAttempts {
rateLimitLock.Lock()
rateLimitMap[ip] = time.Now().Add(time.Duration(PasswordTimeout)*time.Minute).Unix() * RateLimit
rateLimitLock.Unlock()
}
}
// Login2FA login using username, password and otp for users with OTPRequired = true
func Login2FAKey(r *http.Request, key string, otpPass string) *Session {
s := getSessionByKey(key)
valid, otpPending := isValidSessionOTP(r, s)
if valid {
if otpPending && s.User.VerifyOTP(otpPass) {
s.PendingOTP = false
s.Save()
}
return s
}
return nil
}
// Logout logs out a user
func Logout(r *http.Request) {
s := getSessionFromRequest(r)
if s.ID == 0 {
return
}
// Store Logout to the user log
func() {
log := &Log{}
log.SignIn(s.User.Username, log.Action.Logout(), r)
log.Save()
}()
s.Logout()
// Delete the cookie from memory if we sessions are cached
if CacheSessions {
cachedSessionsMutex.Lock() // Lock the mutex in order to protect from concurrent writes
defer cachedSessionsMutex.Unlock() // Ensure the mutex is unlocked when the function exits
delete(cachedSessions, s.Key)
}
IncrementMetric("uadmin/security/logout")
}
// ValidateIP is a function to check if the IP in the request is allowed in the allowed based on allowed
// and block strings
func ValidateIP(r *http.Request, allow string, block string) bool {
allowed := false
allowSize := uint32(0)
allowList := strings.Split(allow, ",")
for _, net := range allowList {
if v, size := requestInNet(r, net); v {
allowed = true
if size > allowSize {
allowSize = size
}
}
}
blockList := strings.Split(block, ",")
for _, net := range blockList {
if v, size := requestInNet(r, net); v {
if size > allowSize {
allowed = false
break
}
}
}
if !allowed {
IncrementMetric("uadmin/security/blockedip")
}
return allowed
}
func requestInNet(r *http.Request, net string) (bool, uint32) {
ipStr := GetRemoteIP(r)
// Check if the IP is V4
if strings.Contains(ipStr, ".") {
var ip uint32
var subnet uint32
var oct uint64
var mask uint32
// check if the net is IPv4
if !strings.Contains(net, ".") && net != "*" && net != "" {
return false, 0
}
// Convert the IP to uint32
ipParts := strings.Split(strings.Split(ipStr, ":")[0], ".")
for i, o := range ipParts {
oct, _ = strconv.ParseUint(o, 10, 8)
ip += uint32(oct << ((3 - uint(i)) * 8))
}
// convert the net to uint32
// but first convert standard nets to IPv4 format
if net == "*" {
net = "0.0.0.0/0"
} else if net == "" {
net = "255.255.255.255/32"
} else if !strings.Contains(net, "/") {
net += "/32"
}
ipParts = strings.Split(strings.Split(net, "/")[0], ".")
for i, o := range ipParts {
oct, _ = strconv.ParseUint(o, 10, 8)
subnet += uint32(oct << ((3 - uint(i)) * 8))
}
maskLength := getNetSize(r, net)
mask -= uint32(math.Pow(2, float64(32-maskLength)))
return ((ip & mask) ^ subnet) == 0, uint32(maskLength)
}
// Process IPV6
var ip1 uint64
var ip2 uint64
var subnet1 uint64
var subnet2 uint64
var oct uint64
var mask1 uint64
var mask2 uint64
// check if the net is IPv6
if strings.Contains(net, ".") && net != "*" && net != "" {
return false, 0
}
// Normalize IP
ipS := GetRemoteIP(r) // [::1]:10000
ipS = strings.Trim(ipS, "[") // ::1]:10000
ipS = strings.Split(ipS, "]")[0] // ::1
if strings.HasPrefix(ipS, "::") {
ipS = "0" + ipS
} else if strings.HasSuffix(ipS, "::") {
ipS = ipS + "0"
}
// find and replace ::
ipParts := strings.Split(ipS, ":")
ipFinalParts := []uint16{}
processedDC := false
for i := range ipParts {
if ipParts[i] == "" && !processedDC {
processedDC = true
for counter := 0; counter < 8-i-(len(ipParts)-(i+1)); counter++ {
//oct, _ = strconv.ParseUint(ipParts[i], 16, 16)
ipFinalParts = append(ipFinalParts, uint16(0))
}
} else {
oct, _ = strconv.ParseUint(ipParts[i], 16, 16)
ipFinalParts = append(ipFinalParts, uint16(oct))
}
}
// Parse the IP into two uint64 variables
for i := 0; i < 4; i++ {
oct = uint64(ipFinalParts[i])
ip1 += uint64((oct << ((3 - uint(i)) * 16)))
}
for i := 0; i < 4; i++ {
oct = uint64(ipFinalParts[i+4])
ip2 += uint64((oct << ((3 - uint(i)) * 16)))
}
subnetv6 := net
if subnetv6 == "*" {
subnetv6 = "0::0/0"
} else if subnetv6 == "" {
subnetv6 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128"
} else if !strings.Contains(subnetv6, "/") {
subnetv6 = subnetv6 + "/128"
}
maskS := strings.Split(subnetv6, "/")[1]
subnetv6 = strings.Split(subnetv6, "/")[0]
if strings.HasPrefix(subnetv6, "::") {
subnetv6 = "0" + subnetv6
} else if strings.HasSuffix(subnetv6, "::") {
subnetv6 = subnetv6 + "0"
}
// find and replace ::
ipParts = strings.Split(subnetv6, ":")
ipFinalParts = []uint16{}
processedDC = false
for i := range ipParts {
if ipParts[i] == "" && !processedDC {
processedDC = true
for counter := 0; counter < 8-i-(len(ipParts)-(i+1)); counter++ {
//oct, _ = strconv.ParseUint(ipParts[i], 16, 16)
ipFinalParts = append(ipFinalParts, uint16(0))
}
} else {
oct, _ = strconv.ParseUint(ipParts[i], 16, 16)
ipFinalParts = append(ipFinalParts, uint16(oct))
}
}
for i := 0; i < 4; i++ {
oct = uint64(ipFinalParts[i])
subnet1 += uint64((oct << ((3 - uint(i)) * 16)))
}
for i := 0; i < 4; i++ {
oct = uint64(ipFinalParts[i+4])
subnet2 += uint64((oct << ((3 - uint(i)) * 16)))
}
oct, _ = strconv.ParseUint(maskS, 10, 8)
maskLength := int(oct)
maskLength2 := math.Max(float64(maskLength-64), 0)
maskLength1 := float64(maskLength) - maskLength2
mask1 -= uint64(math.Pow(2, 64-maskLength1))
mask2 -= uint64(math.Pow(2, 64-maskLength2))
if maskLength1 == 0 {
mask1 = 0
}
if maskLength2 == 0 {
mask2 = 0
}
xored1 := (ip1 & mask1) ^ subnet1
xored2 := (ip2 & mask2) ^ subnet2
return xored1 == 0 && xored2 == 0, uint32(maskLength)
}
func getNetSize(r *http.Request, net string) int {
var maskLength int
var oct uint64
// Check if the IP is V4
if strings.Contains(GetRemoteIP(r), ".") {
// Get the Netmask
oct, _ = strconv.ParseUint(strings.Split(net, "/")[1], 10, 8)
maskLength = int(oct)
}
return maskLength
}
func getSessionByKey(key string) *Session {
s := Session{}
if CacheSessions {
cachedSessionsMutex.RLock() // Lock the mutex in order to protect from concurrent writes
defer cachedSessionsMutex.RUnlock() // Ensure the mutex is unlocked when the function exits
s = cachedSessions[key]
} else {
Get(&s, "`key` = ?", key)
}
if s.ID == 0 {
return nil
}
return &s
}
func getJWT(r *http.Request) string {
// JWT
if r.Header.Get("Authorization") == "" {
return ""
}
if !strings.HasPrefix(r.Header.Get("Authorization"), "Bearer") {
return ""
}
jwtToken := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
jwtParts := strings.Split(jwtToken, ".")
if len(jwtParts) != 3 {
return ""
}
jHeader, err := base64.RawURLEncoding.WithPadding(base64.NoPadding).DecodeString(jwtParts[0])
if err != nil {
return ""
}
jPayload, err := base64.RawURLEncoding.WithPadding(base64.NoPadding).DecodeString(jwtParts[1])
if err != nil {
return ""
}
header := map[string]interface{}{}
err = json.Unmarshal(jHeader, &header)
if err != nil {
return ""
}
// Get data from payload
payload := map[string]interface{}{}
err = json.Unmarshal(jPayload, &payload)
if err != nil {
return ""
}
// Verify issuer
SSOLogin := false
if iss, ok := payload["iss"].(string); ok {
if iss != JWTIssuer {
accepted := false
for _, fiss := range AcceptedJWTIssuers {
if fiss == iss {
accepted = true
break
}
}
if !accepted {
return ""
}
SSOLogin = true
}
} else {
return ""
}
// verify audience
if aud, ok := payload["aud"].(string); ok {
if aud != JWTIssuer {
return ""
}
} else if aud, ok := payload["aud"].([]string); ok {
accepted := false
for _, audItem := range aud {
if audItem == JWTIssuer {
accepted = true
break
}
}
if !accepted {
return ""
}
} else {
return ""
}
// if there is no subject, return empty session
if _, ok := payload["sub"].(string); !ok {
return ""
}
sub := payload["sub"].(string)
user := User{}
Get(&user, "username = ?", sub)
if user.ID == 0 && SSOLogin {
now := time.Now()
user := User{
Username: sub,
FirstName: payload["given_name"].(string),
LastName: payload["family_name"].(string),
Active: true,
Admin: func() bool {
for _, group := range payload["groups"].([]interface{}) {
if group.(map[string]interface{})["id"].(float64) == 0 {
return true
}
}
return false
}(),
LastLogin: &now,
RemoteAccess: true, //TODO: add remote access in JWT
Password: GenerateBase64(64),
}
// TODO: Add custom function to customize the user before saving
// this function will receive the following parameters:
// payload, *user
user.Save()
// process entitlements
// TODO: find a way to refresh entitlements every login
} else if user.ID == 0 {
return ""
}
session := user.GetActiveSession()
if session == nil && SSOLogin {
session = &Session{
UserID: user.ID,
Active: true,
LoginTime: time.Now(),
IP: GetRemoteIP(r),
}
session.GenerateKey()
// TODO: Add custom function to customize the user session
// this function will receive the following parameters:
// payload, user, *session
session.Save()
} else if session == nil {
return ""
}
// TODO: verify exp
// Verify the signature
alg := "HS256"
if v, ok := header["alg"].(string); ok {
alg = v
}
if _, ok := header["typ"]; ok {
if v, ok := header["typ"].(string); !ok || v != "JWT" {
return ""
}
}
// verify signature
switch alg {
case "HS256":
// TODO: allow third party JWT signature authentication
hash := hmac.New(sha256.New, []byte(JWT+session.Key))
hash.Write([]byte(jwtParts[0] + "." + jwtParts[1]))
token := hash.Sum(nil)
b64Token := base64.RawURLEncoding.EncodeToString(token)
if b64Token != jwtParts[2] {
return ""
}
case "RS256":
if !verifyRSA(jwtToken, SSOLogin) {
return ""
}
default:
// For now, only support HMAC-SHA256
return ""
}
return session.Key
}
var jwtIssuerCerts = map[[2]string][]byte{}
func getJWTRSAPublicKeySSO(jwtToken *jwt.Token) *rsa.PublicKey {
iss, err := jwtToken.Claims.GetIssuer()
if err != nil {
return nil
}
kid, _ := jwtToken.Header["kid"].(string)
if kid == "" {
return nil
}
if val, ok := jwtIssuerCerts[[2]string{iss, kid}]; ok {
cert, _ := jwt.ParseRSAPublicKeyFromPEM(val)
return cert
}
res, err := http.Get(iss + "/.well-known/openid-configuration")
if err != nil {
return nil
}
if res.StatusCode != 200 {
return nil
}
buf, err := io.ReadAll(res.Body)
if err != nil {
return nil
}
obj := map[string]interface{}{}
err = json.Unmarshal(buf, &obj)
if err != nil {
return nil
}
crtURL := ""
if val, ok := obj["jwks_uri"].(string); !ok || val == "" {
return nil
} else {
crtURL = val
}
res, err = http.Get(crtURL)
if err != nil {
return nil
}
if res.StatusCode != 200 {
return nil
}
buf, err = io.ReadAll(res.Body)
if err != nil {
return nil
}
certObj := map[string][]map[string]string{}
err = json.Unmarshal(buf, &certObj)
if err != nil {
return nil
}
if val, ok := certObj["keys"]; !ok || len(val) == 0 {
return nil
}
var cert map[string]string
for i := range certObj["keys"] {
if certObj["keys"][i]["kid"] == kid {
cert = certObj["keys"][i]
break
}
}
if cert == nil {
return nil
}
N := new(big.Int)
buf, _ = base64.RawURLEncoding.DecodeString(cert["n"])
N = N.SetBytes(buf)
E := new(big.Int)
buf, _ = base64.RawURLEncoding.DecodeString(cert["e"])
E = E.SetBytes(buf)
publicCert := rsa.PublicKey{
N: N,
E: int(E.Int64()),
}
return &publicCert
}
func getJWTRSAPublicKeyLocal(jwtToken *jwt.Token) *rsa.PublicKey {
pubKeyPEM, err := os.ReadFile(".jwt-rsa-public.pem")
if err != nil {
return nil
}
pubKey, err := jwt.ParseRSAPublicKeyFromPEM(pubKeyPEM)
if err != nil {
return nil
}
return pubKey
}
func verifyRSA(token string, SSOLogin bool) bool {
tok, err := jwt.Parse(token, func(jwtToken *jwt.Token) (interface{}, error) {
if _, ok := jwtToken.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected method: %s", jwtToken.Header["alg"])
}
var pubKey *rsa.PublicKey
if SSOLogin {
pubKey = getJWTRSAPublicKeySSO(jwtToken)
} else {
pubKey = getJWTRSAPublicKeyLocal(jwtToken)
}
if pubKey == nil {