-
Notifications
You must be signed in to change notification settings - Fork 163
/
go-auth.go
510 lines (427 loc) · 13.4 KB
/
go-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
package main
import "C"
import (
"fmt"
"log"
"strconv"
"strings"
"time"
b64 "encoding/base64"
goredis "github.com/go-redis/redis"
bes "github.com/iegomez/mosquitto-go-auth/backends"
)
type Backend interface {
GetUser(username, password string) bool
GetSuperuser(username string) bool
CheckAcl(username, topic, clientId string, acc int32) bool
GetName() string
}
type CommonData struct {
Backends []Backend
Postgres bes.Postgres
Files bes.Files
Jwt bes.JWT
Redis bes.Redis
Superusers []string
AclCacheSeconds int64
AuthCacheSeconds int64
UseCache bool
RedisCache *goredis.Client
CheckPrefix bool
Prefixes map[string]string
}
//Cache stores necessary values for Redis cache
type Cache struct {
Host string
Port string
Password string
DB int32
}
var allowedBackends = map[string]bool{
"postgres": true,
"jwt": true,
"redis": true,
"http": true,
"files": true,
}
var backends []string
var authOpts map[string]string
var cache Cache
var commonData CommonData
//export AuthPluginInit
func AuthPluginInit(keys []string, values []string, authOptsNum int) {
//Initialize Cache with default values
cache = Cache{
Host: "localhost",
Port: "6379",
Password: "",
DB: 0,
}
commonBackends := make([]Backend, len(allowedBackends), len(allowedBackends))
superusers := make([]string, 10, 10)
//Initialize common struct with default and given values
commonData = CommonData{
Backends: commonBackends,
Superusers: superusers,
AclCacheSeconds: 30,
AuthCacheSeconds: 30,
CheckPrefix: false,
Prefixes: make(map[string]string),
}
//First, get backends
backendsOk := false
authOpts = make(map[string]string)
for i := 0; i < authOptsNum; i++ {
if keys[i] == "backends" {
backends = strings.Split(strings.Replace(values[i], " ", "", -1), ",")
if len(backends) > 0 {
backendsCheck := true
for _, backend := range backends {
if _, ok := allowedBackends[backend]; !ok {
backendsCheck = false
log.Printf("backend not allowed: %s\n", backend)
}
}
backendsOk = backendsCheck
}
} else {
authOpts[keys[i]] = values[i]
}
}
//Log and end program if backends are wrong
if !backendsOk {
log.Fatal("\nbackends error\n")
}
//Initialize backends
for _, bename := range backends {
var beIface Backend
var bErr error
if bename == "postgres" {
beIface, bErr = bes.NewPostgres(authOpts)
commonData.Postgres = beIface.(bes.Postgres)
} else if bename == "jwt" {
beIface, bErr = bes.NewJWT(authOpts)
commonData.Jwt = beIface.(bes.JWT)
} else if bename == "files" {
beIface, bErr = bes.NewFiles(authOpts)
commonData.Files = beIface.(bes.Files)
} else if bename == "redis" {
beIface, bErr = bes.NewRedis(authOpts)
commonData.Redis = beIface.(bes.Redis)
}
if bErr != nil {
log.Fatalf("Backend register error: couldn't initialize %s backend with error %s.\n", bename, bErr)
} else {
log.Printf("Backend registered: %s\n", beIface.GetName())
}
}
if cache, ok := authOpts["cache"]; ok && cache == "true" {
log.Println("Cache set")
commonData.UseCache = true
} else {
log.Printf("No cache, got %s", cache)
commonData.UseCache = false
}
if commonData.UseCache {
if cacheHost, ok := authOpts["cache_host"]; ok {
cache.Host = cacheHost
}
if cachePort, ok := authOpts["cache_port"]; ok {
cache.Port = cachePort
}
if cachePassword, ok := authOpts["cache_password"]; ok {
cache.Password = cachePassword
}
if cacheDB, ok := authOpts["cache_db"]; ok {
db, err := strconv.ParseInt(cacheDB, 10, 32)
if err != nil {
cache.DB = int32(db)
}
}
if authCacheSec, ok := authOpts["auth_cache_seconds"]; ok {
authSec, err := strconv.ParseInt(authCacheSec, 10, 64)
if err != nil {
commonData.AuthCacheSeconds = authSec
}
}
if aclCacheSec, ok := authOpts["acl_cache_seconds"]; ok {
aclSec, err := strconv.ParseInt(aclCacheSec, 10, 64)
if err != nil {
commonData.AclCacheSeconds = aclSec
}
}
addr := fmt.Sprintf("%s:%s", cache.Host, cache.Port)
//If cache is on, try to start redis.
goredisClient := goredis.NewClient(&goredis.Options{
Addr: addr,
Password: cache.Password, // no password set
DB: int(cache.DB), // use default DB
})
_, err := goredisClient.Ping().Result()
if err != nil {
log.Printf("couldn't start Redis, defaulting to no cache. error: %s\n", err)
commonData.UseCache = false
} else {
commonData.RedisCache = goredisClient
log.Printf("started redis client")
}
}
if checkPrefix, ok := authOpts["check_prefix"]; ok && checkPrefix == "true" {
//Check that backends match prefixes.
if prefixesStr, ok := authOpts["prefixes"]; ok {
prefixes := strings.Split(strings.Replace(prefixesStr, " ", "", -1), ",")
if len(prefixes) == len(backends) {
//Set prefixes
for i, backend := range backends {
commonData.Prefixes[prefixes[i]] = backend
}
log.Printf("Prefixes enabled for backends %s with prefixes %s.\n", authOpts["backends"], authOpts["prefixes"])
commonData.CheckPrefix = true
} else {
log.Printf("Error: got %d backends and %d prefixes, defaulting to prefixes disabled.\n", len(backends), len(prefixes))
commonData.CheckPrefix = false
}
} else {
log.Println("Error: prefixes enabled but no options given, defaulting to prefixes disabled.")
commonData.CheckPrefix = false
}
} else {
commonData.CheckPrefix = false
}
}
//export AuthUnpwdCheck
func AuthUnpwdCheck(username, password string) bool {
//Loop through backends checking for user.
authenticated := false
var cached = false
var granted = false
if commonData.UseCache {
log.Printf("checking auth cache for %s\n", username)
cached, granted = CheckAuthCache(username, password)
if cached {
log.Printf("found in cache: %s\n", username)
return granted
}
}
//If prefixes are enabled, checkt if username has a valid prefix and use the correct backend if so.
if commonData.CheckPrefix {
validPrefix, bename := CheckPrefix(username)
if validPrefix {
var backend Backend
if bename == "postgres" {
backend = commonData.Postgres
} else if bename == "jwt" {
backend = commonData.Jwt
} else if bename == "files" {
backend = commonData.Files
} else if bename == "redis" {
backend = commonData.Redis
}
if backend.GetUser(username, password) {
authenticated = true
log.Printf("user %s authenticated with backend %s\n", username, backend.GetName())
}
} else {
//If there's no valid prefix, check all backends.
authenticated = CheckBackendsAuth(username, password)
}
} else {
authenticated = CheckBackendsAuth(username, password)
}
if commonData.UseCache {
authGranted := "false"
if authenticated {
authGranted = "true"
}
log.Printf("setting auth cache for %s\n", username)
SetAuthCache(username, password, authGranted)
}
return authenticated
}
//export AuthAclCheck
func AuthAclCheck(clientid, username, topic string, acc int) bool {
aclCheck := false
var cached = false
var granted = false
if commonData.UseCache {
log.Printf("checking acl cache for %s\n", username)
cached, granted = CheckAclCache(username, topic, clientid, acc)
if cached {
log.Printf("found in cache: %s\n", username)
return granted
}
}
//If prefixes are enabled, checkt if username has a valid prefix and use the correct backend if so.
//Else, check all backends.
if commonData.CheckPrefix {
validPrefix, bename := CheckPrefix(username)
if validPrefix {
var backend Backend
if bename == "postgres" {
backend = commonData.Postgres
} else if bename == "jwt" {
backend = commonData.Jwt
} else if bename == "files" {
backend = commonData.Files
} else if bename == "redis" {
backend = commonData.Redis
}
log.Printf("Superuser check with backend %s\n", backend.GetName())
if backend.GetSuperuser(username) {
log.Printf("superuser %s acl authenticated with backend %s\n", username, backend.GetName())
aclCheck = true
}
//If not superuser, check acl.
if !aclCheck {
log.Printf("Acl check with backend %s\n", backend.GetName())
if backend.CheckAcl(username, topic, clientid, int32(acc)) {
log.Printf("user %s acl authenticated with backend %s\n", username, backend.GetName())
aclCheck = true
}
}
} else {
//If there's no valid prefix, check all backends.
aclCheck = CheckBackendsAcl(username, topic, clientid, acc)
}
} else {
aclCheck = CheckBackendsAcl(username, topic, clientid, acc)
}
if commonData.UseCache {
authGranted := "false"
if aclCheck {
authGranted = "true"
}
log.Printf("setting acl cache (granted = %s) for %s\n", authGranted, username)
SetAclCache(username, topic, clientid, acc, authGranted)
}
log.Printf("Acl is %s for user %s\n", aclCheck, username)
return aclCheck
}
//export AuthPskKeyGet
func AuthPskKeyGet() bool {
return true
}
//CheckAuthCache checks if the username/password pair is present in the cache. Return if it's present and, if so, if it was granted privileges.
func CheckAuthCache(username, password string) (bool, bool) {
pair := b64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("auth%s%s", username, password)))
val, err := commonData.RedisCache.Get(pair).Result()
if err != nil {
return false, false
}
//refresh expiration
commonData.RedisCache.Expire(pair, time.Duration(commonData.AuthCacheSeconds)*time.Second)
if val == "true" {
return true, true
}
return true, false
}
//SetAuthCache sets a pair, granted option and expiration time.
func SetAuthCache(username, password string, granted string) error {
pair := b64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("auth%s%s", username, password)))
err := commonData.RedisCache.Set(pair, granted, time.Duration(commonData.AuthCacheSeconds)*time.Second).Err()
if err != nil {
return err
}
return nil
}
//CheckAclCache checks if the username/topic/clientid/acc mix is present in the cache. Return if it's present and, if so, if it was granted privileges.
func CheckAclCache(username, topic, clientid string, acc int) (bool, bool) {
pair := b64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("acl%s%s%s%d", username, topic, clientid, acc)))
val, err := commonData.RedisCache.Get(pair).Result()
if err != nil {
return false, false
}
//refresh expiration
commonData.RedisCache.Expire(pair, time.Duration(commonData.AclCacheSeconds)*time.Second)
if val == "true" {
return true, true
}
return true, false
}
//SetAclCache sets a mix, granted option and expiration time.
func SetAclCache(username, topic, clientid string, acc int, granted string) error {
pair := b64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("acl%s%s%s%d", username, topic, clientid, acc)))
err := commonData.RedisCache.Set(pair, granted, time.Duration(commonData.AclCacheSeconds)*time.Second).Err()
if err != nil {
return err
}
return nil
}
//CheckPrefix checks if a username contains a valid prefix. If so, returns ok and the suitable backend name; else, !ok and empty string.
func CheckPrefix(username string) (bool, string) {
if strings.Index(username, "_") > 0 {
userPrefix := username[0:strings.Index(username, "_")]
if prefix, ok := commonData.Prefixes[userPrefix]; ok {
log.Printf("Found prefix for user %s, using backend %s.\n", username, prefix)
return true, prefix
}
}
return false, ""
}
//CheckBackendsAuth checks for all backends if a username is authenticated and sets the authenticated param.
func CheckBackendsAuth(username, password string) bool {
authenticated := false
for _, bename := range backends {
var backend Backend
if bename == "postgres" {
backend = commonData.Postgres
} else if bename == "jwt" {
backend = commonData.Jwt
} else if bename == "files" {
backend = commonData.Files
} else if bename == "redis" {
backend = commonData.Redis
}
if backend.GetUser(username, password) {
authenticated = true
log.Printf("user %s authenticated with backend %s\n", username, backend.GetName())
break
}
}
return authenticated
}
//CheckBackendsAcl checks for all backends if a username is superuser or has acl rights and sets the aclCheck param.
func CheckBackendsAcl(username, topic, clientid string, acc int) bool {
//Check superusers first
aclCheck := false
for _, bename := range backends {
var backend Backend
if bename == "postgres" {
backend = commonData.Postgres
} else if bename == "jwt" {
backend = commonData.Jwt
} else if bename == "files" {
backend = commonData.Files
} else if bename == "redis" {
backend = commonData.Redis
}
log.Printf("Superuser check with backend %s\n", backend.GetName())
if backend.GetSuperuser(username) {
log.Printf("superuser %s acl authenticated with backend %s\n", username, backend.GetName())
aclCheck = true
break
}
}
if !aclCheck {
for _, bename := range backends {
var backend Backend
if bename == "postgres" {
backend = commonData.Postgres
} else if bename == "jwt" {
backend = commonData.Jwt
} else if bename == "files" {
backend = commonData.Files
} else if bename == "redis" {
backend = commonData.Redis
}
log.Printf("Acl check with backend %s\n", backend.GetName())
if backend.CheckAcl(username, topic, clientid, int32(acc)) {
log.Printf("user %s acl authenticated with backend %s\n", username, backend.GetName())
aclCheck = true
break
}
}
}
return aclCheck
}
func main() {}