/
LDAPLoginModule.java
733 lines (647 loc) · 28.1 KB
/
LDAPLoginModule.java
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.activemq.artemis.spi.core.security.jaas;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.PartialResultException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.Principal;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import org.apache.activemq.artemis.core.server.ActiveMQServerLogger;
import org.apache.activemq.artemis.utils.ExceptionUtil;
import org.apache.activemq.artemis.utils.PasswordMaskingUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.invoke.MethodHandles;
public class LDAPLoginModule implements AuditLoginModule {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
enum ConfigKey {
DEBUG("debug"),
INITIAL_CONTEXT_FACTORY("initialContextFactory"),
CONNECTION_URL("connectionURL"),
CONNECTION_USERNAME("connectionUsername"),
CONNECTION_PASSWORD("connectionPassword"),
CONNECTION_PROTOCOL("connectionProtocol"),
AUTHENTICATION("authentication"),
USER_BASE("userBase"),
USER_SEARCH_MATCHING("userSearchMatching"),
USER_SEARCH_SUBTREE("userSearchSubtree"),
ROLE_BASE("roleBase"),
ROLE_NAME("roleName"),
ROLE_SEARCH_MATCHING("roleSearchMatching"),
ROLE_SEARCH_SUBTREE("roleSearchSubtree"),
USER_ROLE_NAME("userRoleName"),
EXPAND_ROLES("expandRoles"),
EXPAND_ROLES_MATCHING("expandRolesMatching"),
SASL_LOGIN_CONFIG_SCOPE("saslLoginConfigScope"),
AUTHENTICATE_USER("authenticateUser"),
REFERRAL("referral"),
IGNORE_PARTIAL_RESULT_EXCEPTION("ignorePartialResultException"),
PASSWORD_CODEC("passwordCodec"),
CONNECTION_POOL("connectionPool"),
CONNECTION_TIMEOUT("connectionTimeout"),
READ_TIMEOUT("readTimeout"),
NO_CACHE_EXCEPTIONS("noCacheExceptions");
private final String name;
ConfigKey(String name) {
this.name = name;
}
String getName() {
return name;
}
static boolean contains(String key) {
for (ConfigKey k: values()) {
if (k.name.equals(key)) {
return true;
}
}
return false;
}
}
protected DirContext context;
private Subject subject;
private CallbackHandler handler;
private final Set<LDAPLoginProperty> config = new HashSet<>();
private String username;
private final Set<RolePrincipal> groups = new HashSet<>();
private boolean userAuthenticated = false;
private boolean authenticateUser = true;
private Subject brokerGssapiIdentity = null;
private boolean isRoleAttributeSet = false;
private String roleAttributeName = null;
private List<String> noCacheExceptions;
private String codecClass = null;
@Override
public void initialize(Subject subject,
CallbackHandler callbackHandler,
Map<String, ?> sharedState,
Map<String, ?> options) {
this.subject = subject;
this.handler = callbackHandler;
// copy all options to config, ignoring non-string entries
config.clear();
for (Map.Entry<String, ?> entry : options.entrySet()) {
if (entry.getValue() instanceof String) {
config.add(new LDAPLoginProperty(entry.getKey(), (String) entry.getValue()));
}
}
if (isLoginPropertySet(ConfigKey.AUTHENTICATE_USER)) {
authenticateUser = Boolean.parseBoolean(getLDAPPropertyValue(ConfigKey.AUTHENTICATE_USER));
}
isRoleAttributeSet = isLoginPropertySet(ConfigKey.ROLE_NAME);
roleAttributeName = getLDAPPropertyValue(ConfigKey.ROLE_NAME);
codecClass = getLDAPPropertyValue(ConfigKey.PASSWORD_CODEC);
if (isLoginPropertySet(ConfigKey.NO_CACHE_EXCEPTIONS)) {
noCacheExceptions = Arrays.asList(getLDAPPropertyValue(ConfigKey.NO_CACHE_EXCEPTIONS).split(","));
noCacheExceptions.replaceAll(String::trim);
} else {
noCacheExceptions = Collections.emptyList();
}
}
private String getPlainPassword(String password) {
try {
return PasswordMaskingUtil.resolveMask(password, codecClass);
} catch (Exception e) {
throw new IllegalArgumentException("Failed to decode password", e);
}
}
@Override
public boolean login() throws LoginException {
if (!authenticateUser) {
return false;
}
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback("User name");
callbacks[1] = new PasswordCallback("Password", false);
try {
handler.handle(callbacks);
} catch (IOException | UnsupportedCallbackException e) {
throw (LoginException) new LoginException().initCause(e);
}
String password = null;
username = ((NameCallback) callbacks[0]).getName();
if (username == null) {
return false;
}
if (((PasswordCallback) callbacks[1]).getPassword() != null) {
password = new String(((PasswordCallback) callbacks[1]).getPassword());
}
/*
* https://tools.ietf.org/html/rfc4513#section-6.3.1
*
* Clients that use the results from a simple Bind operation to make
* authorization decisions should actively detect unauthenticated Bind
* requests (by verifying that the supplied password is not empty) and
* react appropriately.
*/
if (password == null || password.length() == 0) {
throw new FailedLoginException("Password cannot be null or empty");
}
// authenticate will throw LoginException
// in case of failed authentication
authenticate(username, password);
userAuthenticated = true;
return true;
}
@Override
public boolean logout() throws LoginException {
clear();
return true;
}
@Override
public boolean commit() throws LoginException {
boolean result = userAuthenticated;
Set<UserPrincipal> authenticatedUsers = subject.getPrincipals(UserPrincipal.class);
Set<Principal> principals = subject.getPrincipals();
if (result) {
principals.add(new UserPrincipal(username));
}
// assign roles to any other UserPrincipal
for (UserPrincipal authenticatedUser : authenticatedUsers) {
List<String> roles = new ArrayList<>();
try {
String dn = resolveDN(authenticatedUser.getName(), roles);
resolveRolesForDN(context, dn, authenticatedUser.getName(), roles);
} catch (NamingException e) {
closeContext();
FailedLoginException ex = new FailedLoginException("Error contacting LDAP");
ex.initCause(e);
throw ex;
}
}
principals.addAll(groups);
clear();
return result;
}
private void clear() {
username = null;
userAuthenticated = false;
closeContext();
}
@Override
public boolean abort() throws LoginException {
registerFailureForAudit(username);
clear();
return true;
}
protected void closeContext() {
if (context != null) {
try {
context.close();
context = null;
} catch (Exception e) {
ActiveMQServerLogger.LOGGER.failedToCloseContext(e);
}
}
}
protected boolean authenticate(String username, String password) throws LoginException {
List<String> roles = new ArrayList<>();
try {
String dn = resolveDN(username, roles);
// check the credentials by binding to server
if (bindUser(context, dn, password)) {
// if authenticated add more roles
resolveRolesForDN(context, dn, username, roles);
} else {
throw new FailedLoginException("Password does not match for user: " + username);
}
} catch (NamingException e) {
closeContext();
FailedLoginException ex = new FailedLoginException("Error contacting LDAP");
ex.initCause(e);
throw ex;
}
return true;
}
private void resolveRolesForDN(DirContext context, String dn, String username, List<String> roles) throws NamingException {
addRoles(context, dn, username, roles);
logger.debug("Roles {} for user {}", roles, username);
for (String role : roles) {
groups.add(new RolePrincipal(role));
}
}
private String resolveDN(String username, List<String> roles) throws FailedLoginException {
String dn = null;
logger.debug("Create the LDAP initial context.");
try {
openContext();
} catch (Exception e) {
return handleException(e, "Error opening LDAP connection");
}
if (!isLoginPropertySet(ConfigKey.USER_SEARCH_MATCHING)) {
return username;
}
MessageFormat userSearchMatchingFormat = new MessageFormat(getLDAPPropertyValue(ConfigKey.USER_SEARCH_MATCHING));
boolean userSearchSubtreeBool = Boolean.parseBoolean(getLDAPPropertyValue(ConfigKey.USER_SEARCH_SUBTREE));
boolean ignorePartialResultExceptionBool = Boolean.parseBoolean(getLDAPPropertyValue(ConfigKey.IGNORE_PARTIAL_RESULT_EXCEPTION));
try {
String filter = userSearchMatchingFormat.format(new String[]{doRFC2254Encoding(username)});
SearchControls constraints = new SearchControls();
if (userSearchSubtreeBool) {
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
// setup attributes
List<String> list = new ArrayList<>();
if (isLoginPropertySet(ConfigKey.USER_ROLE_NAME)) {
list.add(getLDAPPropertyValue(ConfigKey.USER_ROLE_NAME));
}
String[] attribs = new String[list.size()];
list.toArray(attribs);
constraints.setReturningAttributes(attribs);
if (logger.isDebugEnabled()) {
logger.debug("Get the user DN.");
logger.debug("Looking for the user in LDAP with ");
logger.debug(" base DN: {}", getLDAPPropertyValue(ConfigKey.USER_BASE));
logger.debug(" filter: {}", filter);
}
NamingEnumeration<SearchResult> results = null;
try {
results = Subject.doAs(brokerGssapiIdentity, (PrivilegedExceptionAction< NamingEnumeration<SearchResult>>) () -> context.search(getLDAPPropertyValue(ConfigKey.USER_BASE), filter, constraints));
} catch (PrivilegedActionException e) {
Exception cause = e.getException();
FailedLoginException ex = new FailedLoginException("Error executing search query to resolve DN");
ex.initCause(cause);
throw ex;
}
if (results == null || !results.hasMore()) {
throw new FailedLoginException("User " + username + " not found in LDAP.");
}
SearchResult result = results.next();
try {
if (results.hasMore()) {
// ignore for now
}
} catch (PartialResultException e) {
// Workaround for AD servers not handling referrals correctly.
if (ignorePartialResultExceptionBool) {
logger.debug("PartialResultException encountered and ignored", e);
} else {
throw e;
}
}
if (result.isRelative()) {
logger.debug("LDAP returned a relative name: {}", result.getName());
NameParser parser = context.getNameParser("");
Name contextName = parser.parse(context.getNameInNamespace());
Name baseName = parser.parse(getLDAPPropertyValue(ConfigKey.USER_BASE));
Name entryName = parser.parse(result.getName());
Name name = contextName.addAll(baseName);
name = name.addAll(entryName);
dn = name.toString();
} else {
logger.debug("LDAP returned an absolute name: {}", result.getName());
try {
URI uri = new URI(result.getName());
String path = uri.getPath();
if (path.startsWith("/")) {
dn = path.substring(1);
} else {
dn = path;
}
} catch (URISyntaxException e) {
closeContext();
FailedLoginException ex = new FailedLoginException("Error parsing absolute name as URI.");
ex.initCause(e);
throw ex;
}
}
logger.debug("Using DN [{}] for binding.", dn);
Attributes attrs = result.getAttributes();
if (attrs == null) {
throw new FailedLoginException("User found, but LDAP entry malformed: " + username);
}
if (isLoginPropertySet(ConfigKey.USER_ROLE_NAME)) {
Attribute roleNames = attrs.get(getLDAPPropertyValue(ConfigKey.USER_ROLE_NAME));
if (roleNames != null) {
NamingEnumeration<?> e = roleNames.getAll();
while (e.hasMore()) {
String roleDnString = (String) e.next();
if (isRoleAttributeSet) {
// parse out the attribute from the group Dn
LdapName ldapRoleName = new LdapName(roleDnString);
for (int i = 0; i < ldapRoleName.size(); i++) {
Rdn candidate = ldapRoleName.getRdn(i);
if (roleAttributeName.equals(candidate.getType())) {
roles.add((String) candidate.getValue());
}
}
} else {
roles.add(roleDnString);
}
}
}
}
} catch (NamingException e) {
closeContext();
handleException(e, "Error contacting LDAP");
}
return dn;
}
private String handleException(Exception e, String s) throws FailedLoginException {
FailedLoginException ex = new FailedLoginException(s);
if (noCacheExceptions.contains(ExceptionUtil.getRootCause(e).getClass().getName())) {
ex.initCause(new NoCacheLoginException());
} else {
ex.initCause(e);
}
throw ex;
}
protected void addRoles(DirContext context,
String dn,
String username,
List<String> currentRoles) throws NamingException {
if (!isLoginPropertySet(ConfigKey.ROLE_SEARCH_MATCHING)) {
return;
}
MessageFormat roleSearchMatchingFormat = new MessageFormat(getLDAPPropertyValue(ConfigKey.ROLE_SEARCH_MATCHING));
boolean roleSearchSubtreeBool = Boolean.parseBoolean(getLDAPPropertyValue(ConfigKey.ROLE_SEARCH_SUBTREE));
boolean expandRolesBool = Boolean.parseBoolean(getLDAPPropertyValue(ConfigKey.EXPAND_ROLES));
boolean ignorePartialResultExceptionBool = Boolean.parseBoolean(getLDAPPropertyValue(ConfigKey.IGNORE_PARTIAL_RESULT_EXCEPTION));
final String filter = roleSearchMatchingFormat.format(new String[]{doRFC2254Encoding(dn), doRFC2254Encoding(username)});
SearchControls constraints = new SearchControls();
if (roleSearchSubtreeBool) {
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
if (logger.isDebugEnabled()) {
logger.debug("Get user roles.");
logger.debug("Looking for the user roles in LDAP with ");
logger.debug(" base DN: {}", getLDAPPropertyValue(ConfigKey.ROLE_BASE));
logger.debug(" filter: {}", filter);
}
HashSet<String> haveSeenNames = new HashSet<>();
Queue<String> pendingNameExpansion = new LinkedList<>();
NamingEnumeration<SearchResult> results = null;
try {
results = Subject.doAs(brokerGssapiIdentity, (PrivilegedExceptionAction< NamingEnumeration<SearchResult>>) () -> context.search(getLDAPPropertyValue(ConfigKey.ROLE_BASE), filter, constraints));
} catch (PrivilegedActionException e) {
Exception cause = e.getException();
NamingException ex = new NamingException("Error executing search query to resolve roles");
ex.initCause(cause);
throw ex;
}
try {
while (results.hasMore()) {
SearchResult result = results.next();
if (expandRolesBool) {
haveSeenNames.add(result.getNameInNamespace());
pendingNameExpansion.add(result.getNameInNamespace());
}
addRoleAttribute(result, currentRoles);
}
} catch (PartialResultException e) {
// Workaround for AD servers not handling referrals correctly.
if (ignorePartialResultExceptionBool) {
logger.debug("PartialResultException encountered and ignored", e);
} else {
throw e;
}
}
if (expandRolesBool) {
MessageFormat expandRolesMatchingFormat = new MessageFormat(getLDAPPropertyValue(ConfigKey.EXPAND_ROLES_MATCHING));
while (!pendingNameExpansion.isEmpty()) {
String name = pendingNameExpansion.remove();
final String expandFilter = expandRolesMatchingFormat.format(new String[]{name});
if (logger.isDebugEnabled()) {
logger.debug("Get 'expanded' user roles.");
logger.debug("Looking for the 'expanded' user roles in LDAP with ");
logger.debug(" base DN: {}", getLDAPPropertyValue(ConfigKey.ROLE_BASE));
logger.debug(" filter: {}", expandFilter);
}
try {
results = Subject.doAs(brokerGssapiIdentity, (PrivilegedExceptionAction< NamingEnumeration<SearchResult>>) () -> context.search(getLDAPPropertyValue(ConfigKey.ROLE_BASE), expandFilter, constraints));
} catch (PrivilegedActionException e) {
Exception cause = e.getException();
NamingException ex = new NamingException("Error executing search query to expand roles");
ex.initCause(cause);
throw ex;
}
try {
while (results.hasMore()) {
SearchResult result = results.next();
name = result.getNameInNamespace();
if (!haveSeenNames.contains(name)) {
addRoleAttribute(result, currentRoles);
haveSeenNames.add(name);
pendingNameExpansion.add(name);
}
}
} catch (PartialResultException e) {
// Workaround for AD servers not handling referrals correctly.
if (ignorePartialResultExceptionBool) {
logger.debug("PartialResultException encountered and ignored", e);
} else {
throw e;
}
}
}
}
}
protected String doRFC2254Encoding(String inputString) {
StringBuilder buf = new StringBuilder(inputString.length());
for (int i = 0; i < inputString.length(); i++) {
char c = inputString.charAt(i);
switch (c) {
case '\\':
buf.append("\\5c");
break;
case '*':
buf.append("\\2a");
break;
case '(':
buf.append("\\28");
break;
case ')':
buf.append("\\29");
break;
case '\0':
buf.append("\\00");
break;
default:
buf.append(c);
break;
}
}
return buf.toString();
}
protected boolean bindUser(DirContext context, String dn, String password) throws NamingException {
boolean isValid = false;
logger.debug("Binding the user.");
context.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
context.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
try {
String baseDn = getLDAPPropertyValue(ConfigKey.CONNECTION_URL).replaceFirst(".*/", ",");
String userDn = dn.replace(baseDn, "");
logger.debug("Get user Attributes with dn {}", userDn);
context.getAttributes(userDn, null);
isValid = true;
logger.debug("User {} successfully bound.", dn);
} catch (AuthenticationException e) {
isValid = false;
logger.debug("Authentication failed for dn={}", dn);
}
if (isLoginPropertySet(ConfigKey.CONNECTION_USERNAME)) {
context.addToEnvironment(Context.SECURITY_PRINCIPAL, getLDAPPropertyValue(ConfigKey.CONNECTION_USERNAME));
} else {
context.removeFromEnvironment(Context.SECURITY_PRINCIPAL);
}
if (isLoginPropertySet(ConfigKey.CONNECTION_PASSWORD)) {
context.addToEnvironment(Context.SECURITY_CREDENTIALS, getPlainPassword(getLDAPPropertyValue(ConfigKey.CONNECTION_PASSWORD)));
} else {
context.removeFromEnvironment(Context.SECURITY_CREDENTIALS);
}
context.addToEnvironment(Context.SECURITY_AUTHENTICATION, getLDAPPropertyValue(ConfigKey.AUTHENTICATION));
return isValid;
}
private void addRoleAttribute(SearchResult searchResult, List<String> roles) throws NamingException {
if (isRoleAttributeSet) {
Attribute roleAttribute = searchResult.getAttributes().get(roleAttributeName);
if (roleAttribute != null) {
roles.add((String) roleAttribute.get());
}
} else {
roles.add(searchResult.getNameInNamespace());
}
}
protected void openContext() throws Exception {
if (context == null) {
try {
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, getLDAPPropertyValue(ConfigKey.INITIAL_CONTEXT_FACTORY));
env.put(Context.SECURITY_PROTOCOL, getLDAPPropertyValue(ConfigKey.CONNECTION_PROTOCOL));
env.put(Context.PROVIDER_URL, getLDAPPropertyValue(ConfigKey.CONNECTION_URL));
env.put(Context.SECURITY_AUTHENTICATION, getLDAPPropertyValue(ConfigKey.AUTHENTICATION));
if (isLoginPropertySet(ConfigKey.CONNECTION_POOL)) {
env.put("com.sun.jndi.ldap.connect.pool", getLDAPPropertyValue(ConfigKey.CONNECTION_POOL));
}
if (isLoginPropertySet(ConfigKey.CONNECTION_TIMEOUT)) {
env.put("com.sun.jndi.ldap.connect.timeout", getLDAPPropertyValue(ConfigKey.CONNECTION_TIMEOUT));
}
if (isLoginPropertySet(ConfigKey.READ_TIMEOUT)) {
env.put("com.sun.jndi.ldap.read.timeout", getLDAPPropertyValue(ConfigKey.READ_TIMEOUT));
}
// handle LDAP referrals
// valid values are "throw", "ignore" and "follow"
String referral = "ignore";
if (getLDAPPropertyValue(ConfigKey.REFERRAL) != null) {
referral = getLDAPPropertyValue(ConfigKey.REFERRAL);
}
env.put(Context.REFERRAL, referral);
logger.debug("Referral handling: {}", referral);
if ("GSSAPI".equalsIgnoreCase(getLDAPPropertyValue(ConfigKey.AUTHENTICATION))) {
final String configScope = isLoginPropertySet(ConfigKey.SASL_LOGIN_CONFIG_SCOPE) ? getLDAPPropertyValue(ConfigKey.SASL_LOGIN_CONFIG_SCOPE) : "broker-sasl-gssapi";
try {
LoginContext loginContext = new LoginContext(configScope);
loginContext.login();
brokerGssapiIdentity = loginContext.getSubject();
} catch (LoginException e) {
e.printStackTrace();
FailedLoginException ex = new FailedLoginException("Error contacting LDAP using GSSAPI in JAAS loginConfigScope: " + configScope);
ex.initCause(e);
throw ex;
}
} else {
if (isLoginPropertySet(ConfigKey.CONNECTION_USERNAME)) {
env.put(Context.SECURITY_PRINCIPAL, getLDAPPropertyValue(ConfigKey.CONNECTION_USERNAME));
} else {
throw new NamingException("Empty username is not allowed");
}
if (isLoginPropertySet(ConfigKey.CONNECTION_PASSWORD)) {
env.put(Context.SECURITY_CREDENTIALS, getPlainPassword(getLDAPPropertyValue(ConfigKey.CONNECTION_PASSWORD)));
} else {
throw new NamingException("Empty password is not allowed");
}
}
extendInitialEnvironment(config, env);
try {
context = Subject.doAs(brokerGssapiIdentity, (PrivilegedExceptionAction<DirContext>) () -> new InitialDirContext(env));
} catch (PrivilegedActionException e) {
throw e.getException();
}
} catch (NamingException e) {
closeContext();
ActiveMQServerLogger.LOGGER.failedToOpenContext(e);
throw e;
}
}
}
protected void extendInitialEnvironment(Set<LDAPLoginProperty> moduleConfig, Hashtable<String, String> initialContextEnv) {
// sub-classes may override the method if the default implementation is not sufficient:
// add all non-module configs to initial DirContext environment to support passing
// any custom/future property to InitialDirContext construction
for (LDAPLoginProperty prop: moduleConfig) {
String propName = prop.getPropertyName();
if (initialContextEnv.get(propName) == null && !ConfigKey.contains(propName)) {
initialContextEnv.put(propName, prop.getPropertyValue());
}
}
}
private String getLDAPPropertyValue(ConfigKey key) {
for (LDAPLoginProperty conf : config)
if (conf.getPropertyName().equals(key.getName())) {
return conf.getPropertyValue();
}
return null;
}
private boolean isLoginPropertySet(ConfigKey key) {
for (LDAPLoginProperty conf : config) {
if (conf.getPropertyName().equals(key.getName()) && (conf.getPropertyValue() != null && !"".equals(conf.getPropertyValue()))) {
return true;
}
}
return false;
}
}