-
Notifications
You must be signed in to change notification settings - Fork 26
/
LDAPAuthUtils.java
1623 lines (1421 loc) · 64.2 KB
/
LDAPAuthUtils.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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2005 Sun Microsystems Inc. All Rights Reserved
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the License). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the License at
* https://opensso.dev.java.net/public/CDDLv1.0.html or
* opensso/legal/CDDLv1.0.txt
* See the License for the specific language governing
* permission and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* Header Notice in each file and include the License file
* at opensso/legal/CDDLv1.0.txt.
* If applicable, add the following below the CDDL Header,
* with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* $Id: LDAPAuthUtils.java,v 1.21 2009/12/28 03:01:26 222713 Exp $
*
* Portions Copyrighted 2011-2016 ForgeRock AS.
* Portions Copyrighted 2014-2016 Nomura Research Institute, Ltd
* Portions Copyrighted 2023 Wren Security
*/
package org.forgerock.openam.ldap;
import static org.forgerock.openam.ldap.LDAPUtils.convertToLDAPURLs;
import static org.forgerock.openam.ldap.LDAPUtils.newFailoverConnectionPool;
import static org.forgerock.openam.utils.CollectionUtils.asList;
import static org.forgerock.opendj.ldap.LDAPConnectionFactory.*;
import com.iplanet.sso.SSOToken;
import com.sun.identity.authentication.util.ISAuthConstants;
import com.sun.identity.common.ShutdownManager;
import com.sun.identity.security.AdminTokenAction;
import com.sun.identity.shared.datastruct.CollectionHelper;
import com.sun.identity.shared.debug.Debug;
import com.sun.identity.sm.ServiceSchema;
import com.sun.identity.sm.ServiceSchemaManager;
import java.nio.charset.Charset;
import java.security.AccessController;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import org.forgerock.opendj.ldap.Attribute;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.Connection;
import org.forgerock.opendj.ldap.ConnectionFactory;
import org.forgerock.opendj.ldap.Connections;
import org.forgerock.opendj.ldap.DecodeException;
import org.forgerock.opendj.ldap.DecodeOptions;
import org.forgerock.opendj.ldap.Filter;
import org.forgerock.opendj.ldap.LdapException;
import org.forgerock.opendj.ldap.ModificationType;
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.SSLContextBuilder;
import org.forgerock.opendj.ldap.SearchResultReferenceIOException;
import org.forgerock.opendj.ldap.SearchScope;
import org.forgerock.opendj.ldap.TrustManagers;
import org.forgerock.opendj.ldap.controls.Control;
import org.forgerock.opendj.ldap.controls.PasswordExpiredResponseControl;
import org.forgerock.opendj.ldap.controls.PasswordExpiringResponseControl;
import org.forgerock.opendj.ldap.controls.PasswordPolicyErrorType;
import org.forgerock.opendj.ldap.controls.PasswordPolicyRequestControl;
import org.forgerock.opendj.ldap.controls.PasswordPolicyResponseControl;
import org.forgerock.opendj.ldap.controls.PasswordPolicyWarningType;
import org.forgerock.opendj.ldap.requests.BindRequest;
import org.forgerock.opendj.ldap.requests.ModifyRequest;
import org.forgerock.opendj.ldap.requests.SearchRequest;
import org.forgerock.opendj.ldap.responses.BindResult;
import org.forgerock.opendj.ldap.responses.Result;
import org.forgerock.opendj.ldap.responses.SearchResultEntry;
import org.forgerock.opendj.ldif.ConnectionEntryReader;
import org.forgerock.util.Options;
import org.forgerock.util.thread.listener.ShutdownListener;
import org.forgerock.util.time.Duration;
public class LDAPAuthUtils {
private boolean returnUserDN;
private String authDN = "";
private Set<String> userSearchAttrs = null;
private String searchFilter = "";
private String userNamingValue = null;
private String userNamingAttr = null;
private String baseDN;
private Set<String> primaryServers;
private Set<String> secondaryServers;
//only used for logging
private Set<String> servers;
private String userDN;
private String userPassword;
private String userId;
private char[] authPassword;
private String expiryTime;
private SearchScope searchScope;
private int heartBeatInterval = 10;
private String heartBeatTimeUnit;
private ModuleState screenState;
private int graceLogins;
private int operationsTimeout = 0;
private final Debug debug;
private boolean isSecure = false;
private boolean useStartTLS = false;
private boolean beheraEnabled = true;
private boolean trustAll = true;
private boolean isAd = false;
private String protocolVersion;
// Resource Bundle used to get l10N message
private ResourceBundle bundle;
private static Map<String, ConnectionFactory> connectionPools =
new ConcurrentHashMap<String, ConnectionFactory>();
private static Map<String, ConnectionFactory> adminConnectionPools =
new ConcurrentHashMap<String, ConnectionFactory>();
private ConnectionFactory cPool = null;
private ConnectionFactory acPool = null;
private final static int NO_EXPIRY_TIME = -1;
private final static int MIN_CONNECTION_POOL_SIZE = 1;
private final static int MAX_CONNECTION_POOL_SIZE = 10;
private final static String CONNECTION_POOL_SIZE_ATTR =
"iplanet-am-auth-ldap-connection-pool-size";
private final static String CONNECTION_POOL_DEFAULT_SIZE_ATTR =
"iplanet-am-auth-ldap-connection-pool-default-size";
private final static String SPACE = " ";
private final static String COLON = ":";
private static int minDefaultPoolSize = MIN_CONNECTION_POOL_SIZE;
private static int maxDefaultPoolSize = MAX_CONNECTION_POOL_SIZE;
// contains host:port:min:max
private static Set<String> poolSize = null;
private Set<String> userAttributes = new HashSet<String>();
private Map<String, Set<String>> userAttributeValues = new HashMap<String, Set<String>>();
private boolean isDynamicUserEnabled;
private String [] attrs = null;
private static String AD_PASSWORD_EXPIRED = "data 532";
private static String S4_PASSWORD_EXPIRED = "NT_STATUS_PASSWORD_EXPIRED";
private static String AD_ACCOUNT_DISABLED = "data 533";
private static String S4_ACCOUNT_DISABLED = "NT_STATUS_ACCOUNT_DISABLED";
private static String AD_ACCOUNT_EXPIRED = "data 701";
private static String S4_ACCOUNT_EXPIRED = "NT_STATUS_ACCOUNT_EXPIRED";
private static String AD_PASSWORD_RESET = "data 773";
private static String S4_PASSWORD_RESET = "NT_STATUS_PASSWORD_MUST_CHANGE";
private static String AD_ACCOUNT_LOCKED = "data 775";
private static String S4_ACCOUNT_LOCKED = "NT_STATUS_ACCOUNT_LOCKED_OUT";
private static String LDAP_PASSWD_ATTR = "userpassword";
private static String AD_PASSWD_ATTR = "UnicodePwd";
static {
Debug staticDebug = Debug.getInstance("amAuthLDAP");
SSOToken dUserToken;
try {
// Gets the Admin SSOToken.
// This API figures out admin DN and password and constructs
// the SSOToken.
dUserToken = AccessController.doPrivileged(AdminTokenAction.getInstance());
ServiceSchemaManager scm = new ServiceSchemaManager(
"iPlanetAMAuthService", dUserToken);
ServiceSchema schema = scm.getGlobalSchema();
Map attrs = schema.getAttributeDefaults();
poolSize = (Set<String>) attrs.get(CONNECTION_POOL_SIZE_ATTR);
String defaultPoolSize = CollectionHelper.getMapAttr(attrs,
CONNECTION_POOL_DEFAULT_SIZE_ATTR,"");
int index = defaultPoolSize.indexOf(COLON);
if (index != -1) {
try {
minDefaultPoolSize = Integer.parseInt(
defaultPoolSize.substring(0,index));
} catch (NumberFormatException ex) {
staticDebug.error("Invalid ldap connection pool min size", ex);
}
try {
maxDefaultPoolSize = Integer.parseInt(
defaultPoolSize.substring(index + 1));
} catch (NumberFormatException ex) {
staticDebug.error("Invalid ldap connection pool max size", ex);
}
if (maxDefaultPoolSize < minDefaultPoolSize) {
staticDebug.error("ldap connection pool max size is less" +
" than min size");
minDefaultPoolSize = MIN_CONNECTION_POOL_SIZE;
maxDefaultPoolSize = MAX_CONNECTION_POOL_SIZE;
}
} else {
staticDebug.error("Invalid ldap connection pool size");
}
} catch (Exception ex) {
staticDebug.error("Unable to get ldap connection pool size", ex);
}
}
/**
* Constructor initializing the basic parameters.
*
* @param host Primary server host name.
* @param port Primary server port.
* @param secondaryServers List of secondary servers.
* @param isSecure <code>true</code> if connection to server is secured.
* @param bundle ResourceBundle to be used for getting localized messages.
* @param baseDN Directory Base DN.
* @throws LDAPUtilException If the provided search base was invalid.
*/
public LDAPAuthUtils(String host, int port, Set<String> secondaryServers, boolean isSecure,
ResourceBundle bundle, String baseDN, Debug debug) throws LDAPUtilException {
this(Collections.singleton(host + ":" + port), secondaryServers, isSecure, bundle, baseDN, debug);
}
/**
* Constructor initializing the basic parameters.
*
* @param primaryServers List of primary servers.
* @param secondaryServers List of secondary servers.
* @param isSecure <code>true</code> if connection to server is secured.
* @param bundle ResourceBundle to be used for getting localized messages.
* @param baseDN Directory Base DN.
* @throws LDAPUtilException If the provided search base was invalid.
*/
public LDAPAuthUtils(Set<String> primaryServers, Set<String> secondaryServers, boolean isSecure,
ResourceBundle bundle, String baseDN, Debug debug) throws LDAPUtilException {
this.primaryServers = primaryServers;
this.secondaryServers = secondaryServers;
servers = new LinkedHashSet<String>(primaryServers);
servers.addAll(secondaryServers);
this.bundle = bundle;
this.isSecure = isSecure;
this.baseDN = baseDN;
this.debug = debug;
if (baseDN == null || baseDN.length() < 1) {
debug.message("Invalid search Base");
throw new LDAPUtilException("SchBaseInvalid", (Object[]) null);
}
}
private ConnectionFactory createConnectionPool(Map<String, ConnectionFactory> connectionPools,
String bindingUser, char[] bindingPwd) throws LdapException, LDAPUtilException {
ConnectionFactory connPool;
try {
String configName = servers.toString() + ":" + bindingUser;
connPool = connectionPools.get(configName);
if (connPool == null) {
synchronized (connectionPools) {
connPool = connectionPools.get(configName);
Options options = Options.defaultOptions()
.set(REQUEST_TIMEOUT, new Duration((long) operationsTimeout, TimeUnit.SECONDS));
if (connPool == null) {
if (debug.messageEnabled()) {
debug.message("Create ConnectionPool for servers:\n" + servers);
}
// Since connection pool for search and authentication
// are different, each gets half the configured size
int min = minDefaultPoolSize / 2 + 1;
int max = maxDefaultPoolSize / 2;
if (min >= max) {
min = max - 1;
}
Set<LDAPURL> primaryUrls = convertToLDAPURLs(primaryServers);
Set<LDAPURL> secondaryUrls = convertToLDAPURLs(secondaryServers);
if (poolSize != null && !poolSize.isEmpty()) {
String tmpmin = null;
String tmpmax = null;
for (String val : poolSize) {
// host:port:min:max
StringTokenizer stz = new StringTokenizer(val, ":");
if (stz.countTokens() == 4) {
LDAPURL url = LDAPURL.valueOf(stz.nextToken() + ":" + stz.nextToken());
if (primaryUrls.contains(url) || secondaryUrls.contains(url)) {
tmpmin = stz.nextToken();
tmpmax = stz.nextToken();
break;
}
}
}
if (tmpmin != null) {
try {
min = Integer.parseInt(tmpmin);
max = Integer.parseInt(tmpmax);
if (max < min) {
debug.error("ldap connection pool max size is less than min size");
min = minDefaultPoolSize;
max = maxDefaultPoolSize;
}
} catch (NumberFormatException ex) {
debug.error("Invalid ldap connection pool size", ex);
min = minDefaultPoolSize;
max = maxDefaultPoolSize;
}
}
}
if (debug.messageEnabled()) {
debug.message("LDAPAuthUtils.LDAPAuthUtils: min="
+ min + ", max=" + max);
}
if (isSecure) {
SSLContextBuilder builder = new SSLContextBuilder();
if (trustAll) {
builder.setTrustManager(TrustManagers.trustAll());
}
SSLContext sslContext = builder.setProtocol(protocolVersion).getSSLContext();
options.set(SSL_CONTEXT, sslContext);
if (useStartTLS) {
options.set(SSL_USE_STARTTLS, true);
}
}
final ConnectionFactory connFactory;
ConnectionFactory primaryCf = newFailoverConnectionPool(primaryUrls, bindingUser,
bindingPwd, max, heartBeatInterval, heartBeatTimeUnit, options);
if (secondaryServers.isEmpty()) {
connFactory = primaryCf;
} else {
ConnectionFactory secondaryCf = newFailoverConnectionPool(secondaryUrls, bindingUser,
bindingPwd, max, heartBeatInterval, heartBeatTimeUnit, options);
connFactory = Connections.newFailoverLoadBalancer(asList(primaryCf, secondaryCf), options);
}
ShutdownManager shutdownMan = com.sun.identity.common.ShutdownManager.getInstance();
shutdownMan.addShutdownListener(new ShutdownListener() {
public void shutdown() {
connFactory.close();
}
});
connPool = connFactory;
connectionPools.put(configName, connPool);
}
}
}
} catch (GeneralSecurityException gse) {
debug.error("Unable to create connection pool", gse);
throw new LDAPUtilException(gse);
}
return connPool;
}
/**
* Authenticates to the LDAP server using user input.
*/
public void authenticateUser(String user, String password)
throws LDAPUtilException {
if (password == null) {
// password of zero length should be allowed.
throw new LDAPUtilException("PwdInvalid",
ResultCode.INVALID_CREDENTIALS, null);
}
userId = user;
userPassword = password;
//retry just once if connection was closing
boolean shouldRetry = false;
do {
try {
searchForUser();
if (screenState == ModuleState.SERVER_DOWN || screenState == ModuleState.USER_NOT_FOUND) {
return;
}
authenticate();
shouldRetry = false;
} catch (LDAPUtilException e) {
// cases for err=53
// - disconnect in progress
// - backend unavailable (read-only, etc)
// - server locked down
// - reject unauthenticated requests
// - low disk space (updates only)
// - bind with no password (binds only)
// retrying in case "disconnect in progress"
// there should be arg to err 53 from LDAPAuthUtils
if (ResultCode.UNWILLING_TO_PERFORM.equals(e.getResultCode())) {
// if the flag is already on, then we've already retried.
// not retrying more than once
if (!shouldRetry) {
Object[] errMsg = e.getMessageArgs();
debug.error("Retying user authentication due to err("+ResultCode.UNWILLING_TO_PERFORM+") '"+errMsg[0]+"'");
// datastore was closing recycled connection. retry.
shouldRetry = true;
} else {
shouldRetry = false;
throw e;
}
} else {
// generic failure. do not retry
throw e;
}
}
} while (shouldRetry);
}
/**
* Returns connection from pool. Re-authenticate if necessary
*
* @return connection that is available to use
*/
private Connection getConnection() throws LdapException, LDAPUtilException {
if (cPool == null) {
cPool = createConnectionPool(connectionPools, null, null);
}
return cPool.getConnection();
}
/**
* Get connection from pool. Re-authenticate if necessary
* @return connection that is available to use
*/
private Connection getAdminConnection() throws LdapException, LDAPUtilException {
if (acPool == null) {
acPool = createConnectionPool(adminConnectionPools, authDN, authPassword);
}
return acPool.getConnection();
}
/**
* Updates to new password by using the parameters passed by the user.
*
* @param oldPwd Current password entered.
* @param password New password entered.
* @param confirmPassword Confirm password.
*/
public void changePassword(
String oldPwd,
String password,
String confirmPassword
) throws LDAPUtilException {
if (password.equals(oldPwd)){
setState(ModuleState.WRONG_PASSWORD_ENTERED);
return;
}
if (!(password.equals(confirmPassword))) {
setState(ModuleState.PASSWORD_MISMATCH);
return;
}
if (password.equals(userId)) {
setState(ModuleState.USER_PASSWORD_SAME);
return;
}
Connection modConn = null;
List<Control> controls;
try {
ModifyRequest mods = LDAPRequests.newModifyRequest(userDN);
if (beheraEnabled) {
mods.addControl(PasswordPolicyRequestControl.newControl(false));
}
if (!isAd) {
mods.addModification(ModificationType.DELETE, LDAP_PASSWD_ATTR, oldPwd);
mods.addModification(ModificationType.ADD, LDAP_PASSWD_ATTR, password);
modConn = getConnection();
modConn.bind(LDAPRequests.newSimpleBindRequest(userDN, oldPwd.toCharArray()));
} else {
mods.addModification(ModificationType.DELETE, AD_PASSWD_ATTR, updateADPassword(oldPwd));
mods.addModification(ModificationType.ADD, AD_PASSWD_ATTR, updateADPassword(password));
modConn = getAdminConnection();
}
Result modResult = modConn.modify(mods);
controls = processControls(modResult);
// Were there any password policy controls returned?
PasswordPolicyResult result = checkControls(controls);
if (result == null) {
if (debug.messageEnabled()) {
debug.message("No controls returned");
}
setState(ModuleState.PASSWORD_UPDATED_SUCCESSFULLY);
} else {
processPasswordPolicyControls(result);
}
} catch (LdapException ere) {
if (ere.getResult().getResultCode().equals(ResultCode.CONSTRAINT_VIOLATION)) {
PasswordPolicyResult result = checkControls(processControls(ere.getResult()));
if (result != null) {
processPasswordPolicyControls(result);
} else {
if (isAd) {
setState(ModuleState.PASSWORD_NOT_UPDATE);
} else {
setState(ModuleState.INSUFFICIENT_PASSWORD_QUALITY);
}
}
} else if (ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_CONNECT_ERROR) ||
ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_SERVER_DOWN) ||
ere.getResult().getResultCode().equals(ResultCode.UNAVAILABLE) ||
ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_TIMEOUT)) {
if (debug.messageEnabled()) {
debug.message("changepassword:Cannot connect to " + servers + ": ", ere);
}
setState(ModuleState.SERVER_DOWN);
return;
} else if (ere.getResult().getResultCode().equals(ResultCode.UNWILLING_TO_PERFORM)) {
// Were there any password policy controls returned?
PasswordPolicyResult result = checkControls(processControls(ere.getResult()));
if (result != null) {
processPasswordPolicyControls(result);
} else {
setState(ModuleState.INSUFFICIENT_PASSWORD_QUALITY);
}
} else if (ere.getResult().getResultCode().equals(ResultCode.INVALID_CREDENTIALS)) {
Result r = ere.getResult();
if (r != null) {
// Were there any password policy controls returned?
PasswordPolicyResult result = checkControls(processControls(r));
if (result != null) {
processPasswordPolicyControls(result);
}
}
setState(ModuleState.PASSWORD_NOT_UPDATE);
} else {
setState(ModuleState.PASSWORD_NOT_UPDATE);
}
if (debug.warningEnabled()) {
debug.warning("Cannot update : ", ere);
}
} finally {
if (modConn != null) {
modConn.close();
}
}
}
private String buildUserFilter() {
Filter filter;
if (userSearchAttrs.size() == 1) {
filter = Filter.equality(userSearchAttrs.iterator().next(), userId);
} else {
List<Filter> searchFilters = new ArrayList<Filter>(userSearchAttrs.size());
for (String searchAttr : userSearchAttrs) {
searchFilters.add(Filter.equality(searchAttr, userId));
}
filter = Filter.or(searchFilters);
}
return filter.toString();
}
private ByteString updateADPassword(String password) {
String quotedPassword = "\"" + password + "\"";
byte[] newUnicodePassword = quotedPassword.getBytes(Charset.forName("UTF-16LE"));
return ByteString.wrap(newUnicodePassword);
}
/**
* Searches and returns user for a specified attribute using parameters
* specified in constructor and/or by setting properties.
*/
public void searchForUser()
throws LDAPUtilException {
// make some special case where searchScope == BASE
// construct the userDN without searching directory
// assume that there is only one user attribute
if (searchScope == SearchScope.BASE_OBJECT) {
if (userSearchAttrs.size() == 1) {
StringBuilder dnBuffer = new StringBuilder();
dnBuffer.append((String) userSearchAttrs.iterator().next());
dnBuffer.append("=");
dnBuffer.append(userId);
dnBuffer.append(",");
dnBuffer.append(baseDN);
userDN = dnBuffer.toString();
if (debug.messageEnabled()) {
debug.message("searchForUser, searchScope = BASE," +
"userDN =" + userDN);
}
if (!isDynamicUserEnabled &&
userSearchAttrs.contains(userNamingAttr)) {
return;
} else if (isDynamicUserEnabled &&
(userAttributes == null || userAttributes.isEmpty())) {
debug.message("user creation attribute list is empty ");
return;
}
baseDN=userDN;
} else {
if (debug.messageEnabled()) {
debug.message("cannot find user entry using scope=0"+
"setting scope=1");
}
searchScope = SearchScope.SINGLE_LEVEL;
}
}
if (searchFilter == null || searchFilter.length() == 0) {
searchFilter = buildUserFilter();
} else {
StringBuilder bindFilter = new StringBuilder(200);
if (userId != null) {
bindFilter.append("(&");
bindFilter.append(buildUserFilter());
bindFilter.append(searchFilter);
bindFilter.append(")");
} else {
bindFilter.append(searchFilter);
}
searchFilter = bindFilter.toString();
}
userDN = null;
Connection conn = null;
try {
if (debug.messageEnabled()) {
debug.message("Connecting to " + servers + "\nSearching " + baseDN + " for " + searchFilter
+ "\nscope = " + searchScope);
}
// Search
int userAttrSize=0;
if (attrs == null) {
if ((userAttributes == null) || (userAttributes.isEmpty())){
userAttrSize = 2;
attrs = new String[userAttrSize];
attrs[0] ="dn";
attrs[1] = userNamingAttr;
} else {
userAttrSize = userAttributes.size();
attrs = new String[userAttrSize + 2];
attrs[0] = "dn";
attrs[1] = userNamingAttr;
Iterator attrItr = userAttributes.iterator();
for (int i = 2; i < userAttrSize + 2; i++) {
attrs[i] = (String)attrItr.next();
}
}
}
if (debug.messageEnabled()) {
debug.message("userAttrSize is : " + userAttrSize);
}
ConnectionEntryReader results;
SearchRequest searchForUser = LDAPRequests.newSearchRequest(baseDN, searchScope, searchFilter, attrs);
int userMatches = 0;
SearchResultEntry entry;
boolean userNamingValueSet=false;
try {
conn = getAdminConnection();
results = conn.search(searchForUser);
while (results.hasNext()) {
if (results.isEntry()) {
entry = results.readEntry();
userDN = entry.getName().toString();
userMatches++;
if (attrs != null && attrs.length > 1) {
userNamingValueSet = true;
Attribute attr = entry.getAttribute(userNamingAttr);
if (attr != null) {
userNamingValue = attr.firstValueAsString();
}
if (isDynamicUserEnabled && (attrs.length > 2)) {
for (int i = 2; i < userAttrSize + 2; i++) {
attr = entry.getAttribute(attrs[i]);
if (attr != null) {
Set<String> s = new HashSet<String>();
Iterator<ByteString> values = attr.iterator();
while (values.hasNext()) {
s.add(values.next().toString());
}
userAttributeValues.put(attrs[i], s);
}
}
}
}
} else {
//read and ignore references
results.readReference();
}
}
} finally {
if (conn != null) {
conn.close();
}
}
if (userNamingValueSet && (userDN == null ||
userNamingValue == null)) {
if (debug.messageEnabled()) {
debug.message("Cannot find entries for " + searchFilter);
}
setState(ModuleState.USER_NOT_FOUND);
return;
} else {
if (userDN == null) {
if (debug.messageEnabled()) {
debug.message(
"Cannot find entries for " + searchFilter);
}
setState(ModuleState.USER_NOT_FOUND);
return;
} else {
setState(ModuleState.USER_FOUND);
}
}
if (userMatches > 1) {
// multiple user matches found
debug.error(
"searchForUser : Multiple matches found for user '" + userId +
"'. Please modify search start DN/filter/scope " +
"to make sure unique match returned. Contact your " +
"administrator to fix the problem");
throw new LDAPUtilException("multipleUserMatchFound",
(Object[])null);
}
} catch (LdapException ere) {
if (debug.warningEnabled()) {
debug.warning("Search for User error: ", ere);
debug.warning("resultCode: " + ere.getResult().getResultCode());
}
if (ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_CONNECT_ERROR) ||
ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_SERVER_DOWN) ||
ere.getResult().getResultCode().equals(ResultCode.UNAVAILABLE) ||
ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_TIMEOUT)) {
if (debug.warningEnabled()) {
debug.warning("Cannot connect to " + servers, ere);
}
setState(ModuleState.SERVER_DOWN);
} else if (ere.getResult().getResultCode().equals(ResultCode.INVALID_CREDENTIALS)) {
if (debug.warningEnabled()) {
debug.warning("Cannot authenticate ");
}
throw new LDAPUtilException("FConnect",
ResultCode.INVALID_CREDENTIALS, null);
} else if (ere.getResult().getResultCode().equals(ResultCode.UNWILLING_TO_PERFORM)) {
if (debug.warningEnabled()) {
debug.message("Account Inactivated or Locked ");
}
throw new LDAPUtilException("FConnect",
ResultCode.UNWILLING_TO_PERFORM, null);
} else if (ere.getResult().getResultCode().equals(ResultCode.NO_SUCH_OBJECT)) {
throw new LDAPUtilException("noUserMatchFound",
ResultCode.NO_SUCH_OBJECT, null);
} else {
if (debug.warningEnabled()) {
debug.warning("Exception while searching", ere);
}
setState(ModuleState.USER_NOT_FOUND);
}
} catch (SearchResultReferenceIOException srrio) {
debug.error("Unable to complete search for user: " + userId, srrio);
throw new LDAPUtilException(srrio);
}
}
/**
* Connect to LDAP server using parameters specified in
* constructor and/or by setting properties attempt to authenticate.
* checks for the password controls and sets to the appropriate states
*/
private void authenticate()
throws LDAPUtilException {
Connection conn = null;
List<Control> controls = null;
try {
try {
BindRequest bindRequest =
LDAPRequests.newSimpleBindRequest(userDN, userPassword.toCharArray());
if (beheraEnabled) {
bindRequest.addControl(PasswordPolicyRequestControl.newControl(false));
}
conn = getConnection();
BindResult bindResult = conn.bind(bindRequest);
controls = processControls(bindResult);
} finally {
if (conn != null) {
conn.close();
}
}
// Were there any password policy controls returned?
PasswordPolicyResult result = checkControls(controls);
if (result == null) {
if (debug.messageEnabled()) {
debug.message("No controls returned");
}
setState(ModuleState.SUCCESS);
} else {
processPasswordPolicyControls(result);
}
} catch(LdapException ere) {
if (ere.getResult().getResultCode().equals(ResultCode.INVALID_CREDENTIALS)) {
if (!isAd) {
controls = processControls(ere.getResult());
PasswordPolicyResult result = checkControls(controls);
if (result != null && result.getPasswordPolicyErrorType() != null &&
result.getPasswordPolicyErrorType().equals(PasswordPolicyErrorType.PASSWORD_EXPIRED)) {
if (result.getPasswordPolicyWarningType() != null) {
//there is a warning about the grace logins, so in
//this case the credential was actually wrong
throw new LDAPUtilException("CredInvalid",
ResultCode.INVALID_CREDENTIALS, null);
} else {
if(debug.messageEnabled()) {
debug.message("Password expired and must be reset");
}
setState(ModuleState.PASSWORD_EXPIRED_STATE);
}
} else if (result != null && result.getPasswordPolicyErrorType() != null &&
result.getPasswordPolicyErrorType().equals(PasswordPolicyErrorType.ACCOUNT_LOCKED)) {
if (debug.messageEnabled()) {
debug.message("Account Locked");
}
processPasswordPolicyControls(result);
} else {
if (debug.messageEnabled()) {
debug.message("Failed auth due to invalid credentials");
}
throw new LDAPUtilException("CredInvalid",
ResultCode.INVALID_CREDENTIALS, null);
}
} else {
PasswordPolicyResult result = checkADResult(ere.getResult().getDiagnosticMessage());
if (result != null) {
processPasswordPolicyControls(result);
} else {
if (debug.messageEnabled()) {
debug.message("Failed auth due to invalid credentials");
}
throw new LDAPUtilException("CredInvalid",
ResultCode.INVALID_CREDENTIALS, null);
}
}
} else if (ere.getResult().getResultCode().equals(ResultCode.NO_SUCH_OBJECT)) {
if (debug.messageEnabled()) {
debug.message("user does not exist");
}
throw new LDAPUtilException("UsrNotExist",
ResultCode.NO_SUCH_OBJECT, null);
} else if (ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_CONNECT_ERROR) ||
ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_SERVER_DOWN) ||
ere.getResult().getResultCode().equals(ResultCode.UNAVAILABLE) ||
ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_TIMEOUT)) {
if (debug.messageEnabled()) {
debug.message("Cannot connect to " + servers, ere);
}
setState(ModuleState.SERVER_DOWN);
} else if (ere.getResult().getResultCode().equals(ResultCode.UNWILLING_TO_PERFORM)) {
if (debug.messageEnabled()) {
debug.message(servers + " unwilling to perform auth request");
}
// cases for err=53
// - disconnect in progress
// - backend unavailable (read-only, etc)
// - server locked down
// - reject unauthenticated requests
// - low disk space (updates only)
// - bind with no password (binds only)
String[] args = { ere.getMessage() };
throw new LDAPUtilException("FConnect", ResultCode.UNWILLING_TO_PERFORM, args);
} else if (ere.getResult().getResultCode().equals(ResultCode.INAPPROPRIATE_AUTHENTICATION)) {
if (debug.messageEnabled()) {
debug.message("Failed auth due to inappropriate authentication");
}
throw new LDAPUtilException("amAuth", "InappAuth",
ResultCode.INAPPROPRIATE_AUTHENTICATION, null);
} else if (ere.getResult().getResultCode().equals(ResultCode.CONSTRAINT_VIOLATION)) {
if (debug.messageEnabled()) {
debug.message("Exceed password retry limit.");
}
throw new LDAPUtilException(ISAuthConstants.EXCEED_RETRY_LIMIT,
ResultCode.CONSTRAINT_VIOLATION, null);
} else {
if (debug.messageEnabled()) {
debug.message("Cannot authenticate to " + servers, ere);
}
throw new LDAPUtilException("amAuth", "FAuth", null, null);
}
}
}
private List<Control> processControls(Result result) {
if (result == null) {
return Collections.EMPTY_LIST;
}
List<Control> controls = new ArrayList<Control>();
DecodeOptions options = new DecodeOptions();
Control c;
try {
c = result.getControl(PasswordExpiredResponseControl.DECODER, options);
if (c != null) {
controls.add(c);
}
} catch (DecodeException de) {
if (debug.warningEnabled()) {
debug.warning("unable to decode PasswordExpiredResponseControl", de);
}
}
try {
c = result.getControl(PasswordExpiringResponseControl.DECODER, options);
if (c != null) {
controls.add(c);
}
} catch (DecodeException de) {
if (debug.warningEnabled()) {
debug.warning("unable to decode PasswordExpiringResponseControl", de);
}
}
try {
c = result.getControl(PasswordPolicyResponseControl.DECODER, options);