1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package edu.internet2.middleware.shibboleth.common.attribute.resolver.provider.dataConnector;
18
19 import java.io.IOException;
20 import java.security.GeneralSecurityException;
21 import java.security.KeyStore;
22 import java.security.cert.X509Certificate;
23 import java.util.HashMap;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.StringTokenizer;
28
29 import javax.naming.NamingException;
30 import javax.naming.directory.SearchResult;
31 import javax.net.ssl.HostnameVerifier;
32 import javax.net.ssl.KeyManager;
33 import javax.net.ssl.KeyManagerFactory;
34 import javax.net.ssl.SSLContext;
35 import javax.net.ssl.SSLSocketFactory;
36 import javax.net.ssl.TrustManager;
37 import javax.net.ssl.TrustManagerFactory;
38
39 import org.opensaml.xml.security.x509.X509Credential;
40 import org.opensaml.xml.util.DatatypeHelper;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.springframework.context.ApplicationEvent;
44 import org.springframework.context.ApplicationListener;
45
46 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
47 import edu.internet2.middleware.shibboleth.common.attribute.provider.BasicAttribute;
48 import edu.internet2.middleware.shibboleth.common.attribute.resolver.AttributeResolutionException;
49 import edu.internet2.middleware.shibboleth.common.attribute.resolver.provider.ShibbolethResolutionContext;
50 import edu.internet2.middleware.shibboleth.common.attribute.resolver.provider.dataConnector.TemplateEngine.CharacterEscapingStrategy;
51 import edu.internet2.middleware.shibboleth.common.session.LogoutEvent;
52 import edu.vt.middleware.ldap.Ldap;
53 import edu.vt.middleware.ldap.LdapConfig;
54 import edu.vt.middleware.ldap.LdapPool;
55 import edu.vt.middleware.ldap.LdapUtil;
56
57
58
59
60 public class LdapDataConnector extends BaseDataConnector implements ApplicationListener {
61
62
63 public static enum SEARCH_SCOPE {
64
65 OBJECT,
66
67 ONELEVEL,
68
69 SUBTREE
70 };
71
72
73 public static enum AUTHENTICATION_TYPE {
74
75 ANONYMOUS,
76
77 SIMPLE,
78
79 STRONG,
80
81 EXTERNAL,
82
83 DIGEST_MD5,
84
85 CRAM_MD5,
86
87 GSSAPI
88 };
89
90
91 private static Logger log = LoggerFactory.getLogger(LdapDataConnector.class);
92
93
94 private TrustManager[] sslTrustManagers;
95
96
97 private KeyManager[] sslKeyManagers;
98
99
100 private boolean mergeMultipleResults;
101
102
103 private boolean noResultsIsError;
104
105
106 private boolean cacheResults;
107
108
109 private TemplateEngine filterCreator;
110
111
112 private String filterTemplateName;
113
114
115 private String filterTemplate;
116
117
118 private String[] returnAttributes;
119
120
121 private LdapConfig ldapConfig;
122
123
124 private LdapPool ldapPool;
125
126
127 private int poolMaxIdle;
128
129
130 private int poolInitIdleCapacity;
131
132
133 private Map<String, Map<String, Map<String, BaseAttribute>>> cache;
134
135
136 private boolean initialized;
137
138
139 private final LDAPValueEscapingStrategy escapingStrategy;
140
141
142
143
144
145
146
147
148
149
150 public LdapDataConnector(String ldapUrl, String ldapBaseDn, boolean startTls, int maxIdle, int initIdleCapacity) {
151 super();
152 ldapConfig = new LdapConfig(ldapUrl, ldapBaseDn);
153 ldapConfig.useTls(startTls);
154 poolMaxIdle = maxIdle;
155 poolInitIdleCapacity = initIdleCapacity;
156 escapingStrategy = new LDAPValueEscapingStrategy();
157 }
158
159
160
161
162 public void initialize() {
163 initialized = true;
164 registerTemplate();
165 initializeLdapPool();
166 initializeCache();
167 }
168
169
170
171
172
173 protected void initializeLdapPool() {
174 if (initialized) {
175 ldapPool = new LdapPool(ldapConfig, poolMaxIdle, poolInitIdleCapacity);
176 }
177 }
178
179
180
181
182
183 protected void initializeCache() {
184 if (cacheResults && initialized) {
185 cache = new HashMap<String, Map<String, Map<String, BaseAttribute>>>();
186 }
187 }
188
189
190
191
192 protected void clearCache() {
193 if (cacheResults && initialized) {
194 cache.clear();
195 }
196 }
197
198
199
200
201
202 protected void registerTemplate() {
203 if (initialized) {
204 filterTemplateName = "shibboleth.resolver.dc." + getId();
205 filterCreator.registerTemplate(filterTemplateName, filterTemplate);
206 }
207 }
208
209
210
211
212
213
214 public boolean isMergeResults() {
215 return mergeMultipleResults;
216 }
217
218
219
220
221
222
223
224
225
226 public void setMergeResults(boolean b) {
227 mergeMultipleResults = b;
228 clearCache();
229 }
230
231
232
233
234
235
236 public boolean isCacheResults() {
237 return cacheResults;
238 }
239
240
241
242
243
244
245
246
247 public void setCacheResults(boolean b) {
248 cacheResults = b;
249 if (!cacheResults) {
250 cache = null;
251 } else {
252 initializeCache();
253 }
254 }
255
256
257
258
259
260
261 public boolean isNoResultsIsError() {
262 return noResultsIsError;
263 }
264
265
266
267
268
269
270 public void setNoResultsIsError(boolean b) {
271 noResultsIsError = b;
272 }
273
274
275
276
277
278
279 public TemplateEngine getTemplateEngine() {
280 return filterCreator;
281 }
282
283
284
285
286
287
288 public void setTemplateEngine(TemplateEngine engine) {
289 filterCreator = engine;
290 registerTemplate();
291 clearCache();
292 }
293
294
295
296
297
298
299 public String getFilterTemplate() {
300 return filterTemplate;
301 }
302
303
304
305
306
307
308 public void setFilterTemplate(String template) {
309 filterTemplate = template;
310 clearCache();
311 }
312
313
314
315
316
317
318 public String getLdapUrl() {
319 return ldapConfig.getHost();
320 }
321
322
323
324
325
326
327 public String getBaseDn() {
328 return ldapConfig.getBase();
329 }
330
331
332
333
334
335
336 public boolean isUseStartTls() {
337 return ldapConfig.isTlsEnabled();
338 }
339
340
341
342
343
344
345 public SSLSocketFactory getSslSocketFactory() {
346 return ldapConfig.getSslSocketFactory();
347 }
348
349
350
351
352
353
354
355
356
357
358 public void setSslSocketFactory(SSLSocketFactory sf) {
359 ldapConfig.setSslSocketFactory(sf);
360 clearCache();
361 initializeLdapPool();
362 }
363
364
365
366
367
368
369 public TrustManager[] getSslTrustManagers() {
370 return sslTrustManagers;
371 }
372
373
374
375
376
377
378
379
380
381
382
383 public void setSslTrustManagers(X509Credential tc) {
384 if (tc != null) {
385 try {
386 TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
387 KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
388 keystore.load(null, null);
389 for (X509Certificate c : tc.getEntityCertificateChain()) {
390 keystore.setCertificateEntry("ldap_tls_trust_" + c.getSerialNumber(), c);
391 }
392 tmf.init(keystore);
393 sslTrustManagers = tmf.getTrustManagers();
394 SSLContext ctx = SSLContext.getInstance("TLS");
395 ctx.init(sslKeyManagers, sslTrustManagers, null);
396 ldapConfig.setSslSocketFactory(ctx.getSocketFactory());
397 clearCache();
398 initializeLdapPool();
399 } catch (GeneralSecurityException e) {
400 log.error("Error initializing trust managers", e);
401 } catch (IOException e) {
402 log.error("Error initializing trust managers", e);
403 }
404 }
405 }
406
407
408
409
410
411
412 public KeyManager[] getSslKeyManagers() {
413 return sslKeyManagers;
414 }
415
416
417
418
419
420
421
422
423
424
425
426 public void setSslKeyManagers(X509Credential kc) {
427 if (kc != null) {
428 try {
429 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
430 KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
431 keystore.load(null, null);
432 keystore.setKeyEntry("ldap_tls_client_auth", kc.getPrivateKey(), "changeit".toCharArray(), kc
433 .getEntityCertificateChain().toArray(new X509Certificate[0]));
434 kmf.init(keystore, "changeit".toCharArray());
435 sslKeyManagers = kmf.getKeyManagers();
436 SSLContext ctx = SSLContext.getInstance("TLS");
437 ctx.init(sslKeyManagers, sslTrustManagers, null);
438 ldapConfig.setSslSocketFactory(ctx.getSocketFactory());
439 clearCache();
440 initializeLdapPool();
441 } catch (GeneralSecurityException e) {
442 log.error("Error initializing key managers", e);
443 } catch (IOException e) {
444 log.error("Error initializing key managers", e);
445 }
446 }
447 }
448
449
450
451
452
453
454 public HostnameVerifier getHostnameVerifier() {
455 return ldapConfig.getHostnameVerifier();
456 }
457
458
459
460
461
462
463
464
465
466
467 public void setHostnameVerifier(HostnameVerifier hv) {
468 ldapConfig.setHostnameVerifier(hv);
469 clearCache();
470 initializeLdapPool();
471 }
472
473
474
475
476
477
478 public AUTHENTICATION_TYPE getAuthenticationType() {
479 AUTHENTICATION_TYPE type = null;
480 if (ldapConfig.isAnonymousAuth()) {
481 type = AUTHENTICATION_TYPE.ANONYMOUS;
482 } else if (ldapConfig.isSimpleAuth()) {
483 type = AUTHENTICATION_TYPE.SIMPLE;
484 } else if (ldapConfig.isStrongAuth()) {
485 type = AUTHENTICATION_TYPE.STRONG;
486 } else if (ldapConfig.isExternalAuth()) {
487 type = AUTHENTICATION_TYPE.EXTERNAL;
488 } else if (ldapConfig.isDigestMD5Auth()) {
489 type = AUTHENTICATION_TYPE.DIGEST_MD5;
490 } else if (ldapConfig.isCramMD5Auth()) {
491 type = AUTHENTICATION_TYPE.CRAM_MD5;
492 } else if (ldapConfig.isGSSAPIAuth()) {
493 type = AUTHENTICATION_TYPE.GSSAPI;
494 }
495 return type;
496 }
497
498
499
500
501
502
503
504
505
506
507 public void setAuthenticationType(AUTHENTICATION_TYPE type) {
508 if (type == AUTHENTICATION_TYPE.ANONYMOUS) {
509 ldapConfig.useAnonymousAuth();
510 } else if (type == AUTHENTICATION_TYPE.SIMPLE) {
511 ldapConfig.useSimpleAuth();
512 } else if (type == AUTHENTICATION_TYPE.STRONG) {
513 ldapConfig.useStrongAuth();
514 } else if (type == AUTHENTICATION_TYPE.EXTERNAL) {
515 ldapConfig.useExternalAuth();
516 } else if (type == AUTHENTICATION_TYPE.DIGEST_MD5) {
517 ldapConfig.useDigestMD5Auth();
518 } else if (type == AUTHENTICATION_TYPE.CRAM_MD5) {
519 ldapConfig.useCramMD5Auth();
520 } else if (type == AUTHENTICATION_TYPE.GSSAPI) {
521 ldapConfig.useGSSAPIAuth();
522 }
523 clearCache();
524 initializeLdapPool();
525 }
526
527
528
529
530
531
532 public SEARCH_SCOPE getSearchScope() {
533 SEARCH_SCOPE scope = null;
534 if (ldapConfig.isObjectSearchScope()) {
535 scope = SEARCH_SCOPE.OBJECT;
536 } else if (ldapConfig.isOneLevelSearchScope()) {
537 scope = SEARCH_SCOPE.ONELEVEL;
538 } else if (ldapConfig.isSubTreeSearchScope()) {
539 scope = SEARCH_SCOPE.SUBTREE;
540 }
541 return scope;
542 }
543
544
545
546
547
548
549
550
551 public void setSearchScope(SEARCH_SCOPE scope) {
552 if (scope == SEARCH_SCOPE.OBJECT) {
553 ldapConfig.useObjectSearchScope();
554 } else if (scope == SEARCH_SCOPE.SUBTREE) {
555 ldapConfig.useSubTreeSearchScope();
556 } else if (scope == SEARCH_SCOPE.ONELEVEL) {
557 ldapConfig.useOneLevelSearchScope();
558 }
559 clearCache();
560 }
561
562
563
564
565
566
567 public String[] getReturnAttributes() {
568 return returnAttributes;
569 }
570
571
572
573
574
575
576
577
578
579 public void setReturnAttributes(String[] s) {
580 returnAttributes = s;
581 clearCache();
582 }
583
584
585
586
587
588
589 public void setReturnAttributes(String s) {
590 StringTokenizer st = new StringTokenizer(s, ",");
591 String[] ra = new String[st.countTokens()];
592 for (int count = 0; count < st.countTokens(); count++) {
593 ra[count] = st.nextToken();
594 }
595 setReturnAttributes(ra);
596 }
597
598
599
600
601
602
603
604 public int getSearchTimeLimit() {
605 return ldapConfig.getTimeLimit();
606 }
607
608
609
610
611
612
613
614
615
616 public void setSearchTimeLimit(int i) {
617 ldapConfig.setTimeLimit(i);
618 clearCache();
619 }
620
621
622
623
624
625
626
627 public long getMaxResultSize() {
628 return ldapConfig.getCountLimit();
629 }
630
631
632
633
634
635
636
637
638
639 public void setMaxResultSize(long l) {
640 ldapConfig.setCountLimit(l);
641 clearCache();
642 }
643
644
645
646
647
648
649 public boolean isReturningObjects() {
650 return ldapConfig.getReturningObjFlag();
651 }
652
653
654
655
656
657
658
659
660 public void setReturningObjects(boolean b) {
661 ldapConfig.setReturningObjFlag(b);
662 clearCache();
663 }
664
665
666
667
668
669
670 public boolean isLinkDereferencing() {
671 return ldapConfig.getDerefLinkFlag();
672 }
673
674
675
676
677
678
679
680
681 public void setLinkDereferencing(boolean b) {
682 ldapConfig.setDerefLinkFlag(b);
683 clearCache();
684 }
685
686
687
688
689
690
691 public String getPrincipal() {
692 return ldapConfig.getServiceUser();
693 }
694
695
696
697
698
699
700
701
702
703
704 public void setPrincipal(String s) {
705 ldapConfig.setServiceUser(s);
706 clearCache();
707 initializeLdapPool();
708 }
709
710
711
712
713
714
715 public String getPrincipalCredential() {
716 return (String) ldapConfig.getServiceCredential();
717 }
718
719
720
721
722
723
724
725
726
727
728 public void setPrincipalCredential(String s) {
729 ldapConfig.setServiceCredential(s);
730 clearCache();
731 initializeLdapPool();
732 }
733
734
735
736
737
738
739
740
741
742
743 public void setLdapProperties(Map<String, String> ldapProperties) {
744 for (Map.Entry<String, String> entry : ldapProperties.entrySet()) {
745 ldapConfig.setEnvironmentProperties(entry.getKey(), entry.getValue());
746 }
747 clearCache();
748 initializeLdapPool();
749 }
750
751
752 public void onApplicationEvent(ApplicationEvent evt) {
753 if (evt instanceof LogoutEvent) {
754 LogoutEvent logoutEvent = (LogoutEvent) evt;
755 cache.remove(logoutEvent.getUserSession().getPrincipalName());
756 }
757 }
758
759
760 public Map<String, BaseAttribute> resolve(ShibbolethResolutionContext resolutionContext)
761 throws AttributeResolutionException {
762 String searchFilter = filterCreator.createStatement(filterTemplateName, resolutionContext, getDependencyIds(),
763 escapingStrategy);
764 log.debug("Search filter: {}", searchFilter);
765
766
767 Map<String, BaseAttribute> attributes = null;
768
769
770 if (cacheResults) {
771 log.debug("Checking cache for search results");
772 attributes = getCachedAttributes(resolutionContext, searchFilter);
773 if (attributes != null && log.isDebugEnabled()) {
774 log.debug("Returning attributes from cache");
775 }
776 }
777
778
779 if (attributes == null) {
780 log.debug("Retrieving attributes from LDAP");
781 Iterator<SearchResult> results = searchLdap(searchFilter);
782
783 if (noResultsIsError && !results.hasNext()) {
784 throw new AttributeResolutionException("No LDAP entry found for "
785 + resolutionContext.getAttributeRequestContext().getPrincipalName());
786 }
787
788 attributes = buildBaseAttributes(results);
789 if (cacheResults && attributes != null) {
790 setCachedAttributes(resolutionContext, searchFilter, attributes);
791 log.debug("Stored results in the cache");
792 }
793 }
794
795 return attributes;
796 }
797
798
799 public void validate() throws AttributeResolutionException {
800 Ldap ldap = null;
801 try {
802 ldap = (Ldap) ldapPool.borrowObject();
803 if (!ldap.connect()) {
804 throw new NamingException();
805 }
806 } catch (NamingException e) {
807 log.error("An error occured when attempting to search the LDAP: " + ldapConfig.getEnvironment(), e);
808 throw new AttributeResolutionException("An error occurred when attempting to search the LDAP");
809 } catch (Exception e) {
810 log.error("Could not retrieve Ldap object from pool", e);
811 throw new AttributeResolutionException(
812 "An error occurred when attempting to retrieve a LDAP connection from the pool");
813 } finally {
814 if (ldap != null) {
815 try {
816 ldapPool.returnObject(ldap);
817 } catch (Exception e) {
818 log.error("Could not return Ldap object back to pool", e);
819 }
820 }
821 }
822 }
823
824
825
826
827
828
829
830
831 protected Iterator<SearchResult> searchLdap(String searchFilter) throws AttributeResolutionException {
832 Ldap ldap = null;
833 try {
834 ldap = (Ldap) ldapPool.borrowObject();
835 return ldap.search(searchFilter, returnAttributes);
836 } catch (NamingException e) {
837 log.error("An error occured when attempting to search the LDAP: " + ldapConfig.getEnvironment(), e);
838 throw new AttributeResolutionException("An error occurred when attempting to search the LDAP");
839 } catch (Exception e) {
840 log.error("Could not retrieve Ldap object from pool", e);
841 throw new AttributeResolutionException(
842 "An error occurred when attempting to retrieve a LDAP connection from the pool");
843 } finally {
844 if (ldap != null) {
845 try {
846 ldapPool.returnObject(ldap);
847 } catch (Exception e) {
848 log.error("Could not return Ldap object back to pool", e);
849 }
850 }
851 }
852 }
853
854
855
856
857
858
859
860
861 protected Map<String, BaseAttribute> buildBaseAttributes(Iterator<SearchResult> results)
862 throws AttributeResolutionException {
863
864 Map<String, BaseAttribute> attributes = new HashMap<String, BaseAttribute>();
865
866 if (!results.hasNext()) {
867 return attributes;
868 }
869
870 do{
871 SearchResult sr = results.next();
872 Map<String, List<String>> newAttrsMap = null;
873 try{
874 newAttrsMap = LdapUtil.parseAttributes(sr.getAttributes(), true);
875 } catch (NamingException e) {
876 log.error("Error parsing LDAP attributes", e);
877 throw new AttributeResolutionException("Error parsing LDAP attributes");
878 }
879
880 for (Map.Entry<String, List<String>> entry : newAttrsMap.entrySet()) {
881 log.debug("Found the following attribute: {}", entry);
882 BaseAttribute<String> attribute = attributes.get(entry.getKey());
883 if(attribute == null){
884 attribute = new BasicAttribute<String>();
885 ((BasicAttribute)attribute).setId(entry.getKey());
886 attributes.put(entry.getKey(), attribute);
887 }
888
889 List<String> values = entry.getValue();
890 if(values != null && !values.isEmpty()){
891 for(String value : values){
892 if(!DatatypeHelper.isEmpty(value)){
893 attribute.getValues().add(DatatypeHelper.safeTrimOrNullString(value));
894 }
895 }
896 }
897 }
898 }while (mergeMultipleResults && results.hasNext());
899
900 return attributes;
901 }
902
903
904
905
906
907
908
909
910 protected void setCachedAttributes(ShibbolethResolutionContext resolutionContext, String searchFiler,
911 Map<String, BaseAttribute> attributes) {
912 Map<String, Map<String, BaseAttribute>> results = null;
913 String principal = resolutionContext.getAttributeRequestContext().getPrincipalName();
914 if (cache.containsKey(principal)) {
915 results = cache.get(principal);
916 } else {
917 results = new HashMap<String, Map<String, BaseAttribute>>();
918 cache.put(principal, results);
919 }
920 results.put(searchFiler, attributes);
921 }
922
923
924
925
926
927
928
929
930
931 protected Map<String, BaseAttribute> getCachedAttributes(ShibbolethResolutionContext resolutionContext,
932 String searchFilter) {
933 Map<String, BaseAttribute> attributes = null;
934 if (cacheResults) {
935 String principal = resolutionContext.getAttributeRequestContext().getPrincipalName();
936 if (cache.containsKey(principal)) {
937 Map<String, Map<String, BaseAttribute>> results = cache.get(principal);
938 attributes = results.get(searchFilter);
939 }
940 }
941 return attributes;
942 }
943
944
945
946
947 protected class LDAPValueEscapingStrategy implements CharacterEscapingStrategy {
948
949
950 public String escape(String value) {
951 return value.replace("*", "\\*").replace("(", "\\(").replace(")", "\\)").replace("\\", "\\");
952 }
953 }
954 }