1 /* Copyright 2001-2004 The Apache Software Foundation
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
17 * util_ldap.c: LDAP things
19 * Original code from auth_ldap module for Apache v1.3:
20 * Copyright 1998, 1999 Enbridge Pipelines Inc.
21 * Copyright 1999-2001 Dave Carrigan
25 #include <apr_strings.h>
27 #include "ap_config.h"
29 #include "http_config.h"
30 #include "http_core.h"
32 #include "http_protocol.h"
33 #include "http_request.h"
34 #include "util_ldap.h"
35 #include "util_ldap_cache.h"
42 #error mod_ldap requires APR-util to have LDAP support built in
45 /* defines for certificate file types
47 #define LDAP_CA_TYPE_UNKNOWN 0
48 #define LDAP_CA_TYPE_DER 1
49 #define LDAP_CA_TYPE_BASE64 2
50 #define LDAP_CA_TYPE_CERT7_DB 3
53 module AP_MODULE_DECLARE_DATA ldap_module;
55 int util_ldap_handler(request_rec *r);
56 void *util_ldap_create_config(apr_pool_t *p, server_rec *s);
60 * Some definitions to help between various versions of apache.
63 #ifndef DOCTYPE_HTML_2_0
64 #define DOCTYPE_HTML_2_0 "<!DOCTYPE HTML PUBLIC \"-//IETF//" \
65 "DTD HTML 2.0//EN\">\n"
68 #ifndef DOCTYPE_HTML_3_2
69 #define DOCTYPE_HTML_3_2 "<!DOCTYPE HTML PUBLIC \"-//W3C//" \
70 "DTD HTML 3.2 Final//EN\">\n"
73 #ifndef DOCTYPE_HTML_4_0S
74 #define DOCTYPE_HTML_4_0S "<!DOCTYPE HTML PUBLIC \"-//W3C//" \
75 "DTD HTML 4.0//EN\"\n" \
76 "\"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
79 #ifndef DOCTYPE_HTML_4_0T
80 #define DOCTYPE_HTML_4_0T "<!DOCTYPE HTML PUBLIC \"-//W3C//" \
81 "DTD HTML 4.0 Transitional//EN\"\n" \
82 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
85 #ifndef DOCTYPE_HTML_4_0F
86 #define DOCTYPE_HTML_4_0F "<!DOCTYPE HTML PUBLIC \"-//W3C//" \
87 "DTD HTML 4.0 Frameset//EN\"\n" \
88 "\"http://www.w3.org/TR/REC-html40/frameset.dtd\">\n"
91 #define LDAP_CACHE_LOCK() \
92 apr_global_mutex_lock(st->util_ldap_cache_lock)
93 #define LDAP_CACHE_UNLOCK() \
94 apr_global_mutex_unlock(st->util_ldap_cache_lock)
97 static void util_ldap_strdup (char **str, const char *newstr)
105 *str = calloc(1, strlen(newstr)+1);
106 strcpy (*str, newstr);
114 * This handler generates a status page about the current performance of
115 * the LDAP cache. It is enabled as follows:
117 * <Location /ldap-status>
118 * SetHandler ldap-status
122 int util_ldap_handler(request_rec *r)
124 util_ldap_state_t *st = (util_ldap_state_t *)ap_get_module_config(r->server->module_config, &ldap_module);
126 r->allowed |= (1 << M_GET);
127 if (r->method_number != M_GET)
130 if (strcmp(r->handler, "ldap-status")) {
134 r->content_type = "text/html";
138 ap_rputs(DOCTYPE_HTML_3_2
139 "<html><head><title>LDAP Cache Information</title></head>\n", r);
140 ap_rputs("<body bgcolor='#ffffff'><h1 align=center>LDAP Cache Information</h1>\n", r);
142 util_ald_cache_display(r, st);
147 /* ------------------------------------------------------------------ */
151 * Closes an LDAP connection by unlocking it. The next time
152 * util_ldap_connection_find() is called this connection will be
153 * available for reuse.
155 LDAP_DECLARE(void) util_ldap_connection_close(util_ldap_connection_t *ldc)
161 * Is it safe leaving bound connections floating around between the
162 * different modules? Keeping the user bound is a performance boost,
163 * but it is also a potential security problem - maybe.
165 * For now we unbind the user when we finish with a connection, but
166 * we don't have to...
169 /* mark our connection as available for reuse */
172 apr_thread_mutex_unlock(ldc->lock);
178 * Destroys an LDAP connection by unbinding and closing the connection to
179 * the LDAP server. It is used to bring the connection back to a known
180 * state after an error, and during pool cleanup.
182 LDAP_DECLARE_NONSTD(apr_status_t) util_ldap_connection_unbind(void *param)
184 util_ldap_connection_t *ldc = param;
188 ldap_unbind_s(ldc->ldap);
199 * Clean up an LDAP connection by unbinding and unlocking the connection.
200 * This function is registered with the pool cleanup function - causing
201 * the LDAP connections to be shut down cleanly on graceful restart.
203 LDAP_DECLARE_NONSTD(apr_status_t) util_ldap_connection_cleanup(void *param)
205 util_ldap_connection_t *ldc = param;
209 /* unbind and disconnect from the LDAP server */
210 util_ldap_connection_unbind(ldc);
212 /* free the username and password */
214 free((void*)ldc->bindpw);
217 free((void*)ldc->binddn);
220 /* unlock this entry */
221 util_ldap_connection_close(ldc);
230 * Connect to the LDAP server and binds. Does not connect if already
231 * connected (i.e. ldc->ldap is non-NULL.) Does not bind if already bound.
233 * Returns LDAP_SUCCESS on success; and an error code on failure
235 LDAP_DECLARE(int) util_ldap_connection_open(request_rec *r,
236 util_ldap_connection_t *ldc)
240 int version = LDAP_VERSION3;
242 util_ldap_state_t *st = (util_ldap_state_t *)ap_get_module_config(
243 r->server->module_config, &ldap_module);
245 /* If the connection is already bound, return
249 ldc->reason = "LDAP: connection open successful (already bound)";
253 /* create the ldap session handle
255 if (NULL == ldc->ldap)
257 /* clear connection requested */
260 ldc->ldap = ldap_init(const_cast(ldc->host), ldc->port);
262 else /* ssl connnection requested */
264 /* check configuration to make sure it supports SSL
270 #if APR_HAS_NOVELL_LDAPSDK
271 ldc->ldap = ldapssl_init(ldc->host, ldc->port, 1);
273 #elif APR_HAS_NETSCAPE_LDAPSDK
274 ldc->ldap = ldapssl_init(ldc->host, ldc->port, 1);
276 #elif APR_HAS_OPENLDAP_LDAPSDK
277 ldc->ldap = ldap_init(ldc->host, ldc->port);
278 if (NULL != ldc->ldap)
280 int SSLmode = LDAP_OPT_X_TLS_HARD;
281 result = ldap_set_option(ldc->ldap, LDAP_OPT_X_TLS, &SSLmode);
282 if (LDAP_SUCCESS != result)
284 ldap_unbind_s(ldc->ldap);
285 ldc->reason = "LDAP: ldap_set_option - LDAP_OPT_X_TLS_HARD failed";
290 #elif APR_HAS_MICROSOFT_LDAPSDK
291 ldc->ldap = ldap_sslinit(const_cast(ldc->host), ldc->port, 1);
294 ldc->reason = "LDAP: ssl connections not supported";
295 #endif /* APR_HAS_NOVELL_LDAPSDK */
297 #endif /* APR_HAS_LDAP_SSL */
300 ldc->reason = "LDAP: ssl connections not supported";
303 if (NULL == ldc->ldap)
306 if (NULL == ldc->reason)
307 ldc->reason = "LDAP: ldap initialization failed";
311 /* Set the alias dereferencing option */
312 ldap_set_option(ldc->ldap, LDAP_OPT_DEREF, &(ldc->deref));
314 /* always default to LDAP V3 */
315 ldap_set_option(ldc->ldap, LDAP_OPT_PROTOCOL_VERSION, &version);
320 /* loop trying to bind up to 10 times if LDAP_SERVER_DOWN error is
321 * returned. Break out of the loop on Success or any other error.
323 * NOTE: Looping is probably not a great idea. If the server isn't
324 * responding the chances it will respond after a few tries are poor.
325 * However, the original code looped and it only happens on
326 * the error condition.
328 for (failures=0; failures<10; failures++)
330 result = ldap_simple_bind_s(ldc->ldap, const_cast(ldc->binddn), const_cast(ldc->bindpw));
331 if (LDAP_SERVER_DOWN != result)
335 /* free the handle if there was an error
337 if (LDAP_SUCCESS != result)
339 ldap_unbind_s(ldc->ldap);
342 ldc->reason = "LDAP: ldap_simple_bind_s() failed";
346 ldc->reason = "LDAP: connection open successful";
354 * Find an existing ldap connection struct that matches the
355 * provided ldap connection parameters.
357 * If not found in the cache, a new ldc structure will be allocated from st->pool
358 * and returned to the caller. If found in the cache, a pointer to the existing
359 * ldc structure will be returned.
361 LDAP_DECLARE(util_ldap_connection_t *)util_ldap_connection_find(request_rec *r, const char *host, int port,
362 const char *binddn, const char *bindpw, deref_options deref,
365 struct util_ldap_connection_t *l, *p; /* To traverse the linked list */
367 util_ldap_state_t *st =
368 (util_ldap_state_t *)ap_get_module_config(r->server->module_config,
373 /* mutex lock this function */
375 apr_thread_mutex_create(&st->mutex, APR_THREAD_MUTEX_DEFAULT, st->pool);
377 apr_thread_mutex_lock(st->mutex);
380 /* Search for an exact connection match in the list that is not
383 for (l=st->connections,p=NULL; l; l=l->next) {
385 if (APR_SUCCESS == apr_thread_mutex_trylock(l->lock)) {
387 if ((l->port == port) && (strcmp(l->host, host) == 0) &&
388 ((!l->binddn && !binddn) || (l->binddn && binddn && !strcmp(l->binddn, binddn))) &&
389 ((!l->bindpw && !bindpw) || (l->bindpw && bindpw && !strcmp(l->bindpw, bindpw))) &&
390 (l->deref == deref) && (l->secure == secure)) {
395 /* If this connection didn't match the criteria, then we
396 * need to unlock the mutex so it is available to be reused.
398 apr_thread_mutex_unlock(l->lock);
404 /* If nothing found, search again, but we don't care about the
405 * binddn and bindpw this time.
408 for (l=st->connections,p=NULL; l; l=l->next) {
410 if (APR_SUCCESS == apr_thread_mutex_trylock(l->lock)) {
413 if ((l->port == port) && (strcmp(l->host, host) == 0) &&
414 (l->deref == deref) && (l->secure == secure)) {
416 /* the bind credentials have changed */
418 util_ldap_strdup((char**)&(l->binddn), binddn);
419 util_ldap_strdup((char**)&(l->bindpw), bindpw);
423 /* If this connection didn't match the criteria, then we
424 * need to unlock the mutex so it is available to be reused.
426 apr_thread_mutex_unlock(l->lock);
433 /* artificially disable cache */
436 /* If no connection what found after the second search, we
442 * Add the new connection entry to the linked list. Note that we
443 * don't actually establish an LDAP connection yet; that happens
444 * the first time authentication is requested.
446 /* create the details to the pool in st */
447 l = apr_pcalloc(st->pool, sizeof(util_ldap_connection_t));
449 apr_thread_mutex_create(&l->lock, APR_THREAD_MUTEX_DEFAULT, st->pool);
450 apr_thread_mutex_lock(l->lock);
454 l->host = apr_pstrdup(st->pool, host);
457 util_ldap_strdup((char**)&(l->binddn), binddn);
458 util_ldap_strdup((char**)&(l->bindpw), bindpw);
461 /* add the cleanup to the pool */
462 apr_pool_cleanup_register(l->pool, l,
463 util_ldap_connection_cleanup,
464 apr_pool_cleanup_null);
475 apr_thread_mutex_unlock(st->mutex);
480 /* ------------------------------------------------------------------ */
483 * Compares two DNs to see if they're equal. The only way to do this correctly is to
484 * search for the dn and then do ldap_get_dn() on the result. This should match the
485 * initial dn, since it would have been also retrieved with ldap_get_dn(). This is
486 * expensive, so if the configuration value compare_dn_on_server is
487 * false, just does an ordinary strcmp.
489 * The lock for the ldap cache should already be acquired.
491 LDAP_DECLARE(int) util_ldap_cache_comparedn(request_rec *r, util_ldap_connection_t *ldc,
492 const char *url, const char *dn, const char *reqdn,
493 int compare_dn_on_server)
496 util_url_node_t *curl;
497 util_url_node_t curnode;
498 util_dn_compare_node_t *node;
499 util_dn_compare_node_t newnode;
501 LDAPMessage *res, *entry;
504 util_ldap_state_t *st = (util_ldap_state_t *)ap_get_module_config(r->server->module_config, &ldap_module);
506 /* get cache entry (or create one) */
510 curl = util_ald_cache_fetch(st->util_ldap_cache, &curnode);
512 curl = util_ald_create_caches(st, url);
516 /* a simple compare? */
517 if (!compare_dn_on_server) {
518 /* unlock this read lock */
519 if (strcmp(dn, reqdn)) {
520 ldc->reason = "DN Comparison FALSE (direct strcmp())";
521 return LDAP_COMPARE_FALSE;
524 ldc->reason = "DN Comparison TRUE (direct strcmp())";
525 return LDAP_COMPARE_TRUE;
530 /* no - it's a server side compare */
533 /* is it in the compare cache? */
534 newnode.reqdn = (char *)reqdn;
535 node = util_ald_cache_fetch(curl->dn_compare_cache, &newnode);
537 /* If it's in the cache, it's good */
538 /* unlock this read lock */
540 ldc->reason = "DN Comparison TRUE (cached)";
541 return LDAP_COMPARE_TRUE;
544 /* unlock this read lock */
549 if (failures++ > 10) {
550 /* too many failures */
554 /* make a server connection */
555 if (LDAP_SUCCESS != (result = util_ldap_connection_open(r, ldc))) {
556 /* connect to server failed */
560 /* search for reqdn */
561 if ((result = ldap_search_ext_s(ldc->ldap, const_cast(reqdn), LDAP_SCOPE_BASE,
562 "(objectclass=*)", NULL, 1,
563 NULL, NULL, NULL, -1, &res)) == LDAP_SERVER_DOWN) {
564 ldc->reason = "DN Comparison ldap_search_ext_s() failed with server down";
565 util_ldap_connection_unbind(ldc);
568 if (result != LDAP_SUCCESS) {
569 /* search for reqdn failed - no match */
570 ldc->reason = "DN Comparison ldap_search_ext_s() failed";
574 entry = ldap_first_entry(ldc->ldap, res);
575 searchdn = ldap_get_dn(ldc->ldap, entry);
578 if (strcmp(dn, searchdn) != 0) {
579 /* compare unsuccessful */
580 ldc->reason = "DN Comparison FALSE (checked on server)";
581 result = LDAP_COMPARE_FALSE;
585 /* compare successful - add to the compare cache */
587 newnode.reqdn = (char *)reqdn;
588 newnode.dn = (char *)dn;
590 node = util_ald_cache_fetch(curl->dn_compare_cache, &newnode);
591 if ((node == NULL) ||
592 (strcmp(reqdn, node->reqdn) != 0) || (strcmp(dn, node->dn) != 0)) {
594 util_ald_cache_insert(curl->dn_compare_cache, &newnode);
598 ldc->reason = "DN Comparison TRUE (checked on server)";
599 result = LDAP_COMPARE_TRUE;
601 ldap_memfree(searchdn);
607 * Does an generic ldap_compare operation. It accepts a cache that it will use
608 * to lookup the compare in the cache. We cache two kinds of compares
609 * (require group compares) and (require user compares). Each compare has a different
610 * cache node: require group includes the DN; require user does not because the
611 * require user cache is owned by the
614 LDAP_DECLARE(int) util_ldap_cache_compare(request_rec *r, util_ldap_connection_t *ldc,
615 const char *url, const char *dn,
616 const char *attrib, const char *value)
619 util_url_node_t *curl;
620 util_url_node_t curnode;
621 util_compare_node_t *compare_nodep;
622 util_compare_node_t the_compare_node;
623 apr_time_t curtime = 0; /* silence gcc -Wall */
626 util_ldap_state_t *st =
627 (util_ldap_state_t *)ap_get_module_config(r->server->module_config,
630 /* get cache entry (or create one) */
633 curl = util_ald_cache_fetch(st->util_ldap_cache, &curnode);
635 curl = util_ald_create_caches(st, url);
640 /* make a comparison to the cache */
642 curtime = apr_time_now();
644 the_compare_node.dn = (char *)dn;
645 the_compare_node.attrib = (char *)attrib;
646 the_compare_node.value = (char *)value;
647 the_compare_node.result = 0;
649 compare_nodep = util_ald_cache_fetch(curl->compare_cache, &the_compare_node);
651 if (compare_nodep != NULL) {
653 if (curtime - compare_nodep->lastcompare > st->compare_cache_ttl) {
654 /* ...but it is too old */
655 util_ald_cache_remove(curl->compare_cache, compare_nodep);
658 /* ...and it is good */
659 /* unlock this read lock */
661 if (LDAP_COMPARE_TRUE == compare_nodep->result) {
662 ldc->reason = "Comparison true (cached)";
663 return compare_nodep->result;
665 else if (LDAP_COMPARE_FALSE == compare_nodep->result) {
666 ldc->reason = "Comparison false (cached)";
667 return compare_nodep->result;
669 else if (LDAP_NO_SUCH_ATTRIBUTE == compare_nodep->result) {
670 ldc->reason = "Comparison no such attribute (cached)";
671 return compare_nodep->result;
674 ldc->reason = "Comparison undefined (cached)";
675 return compare_nodep->result;
679 /* unlock this read lock */
684 if (failures++ > 10) {
685 /* too many failures */
688 if (LDAP_SUCCESS != (result = util_ldap_connection_open(r, ldc))) {
693 if ((result = ldap_compare_s(ldc->ldap, const_cast(dn), const_cast(attrib), const_cast(value)))
694 == LDAP_SERVER_DOWN) {
695 /* connection failed - try again */
696 ldc->reason = "ldap_compare_s() failed with server down";
697 util_ldap_connection_unbind(ldc);
701 ldc->reason = "Comparison complete";
702 if ((LDAP_COMPARE_TRUE == result) ||
703 (LDAP_COMPARE_FALSE == result) ||
704 (LDAP_NO_SUCH_ATTRIBUTE == result)) {
706 /* compare completed; caching result */
708 the_compare_node.lastcompare = curtime;
709 the_compare_node.result = result;
711 /* If the node doesn't exist then insert it, otherwise just update it with
713 compare_nodep = util_ald_cache_fetch(curl->compare_cache, &the_compare_node);
714 if ((compare_nodep == NULL) ||
715 (strcmp(the_compare_node.dn, compare_nodep->dn) != 0) ||
716 (strcmp(the_compare_node.attrib, compare_nodep->attrib) != 0) ||
717 (strcmp(the_compare_node.value, compare_nodep->value) != 0)) {
719 util_ald_cache_insert(curl->compare_cache, &the_compare_node);
722 compare_nodep->lastcompare = curtime;
723 compare_nodep->result = result;
727 if (LDAP_COMPARE_TRUE == result) {
728 ldc->reason = "Comparison true (adding to cache)";
729 return LDAP_COMPARE_TRUE;
731 else if (LDAP_COMPARE_FALSE == result) {
732 ldc->reason = "Comparison false (adding to cache)";
733 return LDAP_COMPARE_FALSE;
736 ldc->reason = "Comparison no such attribute (adding to cache)";
737 return LDAP_NO_SUCH_ATTRIBUTE;
743 LDAP_DECLARE(int) util_ldap_cache_checkuserid(request_rec *r, util_ldap_connection_t *ldc,
744 const char *url, const char *basedn, int scope, char **attrs,
745 const char *filter, const char *bindpw, const char **binddn,
746 const char ***retvals)
748 const char **vals = NULL;
750 LDAPMessage *res, *entry;
754 util_url_node_t *curl; /* Cached URL node */
755 util_url_node_t curnode;
756 util_search_node_t *search_nodep; /* Cached search node */
757 util_search_node_t the_search_node;
760 util_ldap_state_t *st =
761 (util_ldap_state_t *)ap_get_module_config(r->server->module_config,
764 /* Get the cache node for this url */
767 curl = (util_url_node_t *)util_ald_cache_fetch(st->util_ldap_cache, &curnode);
769 curl = util_ald_create_caches(st, url);
775 the_search_node.username = filter;
776 search_nodep = util_ald_cache_fetch(curl->search_cache, &the_search_node);
777 if (search_nodep != NULL && search_nodep->bindpw) {
779 /* found entry in search cache... */
780 curtime = apr_time_now();
783 * Remove this item from the cache if its expired, or if the
784 * sent password doesn't match the storepassword.
786 if ((curtime - search_nodep->lastbind) > st->search_cache_ttl) {
787 /* ...but entry is too old */
788 util_ald_cache_remove(curl->search_cache, search_nodep);
790 else if (strcmp(search_nodep->bindpw, bindpw) != 0) {
791 /* ...but cached password doesn't match sent password */
792 util_ald_cache_remove(curl->search_cache, search_nodep);
795 /* ...and entry is valid */
796 *binddn = search_nodep->dn;
797 *retvals = search_nodep->vals;
799 ldc->reason = "Authentication successful (cached)";
803 /* unlock this read lock */
808 * At this point, there is no valid cached search, so lets do the search.
812 * If any LDAP operation fails due to LDAP_SERVER_DOWN, control returns here.
815 if (failures++ > 10) {
818 if (LDAP_SUCCESS != (result = util_ldap_connection_open(r, ldc))) {
822 /* try do the search */
823 if ((result = ldap_search_ext_s(ldc->ldap,
824 const_cast(basedn), scope,
825 const_cast(filter), attrs, 0,
826 NULL, NULL, NULL, -1, &res)) == LDAP_SERVER_DOWN) {
827 ldc->reason = "ldap_search_ext_s() for user failed with server down";
828 util_ldap_connection_unbind(ldc);
832 /* if there is an error (including LDAP_NO_SUCH_OBJECT) return now */
833 if (result != LDAP_SUCCESS) {
834 ldc->reason = "ldap_search_ext_s() for user failed";
839 * We should have found exactly one entry; to find a different
840 * number is an error.
842 count = ldap_count_entries(ldc->ldap, res);
846 ldc->reason = "User not found";
848 ldc->reason = "User is not unique (search found two or more matches)";
850 return LDAP_NO_SUCH_OBJECT;
853 entry = ldap_first_entry(ldc->ldap, res);
855 /* Grab the dn, copy it into the pool, and free it again */
856 dn = ldap_get_dn(ldc->ldap, entry);
857 *binddn = apr_pstrdup(r->pool, dn);
861 * A bind to the server with an empty password always succeeds, so
862 * we check to ensure that the password is not empty. This implies
863 * that users who actually do have empty passwords will never be
864 * able to authenticate with this module. I don't see this as a big
867 if (strlen(bindpw) <= 0) {
869 ldc->reason = "Empty password not allowed";
870 return LDAP_INVALID_CREDENTIALS;
874 * Attempt to bind with the retrieved dn and the password. If the bind
875 * fails, it means that the password is wrong (the dn obviously
876 * exists, since we just retrieved it)
879 ldap_simple_bind_s(ldc->ldap, const_cast(*binddn), const_cast(bindpw))) ==
881 ldc->reason = "ldap_simple_bind_s() to check user credentials failed with server down";
883 util_ldap_connection_unbind(ldc);
887 /* failure? if so - return */
888 if (result != LDAP_SUCCESS) {
889 ldc->reason = "ldap_simple_bind_s() to check user credentials failed";
891 util_ldap_connection_unbind(ldc);
896 * We have just bound the connection to a different user and password
897 * combination, which might be reused unintentionally next time this
898 * connection is used from the connection pool. To ensure no confusion,
899 * we mark the connection as unbound.
905 * Get values for the provided attributes.
911 vals = apr_pcalloc(r->pool, sizeof(char *) * (k+1));
917 values = ldap_get_values(ldc->ldap, entry, attrs[i]);
918 while (values && values[j]) {
919 str = str ? apr_pstrcat(r->pool, str, "; ", values[j], NULL) : apr_pstrdup(r->pool, values[j]);
922 ldap_value_free(values);
930 * Add the new username to the search cache.
934 the_search_node.username = filter;
935 the_search_node.dn = *binddn;
936 the_search_node.bindpw = bindpw;
937 the_search_node.lastbind = apr_time_now();
938 the_search_node.vals = vals;
940 /* Search again to make sure that another thread didn't ready insert this node
941 into the cache before we got here. If it does exist then update the lastbind */
942 search_nodep = util_ald_cache_fetch(curl->search_cache, &the_search_node);
943 if ((search_nodep == NULL) ||
944 (strcmp(*binddn, search_nodep->dn) != 0) || (strcmp(bindpw, search_nodep->bindpw) != 0)) {
946 util_ald_cache_insert(curl->search_cache, &the_search_node);
949 search_nodep->lastbind = the_search_node.lastbind;
955 ldc->reason = "Authentication successful";
961 * Reports if ssl support is enabled
963 * 1 = enabled, 0 = not enabled
965 LDAP_DECLARE(int) util_ldap_ssl_supported(request_rec *r)
967 util_ldap_state_t *st = (util_ldap_state_t *)ap_get_module_config(
968 r->server->module_config, &ldap_module);
970 return(st->ssl_support);
974 /* ---------------------------------------- */
975 /* config directives */
978 static const char *util_ldap_set_cache_bytes(cmd_parms *cmd, void *dummy, const char *bytes)
980 util_ldap_state_t *st =
981 (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
984 st->cache_bytes = atol(bytes);
986 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server,
987 "[%" APR_PID_T_FMT "] ldap cache: Setting shared memory "
988 " cache size to %" APR_SIZE_T_FMT " bytes.",
989 getpid(), st->cache_bytes);
994 static const char *util_ldap_set_cache_file(cmd_parms *cmd, void *dummy, const char *file)
996 util_ldap_state_t *st =
997 (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1001 st->cache_file = ap_server_root_relative(st->pool, file);
1004 st->cache_file = NULL;
1007 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server,
1008 "LDAP cache: Setting shared memory cache file to %s bytes.",
1014 static const char *util_ldap_set_cache_ttl(cmd_parms *cmd, void *dummy, const char *ttl)
1016 util_ldap_state_t *st =
1017 (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1020 st->search_cache_ttl = atol(ttl) * 1000000;
1022 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server,
1023 "[%d] ldap cache: Setting cache TTL to %ld microseconds.",
1024 getpid(), st->search_cache_ttl);
1029 static const char *util_ldap_set_cache_entries(cmd_parms *cmd, void *dummy, const char *size)
1031 util_ldap_state_t *st =
1032 (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1036 st->search_cache_size = atol(size);
1037 if (st->search_cache_size < 0) {
1038 st->search_cache_size = 0;
1041 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server,
1042 "[%d] ldap cache: Setting search cache size to %ld entries.",
1043 getpid(), st->search_cache_size);
1048 static const char *util_ldap_set_opcache_ttl(cmd_parms *cmd, void *dummy, const char *ttl)
1050 util_ldap_state_t *st =
1051 (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1054 st->compare_cache_ttl = atol(ttl) * 1000000;
1056 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server,
1057 "[%d] ldap cache: Setting operation cache TTL to %ld microseconds.",
1058 getpid(), st->compare_cache_ttl);
1063 static const char *util_ldap_set_opcache_entries(cmd_parms *cmd, void *dummy, const char *size)
1065 util_ldap_state_t *st =
1066 (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1069 st->compare_cache_size = atol(size);
1070 if (st->compare_cache_size < 0) {
1071 st->compare_cache_size = 0;
1074 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server,
1075 "[%d] ldap cache: Setting operation cache size to %ld entries.",
1076 getpid(), st->compare_cache_size);
1081 static const char *util_ldap_set_cert_auth(cmd_parms *cmd, void *dummy, const char *file)
1083 util_ldap_state_t *st =
1084 (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1086 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1091 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server,
1092 "LDAP: SSL trusted certificate authority file - %s",
1095 st->cert_auth_file = ap_server_root_relative(cmd->pool, file);
1101 static const char *util_ldap_set_cert_type(cmd_parms *cmd, void *dummy, const char *Type)
1103 util_ldap_state_t *st =
1104 (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1106 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1111 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server,
1112 "LDAP: SSL trusted certificate authority file type - %s",
1115 if (0 == strcmp("DER_FILE", Type))
1116 st->cert_file_type = LDAP_CA_TYPE_DER;
1118 else if (0 == strcmp("BASE64_FILE", Type))
1119 st->cert_file_type = LDAP_CA_TYPE_BASE64;
1121 else if (0 == strcmp("CERT7_DB_PATH", Type))
1122 st->cert_file_type = LDAP_CA_TYPE_CERT7_DB;
1125 st->cert_file_type = LDAP_CA_TYPE_UNKNOWN;
1131 void *util_ldap_create_config(apr_pool_t *p, server_rec *s)
1133 util_ldap_state_t *st =
1134 (util_ldap_state_t *)apr_pcalloc(p, sizeof(util_ldap_state_t));
1138 st->cache_bytes = 100000;
1139 st->search_cache_ttl = 600000000;
1140 st->search_cache_size = 1024;
1141 st->compare_cache_ttl = 600000000;
1142 st->compare_cache_size = 1024;
1143 st->connections = NULL;
1144 st->cert_auth_file = NULL;
1145 st->cert_file_type = LDAP_CA_TYPE_UNKNOWN;
1146 st->ssl_support = 0;
1151 static apr_status_t util_ldap_cleanup_module(void *data)
1153 #if APR_HAS_LDAP_SSL && APR_HAS_NOVELL_LDAPSDK
1154 server_rec *s = data;
1155 util_ldap_state_t *st = (util_ldap_state_t *)ap_get_module_config(
1156 s->module_config, &ldap_module);
1158 if (st->ssl_support)
1159 ldapssl_client_deinit();
1165 static int util_ldap_post_config(apr_pool_t *p, apr_pool_t *plog,
1166 apr_pool_t *ptemp, server_rec *s)
1168 int rc = LDAP_SUCCESS;
1169 apr_status_t result;
1170 char buf[MAX_STRING_LEN];
1171 server_rec *s_vhost;
1172 util_ldap_state_t *st_vhost;
1174 util_ldap_state_t *st =
1175 (util_ldap_state_t *)ap_get_module_config(s->module_config, &ldap_module);
1178 const char *userdata_key = "util_ldap_init";
1180 /* util_ldap_post_config() will be called twice. Don't bother
1181 * going through all of the initialization on the first call
1182 * because it will just be thrown away.*/
1183 apr_pool_userdata_get(&data, userdata_key, s->process->pool);
1185 apr_pool_userdata_set((const void *)1, userdata_key,
1186 apr_pool_cleanup_null, s->process->pool);
1188 #if APR_HAS_SHARED_MEMORY
1189 /* If the cache file already exists then delete it. Otherwise we are
1190 * going to run into problems creating the shared memory. */
1191 if (st->cache_file) {
1192 char *lck_file = apr_pstrcat (st->pool, st->cache_file, ".lck", NULL);
1193 apr_file_remove(st->cache_file, ptemp);
1194 apr_file_remove(lck_file, ptemp);
1200 #if APR_HAS_SHARED_MEMORY
1201 /* initializing cache if shared memory size is not zero and we already don't have shm address */
1202 if (!st->cache_shm && st->cache_bytes > 0) {
1204 result = util_ldap_cache_init(p, st);
1205 if (result != APR_SUCCESS) {
1206 apr_strerror(result, buf, sizeof(buf));
1207 ap_log_error(APLOG_MARK, APLOG_ERR, result, s,
1208 "LDAP cache: error while creating a shared memory segment: %s", buf);
1212 #if APR_HAS_SHARED_MEMORY
1213 if (st->cache_file) {
1214 st->lock_file = apr_pstrcat (st->pool, st->cache_file, ".lck", NULL);
1218 st->lock_file = ap_server_root_relative(st->pool, tmpnam(NULL));
1220 result = apr_global_mutex_create(&st->util_ldap_cache_lock, st->lock_file, APR_LOCK_DEFAULT, st->pool);
1221 if (result != APR_SUCCESS) {
1225 /* merge config in all vhost */
1228 st_vhost = (util_ldap_state_t *)ap_get_module_config(s_vhost->module_config, &ldap_module);
1230 #if APR_HAS_SHARED_MEMORY
1231 st_vhost->cache_shm = st->cache_shm;
1232 st_vhost->cache_rmm = st->cache_rmm;
1233 st_vhost->cache_file = st->cache_file;
1234 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, result, s,
1235 "LDAP merging Shared Cache conf: shm=0x%pp rmm=0x%pp for VHOST: %s",
1236 st->cache_shm, st->cache_rmm, s_vhost->server_hostname);
1238 st_vhost->lock_file = st->lock_file;
1239 s_vhost = s_vhost->next;
1241 #if APR_HAS_SHARED_MEMORY
1244 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, "LDAP cache: LDAPSharedCacheSize is zero, disabling shared memory cache");
1248 /* log the LDAP SDK used
1250 #if APR_HAS_NETSCAPE_LDAPSDK
1252 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
1253 "LDAP: Built with Netscape LDAP SDK" );
1255 #elif APR_HAS_NOVELL_LDAPSDK
1257 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
1258 "LDAP: Built with Novell LDAP SDK" );
1260 #elif APR_HAS_OPENLDAP_LDAPSDK
1262 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
1263 "LDAP: Built with OpenLDAP LDAP SDK" );
1265 #elif APR_HAS_MICROSOFT_LDAPSDK
1267 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
1268 "LDAP: Built with Microsoft LDAP SDK" );
1271 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
1272 "LDAP: Built with unknown LDAP SDK" );
1274 #endif /* APR_HAS_NETSCAPE_LDAPSDK */
1278 apr_pool_cleanup_register(p, s, util_ldap_cleanup_module,
1279 util_ldap_cleanup_module);
1281 /* initialize SSL support if requested
1283 if (st->cert_auth_file)
1285 #if APR_HAS_LDAP_SSL /* compiled with ssl support */
1287 #if APR_HAS_NETSCAPE_LDAPSDK
1289 /* Netscape sdk only supports a cert7.db file
1291 if (st->cert_file_type == LDAP_CA_TYPE_CERT7_DB)
1293 rc = ldapssl_client_init(st->cert_auth_file, NULL);
1297 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s,
1298 "LDAP: Invalid LDAPTrustedCAType directive - "
1299 "CERT7_DB_PATH type required");
1303 #elif APR_HAS_NOVELL_LDAPSDK
1305 /* Novell SDK supports DER or BASE64 files
1307 if (st->cert_file_type == LDAP_CA_TYPE_DER ||
1308 st->cert_file_type == LDAP_CA_TYPE_BASE64 )
1310 rc = ldapssl_client_init(NULL, NULL);
1311 if (LDAP_SUCCESS == rc)
1313 if (st->cert_file_type == LDAP_CA_TYPE_BASE64)
1314 rc = ldapssl_add_trusted_cert(st->cert_auth_file,
1315 LDAPSSL_CERT_FILETYPE_B64);
1317 rc = ldapssl_add_trusted_cert(st->cert_auth_file,
1318 LDAPSSL_CERT_FILETYPE_DER);
1320 if (LDAP_SUCCESS != rc)
1321 ldapssl_client_deinit();
1326 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s,
1327 "LDAP: Invalid LDAPTrustedCAType directive - "
1328 "DER_FILE or BASE64_FILE type required");
1332 #elif APR_HAS_OPENLDAP_LDAPSDK
1334 /* OpenLDAP SDK supports BASE64 files
1336 if (st->cert_file_type == LDAP_CA_TYPE_BASE64)
1338 rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, st->cert_auth_file);
1342 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s,
1343 "LDAP: Invalid LDAPTrustedCAType directive - "
1344 "BASE64_FILE type required");
1349 #elif APR_HAS_MICROSOFT_LDAPSDK
1351 /* Microsoft SDK use the registry certificate store - always
1352 * assume support is always available
1358 #endif /* APR_HAS_NETSCAPE_LDAPSDK */
1360 #else /* not compiled with SSL Support */
1362 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
1363 "LDAP: Not built with SSL support." );
1366 #endif /* APR_HAS_LDAP_SSL */
1368 if (LDAP_SUCCESS == rc)
1370 st->ssl_support = 1;
1374 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1375 "LDAP: SSL initialization failed");
1376 st->ssl_support = 0;
1380 /* The Microsoft SDK uses the registry certificate store -
1381 * always assume support is available
1383 #if APR_HAS_MICROSOFT_LDAPSDK
1384 st->ssl_support = 1;
1388 /* log SSL status - If SSL isn't available it isn't necessarily
1389 * an error because the modules asking for LDAP connections
1390 * may not ask for SSL support
1392 if (st->ssl_support)
1394 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
1395 "LDAP: SSL support available" );
1399 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
1400 "LDAP: SSL support unavailable" );
1406 static void util_ldap_child_init(apr_pool_t *p, server_rec *s)
1409 util_ldap_state_t *st =
1410 (util_ldap_state_t *)ap_get_module_config(s->module_config, &ldap_module);
1412 sts = apr_global_mutex_child_init(&st->util_ldap_cache_lock, st->lock_file, p);
1413 if (sts != APR_SUCCESS) {
1414 ap_log_error(APLOG_MARK, APLOG_CRIT, sts, s, "failed to init caching lock in child process");
1418 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, s,
1419 "INIT global mutex %s in child %d ", st->lock_file, getpid());
1423 command_rec util_ldap_cmds[] = {
1424 AP_INIT_TAKE1("LDAPSharedCacheSize", util_ldap_set_cache_bytes, NULL, RSRC_CONF,
1425 "Sets the size of the shared memory cache in bytes. "
1426 "Zero means disable the shared memory cache. Defaults to 100KB."),
1428 AP_INIT_TAKE1("LDAPSharedCacheFile", util_ldap_set_cache_file, NULL, RSRC_CONF,
1429 "Sets the file of the shared memory cache."
1430 "Nothing means disable the shared memory cache."),
1432 AP_INIT_TAKE1("LDAPCacheEntries", util_ldap_set_cache_entries, NULL, RSRC_CONF,
1433 "Sets the maximum number of entries that are possible in the LDAP "
1435 "Zero means no limit; -1 disables the cache. Defaults to 1024 entries."),
1437 AP_INIT_TAKE1("LDAPCacheTTL", util_ldap_set_cache_ttl, NULL, RSRC_CONF,
1438 "Sets the maximum time (in seconds) that an item can be cached in the LDAP "
1439 "search cache. Zero means no limit. Defaults to 600 seconds (10 minutes)."),
1441 AP_INIT_TAKE1("LDAPOpCacheEntries", util_ldap_set_opcache_entries, NULL, RSRC_CONF,
1442 "Sets the maximum number of entries that are possible in the LDAP "
1444 "Zero means no limit; -1 disables the cache. Defaults to 1024 entries."),
1446 AP_INIT_TAKE1("LDAPOpCacheTTL", util_ldap_set_opcache_ttl, NULL, RSRC_CONF,
1447 "Sets the maximum time (in seconds) that an item is cached in the LDAP "
1448 "operation cache. Zero means no limit. Defaults to 600 seconds (10 minutes)."),
1450 AP_INIT_TAKE1("LDAPTrustedCA", util_ldap_set_cert_auth, NULL, RSRC_CONF,
1451 "Sets the file containing the trusted Certificate Authority certificate. "
1452 "Used to validate the LDAP server certificate for SSL connections."),
1454 AP_INIT_TAKE1("LDAPTrustedCAType", util_ldap_set_cert_type, NULL, RSRC_CONF,
1455 "Specifies the type of the Certificate Authority file. "
1456 "The following types are supported: "
1457 " DER_FILE - file in binary DER format "
1458 " BASE64_FILE - file in Base64 format "
1459 " CERT7_DB_PATH - Netscape certificate database file "),
1463 static void util_ldap_register_hooks(apr_pool_t *p)
1465 ap_hook_post_config(util_ldap_post_config,NULL,NULL,APR_HOOK_MIDDLE);
1466 ap_hook_handler(util_ldap_handler, NULL, NULL, APR_HOOK_MIDDLE);
1467 ap_hook_child_init(util_ldap_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1470 module ldap_module = {
1471 STANDARD20_MODULE_STUFF,
1472 NULL, /* dir config creater */
1473 NULL, /* dir merger --- default is to override */
1474 util_ldap_create_config, /* server config */
1475 NULL, /* merge server config */
1476 util_ldap_cmds, /* command table */
1477 util_ldap_register_hooks, /* set up request processing hooks */