-
Notifications
You must be signed in to change notification settings - Fork 521
Expand file tree
/
Copy pathLdapAuthProvider.java
More file actions
644 lines (583 loc) · 26.3 KB
/
LdapAuthProvider.java
File metadata and controls
644 lines (583 loc) · 26.3 KB
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2025 DBeaver Corp and others
*
* 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 io.cloudbeaver.service.ldap.auth;
import io.cloudbeaver.DBWUserIdentity;
import io.cloudbeaver.auth.SMAuthProviderAssigner;
import io.cloudbeaver.auth.SMAuthProviderExternal;
import io.cloudbeaver.auth.SMAutoAssign;
import io.cloudbeaver.auth.SMBruteForceProtected;
import io.cloudbeaver.auth.provider.local.LocalAuthProviderConstants;
import io.cloudbeaver.model.session.WebSession;
import io.cloudbeaver.model.user.WebUser;
import io.cloudbeaver.service.ldap.auth.ssl.LdapSslSetting;
import io.cloudbeaver.service.ldap.auth.ssl.LdapSslSocketFactory;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.DBPObject;
import org.jkiss.dbeaver.model.auth.SMSession;
import org.jkiss.dbeaver.model.data.json.JSONUtils;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.security.SMAuthProviderCustomConfiguration;
import org.jkiss.dbeaver.model.security.SMController;
import org.jkiss.utils.CommonUtils;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.*;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
public class LdapAuthProvider implements SMAuthProviderExternal<SMSession>, SMBruteForceProtected, SMAuthProviderAssigner {
private static final Log log = Log.getLog(LdapAuthProvider.class);
public static final String LDAP_AUTH_PROVIDER_ID = "ldap";
private static final int DEFAULT_TIME_LIMIT = 30_000;
public LdapAuthProvider() {
}
@NotNull
@Override
public Map<String, Object> authExternalUser(
@NotNull DBRProgressMonitor monitor,
@Nullable SMAuthProviderCustomConfiguration providerConfig,
@NotNull Map<String, Object> authParameters
) throws DBException {
if (providerConfig == null) {
throw new DBException("LDAP provider config is null");
}
String userName = JSONUtils.getString(authParameters, LdapConstants.CRED_USER_DN);
if (CommonUtils.isEmpty(userName)) {
throw new DBException("LDAP user dn is empty");
}
String password = JSONUtils.getString(authParameters, LdapConstants.CRED_PASSWORD);
if (CommonUtils.isEmpty(password)) {
throw new DBException("LDAP password is empty");
}
LdapSettings ldapSettings = new LdapSettings(providerConfig);
Map<String, String> environment = creteAuthEnvironment(ldapSettings);
Map<String, Object> userData = new HashMap<>();
if (!LdapUtils.isFullDN(userName, ldapSettings.getBaseDN()) && CommonUtils.isNotEmpty(ldapSettings.getLoginAttribute())) {
userData = validateAndLoginUserAccessByUsername(userName, password, ldapSettings);
}
if (CommonUtils.isEmpty(userData)) {
String fullUserDN = buildFullUserDN(userName, ldapSettings);
validateUserAccess(fullUserDN, ldapSettings);
userData = authenticateLdap(fullUserDN, password, ldapSettings, null, environment);
}
return userData;
}
@NotNull
@Override
public SMAutoAssign detectAutoAssignments(
@NotNull DBRProgressMonitor monitor,
@NotNull SMAuthProviderCustomConfiguration providerConfig,
@NotNull Map<String, Object> authParameters
) throws DBException {
List<String> autoAssignmentTeamIds = detectAutoAssignmentTeam(new LdapSettings(providerConfig), authParameters);
SMAutoAssign smAutoAssign = new SMAutoAssign();
autoAssignmentTeamIds.forEach(smAutoAssign::addExternalTeamId);
return smAutoAssign;
}
@Override
public void postAuthentication() {
LdapSslSocketFactory.removeContextFactory();
}
@Nullable
@Override
public String getExternalTeamIdMetadataFieldName() {
return LdapConstants.LDAP_META_GROUP_NAME;
}
/**
* Find user and validate in ldap by uniq parameter from identityProviders
*
*/
private Map<String, Object> validateAndLoginUserAccessByUsername(
@NotNull String login,
@NotNull String password,
@NotNull LdapSettings ldapSettings
) throws DBException {
if (
CommonUtils.isEmpty(ldapSettings.getBindUserDN())
|| CommonUtils.isEmpty(ldapSettings.getBindUserPassword())
) {
return null;
}
Map<String, String> serviceUserContext = creteAuthEnvironment(ldapSettings);
serviceUserContext.put(Context.SECURITY_PRINCIPAL, ldapSettings.getBindUserDN());
serviceUserContext.put(Context.SECURITY_CREDENTIALS, ldapSettings.getBindUserPassword());
DirContext serviceContext;
try {
serviceContext = initConnection(serviceUserContext);
String userDN = findUserDN(serviceContext, ldapSettings, login);
if (userDN == null) {
return null;
}
return authenticateLdap(userDN, password, ldapSettings, login, creteAuthEnvironment(ldapSettings));
} catch (Exception e) {
throw new DBException("LDAP authentication failed: " + e.getMessage(), e);
}
}
/**
* Find user and validate in ldap by fullUserDN
*/
private void validateUserAccess(
@NotNull String fullUserDN,
@NotNull LdapSettings ldapSettings
) throws DBException {
if (
CommonUtils.isEmpty(ldapSettings.getFilter())
|| CommonUtils.isEmpty(ldapSettings.getBindUserDN())
|| CommonUtils.isEmpty(ldapSettings.getBindUserPassword())
) {
return;
}
var environment = creteAuthEnvironment(ldapSettings);
environment.put(Context.SECURITY_PRINCIPAL, ldapSettings.getBindUserDN());
environment.put(Context.SECURITY_CREDENTIALS, ldapSettings.getBindUserPassword());
DirContext bindUserContext;
try {
bindUserContext = initConnection(environment);
SearchControls searchControls = createSearchControls();
var searchResult = bindUserContext.search(fullUserDN, ldapSettings.getFilter(), searchControls);
if (!searchResult.hasMore()) {
throw new DBException("Access denied");
}
} catch (DBException e) {
throw e;
} catch (Exception e) {
throw new DBException("LDAP user access validation by filter failed: " + e.getMessage(), e);
}
}
protected String getAttributeValue(Attributes attributes, String attributeName) throws NamingException {
Attribute attribute = attributes.get(attributeName);
return attribute != null ? attribute.get().toString() : null;
}
@NotNull
protected String getAttributeValueSafe(@NotNull Attributes attributes, @NotNull String attrName) {
try {
Attribute attr = attributes.get(attrName.toLowerCase());
return attr != null ? (String) attr.get() : "";
} catch (Exception e) {
log.debug("Can't extract '" + attrName + "' from ldap attributes");
return "";
}
}
@NotNull
public Map<String, String> creteAuthEnvironment(LdapSettings ldapSettings) throws DBException {
Map<String, String> environment = new HashMap<>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, ldapSettings.getLdapProviderUrl());
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
try {
configureSsl(ldapSettings, environment);
} catch (Exception e) {
log.error("Can't establish ssl connection", e);
throw new DBException("Can't establish ssl connection", e);
}
return environment;
}
private void configureSsl(LdapSettings ldapSettings, Map<String, String> environment) throws Exception {
LdapSslSetting ldapSslSetting = ldapSettings.getLdapSslSetting();
if (!ldapSslSetting.isEnable() || CommonUtils.isEmpty(ldapSslSetting.getSslCert())) {
return;
}
CertificateFactory cf = CertificateFactory.getInstance("X.509");
byte[] decoded = Base64.getDecoder().decode(ldapSslSetting.getSslCert());
ByteArrayInputStream certStream = new ByteArrayInputStream(decoded);
Certificate cert = cf.generateCertificate(certStream);
KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
ts.load(null, null);
ts.setCertificateEntry("trusted-root", cert);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ts);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());
LdapSslSocketFactory.setContextFactory(sslContext);
environment.put("java.naming.ldap.factory.socket", LdapSslSocketFactory.class.getName());
}
protected String findUserDN(DirContext serviceContext, LdapSettings ldapSettings, String userIdentifier) throws DBException {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setReturningAttributes(new String[]{"distinguishedName"});
NamingEnumeration<SearchResult> results = findByFilter(
serviceContext,
ldapSettings,
buildSearchFilter(ldapSettings, userIdentifier),
searchControls
);
try {
if (results.hasMore()) {
return results.next().getNameInNamespace();
}
} catch (NamingException e) {
throw new DBException("Error finding user DN: " + e.getMessage(), e);
}
return null;
}
public NamingEnumeration<SearchResult> findByFilter(
@NotNull DirContext serviceContext,
@NotNull LdapSettings ldapSettings,
@NotNull String searchFilter,
@NotNull SearchControls searchControls
) throws DBException {
try {
String baseDN = getBaseDN(serviceContext, ldapSettings);
return serviceContext.search(baseDN, searchFilter, searchControls);
} catch (Exception e) {
throw new DBException("Error finding user DN: " + e.getMessage(), e);
}
}
private String getBaseDN(DirContext serviceContext, LdapSettings ldapSettings) throws DBException {
if (CommonUtils.isEmpty(ldapSettings.getBaseDN())) {
return getRootDN(serviceContext);
}
return ldapSettings.getBaseDN();
}
private String buildSearchFilter(LdapSettings ldapSettings, String userIdentifier) {
String userFilter = String.format("(%s=%s)", ldapSettings.getLoginAttribute(), userIdentifier);
if (CommonUtils.isNotEmpty(ldapSettings.getFilter())) {
return String.format("(&%s%s)", userFilter, ldapSettings.getFilter());
}
return userFilter;
}
private String getRootDN(DirContext adminContext) throws DBException {
try {
Attributes attributes = adminContext.getAttributes("", new String[]{"namingContexts"});
Attribute namingContexts = attributes.get("namingContexts");
if (namingContexts != null && namingContexts.size() > 0) {
return (String) namingContexts.get(0);
}
throw new DBException("Root DN not found in namingContexts");
} catch (Exception e) {
throw new DBException("Error retrieving root DN: " + e.getMessage(), e);
}
}
@NotNull
private String findUserNameFromDN(@NotNull String fullUserDN, @NotNull LdapSettings ldapSettings)
throws DBException {
try {
LdapName ldapDN = new LdapName(fullUserDN);
for (Rdn rdn : ldapDN.getRdns()) {
if (rdn.getType().equalsIgnoreCase(ldapSettings.getUserIdentifierAttr())) {
Object v = rdn.getValue();
if (v instanceof byte[]) {
return new String((byte[]) v, StandardCharsets.UTF_8);
}
return String.valueOf(v);
}
}
throw new DBException("Failed to determine userId from user DN: " + fullUserDN);
} catch (Exception e) {
throw new DBException("Invalid user DN: " + fullUserDN, e);
}
}
@NotNull
@Override
public DBWUserIdentity getUserIdentity(
@NotNull DBRProgressMonitor monitor,
@Nullable SMAuthProviderCustomConfiguration customConfiguration,
@NotNull Map<String, Object> authParameters
) throws DBException {
String userName = JSONUtils.getString(authParameters, LocalAuthProviderConstants.CRED_USER);
if (CommonUtils.isEmpty(userName)) {
throw new DBException("LDAP user name is empty");
}
String displayName = JSONUtils.getString(authParameters, LocalAuthProviderConstants.CRED_DISPLAY_NAME);
if (CommonUtils.isEmpty(displayName)) {
displayName = userName;
}
return new DBWUserIdentity(userName, displayName);
}
@Nullable
@Override
public DBPObject getUserDetails(
@NotNull DBRProgressMonitor monitor,
@NotNull WebSession webSession,
@NotNull SMSession session,
@NotNull WebUser user,
boolean selfIdentity
) throws DBException {
return null;
}
@NotNull
@Override
public String validateLocalAuth(
@NotNull DBRProgressMonitor monitor,
@NotNull SMController securityController,
@NotNull SMAuthProviderCustomConfiguration providerConfig,
@NotNull Map<String, Object> userCredentials,
@Nullable String activeUserId
) throws DBException {
String userId = JSONUtils.getString(userCredentials, LdapConstants.CRED_USERNAME);
String oldUsername = JSONUtils.getString(userCredentials, LdapConstants.CRED_USER_DN);
if (CommonUtils.isNotEmpty(oldUsername)) {
oldUsername = findUserNameFromDN(oldUsername, new LdapSettings(providerConfig));
Map<String, Object> oldUserLDAP = securityController.getUserCredentials(oldUsername, LDAP_AUTH_PROVIDER_ID);
userCredentials.putAll(oldUserLDAP);
if (userCredentials.get("user").equals(oldUsername)) {
userId = oldUsername;
}
}
if (CommonUtils.isEmpty(userId)) {
throw new DBException("LDAP user id not found");
}
return activeUserId == null ? userId : activeUserId;
}
@Override
public SMSession openSession(
@NotNull DBRProgressMonitor monitor,
@NotNull SMSession mainSession,
@Nullable SMAuthProviderCustomConfiguration customConfiguration,
@NotNull Map<String, Object> userCredentials
) throws DBException {
return new LdapSession(mainSession, mainSession.getSessionSpace(), userCredentials);
}
@Override
public void closeSession(@NotNull SMSession mainSession, SMSession session) throws DBException {
}
@Override
public void refreshSession(
@NotNull DBRProgressMonitor monitor,
@NotNull SMSession mainSession,
SMSession session
) throws DBException {
}
@Override
public Object getInputUsername(@NotNull Map<String, Object> cred) {
return cred.get(LdapConstants.CRED_USER_DN);
}
private String buildFullUserDN(String userName, LdapSettings ldapSettings) {
String fullUserDN = userName;
if (!CommonUtils.startsWithIgnoreCase(fullUserDN, ldapSettings.getUserIdentifierAttr())) {
fullUserDN = String.join("=", ldapSettings.getUserIdentifierAttr(), userName);
}
if (CommonUtils.isNotEmpty(ldapSettings.getBaseDN()) && !CommonUtils.endsWithIgnoreCase(fullUserDN, ldapSettings.getBaseDN())) {
fullUserDN = String.join(",", fullUserDN, ldapSettings.getBaseDN());
}
return fullUserDN;
}
private SearchControls createSearchControls() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setTimeLimit(DEFAULT_TIME_LIMIT);
searchControls.setReturningAttributes(new String[]{"*", "+"});
return searchControls;
}
private Map<String, Object> authenticateLdap(
@NotNull String userDN,
@NotNull String password,
@NotNull LdapSettings ldapSettings,
@Nullable String login,
@NotNull Map<String, String> environment
) throws DBException {
Map<String, Object> userData = new HashMap<>();
environment.put(Context.SECURITY_PRINCIPAL, userDN);
environment.put(Context.SECURITY_CREDENTIALS, password);
DirContext userContext = null;
try {
userContext = initConnection(environment);
SearchControls searchControls = createSearchControls();
String userId = "";
var searchResult = userContext.search(userDN, "objectClass=*", searchControls);
if (searchResult.hasMore()) {
SearchResult result = searchResult.next();
Attributes attributes = result.getAttributes();
userId = getAttributeValue(attributes, "objectGUID");
if (userId == null) {
userId = getAttributeValue(attributes, "entryUUID");
}
userData.put(
LdapConstants.LDAP_META_GROUP_NAME,
getAttributeValueSafe(
attributes,
ldapSettings.getProviderConfiguration().getParameter(LdapConstants.LDAP_META_GROUP_NAME)
)
);
doCustomModifyUserDataAfterAuthentication(ldapSettings, attributes, userData);
}
userData.putIfAbsent(LdapConstants.CRED_USERNAME, CommonUtils.isNotEmpty(login) ? login : userId);
userData.put(LdapConstants.CRED_USER_DN, userDN);
userData.put(LdapConstants.CRED_PASSWORD, password);
userData.put(LdapConstants.CRED_DISPLAY_NAME, CommonUtils.isNotEmpty(login) ? login : findUserNameFromDN(userDN, ldapSettings));
userData.put(LdapConstants.CRED_SESSION_ID, UUID.randomUUID());
return userData;
} catch (Exception e) {
throw new DBException("LDAP authentication failed: " + e.getMessage(), e);
} finally {
if (userContext != null) {
try {
userContext.close();
} catch (NamingException e) {
log.warn("Error closing LDAP user context", e);
}
}
}
}
protected void doCustomModifyUserDataAfterAuthentication(LdapSettings ldapSettings, Attributes attributes, Map<String, Object> userData) {
}
@NotNull
protected List<String> detectAutoAssignmentTeam(
@NotNull LdapSettings ldapSettings,
@NotNull Map<String, Object> authParameters
) throws DBException {
String userName = JSONUtils.getString(authParameters, LdapConstants.CRED_USERNAME);
if (CommonUtils.isEmpty(userName)) {
throw new DBException("LDAP user name is empty");
}
String fullDN = JSONUtils.getString(authParameters, LdapConstants.CRED_USER_DN);
String userDN;
if (!CommonUtils.isEmpty(fullDN)) {
userDN = fullDN;
} else {
userDN = getUserDN(ldapSettings, JSONUtils.getString(authParameters, LdapConstants.CRED_DISPLAY_NAME));
}
if (userDN == null) {
return Collections.emptyList();
}
List<String> result = new ArrayList<>();
result.add(userDN);
result.addAll(getGroupForMember(userDN, ldapSettings, authParameters));
return result;
}
private String getUserDN(LdapSettings ldapSettings, String displayName) {
DirContext context;
try {
context = initConnection(creteAuthEnvironment(ldapSettings));
return findUserDN(context, ldapSettings, displayName);
} catch (Exception e) {
log.error("User not found", e);
return null;
}
}
@NotNull
protected List<String> getGroupForMember(String fullDN, LdapSettings ldapSettings, Map<String, Object> authParameters) {
DirContext context = null;
Set<String> result = new LinkedHashSet<>();
try {
Map<String, String> environment = creteAuthEnvironment(ldapSettings);
if (CommonUtils.isEmpty(ldapSettings.getBindUserDN())) {
environment.put(Context.SECURITY_PRINCIPAL, String.valueOf(authParameters.get(LdapConstants.CRED_USER_DN)));
environment.put(Context.SECURITY_CREDENTIALS, String.valueOf(authParameters.get(LdapConstants.CRED_PASSWORD)));
} else {
environment.put(Context.SECURITY_PRINCIPAL, ldapSettings.getBindUserDN());
environment.put(Context.SECURITY_CREDENTIALS, ldapSettings.getBindUserPassword());
}
//it's a hack. Otherwise password will be written to database
authParameters.remove(LdapConstants.CRED_PASSWORD);
String referralHandlingMode = ldapSettings.getReferralHandlingMode();
environment.put(Context.REFERRAL, referralHandlingMode);
if ("follow".equalsIgnoreCase(referralHandlingMode)) {
environment.put("java.naming.ldap.referral.limit", "5");
}
context = initConnection(environment);
List<String> groupsByMemberOfAttribute = findGroupsByMemberOfAttribute(fullDN, context);
log.debug("Found " + groupsByMemberOfAttribute.size() + " groups by memberOf attribute");
result.addAll(groupsByMemberOfAttribute);
List<String> groupsByMemberAttribute = findGroupsByMemberAttribute(fullDN, ldapSettings, context);
log.debug("Found " + groupsByMemberAttribute.size() + " groups by member attribute");
result.addAll(groupsByMemberAttribute);
} catch (Exception e) {
log.error("Group not found", e);
} finally {
try {
if (context != null) {
context.close();
}
} catch (Exception e) {
log.error("Close resource of ldap group search failed", e);
}
}
return new ArrayList<>(result);
}
protected List<String> findGroupsByMemberOfAttribute(String fullDN, DirContext context) throws NamingException {
List<String> result = new ArrayList<>();
SearchControls memberOfSearch = new SearchControls();
memberOfSearch.setSearchScope(SearchControls.OBJECT_SCOPE);
memberOfSearch.setTimeLimit(DEFAULT_TIME_LIMIT);
memberOfSearch.setReturningAttributes(new String[] {"*", "+"});
NamingEnumeration<SearchResult> userRecord = context.search(fullDN, "(objectClass=*)", memberOfSearch);
try {
if (userRecord.hasMore()) {
SearchResult userResult = userRecord.next();
Attributes userAttributes = userResult.getAttributes();
Attribute memberOfAttr = userAttributes.get("memberOf");
if (memberOfAttr != null) {
NamingEnumeration<?> groups = memberOfAttr.getAll();
while (groups.hasMore()) {
String groupDN = String.valueOf(groups.next());
result.add(groupDN);
}
}
}
} finally {
if (userRecord != null) {
userRecord.close();
}
}
return result;
}
protected List<String> findGroupsByMemberAttribute(String fullDN, LdapSettings ldapSettings, DirContext context) throws NamingException {
List<String> result = new ArrayList<>();
String searchFilter = "(member={0})";
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> searchResults = context.search(
ldapSettings.getBaseDN(),
searchFilter,
new Object[] {fullDN},
searchControls
);
try {
while (searchResults.hasMore()) {
try {
SearchResult next = searchResults.next();
//add full dn
result.add(next.getNameInNamespace());
//add relative dn to base dn
result.add(next.getName());
} catch (Exception e) {
log.error("Failed fetch user group. Skipping...", e);
}
}
} finally {
if (searchResults != null) {
searchResults.close();
}
}
return result;
}
public DirContext initConnection(Map<String, String> environment) throws DBException {
//this hack is needed for correct LDAPS working. JNDI uses ContextClassLoader instead of OSGI loader
ClassLoader previous = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
try {
return new InitialDirContext(new Hashtable<>(environment));
} catch (Exception e) {
throw new DBException("Can't establish LDAP connection", e);
} finally {
Thread.currentThread().setContextClassLoader(previous);
}
}
}