forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
511 lines (455 loc) · 12.1 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
package uadmin
import (
"context"
"math/big"
"net"
"crypto/rand"
"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 extra salt added to password hashing
var Salt = ""
// bcryptDiff
var bcryptDiff = 12
// cachedSessions is variable for keeping active sessions
var cachedSessions map[string]Session
// invalidAttemps keeps track of invalid password attempts
// per IP address
var invalidAttempts = map[string]int{}
// 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 base64 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 := Session{}
if CacheSessions {
s = cachedSessions[key]
} else {
Get(&s, "`key` = ?", 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 assiged will be a no user session
func SetSessionCookie(w http.ResponseWriter, r *http.Request, s *Session) {
if s == nil {
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: "nouser:" + GenerateBase64(24),
SameSite: http.SameSiteStrictMode,
Path: "/",
Expires: time.Now().AddDate(0, 0, 1),
})
} else {
exDate := time.Time{}
if s.ExpiresOn != nil {
exDate = *s.ExpiresOn
}
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: s.Key,
SameSite: http.SameSiteStrictMode,
Path: "/",
Expires: exDate,
})
}
}
func isValidSession(r *http.Request, s *Session) bool {
if s != nil && s.ID != 0 {
if s.Active && !s.PendingOTP && (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, _, _ := net.SplitHostPort(r.RemoteAddr)
return ip == s.IP
}
return true
}
}
}
return 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 := Session{}
if CacheSessions {
s = cachedSessions[key]
} else {
Get(&s, "`key` = ?", key)
}
if 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()
}()
return nil, false
}
s := user.Login(password, "")
if s != nil && s.ID != 0 {
s.IP, _, _ = net.SplitHostPort(r.RemoteAddr)
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()
}()
}
// Increment password attempts and check if it reached
// the maximum invalid password attempts
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
invalidAttempts[ip]++
if invalidAttempts[ip] >= PasswordAttempts {
rateLimitLock.Lock()
rateLimitMap[ip] = time.Now().Add(time.Duration(PasswordTimeout)*time.Minute).Unix() * RateLimit
rateLimitLock.Unlock()
}
// 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()
}
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) {
// Check if the IP is V4
if strings.Contains(r.RemoteAddr, ".") {
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(r.RemoteAddr, ":")[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 := r.RemoteAddr // [::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(r.RemoteAddr, ".") {
// 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" {
r.ParseForm()
if r.FormValue("session") != "" {
return r.FormValue("session")
}
}
return ""
}
// GetRemoteIP is a function that returns the IP for a remote
// user from a request
func GetRemoteIP(r *http.Request) string {
var ip string
var err error
if ip, _, err = net.SplitHostPort(r.RemoteAddr); err != nil {
return ip
}
return r.RemoteAddr
}