-
Notifications
You must be signed in to change notification settings - Fork 0
/
ldap.go
430 lines (342 loc) · 11.4 KB
/
ldap.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
package core
import (
"errors"
"fmt"
"strings"
"github.com/croessner/nauthilus/server/backend"
"github.com/croessner/nauthilus/server/config"
errors2 "github.com/croessner/nauthilus/server/errors"
"github.com/croessner/nauthilus/server/global"
"github.com/croessner/nauthilus/server/logging"
"github.com/croessner/nauthilus/server/stats"
"github.com/croessner/nauthilus/server/util"
"github.com/go-kit/log/level"
"github.com/go-ldap/ldap/v3"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/prometheus/client_golang/prometheus"
)
// handleMasterUserMode handles the master user mode functionality for authentication.
// If master user mode is enabled and the username contains only one occurrence of the delimiter,
// it splits the username based on the delimiter and returns the appropriate part of the username
// based on the master user mode flag.
//
// Parameters:
// - auth: a pointer to the Authentication struct which contains the user authentication information.
//
// Returns:
// - string: the username based on the master user mode flag.
func handleMasterUserMode(auth *Authentication) string {
if config.LoadableConfig.Server.MasterUser.Enabled {
if strings.Count(auth.Username, config.LoadableConfig.Server.MasterUser.Delimiter) == 1 {
parts := strings.Split(auth.Username, config.LoadableConfig.Server.MasterUser.Delimiter)
if !(len(parts[0]) > 0 && len(parts[1]) > 0) {
return auth.Username
}
if !auth.MasterUserMode {
auth.MasterUserMode = true
// Return master user
return parts[1]
} else {
auth.MasterUserMode = false
// Return real user
return parts[0]
}
}
}
return auth.Username
}
// saveMasterUserTOTPSecret checks if the master user has a TOTP secret and returns it if present.
//
// Parameters:
// - masterUserMode: a boolean indicating if master user mode is enabled.
// - ldapReply: a pointer to the LDAPReply struct containing the LDAP query result.
// - totpSecretField: a string indicating the field in which the TOTP secret is stored in the LDAPReply.
//
// Returns:
// - totpSecretPre: a slice of interface{} containing the TOTP secret if present, nil otherwise.
func saveMasterUserTOTPSecret(masterUserMode bool, ldapReply *backend.LDAPReply, totpSecretField string) (totpSecretPre []any) {
if masterUserMode {
// Check if the master user does have a TOTP secret.
if value, okay := ldapReply.Result[totpSecretField]; okay {
totpSecretPre = value
}
}
return nil
}
// restoreMasterUserTOTPSecret restores the TOTP secret for a master user in the PassDBResult attributes.
// If the totpSecretPre parameter is not empty, it sets the TOTP secret attribute in the attributes map.
// Otherwise, it deletes the TOTP secret attribute from the attributes map.
//
// Parameters:
// - passDBResult: a pointer to the PassDBResult struct which contains the PassDB result attributes.
// - totpSecretPre: an array of any type that represents the TOTP secret from a master user.
// - totpSecretField: a string that represents the field name for the TOTP secret in the attributes map.
func restoreMasterUserTOTPSecret(passDBResult *PassDBResult, totpSecretPre []any, totpSecretField string) {
if totpSecretPre != nil && len(totpSecretPre) != 0 {
// Use the TOTP secret from a master user if it exists.
passDBResult.Attributes[totpSecretField] = totpSecretPre
} else {
// Ignore the user TOTP secret if it exists.
delete(passDBResult.Attributes, totpSecretField)
}
}
// ldapPassDB implements the LDAP password database backend.
//
//nolint:gocognit // Backends are complex
func ldapPassDB(auth *Authentication) (passDBResult *PassDBResult, err error) {
var (
assertOk bool
accountField string
filter string
baseDN string
distinguishedNames any
attributes []string
scope *config.LDAPScope
ldapReply *backend.LDAPReply
protocol *config.LDAPSearchProtocol
)
passDBResult = &PassDBResult{}
ldapReplyChan := make(chan *backend.LDAPReply)
defer close(ldapReplyChan)
if protocol, err = config.LoadableConfig.GetLDAPSearchProtocol(auth.Protocol.Get()); err != nil {
return
}
if accountField, err = protocol.GetAccountField(); err != nil {
return
}
if attributes, err = protocol.GetAttributes(); err != nil {
return
}
if filter, err = protocol.GetUserFilter(); err != nil {
return
}
if baseDN, err = protocol.GetBaseDN(); err != nil {
return
}
if scope, err = protocol.GetScope(); err != nil {
return
}
username := handleMasterUserMode(auth)
ldapRequest := &backend.LDAPRequest{
GUID: auth.GUID,
Command: global.LDAPSearch,
MacroSource: &util.MacroSource{
Username: username,
XLocalIP: auth.XLocalIP,
XPort: auth.XPort,
ClientIP: auth.ClientIP,
XClientPort: auth.XClientPort,
TOTPSecret: auth.TOTPSecret,
Protocol: *auth.Protocol,
},
Filter: filter,
BaseDN: baseDN,
SearchAttributes: attributes,
Scope: *scope,
LDAPReplyChan: ldapReplyChan,
HTTPClientContext: auth.HTTPClientContext,
}
// Find user with account status enabled
backend.LDAPRequestChan <- ldapRequest
ldapReply = <-ldapReplyChan
if ldapReply.Err != nil {
return passDBResult, ldapReply.Err
}
// User not found
if distinguishedNames, assertOk = ldapReply.Result[global.DistinguishedName]; !assertOk {
return
}
if len(distinguishedNames.([]any)) == 0 {
return
}
dn := distinguishedNames.([]any)[global.LDAPSingleValue].(string)
// If a DN was returned and an account field is present, the user was found in the backend.
passDBResult.UserFound = true
passDBResult.Backend = global.BackendLDAP
if _, okay := ldapReply.Result[accountField]; okay {
passDBResult.AccountField = &accountField
}
if protocol.TOTPSecretField != "" {
passDBResult.TOTPSecretField = &protocol.TOTPSecretField
}
if protocol.UniqueUserIDField != "" {
passDBResult.UniqueUserIDField = &protocol.UniqueUserIDField
}
if protocol.DisplayNameField != "" {
passDBResult.DisplayNameField = &protocol.DisplayNameField
} else {
// Fallback
passDBResult.DisplayNameField = &accountField
}
if len(ldapReply.Result) > 0 {
passDBResult.Attributes = ldapReply.Result
}
totpSecretPre := saveMasterUserTOTPSecret(auth.MasterUserMode, ldapReply, protocol.TOTPSecretField)
if !auth.NoAuth {
ldapReplyChan = make(chan *backend.LDAPReply)
ldapUserBindRequest := &backend.LDAPAuthRequest{
GUID: auth.GUID,
BindDN: dn,
BindPW: auth.Password,
LDAPReplyChan: ldapReplyChan,
HTTPClientContext: auth.HTTPClientContext,
}
backend.LDAPAuthRequestChan <- ldapUserBindRequest
ldapReply = <-ldapReplyChan
if ldapReply.Err != nil {
var ldapError *ldap.Error
level.Debug(logging.DefaultLogger).Log(global.LogKeyGUID, auth.GUID, global.LogKeyMsg, err)
if errors.As(err, &ldapError) {
if ldapError.ResultCode != uint16(ldap.LDAPResultInvalidCredentials) {
return passDBResult, ldapError.Err
}
}
// Authentication failed!
return
}
}
passDBResult.Authenticated = true
// We need to do a second user lookup, to retrieve correct data from LDAP.
if auth.MasterUserMode {
auth.NoAuth = true
passDBResult, err = ldapPassDB(auth)
restoreMasterUserTOTPSecret(passDBResult, totpSecretPre, protocol.TOTPSecretField)
}
return
}
// ldapAccountDB implements the list-account mode and returns all known users from an LDAP server.
func ldapAccountDB(auth *Authentication) (accounts AccountList, err error) {
var (
accountField string
filter string
baseDN string
attributes []string
ldapReply *backend.LDAPReply
scope *config.LDAPScope
protocol *config.LDAPSearchProtocol
)
timer := prometheus.NewTimer(stats.FunctionDuration.WithLabelValues("Account", "ldapAccountDB"))
defer timer.ObserveDuration()
ldapReplyChan := make(chan *backend.LDAPReply)
defer close(ldapReplyChan)
if protocol, err = config.LoadableConfig.GetLDAPSearchProtocol(auth.Protocol.Get()); err != nil {
return
}
if accountField, err = protocol.GetAccountField(); err != nil {
return
}
if attributes, err = protocol.GetAttributes(); err != nil {
return
}
if filter, err = protocol.GetListAccountsFilter(); err != nil {
return
}
if baseDN, err = protocol.GetBaseDN(); err != nil {
return
}
if scope, err = protocol.GetScope(); err != nil {
return
}
ldapRequest := &backend.LDAPRequest{
GUID: auth.GUID,
Command: global.LDAPSearch,
MacroSource: &util.MacroSource{
Username: auth.Username,
XLocalIP: auth.XLocalIP,
XPort: auth.XPort,
ClientIP: auth.ClientIP,
XClientPort: auth.XClientPort,
TOTPSecret: auth.TOTPSecret,
Protocol: *auth.Protocol,
},
Filter: filter,
BaseDN: baseDN,
SearchAttributes: attributes,
Scope: *scope,
LDAPReplyChan: ldapReplyChan,
HTTPClientContext: auth.HTTPClientContext,
}
// Find user with account status enabled
backend.LDAPRequestChan <- ldapRequest
ldapReply = <-ldapReplyChan
if ldapReply.Err != nil {
var ldapError *ldap.Error
if errors.As(err, &ldapError) {
return accounts, ldapError.Err
}
return accounts, ldapReply.Err
}
if result, okay := ldapReply.Result[accountField]; okay {
for index := range result {
if account, okay := result[index].(string); okay {
accounts = append(accounts, account)
}
}
}
return
}
// ldapAddTOTPSecret adds a newly generated TOTP secret to an LDAP server.
func ldapAddTOTPSecret(auth *Authentication, totp *TOTPSecret) (err error) {
var (
filter string
baseDN string
configField string
ldapReply *backend.LDAPReply
scope *config.LDAPScope
protocol *config.LDAPSearchProtocol
ldapError *ldap.Error
)
timer := prometheus.NewTimer(stats.FunctionDuration.WithLabelValues("StoreTOTP", "ldapAddTOTPSecret"))
defer timer.ObserveDuration()
ldapReplyChan := make(chan *backend.LDAPReply)
defer close(ldapReplyChan)
if protocol, err = config.LoadableConfig.GetLDAPSearchProtocol(auth.Protocol.Get()); err != nil {
return
}
if filter, err = protocol.GetUserFilter(); err != nil {
return
}
if baseDN, err = protocol.GetBaseDN(); err != nil {
return
}
if scope, err = protocol.GetScope(); err != nil {
return
}
configField = totp.getLDAPTOTPSecret(protocol)
if configField == "" {
err = errors2.ErrLDAPConfig.WithDetail(
fmt.Sprintf("Missing LDAP TOTP secret field; protocol=%s", auth.Protocol.Get()))
return
}
ldapRequest := &backend.LDAPRequest{
GUID: auth.GUID,
Command: global.LDAPModifyAdd,
MacroSource: &util.MacroSource{
Username: auth.Username,
XLocalIP: auth.XLocalIP,
XPort: auth.XPort,
ClientIP: auth.ClientIP,
XClientPort: auth.XClientPort,
TOTPSecret: auth.TOTPSecret,
Protocol: *auth.Protocol,
},
Filter: filter,
BaseDN: baseDN,
Scope: *scope,
LDAPReplyChan: ldapReplyChan,
HTTPClientContext: auth.HTTPClientContext,
}
ldapRequest.ModifyAttributes = make(backend.LDAPModifyAttributes, 2)
ldapRequest.ModifyAttributes[configField] = []string{totp.getValue()}
backend.LDAPRequestChan <- ldapRequest
ldapReply = <-ldapReplyChan
if errors.As(ldapReply.Err, &ldapError) {
return ldapError.Err
}
return ldapReply.Err
}
func ldapGetWebAuthnCredentials(uniqueUserID string) ([]webauthn.Credential, error) {
_ = uniqueUserID
// TODO: Use WebAuthn constructor!
return []webauthn.Credential{}, nil
}