-
Notifications
You must be signed in to change notification settings - Fork 179
/
Copy pathbackends.go
562 lines (470 loc) · 17.1 KB
/
backends.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
package backends
import (
"fmt"
"strings"
"github.com/iegomez/mosquitto-go-auth/hashing"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
type Backend interface {
GetUser(username, password, clientid string) (bool, error)
GetSuperuser(username string) (bool, error)
CheckAcl(username, topic, clientId string, acc int32) (bool, error)
GetName() string
Halt()
}
type Backends struct {
backends map[string]Backend
aclCheckers []string
userCheckers []string
superuserCheckers []string
checkPrefix bool
stripPrefix bool
prefixes map[string]string
disableSuperuser bool
exhaustBackendFirst bool
sortedBackends []string
}
const (
// backends
postgresBackend = "postgres"
jwtBackend = "jwt"
redisBackend = "redis"
httpBackend = "http"
filesBackend = "files"
mysqlBackend = "mysql"
sqliteBackend = "sqlite"
mongoBackend = "mongo"
pluginBackend = "plugin"
grpcBackend = "grpc"
jsBackend = "js"
// checks
aclCheck = "acl"
userCheck = "user"
superuserCheck = "superuser"
// other constants
defaultUserAgent = "mosquitto"
)
// AllowedBackendsOptsPrefix serves as a check for allowed backends and a map from backend to expected opts prefix.
var allowedBackendsOptsPrefix = map[string]string{
postgresBackend: "pg",
jwtBackend: "jwt",
redisBackend: "redis",
httpBackend: "http",
filesBackend: "files",
mysqlBackend: "mysql",
sqliteBackend: "sqlite",
mongoBackend: "mongo",
pluginBackend: "plugin",
grpcBackend: "grpc",
jsBackend: "js",
}
// Initialize sets general options, tries to build the backends and register their checkers.
func Initialize(authOpts map[string]string, logLevel log.Level, version string) (*Backends, error) {
b := &Backends{
backends: make(map[string]Backend),
aclCheckers: make([]string, 0),
userCheckers: make([]string, 0),
superuserCheckers: make([]string, 0),
prefixes: make(map[string]string),
}
// Disable superusers for all backends if option is set.
if authOpts["disable_superuser"] == "true" {
b.disableSuperuser = true
}
// When set, a backend will be checked for superuser (if enabled) and ACL before checking another backend.
if authOpts["exhaust_backend_first"] == "true" {
b.exhaustBackendFirst = true
}
backendsOpt, ok := authOpts["backends"]
if !ok || backendsOpt == "" {
return nil, fmt.Errorf("missing or blank option backends")
}
backends := strings.Split(strings.Replace(backendsOpt, " ", "", -1), ",")
if len(backends) < 1 {
return nil, fmt.Errorf("missing or blank option backends")
}
for _, backend := range backends {
if _, ok := allowedBackendsOptsPrefix[backend]; !ok {
return nil, fmt.Errorf("unknown backend %s", backend)
}
}
err := b.addBackends(authOpts, logLevel, backends, version)
if err != nil {
return nil, err
}
err = b.setCheckers(authOpts)
if err != nil {
return nil, err
}
b.setPrefixes(authOpts, backends)
return b, nil
}
func (b *Backends) addBackends(authOpts map[string]string, logLevel log.Level, backends []string, version string) error {
// Store given backends as given to order them when checking.
//
// This allows to sort user checking, and first exhaust superuser/acl checks of a given backend before checking the next one,
// instead of the default superuser of all backends before checking them again for ACLs.
//
// Neither option is a silver bullet, but at least give some more grained control when paired with
// checkers registering.
b.sortedBackends = make([]string, len(backends))
copy(b.sortedBackends, backends)
for _, bename := range backends {
var beIface Backend
var err error
hasher := hashing.NewHasher(authOpts, allowedBackendsOptsPrefix[bename])
switch bename {
case postgresBackend:
beIface, err = NewPostgres(authOpts, logLevel, hasher)
if err != nil {
log.Fatalf("backend register error: couldn't initialize %s backend with error %s.", bename, err)
} else {
log.Infof("backend registered: %s", beIface.GetName())
b.backends[postgresBackend] = beIface.(Postgres)
}
case jwtBackend:
beIface, err = NewJWT(authOpts, logLevel, hasher, version)
if err != nil {
log.Fatalf("Backend register error: couldn't initialize %s backend with error %s.", bename, err)
} else {
log.Infof("Backend registered: %s", beIface.GetName())
b.backends[jwtBackend] = beIface.(*JWT)
}
case filesBackend:
beIface, err = NewFiles(authOpts, logLevel, hasher)
if err != nil {
log.Fatalf("Backend register error: couldn't initialize %s backend with error %s.", bename, err)
} else {
log.Infof("Backend registered: %s", beIface.GetName())
b.backends[filesBackend] = beIface.(*Files)
}
case redisBackend:
beIface, err = NewRedis(authOpts, logLevel, hasher)
if err != nil {
log.Fatalf("Backend register error: couldn't initialize %s backend with error %s.", bename, err)
} else {
log.Infof("Backend registered: %s", beIface.GetName())
b.backends[redisBackend] = beIface.(Redis)
}
case mysqlBackend:
beIface, err = NewMysql(authOpts, logLevel, hasher)
if err != nil {
log.Fatalf("Backend register error: couldn't initialize %s backend with error %s.", bename, err)
} else {
log.Infof("Backend registered: %s", beIface.GetName())
b.backends[mysqlBackend] = beIface.(Mysql)
}
case httpBackend:
beIface, err = NewHTTP(authOpts, logLevel, version)
if err != nil {
log.Fatalf("Backend register error: couldn't initialize %s backend with error %s.", bename, err)
} else {
log.Infof("Backend registered: %s", beIface.GetName())
b.backends[httpBackend] = beIface.(HTTP)
}
case sqliteBackend:
beIface, err = NewSqlite(authOpts, logLevel, hasher)
if err != nil {
log.Fatalf("Backend register error: couldn't initialize %s backend with error %s.", bename, err)
} else {
log.Infof("Backend registered: %s", beIface.GetName())
b.backends[sqliteBackend] = beIface.(Sqlite)
}
case mongoBackend:
beIface, err = NewMongo(authOpts, logLevel, hasher)
if err != nil {
log.Fatalf("Backend register error: couldn't initialize %s backend with error %s.", bename, err)
} else {
log.Infof("Backend registered: %s", beIface.GetName())
b.backends[mongoBackend] = beIface.(Mongo)
}
case grpcBackend:
beIface, err = NewGRPC(authOpts, logLevel)
if err != nil {
log.Fatalf("Backend register error: couldn't initialize %s backend with error %s.", bename, err)
} else {
log.Infof("Backend registered: %s", beIface.GetName())
b.backends[grpcBackend] = beIface.(*GRPC)
}
case jsBackend:
beIface, err = NewJavascript(authOpts, logLevel)
if err != nil {
log.Fatalf("Backend register error: couldn't initialize %s backend with error %s.", bename, err)
} else {
log.Infof("Backend registered: %s", beIface.GetName())
b.backends[jsBackend] = beIface.(*Javascript)
}
case pluginBackend:
beIface, err = NewCustomPlugin(authOpts, logLevel)
if err != nil {
log.Fatalf("Backend register error: couldn't initialize %s backend with error %s.", bename, err)
} else {
log.Infof("Backend registered: %s", beIface.GetName())
b.backends[pluginBackend] = beIface.(*CustomPlugin)
}
default:
return fmt.Errorf("unkown backend %s", bename)
}
}
return nil
}
func (b *Backends) setCheckers(authOpts map[string]string) error {
// We'll register which plugins will perform checks for user, superuser and acls.
// At least one backend must be registered for user and acl checks.
// When option auth_opt_backend_register is missing for the backend, we register all checks.
for _, name := range b.sortedBackends {
opt := fmt.Sprintf("%s_register", allowedBackendsOptsPrefix[name])
options, ok := authOpts[opt]
if ok {
checkers := strings.Split(strings.Replace(options, " ", "", -1), ",")
for _, check := range checkers {
switch check {
case aclCheck:
b.aclCheckers = append(b.aclCheckers, name)
log.Infof("registered acl checker: %s", name)
case userCheck:
b.userCheckers = append(b.userCheckers, name)
log.Infof("registered user checker: %s", name)
case superuserCheck:
if !b.disableSuperuser {
b.superuserCheckers = append(b.superuserCheckers, name)
log.Infof("registered superuser checker: %s", name)
}
default:
return fmt.Errorf("unsupported check %s found for backend %s", check, name)
}
}
} else {
b.aclCheckers = append(b.aclCheckers, name)
log.Infof("registered acl checker: %s", name)
b.userCheckers = append(b.userCheckers, name)
log.Infof("registered user checker: %s", name)
if !b.disableSuperuser {
b.superuserCheckers = append(b.superuserCheckers, name)
log.Infof("registered superuser checker: %s", name)
}
}
}
if len(b.userCheckers) == 0 && len(b.aclCheckers) == 0 {
return errors.New("no backends registered")
}
return nil
}
// setPrefixes sets options for prefixes handling.
func (b *Backends) setPrefixes(authOpts map[string]string, backends []string) {
checkPrefix, ok := authOpts["check_prefix"]
if !ok || strings.Replace(checkPrefix, " ", "", -1) != "true" {
b.checkPrefix = false
b.stripPrefix = false
return
}
prefixesStr, ok := authOpts["prefixes"]
if !ok {
log.Warn("Error: prefixes enabled but no options given, defaulting to prefixes disabled.")
b.checkPrefix = false
b.stripPrefix = false
return
}
prefixes := strings.Split(strings.Replace(prefixesStr, " ", "", -1), ",")
if len(prefixes) != len(backends) {
log.Errorf("Error: got %d backends and %d prefixes, defaulting to prefixes disabled.", len(backends), len(prefixes))
b.checkPrefix = false
b.stripPrefix = false
return
}
if authOpts["strip_prefix"] == "true" {
b.stripPrefix = true
}
for i, backend := range backends {
b.prefixes[prefixes[i]] = backend
}
log.Infof("prefixes enabled for backends %s with prefixes %s.", authOpts["backends"], authOpts["prefixes"])
b.checkPrefix = true
}
// checkPrefix checks if a username contains a valid prefix. If so, returns ok and the suitable backend name; else, !ok and empty string.
func (b *Backends) lookupPrefix(username string) (bool, string) {
if strings.Index(username, "_") > 0 {
userPrefix := username[0:strings.Index(username, "_")]
if prefix, ok := b.prefixes[userPrefix]; ok {
log.Debugf("Found prefix for user %s, using backend %s.", username, prefix)
return true, prefix
}
}
return false, ""
}
// getPrefixForBackend retrieves the user provided prefix for a given backend.
func (b *Backends) getPrefixForBackend(backend string) string {
for k, v := range b.prefixes {
if v == backend {
return k
}
}
return ""
}
func checkRegistered(bename string, checkers []string) bool {
for _, b := range checkers {
if b == bename {
return true
}
}
return false
}
// AuthUnpwdCheck checks user authentication.
func (b *Backends) AuthUnpwdCheck(username, password, clientid string) (bool, error) {
var authenticated bool
var err error
// If prefixes are enabled, check if username has a valid prefix and use the correct backend if so.
if !b.checkPrefix {
return b.checkAuth(username, password, clientid)
}
validPrefix, bename := b.lookupPrefix(username)
if !validPrefix {
return b.checkAuth(username, password, clientid)
}
if !checkRegistered(bename, b.userCheckers) {
return false, fmt.Errorf("backend %s not registered to check users", bename)
}
// If the backend is JWT and the token was prefixed, then strip the token.
// If the token was passed without a prefix it will be handled in the common case.
// Also strip the prefix if the strip_prefix option was set.
if bename == jwtBackend || b.stripPrefix {
prefix := b.getPrefixForBackend(bename)
username = strings.TrimPrefix(username, prefix+"_")
}
var backend = b.backends[bename]
authenticated, err = backend.GetUser(username, password, clientid)
if authenticated && err == nil {
log.Debugf("user %s authenticated with backend %s", username, backend.GetName())
}
return authenticated, err
}
func (b *Backends) checkAuth(username, password, clientid string) (bool, error) {
var err error
for _, bename := range b.userCheckers {
var backend = b.backends[bename]
log.Debugf("checking user %s with backend %s", username, backend.GetName())
if ok, getUserErr := backend.GetUser(username, password, clientid); ok && getUserErr == nil {
log.Debugf("user %s authenticated with backend %s", username, backend.GetName())
return true, nil
} else if getUserErr != nil && err == nil {
err = getUserErr
}
}
return false, err
}
// AuthAclCheck checks user/topic/acc authorization.
func (b *Backends) AuthAclCheck(clientid, username, topic string, acc int) (bool, error) {
var aclCheck bool
var err error
// If prefixes are enabled, check if username has a valid prefix and use the correct backend if so.
// Else, check all backends.
if !b.checkPrefix {
return b.checkAcl(username, topic, clientid, acc)
}
validPrefix, bename := b.lookupPrefix(username)
if !validPrefix {
return b.checkAcl(username, topic, clientid, acc)
}
// If the backend is JWT and the token was prefixed, then strip the token.
// If the token was passed without a prefix then let it be handled in the common case.
// Also strip the prefix if the strip_prefix option was set.
if bename == jwtBackend || b.stripPrefix {
prefix := b.getPrefixForBackend(bename)
username = strings.TrimPrefix(username, prefix+"_")
}
var backend = b.backends[bename]
// Short circuit checks when superusers are disabled.
if !b.disableSuperuser && checkRegistered(bename, b.superuserCheckers) {
log.Debugf("Superuser check with backend %s", backend.GetName())
aclCheck, err = backend.GetSuperuser(username)
if aclCheck && err == nil {
log.Debugf("superuser %s acl authenticated with backend %s", username, backend.GetName())
}
}
// If not superuser, check acl.
if !aclCheck {
if !checkRegistered(bename, b.aclCheckers) {
return false, fmt.Errorf("backend %s not registered to check acls", bename)
}
log.Debugf("Acl check with backend %s", backend.GetName())
if ok, checkACLErr := backend.CheckAcl(username, topic, clientid, int32(acc)); ok && checkACLErr == nil {
aclCheck = true
log.Debugf("user %s acl authenticated with backend %s", username, backend.GetName())
} else if checkACLErr != nil && err == nil {
err = checkACLErr
}
}
log.Debugf("Acl is %t for user %s", aclCheck, username)
return aclCheck, err
}
func (b *Backends) checkAcl(username, topic, clientid string, acc int) (bool, error) {
// Historically, the plugin checked all backends for superuser first (without order),
// and only then it checked for ACLs.
// If exhaust_backend_first is set, we check backends for both first following order.
if b.exhaustBackendFirst {
return b.exhaustBackendsInOrder(username, topic, clientid, acc)
}
return b.checkSuperuserThenACL(username, topic, clientid, acc)
}
func (b *Backends) exhaustBackendsInOrder(username, topic, clientid string, acc int) (bool, error) {
// Check every backend, in order, for superuser and ACL.
var err error
for _, bename := range b.sortedBackends {
var backend = b.backends[bename]
if !b.disableSuperuser && checkRegistered(bename, b.superuserCheckers) {
log.Debugf("superuser check with backend %s", backend.GetName())
if ok, getSuperuserErr := backend.GetSuperuser(username); ok && getSuperuserErr == nil {
log.Debugf("superuser %s acl authenticated with backend %s", username, backend.GetName())
return true, nil
} else if getSuperuserErr != nil && err == nil {
err = getSuperuserErr
}
}
if checkRegistered(bename, b.aclCheckers) {
log.Debugf("acl check with backend %s", backend.GetName())
if ok, checkACLErr := backend.CheckAcl(username, topic, clientid, int32(acc)); ok && checkACLErr == nil {
log.Debugf("user %s acl authenticated with backend %s", username, backend.GetName())
return true, nil
} else if checkACLErr != nil && err == nil {
err = checkACLErr
}
}
}
// No backend authorized access.
return false, err
}
func (b *Backends) checkSuperuserThenACL(username, topic, clientid string, acc int) (bool, error) {
// Check superusers first
var err error
if !b.disableSuperuser {
for _, bename := range b.superuserCheckers {
var backend = b.backends[bename]
log.Debugf("superuser check with backend %s", backend.GetName())
if ok, getSuperuserErr := backend.GetSuperuser(username); ok && getSuperuserErr == nil {
log.Debugf("superuser %s acl authenticated with backend %s", username, backend.GetName())
return true, nil
} else if getSuperuserErr != nil && err == nil {
err = getSuperuserErr
}
}
}
for _, bename := range b.aclCheckers {
var backend = b.backends[bename]
log.Debugf("Acl check with backend %s", backend.GetName())
if ok, checkACLErr := backend.CheckAcl(username, topic, clientid, int32(acc)); ok && checkACLErr == nil {
log.Debugf("user %s acl authenticated with backend %s", username, backend.GetName())
return true, nil
} else if checkACLErr != nil && err == nil {
err = checkACLErr
}
}
// No backend authorized access.
return false, err
}
func (b *Backends) Halt() {
// Halt every registered backend.
for _, v := range b.backends {
v.Halt()
}
}