-
Notifications
You must be signed in to change notification settings - Fork 0
/
ldap.go
430 lines (354 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
// Copyright Project Harbor Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ldap
import (
"crypto/tls"
"errors"
"fmt"
"net/url"
"strconv"
"strings"
"time"
"github.com/goharbor/harbor/src/common/models"
"github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/core/config"
goldap "gopkg.in/ldap.v2"
)
// ErrNotFound ...
var ErrNotFound = errors.New("entity not found")
// ErrDNSyntax ...
var ErrDNSyntax = errors.New("Invalid DN syntax")
// Session - define a LDAP session
type Session struct {
ldapConfig models.LdapConf
ldapGroupConfig models.LdapGroupConf
ldapConn *goldap.Conn
}
// LoadSystemLdapConfig - load LDAP configure from adminserver
func LoadSystemLdapConfig() (*Session, error) {
authMode, err := config.AuthMode()
if err != nil {
log.Errorf("can't load auth mode from system, error: %v", err)
return nil, err
}
if authMode != "ldap_auth" {
return nil, fmt.Errorf("system auth_mode isn't ldap_auth, please check configuration")
}
ldapConf, err := config.LDAPConf()
if err != nil {
return nil, err
}
ldapGroupConfig, err := config.LDAPGroupConf()
if err != nil {
return nil, err
}
return CreateWithAllConfig(*ldapConf, *ldapGroupConfig)
}
// CreateWithConfig -
func CreateWithConfig(ldapConf models.LdapConf) (*Session, error) {
return CreateWithAllConfig(ldapConf, models.LdapGroupConf{})
}
// CreateWithAllConfig - create a Session with internal config
func CreateWithAllConfig(ldapConf models.LdapConf, ldapGroupConfig models.LdapGroupConf) (*Session, error) {
var session Session
if ldapConf.LdapURL == "" {
return nil, fmt.Errorf("can not get any available LDAP_URL")
}
ldapURL, err := formatURL(ldapConf.LdapURL)
if err != nil {
return nil, err
}
ldapConf.LdapURL = ldapURL
session.ldapConfig = ldapConf
session.ldapGroupConfig = ldapGroupConfig
return &session, nil
}
func formatURL(ldapURL string) (string, error) {
var protocol, hostport string
_, err := url.Parse(ldapURL)
if err != nil {
return "", fmt.Errorf("parse Ldap Host ERR: %s", err)
}
if strings.Contains(ldapURL, "://") {
splitLdapURL := strings.Split(ldapURL, "://")
protocol, hostport = splitLdapURL[0], splitLdapURL[1]
if !((protocol == "ldap") || (protocol == "ldaps")) {
return "", fmt.Errorf("unknown ldap protocol")
}
} else {
hostport = ldapURL
protocol = "ldap"
}
if strings.Contains(hostport, ":") {
splitHostPort := strings.Split(hostport, ":")
port, error := strconv.Atoi(splitHostPort[1])
if error != nil {
return "", fmt.Errorf("illegal url port")
}
if port == 636 {
protocol = "ldaps"
}
} else {
switch protocol {
case "ldap":
hostport = hostport + ":389"
case "ldaps":
hostport = hostport + ":636"
}
}
fLdapURL := protocol + "://" + hostport
return fLdapURL, nil
}
// ConnectionTest - test ldap session connection with system default setting
func (session *Session) ConnectionTest() error {
session, err := LoadSystemLdapConfig()
if err != nil {
return fmt.Errorf("Failed to load system ldap config")
}
return ConnectionTestWithAllConfig(session.ldapConfig, session.ldapGroupConfig)
}
// ConnectionTestWithConfig -
func ConnectionTestWithConfig(ldapConfig models.LdapConf) error {
return ConnectionTestWithAllConfig(ldapConfig, models.LdapGroupConf{})
}
// ConnectionTestWithAllConfig - test ldap session connection, out of the scope of normal session create/close
func ConnectionTestWithAllConfig(ldapConfig models.LdapConf, ldapGroupConfig models.LdapGroupConf) error {
authMode, err := config.AuthMode()
if err != nil {
log.Errorf("Connection test failed %v", err)
return err
}
// If no password present, use the system default password
if ldapConfig.LdapSearchPassword == "" && authMode == "ldap_auth" {
session, err := LoadSystemLdapConfig()
if err != nil {
return fmt.Errorf("Failed to load system ldap config")
}
ldapConfig.LdapSearchPassword = session.ldapConfig.LdapSearchPassword
}
testSession, err := CreateWithAllConfig(ldapConfig, ldapGroupConfig)
if err != nil {
return err
}
err = testSession.Open()
if err != nil {
return err
}
defer testSession.Close()
if testSession.ldapConfig.LdapSearchDn != "" {
err = testSession.Bind(testSession.ldapConfig.LdapSearchDn, testSession.ldapConfig.LdapSearchPassword)
if err != nil {
return err
}
}
return nil
}
// SearchUser - search LDAP user by name
func (session *Session) SearchUser(username string) ([]models.LdapUser, error) {
var ldapUsers []models.LdapUser
ldapFilter := session.createUserFilter(username)
result, err := session.SearchLdap(ldapFilter)
if err != nil {
return nil, err
}
for _, ldapEntry := range result.Entries {
var u models.LdapUser
groupDNList := []string{}
for _, attr := range ldapEntry.Attributes {
// OpenLdap sometimes contain leading space in useranme
val := strings.TrimSpace(attr.Values[0])
log.Debugf("Current ldap entry attr name: %s\n", attr.Name)
switch strings.ToLower(attr.Name) {
case strings.ToLower(session.ldapConfig.LdapUID):
u.Username = val
case "uid":
u.Realname = val
case "cn":
u.Realname = val
case "mail":
u.Email = val
case "email":
u.Email = val
case "memberof":
for _, dnItem := range attr.Values {
groupDNList = append(groupDNList, strings.TrimSpace(dnItem))
log.Debugf("Found memberof %v", dnItem)
}
}
u.GroupDNList = groupDNList
}
u.DN = ldapEntry.DN
ldapUsers = append(ldapUsers, u)
}
return ldapUsers, nil
}
// Bind with specified DN and password, used in authentication
func (session *Session) Bind(dn string, password string) error {
return session.ldapConn.Bind(dn, password)
}
// Open - open Session
func (session *Session) Open() error {
splitLdapURL := strings.Split(session.ldapConfig.LdapURL, "://")
protocol, hostport := splitLdapURL[0], splitLdapURL[1]
host := strings.Split(hostport, ":")[0]
connectionTimeout := session.ldapConfig.LdapConnectionTimeout
goldap.DefaultTimeout = time.Duration(connectionTimeout) * time.Second
switch protocol {
case "ldap":
ldap, err := goldap.Dial("tcp", hostport)
if err != nil {
return err
}
session.ldapConn = ldap
case "ldaps":
log.Debug("Start to dial ldaps")
ldap, err := goldap.DialTLS("tcp", hostport, &tls.Config{ServerName: host, InsecureSkipVerify: !session.ldapConfig.LdapVerifyCert})
if err != nil {
return err
}
session.ldapConn = ldap
}
return nil
}
// SearchLdap to search ldap with the provide filter
func (session *Session) SearchLdap(filter string) (*goldap.SearchResult, error) {
attributes := []string{"uid", "cn", "mail", "email", "memberof"}
lowerUID := strings.ToLower(session.ldapConfig.LdapUID)
if lowerUID != "uid" && lowerUID != "cn" && lowerUID != "mail" && lowerUID != "email" {
attributes = append(attributes, session.ldapConfig.LdapUID)
}
return session.SearchLdapAttribute(session.ldapConfig.LdapBaseDn, filter, attributes)
}
// SearchLdapAttribute - to search ldap with the provide filter, with specified attributes
func (session *Session) SearchLdapAttribute(baseDN, filter string, attributes []string) (*goldap.SearchResult, error) {
if err := session.Bind(session.ldapConfig.LdapSearchDn, session.ldapConfig.LdapSearchPassword); err != nil {
return nil, fmt.Errorf("Can not bind search dn, error: %v", err)
}
filter = strings.TrimSpace(filter)
if !(strings.HasPrefix(filter, "(") || strings.HasSuffix(filter, ")")) {
filter = "(" + filter + ")"
}
log.Debugf("Search ldap with filter:%v", filter)
searchRequest := goldap.NewSearchRequest(
baseDN,
session.ldapConfig.LdapScope,
goldap.NeverDerefAliases,
0, // Unlimited results
0, // Search Timeout
false, // Types only
filter,
attributes,
nil,
)
result, err := session.ldapConn.Search(searchRequest)
if result != nil {
log.Debugf("Found entries:%v\n", len(result.Entries))
} else {
log.Debugf("No entries")
}
if err != nil {
log.Debug("LDAP search error", err)
return nil, err
}
return result, nil
}
// CreateUserFilter - create filter to search user with specified username
func (session *Session) createUserFilter(username string) string {
var filterTag string
if username == "" {
filterTag = "*"
} else {
filterTag = goldap.EscapeFilter(username)
}
ldapFilter := session.ldapConfig.LdapFilter
ldapUID := session.ldapConfig.LdapUID
if ldapFilter == "" {
ldapFilter = "(" + ldapUID + "=" + filterTag + ")"
} else {
ldapFilter = "(&" + ldapFilter + "(" + ldapUID + "=" + filterTag + "))"
}
log.Debug("ldap filter :", ldapFilter)
return ldapFilter
}
// Close - close current session
func (session *Session) Close() {
if session.ldapConn != nil {
session.ldapConn.Close()
}
}
// SearchGroupByName ...
func (session *Session) SearchGroupByName(groupName string) ([]models.LdapGroup, error) {
return session.searchGroup(session.ldapGroupConfig.LdapGroupBaseDN,
session.ldapGroupConfig.LdapGroupFilter,
groupName,
session.ldapGroupConfig.LdapGroupNameAttribute)
}
// SearchGroupByDN ...
func (session *Session) SearchGroupByDN(groupDN string) ([]models.LdapGroup, error) {
if _, err := goldap.ParseDN(groupDN); err != nil {
return nil, ErrDNSyntax
}
groupList, err := session.searchGroup(groupDN, session.ldapGroupConfig.LdapGroupFilter, "", session.ldapGroupConfig.LdapGroupNameAttribute)
if serverError, ok := err.(*goldap.Error); ok {
log.Debugf("resultCode:%v", serverError.ResultCode)
}
if err != nil && goldap.IsErrorWithCode(err, goldap.LDAPResultNoSuchObject) {
return nil, ErrNotFound
}
return groupList, err
}
func (session *Session) searchGroup(baseDN, filter, groupName, groupNameAttribute string) ([]models.LdapGroup, error) {
ldapGroups := make([]models.LdapGroup, 0)
log.Debugf("Groupname: %v, basedn: %v", groupName, baseDN)
ldapFilter := createGroupSearchFilter(filter, groupName, groupNameAttribute)
attributes := []string{groupNameAttribute}
result, err := session.SearchLdapAttribute(baseDN, ldapFilter, attributes)
if err != nil {
return nil, err
}
for _, ldapEntry := range result.Entries {
var group models.LdapGroup
group.GroupDN = ldapEntry.DN
for _, attr := range ldapEntry.Attributes {
// OpenLdap sometimes contain leading space in useranme
val := strings.TrimSpace(attr.Values[0])
log.Debugf("Current ldap entry attr name: %s\n", attr.Name)
switch strings.ToLower(attr.Name) {
case strings.ToLower(groupNameAttribute):
group.GroupName = val
}
}
ldapGroups = append(ldapGroups, group)
}
return ldapGroups, nil
}
func createGroupSearchFilter(oldFilter, groupName, groupNameAttribute string) string {
filter := ""
groupName = goldap.EscapeFilter(groupName)
groupNameAttribute = goldap.EscapeFilter(groupNameAttribute)
if len(oldFilter) == 0 {
if len(groupName) == 0 {
filter = groupNameAttribute + "=*"
} else {
filter = groupNameAttribute + "=*" + groupName + "*"
}
} else {
if len(groupName) == 0 {
filter = oldFilter
} else {
filter = "(&(" + oldFilter + ")(" + groupNameAttribute + "=*" + groupName + "*))"
}
}
return filter
}