-
Notifications
You must be signed in to change notification settings - Fork 2
/
ldap.go
292 lines (264 loc) · 9.27 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
package authaus
import (
//"github.com/mmitton/ldap"
"crypto/tls"
"errors"
"fmt"
"strings"
"time"
"github.com/mavricknz/ldap"
)
type LdapConnectionMode int
const (
LdapConnectionModePlainText LdapConnectionMode = iota
LdapConnectionModeSSL = iota
LdapConnectionModeTLS = iota
)
type LdapImpl struct {
config *ConfigLDAP
}
func (x *LdapImpl) Authenticate(identity, password string) error {
if len(password) == 0 {
// Many LDAP servers (or AD) will allow an anonymous BIND.
// I've never seen the need for a password-less user authenticated against LDAP.
return ErrInvalidPassword
}
con, err := NewLDAPConnect(x.config)
if err != nil {
return err
}
defer con.Close()
// We need to know whether or not we must add the domain to the identity by checking if it contains '@'
if !strings.Contains(identity, "@") {
identity = fmt.Sprintf(`%v@%v`, identity, x.config.LdapDomain)
}
err = con.Bind(identity, password)
if err != nil {
if strings.Index(err.Error(), "Invalid Credentials") != 0 {
return ErrInvalidCredentials
} else {
return err
}
}
return nil
}
func (x *LdapImpl) Close() {
}
func (x *LdapImpl) GetLdapUsers() ([]AuthUser, error) {
var attributes []string = []string{
"sAMAccountName",
"givenName",
"name",
"sn",
"mail",
"mobile",
"userPrincipalName",
}
searchRequest := ldap.NewSearchRequest(
x.config.BaseDN,
ldap.ScopeWholeSubtree, ldap.DerefAlways, 0, 0, false,
x.config.LdapSearchFilter,
attributes,
nil)
con, err := NewLDAPConnectAndBind(x.config)
if err != nil {
return nil, err
}
defer con.Close()
sr, err := con.SearchWithPaging(searchRequest, 100)
if err != nil {
return nil, err
}
getAttributeValue := func(entry ldap.Entry, attribute string) string {
values := entry.GetAttributeValues(attribute)
if len(values) == 0 {
return ""
}
return values[0]
}
if x.config.DebugUserPull {
fmt.Printf("%23v | %16v | %19v | %45v | %15v\n", "username", "name", "surname", "email", "mobile")
}
ldapUsers := make([]AuthUser, len(sr.Entries))
for i, value := range sr.Entries {
// We trim the spaces as we have found that a certain ldap user
// (WilburGS) has an email that ends with a space.
username := strings.TrimSpace(getAttributeValue(*value, "sAMAccountName"))
givenName := strings.TrimSpace(getAttributeValue(*value, "givenName"))
name := strings.TrimSpace(getAttributeValue(*value, "name"))
surname := strings.TrimSpace(getAttributeValue(*value, "sn"))
email := strings.TrimSpace(getAttributeValue(*value, "mail"))
mobile := strings.TrimSpace(getAttributeValue(*value, "mobile"))
userPrincipalName := strings.TrimSpace(getAttributeValue(*value, "userPrincipalName"))
if email == "" && strings.Count(userPrincipalName, "@") == 1 {
// This was first seen in Azure, when integrating with DTPW (Department of Transport and Public Works)
email = userPrincipalName
}
firstName := givenName
if firstName == "" && surname == "" && name != "" {
// We're in dubious best-guess-for-common-english territory here
firstSpace := strings.Index(name, " ")
if firstSpace != -1 {
firstName = name[:firstSpace]
surname = name[firstSpace+1:]
}
}
if x.config.DebugUserPull {
fmt.Printf("%23v | %16v | %19v | %45v | %15v\n", username, firstName, surname, email, mobile)
}
ldapUsers[i] = AuthUser{UserId: NullUserId, Email: email, Username: username, Firstname: firstName, Lastname: surname, Mobilenumber: mobile}
}
return ldapUsers, nil
}
func MergeLDAP(c *Central) {
ldapUsers, err := c.ldap.GetLdapUsers()
if err != nil {
c.Log.Warnf("Failed to retrieve users from LDAP server for merge to take place (%v)", err)
return
}
imqsUsers, err := c.userStore.GetIdentities(GetIdentitiesFlagNone)
if err != nil {
c.Log.Warnf("Failed to retrieve users from Userstore for merge to take place (%v)", err)
return
}
MergeLdapUsersIntoLocalUserStore(c, ldapUsers, imqsUsers)
}
// We are reading users from LDAP/AD and merging them into the IMQS userstore
func MergeLdapUsersIntoLocalUserStore(x *Central, ldapUsers []AuthUser, imqsUsers []AuthUser) {
// Create maps from arrays
imqsUserUsernameMap := make(map[string]AuthUser)
for _, imqsUser := range imqsUsers {
if len(imqsUser.Username) > 0 {
imqsUserUsernameMap[CanonicalizeIdentity(imqsUser.Username)] = imqsUser
}
}
imqsUserEmailMap := make(map[string]AuthUser)
for _, imqsUser := range imqsUsers {
if len(imqsUser.Email) > 0 {
imqsUserEmailMap[CanonicalizeIdentity(imqsUser.Email)] = imqsUser
}
}
ldapUserMap := make(map[string]AuthUser)
for _, ldapUser := range ldapUsers {
ldapUserMap[CanonicalizeIdentity(ldapUser.Username)] = ldapUser
}
// Insert or update
for _, ldapUser := range ldapUsers {
// This log is useful when debugging, but in regular operation the relevant details go into the logs when something changes (see below)
// x.Log.Infof("Merging user %20s %20s %20s '%s'", ldapUser.Username, ldapUser.Firstname, ldapUser.Lastname, ldapUser.Email)
imqsUser, foundWithUsername := imqsUserUsernameMap[CanonicalizeIdentity(ldapUser.Username)]
foundWithEmail := false
if !foundWithUsername {
imqsUser, foundWithEmail = imqsUserEmailMap[CanonicalizeIdentity(ldapUser.Email)]
}
user := imqsUser
user.Email = ldapUser.Email
user.Username = ldapUser.Username
user.Firstname = ldapUser.Firstname
user.Lastname = ldapUser.Lastname
user.Mobilenumber = ldapUser.Mobilenumber
user.Type = UserTypeLDAP
if !foundWithUsername && !foundWithEmail {
user.Created = time.Now().UTC()
user.CreatedBy = UserIdLDAPMerge
user.Modified = time.Now().UTC()
user.ModifiedBy = UserIdLDAPMerge
// WARNING: Weird thing that looked like a compiler bug:
// We have found that a certain ldap user (WilburGS) has an email that ends with a space.
// This space mysteriously disappears when the address of `user` is taken.
if _, err := x.userStore.CreateIdentity(&user, ""); err != nil {
x.Log.Warnf("LDAP merge: Create identity failed with (%v)", err)
}
// Log to audit trail user created
if x.Auditor != nil {
contextData := userInfoToAuditTrailJSON(user, "")
x.Auditor.AuditUserAction(user.Username, "User Profile: "+user.Username, contextData, AuditActionCreated)
}
} else if foundWithEmail || !equalsForLDAPMerge(user, imqsUser) {
if imqsUser.Type == UserTypeDefault {
x.Log.Infof("Updating user of Default user type, to LDAP user type: %v", imqsUser.Email)
}
user.Modified = time.Now().UTC()
user.ModifiedBy = UserIdLDAPMerge
// WARNING: Weird thing that looked like a compiler bug:
// We have found that a certain ldap user (WilburGS) has an email that ends with a space.
// This space mysteriously disappears when the address of `user` is taken.
if err := x.userStore.UpdateIdentity(&user); err != nil {
x.Log.Warnf("LDAP merge: Update identity failed with (%v)", err)
} else {
x.Log.Infof("LDAP merge: Updated user %v", user.Username)
x.Log.Infof("old: %v", userInfoToJSON(imqsUser))
x.Log.Infof("new: %v", userInfoToJSON(user))
}
// Log to audit trail user updated
if x.Auditor != nil {
contextData := userInfoToAuditTrailJSON(user, "")
x.Auditor.AuditUserAction(user.Username, "User Profile: "+user.Username, contextData, AuditActionUpdated)
}
}
}
// Remove
for _, imqsUser := range imqsUsers {
_, found := ldapUserMap[CanonicalizeIdentity(imqsUser.Username)]
if !found {
// We only archive ldap users that are not on the ldap system, but are not on ours, imqs users should remain
if imqsUser.Type == UserTypeLDAP {
if err := x.userStore.ArchiveIdentity(imqsUser.UserId); err != nil {
x.Log.Warnf("LDAP merge: Archive identity failed with (%v)", err)
}
// Log to audit trail user deleted
if x.Auditor != nil {
contextData := userInfoToAuditTrailJSON(imqsUser, "")
x.Auditor.AuditUserAction(imqsUser.Username, "User Profile: "+imqsUser.Username, contextData, AuditActionDeleted)
}
}
}
}
}
func equalsForLDAPMerge(a, b AuthUser) bool {
return a.Email == b.Email &&
a.Firstname == b.Firstname &&
a.Lastname == b.Lastname &&
a.Mobilenumber == b.Mobilenumber &&
a.Username == b.Username
}
func NewLDAPConnectAndBind(config *ConfigLDAP) (*ldap.LDAPConnection, error) {
con, err := NewLDAPConnect(config)
if err != nil {
return nil, err
}
if err := con.Bind(config.LdapUsername, config.LdapPassword); err != nil {
return nil, err
}
return con, nil
}
func NewLDAPConnect(config *ConfigLDAP) (*ldap.LDAPConnection, error) {
con := ldap.NewLDAPConnection(config.LdapHost, config.LdapPort)
con.NetworkConnectTimeout = 30 * time.Second
con.ReadTimeout = 30 * time.Second
ldapMode, legalLdapMode := configLdapNameToMode[config.Encryption]
if !legalLdapMode {
return nil, errors.New(fmt.Sprintf("Unknown ldap mode %v. Recognized modes are TLS, SSL, and empty for unencrypted", config.Encryption))
}
switch ldapMode {
case LdapConnectionModePlainText:
case LdapConnectionModeSSL:
con.IsSSL = true
case LdapConnectionModeTLS:
con.IsTLS = true
}
if config.InsecureSkipVerify {
con.TlsConfig = &tls.Config{}
con.TlsConfig.InsecureSkipVerify = config.InsecureSkipVerify
}
if err := con.Connect(); err != nil {
con.Close()
return nil, err
}
return con, nil
}
func NewAuthenticator_LDAP(config *ConfigLDAP) *LdapImpl {
return &LdapImpl{
config: config,
}
}