forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
782 lines (691 loc) · 18.3 KB
/
auth.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
package uadmin
import (
"context"
"encoding/base64"
"encoding/json"
"math/big"
"net"
"path"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"math"
"net/http"
"strconv"
"strings"
"time"
"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
// 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 = ""
// 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
// 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
}
// hashPass Generates a hash from a password and salt
func hashPass(pass string) string {
password := []byte(pass + Salt)
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
}
// 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 ""
}
header := map[string]interface{}{
"alg": "HS256",
"typ": "JWT",
}
payload := map[string]interface{}{
"sub": s.User.Username,
"iat": s.LastLogin.Unix(),
"iss": JWTIssuer,
"aud": JWTIssuer,
}
if s.ExpiresOn != nil {
payload["exp"] = s.ExpiresOn.Unix()
}
// Check for custom JWT handler
if CustomJWT != nil {
payload = CustomJWT(r, s, payload)
}
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
}
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) {
// 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 {
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 {
s = cachedSessions[key]
} else {
Get(&s, "`key` = ?", key)
}
if s.ID == 0 {
return nil
}
return &s
}
func getSession(r *http.Request) string {
key, err := r.Cookie("session")
if err == nil && key != nil {
return key.Value
}
if r.Method == "GET" && r.FormValue("session") != "" {
return r.FormValue("session")
}
if r.Method == "POST" {
err := r.ParseMultipartForm(2 << 10)
if err != nil {
r.ParseForm()
}
if r.FormValue("session") != "" {
return r.FormValue("session")
}
}
// JWT
if r.Header.Get("Authorization") != "" {
if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer") {
jwt := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
jwtParts := strings.Split(jwt, ".")
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
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 ""
}
}
} 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 {
return ""
}
session := user.GetActiveSession()
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 ""
}
}
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 ""
}
default:
// For now, only support HMAC-SHA256
return ""
}
return session.Key
}
}
return ""
}
// GetRemoteIP is a function that returns the IP for a remote
// user from a request
func GetRemoteIP(r *http.Request) string {
ips := r.Header.Get("X-Forwarded-For")
splitIps := strings.Split(ips, ",")
if ips != "" {
// trim IP list
for i := range splitIps {
splitIps[i] = strings.TrimSpace(splitIps[i])
}
// get last IP in list since ELB prepends other user defined IPs, meaning the last one is the actual client IP.
netIP := net.ParseIP(splitIps[0])
if netIP != nil {
return netIP.String()
}
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
netIP := net.ParseIP(ip)
if netIP != nil {
ip := netIP.String()
if ip == "::1" {
return "127.0.0.1"
}
return ip
}
return r.RemoteAddr
}
// GetHostName is a function that returns the host name from a request
func GetHostName(r *http.Request) string {
host := r.Header.Get("X-Forwarded-Host")
if host != "" {
return host
}
return r.Host
}
// GetSchema is a function that returns the schema for a request (http, https)
func GetSchema(r *http.Request) string {
schema := r.Header.Get("X-Forwarded-Proto")
if schema != "" {
return schema
}
if r.URL.Scheme != "" {
return r.URL.Scheme
}
if r.TLS != nil {
return "https"
}
return "http"
}
func verifyPassword(hash string, plain string) error {
password := []byte(plain + Salt)
hashedPassword := []byte(hash)
return bcrypt.CompareHashAndPassword(hashedPassword, password)
}
// sanitizeFileName is a function to sanitize file names to pretect
// from path traversal attacks using ../
func sanitizeFileName(v string) string {
return path.Clean(strings.ReplaceAll(v, "../", ""))
}