-
Notifications
You must be signed in to change notification settings - Fork 174
/
go-auth.go
426 lines (358 loc) · 10.6 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
package main
import "C"
import (
"context"
"os"
"strconv"
"strings"
"time"
bes "github.com/iegomez/mosquitto-go-auth/backends"
"github.com/iegomez/mosquitto-go-auth/cache"
"github.com/iegomez/mosquitto-go-auth/hashing"
log "github.com/sirupsen/logrus"
)
type AuthPlugin struct {
backends *bes.Backends
useCache bool
logLevel log.Level
logDest string
logFile string
ctx context.Context
cache cache.Store
hasher hashing.HashComparer
retryCount int
useClientidAsUsername bool
}
// errors to signal mosquitto
const (
AuthRejected = 0
AuthGranted = 1
AuthError = 2
)
var authOpts map[string]string //Options passed by mosquitto.
var authPlugin AuthPlugin //General struct with options and conf.
//export AuthPluginInit
func AuthPluginInit(keys []*C.char, values []*C.char, authOptsNum int, version *C.char) {
log.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
})
//Initialize auth plugin struct with default and given values.
authPlugin = AuthPlugin{
logLevel: log.InfoLevel,
ctx: context.Background(),
}
authOpts = make(map[string]string)
for i := 0; i < authOptsNum; i++ {
authOpts[C.GoString(keys[i])] = C.GoString(values[i])
}
if retryCount, ok := authOpts["retry_count"]; ok {
retry, err := strconv.ParseInt(retryCount, 10, 64)
if err == nil {
authPlugin.retryCount = int(retry)
} else {
log.Warningf("couldn't parse retryCount (err: %s), defaulting to 0", err)
}
}
if useClientidAsUsername, ok := authOpts["use_clientid_as_username"]; ok && strings.Replace(useClientidAsUsername, " ", "", -1) == "true" {
log.Info("clientid will be used as username on checks")
authPlugin.useClientidAsUsername = true
} else {
authPlugin.useClientidAsUsername = false
}
//Check if log level is given. Set level if any valid option is given.
if logLevel, ok := authOpts["log_level"]; ok {
logLevel = strings.Replace(logLevel, " ", "", -1)
switch logLevel {
case "debug":
authPlugin.logLevel = log.DebugLevel
case "info":
authPlugin.logLevel = log.InfoLevel
case "warn":
authPlugin.logLevel = log.WarnLevel
case "error":
authPlugin.logLevel = log.ErrorLevel
case "fatal":
authPlugin.logLevel = log.FatalLevel
case "panic":
authPlugin.logLevel = log.PanicLevel
default:
log.Info("log_level unkwown, using default info level")
}
}
if logDest, ok := authOpts["log_dest"]; ok {
switch logDest {
case "stdout":
log.SetOutput(os.Stdout)
case "file":
if logFile, ok := authOpts["log_file"]; ok {
file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err == nil {
log.SetOutput(file)
} else {
log.Errorf("failed to log to file, using default stderr: %s", err)
}
}
default:
log.Info("log_dest unknown, using default stderr")
}
}
var err error
authPlugin.backends, err = bes.Initialize(authOpts, authPlugin.logLevel, C.GoString(version))
if err != nil {
log.Fatalf("error initializing backends: %s", err)
}
if cache, ok := authOpts["cache"]; ok && strings.Replace(cache, " ", "", -1) == "true" {
log.Info("redisCache activated")
authPlugin.useCache = true
} else {
log.Info("No cache set.")
authPlugin.useCache = false
}
if authPlugin.useCache {
setCache(authOpts)
}
}
func setCache(authOpts map[string]string) {
var aclCacheSeconds int64 = 30
var authCacheSeconds int64 = 30
var authJitterSeconds int64 = 0
var aclJitterSeconds int64 = 0
if authCacheSec, ok := authOpts["auth_cache_seconds"]; ok {
authSec, err := strconv.ParseInt(authCacheSec, 10, 64)
if err == nil {
authCacheSeconds = authSec
} else {
log.Warningf("couldn't parse authCacheSeconds (err: %s), defaulting to %d", err, authCacheSeconds)
}
}
if authJitterSec, ok := authOpts["auth_jitter_seconds"]; ok {
authSec, err := strconv.ParseInt(authJitterSec, 10, 64)
if err == nil {
authJitterSeconds = authSec
} else {
log.Warningf("couldn't parse authJitterSeconds (err: %s), defaulting to %d", err, authJitterSeconds)
}
}
if authJitterSeconds > authCacheSeconds {
authJitterSeconds = authCacheSeconds
log.Warningf("authJitterSeconds is larger than authCacheSeconds, defaulting to %d", authJitterSeconds)
}
if aclCacheSec, ok := authOpts["acl_cache_seconds"]; ok {
aclSec, err := strconv.ParseInt(aclCacheSec, 10, 64)
if err == nil {
aclCacheSeconds = aclSec
} else {
log.Warningf("couldn't parse aclCacheSeconds (err: %s), defaulting to %d", err, aclCacheSeconds)
}
}
if aclJitterSec, ok := authOpts["acl_jitter_seconds"]; ok {
aclSec, err := strconv.ParseInt(aclJitterSec, 10, 64)
if err == nil {
aclJitterSeconds = aclSec
} else {
log.Warningf("couldn't parse aclJitterSeconds (err: %s), defaulting to %d", err, aclJitterSeconds)
}
}
if aclJitterSeconds > aclCacheSeconds {
aclJitterSeconds = aclCacheSeconds
log.Warningf("aclJitterSeconds is larger than aclCacheSeconds, defaulting to %d", aclJitterSeconds)
}
reset := false
if cacheReset, ok := authOpts["cache_reset"]; ok && cacheReset == "true" {
reset = true
}
refreshExpiration := false
if refresh, ok := authOpts["cache_refresh"]; ok && refresh == "true" {
refreshExpiration = true
}
switch authOpts["cache_type"] {
case "redis":
host := "localhost"
port := "6379"
db := 3
password := ""
cluster := false
if authOpts["cache_mode"] == "true" {
cluster = true
}
if cachePassword, ok := authOpts["cache_password"]; ok {
password = cachePassword
}
if cluster {
addressesOpt := authOpts["redis_cluster_addresses"]
if addressesOpt == "" {
log.Errorln("cache Redis cluster addresses missing, defaulting to no cache.")
authPlugin.useCache = false
return
}
// Take the given addresses and trim spaces from them.
addresses := strings.Split(addressesOpt, ",")
for i := 0; i < len(addresses); i++ {
addresses[i] = strings.TrimSpace(addresses[i])
}
authPlugin.cache = cache.NewRedisClusterStore(
password,
addresses,
time.Duration(authCacheSeconds)*time.Second,
time.Duration(aclCacheSeconds)*time.Second,
time.Duration(authJitterSeconds)*time.Second,
time.Duration(aclJitterSeconds)*time.Second,
refreshExpiration,
)
} else {
if cacheHost, ok := authOpts["cache_host"]; ok {
host = cacheHost
}
if cachePort, ok := authOpts["cache_port"]; ok {
port = cachePort
}
if cacheDB, ok := authOpts["cache_db"]; ok {
parsedDB, err := strconv.ParseInt(cacheDB, 10, 32)
if err == nil {
db = int(parsedDB)
} else {
log.Warningf("couldn't parse cache db (err: %s), defaulting to %d", err, db)
}
}
authPlugin.cache = cache.NewSingleRedisStore(
host,
port,
password,
db,
time.Duration(authCacheSeconds)*time.Second,
time.Duration(aclCacheSeconds)*time.Second,
time.Duration(authJitterSeconds)*time.Second,
time.Duration(aclJitterSeconds)*time.Second,
refreshExpiration,
)
}
default:
authPlugin.cache = cache.NewGoStore(
time.Duration(authCacheSeconds)*time.Second,
time.Duration(aclCacheSeconds)*time.Second,
time.Duration(authJitterSeconds)*time.Second,
time.Duration(aclJitterSeconds)*time.Second,
refreshExpiration,
)
}
if !authPlugin.cache.Connect(authPlugin.ctx, reset) {
authPlugin.cache = nil
authPlugin.useCache = false
log.Infoln("couldn't start cache, defaulting to no cache")
}
}
//export AuthUnpwdCheck
func AuthUnpwdCheck(username, password, clientid *C.char) uint8 {
var ok bool
var err error
for try := 0; try <= authPlugin.retryCount; try++ {
ok, err = authUnpwdCheck(C.GoString(username), C.GoString(password), C.GoString(clientid))
if err == nil {
break
}
}
if err != nil {
log.Error(err)
return AuthError
}
if ok {
return AuthGranted
}
return AuthRejected
}
func authUnpwdCheck(username, password, clientid string) (bool, error) {
var authenticated bool
var cached bool
var granted bool
var err error
username = setUsername(username, clientid)
if authPlugin.useCache {
log.Debugf("checking auth cache for %s", username)
cached, granted = authPlugin.cache.CheckAuthRecord(authPlugin.ctx, username, password)
if cached {
log.Debugf("found in cache: %s", username)
return granted, nil
}
}
authenticated, err = authPlugin.backends.AuthUnpwdCheck(username, password, clientid)
if authPlugin.useCache && err == nil {
authGranted := "false"
if authenticated {
authGranted = "true"
}
log.Debugf("setting auth cache for %s", username)
if setAuthErr := authPlugin.cache.SetAuthRecord(authPlugin.ctx, username, password, authGranted); setAuthErr != nil {
log.Errorf("set auth cache: %s", setAuthErr)
return false, setAuthErr
}
}
return authenticated, err
}
//export AuthAclCheck
func AuthAclCheck(clientid, username, topic *C.char, acc C.int) uint8 {
var ok bool
var err error
for try := 0; try <= authPlugin.retryCount; try++ {
ok, err = authAclCheck(C.GoString(clientid), C.GoString(username), C.GoString(topic), int(acc))
if err == nil {
break
}
}
if err != nil {
log.Error(err)
return AuthError
}
if ok {
return AuthGranted
}
return AuthRejected
}
func authAclCheck(clientid, username, topic string, acc int) (bool, error) {
var aclCheck bool
var cached bool
var granted bool
var err error
username = setUsername(username, clientid)
if authPlugin.useCache {
log.Debugf("checking acl cache for %s", username)
cached, granted = authPlugin.cache.CheckACLRecord(authPlugin.ctx, username, topic, clientid, acc)
if cached {
log.Debugf("found in cache: %s", username)
return granted, nil
}
}
aclCheck, err = authPlugin.backends.AuthAclCheck(clientid, username, topic, acc)
if authPlugin.useCache && err == nil {
authGranted := "false"
if aclCheck {
authGranted = "true"
}
log.Debugf("setting acl cache (granted = %s) for %s", authGranted, username)
if setACLErr := authPlugin.cache.SetACLRecord(authPlugin.ctx, username, topic, clientid, acc, authGranted); setACLErr != nil {
log.Errorf("set acl cache: %s", setACLErr)
return false, setACLErr
}
}
log.Debugf("Acl is %t for user %s", aclCheck, username)
return aclCheck, err
}
//export AuthPskKeyGet
func AuthPskKeyGet() bool {
return true
}
//export AuthPluginCleanup
func AuthPluginCleanup() {
log.Info("Cleaning up plugin")
//If cache is set, close cache connection.
if authPlugin.cache != nil {
authPlugin.cache.Close()
}
authPlugin.backends.Halt()
}
func setUsername(username, clientid string) string {
if authPlugin.useClientidAsUsername {
return clientid
}
return username
}
func main() {}