-
Notifications
You must be signed in to change notification settings - Fork 161
/
mongo.go
271 lines (211 loc) · 6.2 KB
/
mongo.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
package backends
import (
"context"
"crypto/tls"
"fmt"
"strings"
"time"
. "github.com/iegomez/mosquitto-go-auth/backends/constants"
"github.com/iegomez/mosquitto-go-auth/backends/topics"
"github.com/iegomez/mosquitto-go-auth/hashing"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Mongo struct {
Host string
Port string
Username string
Password string
SaltEncoding string
DBName string
AuthSource string
UsersCollection string
AclsCollection string
Conn *mongo.Client
disableSuperuser bool
hasher hashing.HashComparer
withTLS bool
insecureSkipVerify bool
}
type MongoAcl struct {
Topic string `bson:"topic"`
Acc int32 `bson:"acc"`
}
type MongoUser struct {
Username string `bson:"username"`
PasswordHash string `bson:"password"`
Superuser bool `bson:"superuser"`
Acls []MongoAcl `bson:"acls"`
}
func NewMongo(authOpts map[string]string, logLevel log.Level, hasher hashing.HashComparer) (Mongo, error) {
log.SetLevel(logLevel)
var m = Mongo{
Host: "localhost",
Port: "27017",
Username: "",
Password: "",
DBName: "mosquitto",
AuthSource: "",
UsersCollection: "users",
AclsCollection: "acls",
hasher: hasher,
withTLS: false,
insecureSkipVerify: false,
}
if authOpts["mongo_disable_superuser"] == "true" {
m.disableSuperuser = true
}
if mongoHost, ok := authOpts["mongo_host"]; ok {
m.Host = mongoHost
}
if mongoPort, ok := authOpts["mongo_port"]; ok {
m.Port = mongoPort
}
if mongoUsername, ok := authOpts["mongo_username"]; ok {
m.Username = mongoUsername
}
if mongoPassword, ok := authOpts["mongo_password"]; ok {
m.Password = mongoPassword
}
if mongoDBName, ok := authOpts["mongo_dbname"]; ok {
m.DBName = mongoDBName
}
if mongoAuthSource, ok := authOpts["mongo_authsource"]; ok {
m.AuthSource = mongoAuthSource
}
if usersCollection, ok := authOpts["mongo_users"]; ok {
m.UsersCollection = usersCollection
}
if aclsCollection, ok := authOpts["mongo_acls"]; ok {
m.AclsCollection = aclsCollection
}
if authOpts["mongo_use_tls"] == "true" {
m.withTLS = true
}
if authOpts["mongo_insecure_skip_verify"] == "true" {
m.insecureSkipVerify = true
}
addr := fmt.Sprintf("mongodb:https://%s:%s", m.Host, m.Port)
to := 60 * time.Second
opts := options.ClientOptions{
ConnectTimeout: &to,
}
if m.withTLS {
opts.TLSConfig = &tls.Config{}
}
opts.ApplyURI(addr)
if m.Username != "" && m.Password != "" {
opts.Auth = &options.Credential{
AuthSource: m.DBName,
Username: m.Username,
Password: m.Password,
PasswordSet: true,
}
// Set custom AuthSource db if supplied in config
if m.AuthSource != "" {
opts.Auth.AuthSource = m.AuthSource
log.Infof("mongo backend: set authentication db to: %s", m.AuthSource)
}
}
client, err := mongo.Connect(context.TODO(), &opts)
if err != nil {
return m, errors.Errorf("couldn't start mongo backend: %s", err)
}
m.Conn = client
return m, nil
}
//GetUser checks that the username exists and the given password hashes to the same password.
func (o Mongo) GetUser(username, password, clientid string) (bool, error) {
uc := o.Conn.Database(o.DBName).Collection(o.UsersCollection)
var user MongoUser
err := uc.FindOne(context.TODO(), bson.M{"username": username}).Decode(&user)
if err != nil {
if err == mongo.ErrNoDocuments {
// avoid leaking the fact that user exists or not though error.
return false, nil
}
log.Debugf("Mongo get user error: %s", err)
return false, err
}
if o.hasher.Compare(password, user.PasswordHash) {
return true, nil
}
return false, nil
}
//GetSuperuser checks that the key username:su exists and has value "true".
func (o Mongo) GetSuperuser(username string) (bool, error) {
if o.disableSuperuser {
return false, nil
}
uc := o.Conn.Database(o.DBName).Collection(o.UsersCollection)
var user MongoUser
err := uc.FindOne(context.TODO(), bson.M{"username": username}).Decode(&user)
if err != nil {
if err == mongo.ErrNoDocuments {
// avoid leaking the fact that user exists or not though error.
return false, nil
}
log.Debugf("Mongo get superuser error: %s", err)
return false, err
}
return user.Superuser, nil
}
//CheckAcl gets all acls for the username and tries to match against topic, acc, and username/clientid if needed.
func (o Mongo) CheckAcl(username, topic, clientid string, acc int32) (bool, error) {
//Get user and check his acls.
uc := o.Conn.Database(o.DBName).Collection(o.UsersCollection)
var user MongoUser
err := uc.FindOne(context.TODO(), bson.M{"username": username}).Decode(&user)
if err != nil {
if err == mongo.ErrNoDocuments {
// avoid leaking the fact that user exists or not though error.
return false, nil
}
log.Debugf("Mongo get superuser error: %s", err)
return false, err
}
for _, acl := range user.Acls {
// TODO: needs fixing since it's bypassing MOSQ_ACL_SUBSCRIBE.
if (acl.Acc == acc || acl.Acc == MOSQ_ACL_READWRITE) && topics.Match(acl.Topic, topic) {
return true, nil
}
}
//Now check common acls.
ac := o.Conn.Database(o.DBName).Collection(o.AclsCollection)
cur, err := ac.Find(context.TODO(), bson.M{"acc": bson.M{"$in": []int32{acc, 3}}})
if err != nil {
log.Debugf("Mongo check acl error: %s", err)
return false, err
}
defer cur.Close(context.TODO())
for cur.Next(context.TODO()) {
var acl MongoAcl
err = cur.Decode(&acl)
if err == nil {
aclTopic := strings.Replace(acl.Topic, "%c", clientid, -1)
aclTopic = strings.Replace(aclTopic, "%u", username, -1)
if topics.Match(aclTopic, topic) {
return true, nil
}
} else {
log.Errorf("mongo cursor decode error: %s", err)
}
}
return false, nil
}
//GetName returns the backend's name
func (o Mongo) GetName() string {
return "Mongo"
}
//Halt closes the mongo session.
func (o Mongo) Halt() {
if o.Conn != nil {
err := o.Conn.Disconnect(context.TODO())
if err != nil {
log.Errorf("mongo halt: %s", err)
}
}
}