2 * This program is is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License, version 2 if the
4 * License as published by the Free Software Foundation.
6 * This program is distributed in the hope that it will be useful,
7 * but WITHOUT ANY WARRANTY; without even the implied warranty of
8 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 * GNU General Public License for more details.
11 * You should have received a copy of the GNU General Public License
12 * along with this program; if not, write to the Free Software
13 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 * @brief LDAP module library functions.
21 * @author Arran Cudbard-Bell <a.cudbardb@freeradius.org>
22 * @copyright 2013 Network RADIUS SARL <info@networkradius.com>
23 * @copyright 2013 The FreeRADIUS Server Project.
25 #include <freeradius-devel/radiusd.h>
26 #include <freeradius-devel/modules.h>
27 #include <freeradius-devel/rad_assert.h>
38 /** Converts "bad" strings into ones which are safe for LDAP
40 * This is a callback for xlat operations.
42 * Will escape any characters in input strings that would cause the string to be interpreted as part of a DN and or
43 * filter. Escape sequence is @verbatim \<hex><hex> @endverbatim
45 * @param request The current request.
46 * @param out Pointer to output buffer.
47 * @param outlen Size of the output buffer.
48 * @param in Raw unescaped string.
49 * @param arg Any additional arguments (unused).
51 size_t rlm_ldap_escape_func(UNUSED REQUEST *request, char *out, size_t outlen, char const *in, UNUSED void *arg)
53 static char const encode[] = ",+\"\\<>;*=()";
54 static char const hextab[] = "0123456789abcdef";
57 if (*in && ((*in == ' ') || (*in == '#'))) {
63 * Encode unsafe characters.
65 if (memchr(encode, *in, sizeof(encode) - 1)) {
69 * Only 3 or less bytes available.
74 *out++ = hextab[(*in >> 4) & 0x0f];
75 *out++ = hextab[*in & 0x0f];
85 * Doesn't need encoding
96 /** Check whether a string is a DN
98 * @param str to check.
99 * @return true if string is a DN, else false.
101 int rlm_ldap_is_dn(char const *str)
103 return strrchr(str, ',') == NULL ? false : true;
106 /** Find the place at which the two DN strings diverge
108 * Returns the length of the non matching string in full.
111 * @param part Partial DN as returned by ldap_parse_result.
112 * @return the length of the portion of full which wasn't matched or -1 on error.
114 static size_t rlm_ldap_common_dn(char const *full, char const *part)
116 size_t f_len, p_len, i;
122 f_len = strlen(full);
128 p_len = strlen(part);
133 if ((f_len < p_len) || !f_len) {
137 for (i = 0; i < p_len; i++) {
138 if (part[p_len - i] != full[f_len - i]) {
143 return f_len - p_len;
146 /** Combine and expand filters
148 * @param request Current request.
149 * @param out Where to write the expanded string.
150 * @param outlen Length of output buffer.
151 * @param sub Array of subfilters (may contain NULLs).
152 * @param sublen Number of potential subfilters in array.
153 * @return length of expanded data.
155 ssize_t rlm_ldap_xlat_filter(REQUEST *request, char const **sub, size_t sublen, char *out, size_t outlen)
157 char buffer[LDAP_MAX_FILTER_STR_LEN + 1];
158 char const *in = NULL;
167 * Figure out how many filter elements we need to integrate
169 for (i = 0; i < sublen; i++) {
170 if (sub[i] && *sub[i]) {
189 for (i = 0; i < sublen; i++) {
190 if (sub[i] && (*sub[i] != '\0')) {
191 len += strlcpy(p + len, sub[i], outlen - len);
193 if ((size_t) len >= outlen) {
195 REDEBUG("Out of buffer space creating filter");
202 if ((outlen - len) < 2) {
212 len = radius_xlat(out, outlen, request, in, rlm_ldap_escape_func, NULL);
214 REDEBUG("Failed creating filter");
222 /** Parse response from LDAP server dealing with any errors
224 * Should be called after an LDAP operation. Will check result of operation and if it was successful, then attempt
225 * to retrieve and parse the result.
227 * Will also produce extended error output including any messages the server sent, and information about partial
230 * @param[in] inst of LDAP module.
231 * @param[in] conn Current connection.
232 * @param[in] msgid returned from last operation.
233 * @param[in] dn Last search or bind DN.
234 * @param[out] result Where to write result, if NULL result will be freed.
235 * @param[out] error Where to write the error string, may be NULL, must not be freed.
236 * @param[out] extra Where to write additional error string to, may be NULL (faster) or must be freed
237 * (with talloc_free).
238 * @return One of the LDAP_PROC_* codes.
240 static ldap_rcode_t rlm_ldap_result(ldap_instance_t const *inst, ldap_handle_t const *conn, int msgid, char const *dn,
241 LDAPMessage **result, char const **error, char **extra)
243 ldap_rcode_t status = LDAP_PROC_SUCCESS;
245 int lib_errno = LDAP_SUCCESS; // errno returned by the library.
246 int srv_errno = LDAP_SUCCESS; // errno in the result message.
248 char *part_dn = NULL; // Partial DN match.
249 char *our_err = NULL; // Our extended error message.
250 char *srv_err = NULL; // Server's extended error message.
253 int freeit = false; // Whether the message should be freed after being processed.
256 struct timeval tv; // Holds timeout values.
258 LDAPMessage *tmp_msg; // Temporary message pointer storage if we weren't provided with one.
260 char const *tmp_err; // Temporary error pointer storage if we weren't provided with one.
272 * We always need the result, but our caller may not
282 * Check if there was an error sending the request
284 ldap_get_option(conn->handle, LDAP_OPT_ERROR_NUMBER,
286 if (lib_errno != LDAP_SUCCESS) {
290 memset(&tv, 0, sizeof(tv));
291 tv.tv_sec = inst->res_timeout;
294 * Now retrieve the result and check for errors
295 * ldap_result returns -1 on error, and 0 on timeout
297 lib_errno = ldap_result(conn->handle, msgid, 1, &tv, result);
298 if (lib_errno == 0) {
299 lib_errno = LDAP_TIMEOUT;
304 if (lib_errno == -1) {
305 ldap_get_option(conn->handle, LDAP_OPT_ERROR_NUMBER,
311 * Parse the result and check for errors sent by the server
313 lib_errno = ldap_parse_result(conn->handle, *result,
315 extra ? &part_dn : NULL,
316 extra ? &srv_err : NULL,
322 if (lib_errno != LDAP_SUCCESS) {
323 ldap_get_option(conn->handle, LDAP_OPT_ERROR_NUMBER,
330 if ((lib_errno == LDAP_SUCCESS) && (srv_errno != LDAP_SUCCESS)) {
331 lib_errno = srv_errno;
332 } else if ((lib_errno != LDAP_SUCCESS) && (srv_errno == LDAP_SUCCESS)) {
333 srv_errno = lib_errno;
342 case LDAP_NO_SUCH_OBJECT:
343 *error = "The specified DN wasn't found, check base_dn and identity";
345 status = LDAP_PROC_BAD_DN;
350 * Build our own internal diagnostic string
352 len = rlm_ldap_common_dn(dn, part_dn);
355 our_err = talloc_asprintf(conn, "Match stopped here: [%.*s]%s", len, dn, part_dn ? part_dn : "");
359 case LDAP_INSUFFICIENT_ACCESS:
360 *error = "Insufficient access. Check the identity and password configuration directives";
362 status = LDAP_PROC_NOT_PERMITTED;
365 case LDAP_UNWILLING_TO_PERFORM:
366 *error = "Server was unwilling to perform";
368 status = LDAP_PROC_NOT_PERMITTED;
372 exec_trigger(NULL, inst->cs, "modules.ldap.timeout", true);
374 *error = "Timed out while waiting for server to respond";
376 status = LDAP_PROC_ERROR;
379 case LDAP_FILTER_ERROR:
380 *error = "Bad search filter";
382 status = LDAP_PROC_ERROR;
385 case LDAP_TIMELIMIT_EXCEEDED:
386 exec_trigger(NULL, inst->cs, "modules.ldap.timeout", true);
388 *error = "Time limit exceeded";
392 case LDAP_UNAVAILABLE:
393 case LDAP_SERVER_DOWN:
394 status = LDAP_PROC_RETRY;
398 case LDAP_INVALID_CREDENTIALS:
399 case LDAP_CONSTRAINT_VIOLATION:
400 status = LDAP_PROC_REJECT;
404 case LDAP_OPERATIONS_ERROR:
405 *error = "Please set 'chase_referrals=yes' and 'rebind=yes'. See the ldap module configuration "
410 status = LDAP_PROC_ERROR;
415 *error = ldap_err2string(lib_errno);
418 if (!extra || ((lib_errno == srv_errno) && !our_err && !srv_err)) {
423 * Output the error codes from the library and server
425 p = talloc_zero_array(conn, char, 1);
428 if (lib_errno != srv_errno) {
429 a = talloc_asprintf_append(p, "LDAP lib error: %s (%u), srv error: %s (%u). ",
430 ldap_err2string(lib_errno), lib_errno,
431 ldap_err2string(srv_errno), srv_errno);
441 a = talloc_asprintf_append_buffer(p, "%s. ", our_err);
451 a = talloc_asprintf_append_buffer(p, "Server said: %s. ", srv_err);
469 ldap_memfree(srv_err);
473 ldap_memfree(part_dn);
477 talloc_free(our_err);
480 if ((lib_errno || srv_errno) && *result) {
481 ldap_msgfree(*result);
488 /** Bind to the LDAP directory as a user
490 * Performs a simple bind to the LDAP directory, and handles any errors that occur.
492 * @param[in] inst rlm_ldap configuration.
493 * @param[in] request Current request, this may be NULL, in which case all debug logging is done with radlog.
494 * @param[in,out] pconn to use. May change as this function calls functions which auto re-connect.
495 * @param[in] dn of the user, may be NULL to bind anonymously.
496 * @param[in] password of the user, may be NULL if no password is specified.
497 * @param[in] retry if the server is down.
498 * @return one of the LDAP_PROC_* values.
500 ldap_rcode_t rlm_ldap_bind(ldap_instance_t const *inst, REQUEST *request, ldap_handle_t **pconn, char const *dn,
501 char const *password, int retry)
507 char const *error = NULL;
510 rad_assert(*pconn && (*pconn)->handle);
513 * Bind as anonymous user
518 msgid = ldap_bind((*pconn)->handle, dn, password, LDAP_AUTH_SIMPLE);
519 /* We got a valid message ID */
522 RDEBUG2("Waiting for bind result...");
524 DEBUG2("rlm_ldap (%s): Waiting for bind result...", inst->xlat_name);
528 status = rlm_ldap_result(inst, *pconn, msgid, dn, NULL, &error, &extra);
530 case LDAP_PROC_SUCCESS:
531 LDAP_DBG_REQ("Bind successful");
533 case LDAP_PROC_NOT_PERMITTED:
534 LDAP_ERR_REQ("Bind was not permitted: %s", error);
539 case LDAP_PROC_REJECT:
540 LDAP_ERR_REQ("Bind credentials incorrect: %s", error);
545 case LDAP_PROC_RETRY:
547 *pconn = fr_connection_reconnect(inst->pool, *pconn);
549 LDAP_DBGW_REQ("Bind with %s to %s:%d failed: %s. Got new socket, retrying...",
550 dn, inst->server, inst->port, error);
552 talloc_free(extra); /* don't leak debug info */
558 status = LDAP_PROC_ERROR;
561 * Were not allowed to retry, or there are no more
562 * sockets, treat this as a hard failure.
566 #ifdef HAVE_LDAP_INITIALIZE
568 LDAP_ERR_REQ("Bind with %s to %s failed: %s", dn, inst->server, error);
572 LDAP_ERR_REQ("Bind with %s to %s:%d failed: %s", dn, inst->server,
584 return status; /* caller closes the connection */
588 /** Search for something in the LDAP directory
590 * Binds as the administrative user and performs a search, dealing with any errors.
592 * @param[in] inst rlm_ldap configuration.
593 * @param[in] request Current request.
594 * @param[in,out] pconn to use. May change as this function calls functions which auto re-connect.
595 * @param[in] dn to use as base for the search.
596 * @param[in] scope to use (LDAP_SCOPE_BASE, LDAP_SCOPE_ONE, LDAP_SCOPE_SUB).
597 * @param[in] filter to use, should be pre-escaped.
598 * @param[in] attrs to retrieve.
599 * @param[out] result Where to store the result. Must be freed with ldap_msgfree if LDAP_PROC_SUCCESS is returned.
600 * May be NULL in which case result will be automatically freed after use.
601 * @return One of the LDAP_PROC_* values.
603 ldap_rcode_t rlm_ldap_search(ldap_instance_t const *inst, REQUEST *request, ldap_handle_t **pconn,
604 char const *dn, int scope, char const *filter, char const * const *attrs,
605 LDAPMessage **result)
609 int msgid; // Message id returned by
612 int count = 0; // Number of results we got.
614 struct timeval tv; // Holds timeout values.
616 char const *error = NULL;
619 rad_assert(*pconn && (*pconn)->handle);
622 * OpenLDAP library doesn't declare attrs array as const, but
623 * it really should be *sigh*.
626 memcpy(&search_attrs, &attrs, sizeof(attrs));
629 * Do all searches as the admin user.
631 if ((*pconn)->rebound) {
632 status = rlm_ldap_bind(inst, request, pconn, inst->admin_dn, inst->password, true);
633 if (status != LDAP_PROC_SUCCESS) {
634 return LDAP_PROC_ERROR;
639 (*pconn)->rebound = false;
642 LDAP_DBG_REQ("Performing search in '%s' with filter '%s'", dn, filter);
645 * If LDAP search produced an error it should also be logged
646 * to the ld. result should pick it up without us
647 * having to pass it explicitly.
649 memset(&tv, 0, sizeof(tv));
650 tv.tv_sec = inst->res_timeout;
652 (void) ldap_search_ext((*pconn)->handle, dn, scope, filter, search_attrs, 0, NULL, NULL, &tv, 0, &msgid);
654 LDAP_DBG_REQ("Waiting for search result...");
655 status = rlm_ldap_result(inst, *pconn, msgid, dn, result, &error, &extra);
657 case LDAP_PROC_SUCCESS:
659 case LDAP_PROC_RETRY:
660 *pconn = fr_connection_reconnect(inst->pool, *pconn);
662 LDAP_DBGW_REQ("Search failed: %s. Got new socket, retrying...", error);
664 talloc_free(extra); /* don't leak debug info */
669 status = LDAP_PROC_ERROR;
673 LDAP_ERR_REQ("Failed performing search: %s", error);
674 if (extra) LDAP_ERR_REQ("%s", extra);
680 count = ldap_count_entries((*pconn)->handle, *result);
682 ldap_msgfree(*result);
685 LDAP_DBG_REQ("Search returned no results");
687 status = LDAP_PROC_NO_RESULT;
699 /** Modify something in the LDAP directory
701 * Binds as the administrative user and attempts to modify an LDAP object.
703 * @param[in] inst rlm_ldap configuration.
704 * @param[in] request Current request.
705 * @param[in,out] pconn to use. May change as this function calls functions which auto re-connect.
706 * @param[in] dn of the object to modify.
707 * @param[in] mods to make, see 'man ldap_modify' for more information.
708 * @return One of the LDAP_PROC_* values.
710 ldap_rcode_t rlm_ldap_modify(ldap_instance_t const *inst, REQUEST *request, ldap_handle_t **pconn,
711 char const *dn, LDAPMod *mods[])
715 int msgid; // Message id returned by ldap_search_ext.
717 char const *error = NULL;
720 rad_assert(*pconn && (*pconn)->handle);
723 * Perform all modifications as the admin user.
725 if ((*pconn)->rebound) {
726 status = rlm_ldap_bind(inst, request, pconn, inst->admin_dn, inst->password, true);
727 if (status != LDAP_PROC_SUCCESS) {
728 return LDAP_PROC_ERROR;
733 (*pconn)->rebound = false;
736 RDEBUG2("Modifying object with DN \"%s\"", dn);
738 (void) ldap_modify_ext((*pconn)->handle, dn, mods, NULL, NULL, &msgid);
740 RDEBUG2("Waiting for modify result...");
741 status = rlm_ldap_result(inst, *pconn, msgid, dn, NULL, &error, &extra);
743 case LDAP_PROC_SUCCESS:
745 case LDAP_PROC_RETRY:
746 *pconn = fr_connection_reconnect(inst->pool, *pconn);
748 RWDEBUG("Modify failed: %s. Got new socket, retrying...", error);
750 talloc_free(extra); /* don't leak debug info */
755 status = LDAP_PROC_ERROR;
759 REDEBUG("Failed modifying object: %s", error);
760 REDEBUG("%s", extra);
773 /** Retrieve the DN of a user object
775 * Retrieves the DN of a user and adds it to the control list as LDAP-UserDN. Will also retrieve any attributes
776 * passed and return the result in *result.
778 * This potentially allows for all authorization and authentication checks to be performed in one ldap search
779 * operation, which is a big bonus given the number of crappy, slow *cough*AD*cough* LDAP directory servers out there.
781 * @param[in] inst rlm_ldap configuration.
782 * @param[in] request Current request.
783 * @param[in,out] pconn to use. May change as this function calls functions which auto re-connect.
784 * @param[in] attrs Additional attributes to retrieve, may be NULL.
785 * @param[in] force Query even if the User-DN already exists.
786 * @param[out] result Where to write the result, may be NULL in which case result is discarded.
787 * @param[out] rcode The status of the operation, one of the RLM_MODULE_* codes.
788 * @return The user's DN or NULL on error.
790 char const *rlm_ldap_find_user(ldap_instance_t const *inst, REQUEST *request, ldap_handle_t **pconn,
791 char const *attrs[], int force, LDAPMessage **result, rlm_rcode_t *rcode)
793 static char const *tmp_attrs[] = { NULL };
796 VALUE_PAIR *vp = NULL;
797 LDAPMessage *tmp_msg = NULL, *entry = NULL;
800 char filter[LDAP_MAX_FILTER_STR_LEN];
801 char base_dn[LDAP_MAX_DN_STR_LEN];
803 int freeit = false; //!< Whether the message should
804 //!< be freed after being processed.
806 *rcode = RLM_MODULE_FAIL;
815 memset(&attrs, 0, sizeof(tmp_attrs));
819 * If the caller isn't looking for the result we can just return the current userdn value.
822 vp = pairfind(request->config_items, PW_LDAP_USERDN, 0, TAG_ANY);
824 RDEBUG("Using user DN from request \"%s\"", vp->vp_strvalue);
825 *rcode = RLM_MODULE_OK;
826 return vp->vp_strvalue;
831 * Perform all searches as the admin user.
833 if ((*pconn)->rebound) {
834 status = rlm_ldap_bind(inst, request, pconn, inst->admin_dn, inst->password, true);
835 if (status != LDAP_PROC_SUCCESS) {
836 *rcode = RLM_MODULE_FAIL;
842 (*pconn)->rebound = false;
845 if (radius_xlat(filter, sizeof(filter), request, inst->userobj_filter, rlm_ldap_escape_func, NULL) < 0) {
846 REDEBUG("Unable to create filter");
848 *rcode = RLM_MODULE_INVALID;
852 if (radius_xlat(base_dn, sizeof(base_dn), request, inst->userobj_base_dn, rlm_ldap_escape_func, NULL) < 0) {
853 REDEBUG("Unable to create base_dn");
855 *rcode = RLM_MODULE_INVALID;
859 status = rlm_ldap_search(inst, request, pconn, base_dn, inst->userobj_scope, filter, attrs, result);
861 case LDAP_PROC_SUCCESS:
863 case LDAP_PROC_NO_RESULT:
864 *rcode = RLM_MODULE_NOTFOUND;
867 *rcode = RLM_MODULE_FAIL;
873 entry = ldap_first_entry((*pconn)->handle, *result);
875 ldap_get_option((*pconn)->handle, LDAP_OPT_RESULT_CODE, &ldap_errno);
876 REDEBUG("Failed retrieving entry: %s",
877 ldap_err2string(ldap_errno));
882 dn = ldap_get_dn((*pconn)->handle, entry);
884 ldap_get_option((*pconn)->handle, LDAP_OPT_RESULT_CODE, &ldap_errno);
886 REDEBUG("Retrieving object DN from entry failed: %s",
887 ldap_err2string(ldap_errno));
892 RDEBUG("User object found at DN \"%s\"", dn);
893 vp = pairmake(request, &request->config_items, "LDAP-UserDN", dn, T_OP_EQ);
895 *rcode = RLM_MODULE_OK;
901 if ((freeit || (*rcode != RLM_MODULE_OK)) && *result) {
902 ldap_msgfree(*result);
906 return vp ? vp->vp_strvalue : NULL;
909 /** Check for presence of access attribute in result
911 * @param[in] inst rlm_ldap configuration.
912 * @param[in] request Current request.
913 * @param[in] conn used to retrieve access attributes.
914 * @param[in] entry retrieved by rlm_ldap_find_user or rlm_ldap_search.
915 * @return RLM_MODULE_USERLOCK if the user was denied access, else RLM_MODULE_OK.
917 rlm_rcode_t rlm_ldap_check_access(ldap_instance_t const *inst, REQUEST *request,
918 ldap_handle_t const *conn, LDAPMessage *entry)
920 rlm_rcode_t rcode = RLM_MODULE_OK;
923 vals = ldap_get_values(conn->handle, entry, inst->userobj_access_attr);
925 if (inst->access_positive && (strncmp(vals[0], "false", 5) == 0)) {
926 RDEBUG("\"%s\" attribute exists but is set to 'false' - user locked out");
927 rcode = RLM_MODULE_USERLOCK;
929 RDEBUG("\"%s\" attribute exists - user locked out", inst->userobj_access_attr);
930 rcode = RLM_MODULE_USERLOCK;
933 ldap_value_free(vals);
934 } else if (inst->access_positive) {
935 RDEBUG("No \"%s\" attribute - user locked out", inst->userobj_access_attr);
936 rcode = RLM_MODULE_USERLOCK;
942 /** Verify we got a password from the search
944 * Checks to see if after the LDAP to RADIUS mapping has been completed that a reference password.
946 * @param inst rlm_ldap configuration.
947 * @param request Current request.
949 void rlm_ldap_check_reply(ldap_instance_t const *inst, REQUEST *request)
952 * More warning messages for people who can't be bothered to read the documentation.
954 * Expect_password is set when we process the mapping, and is only true if there was a mapping between
955 * an LDAP attribute and a password reference attribute in the control list.
957 if (inst->expect_password && (debug_flag > 1)) {
958 if (!pairfind(request->config_items, PW_CLEARTEXT_PASSWORD, 0, TAG_ANY) &&
959 !pairfind(request->config_items, PW_NT_PASSWORD, 0, TAG_ANY) &&
960 !pairfind(request->config_items, PW_USER_PASSWORD, 0, TAG_ANY) &&
961 !pairfind(request->config_items, PW_PASSWORD_WITH_HEADER, 0, TAG_ANY) &&
962 !pairfind(request->config_items, PW_CRYPT_PASSWORD, 0, TAG_ANY)) {
963 RWDEBUG("No \"reference\" password added. Ensure the admin user has permission to "
964 "read the password attribute");
965 RWDEBUG("PAP authentication will *NOT* work with Active Directory (if that is what you "
966 "were trying to configure)");
971 #if LDAP_SET_REBIND_PROC_ARGS == 3
972 /** Callback for OpenLDAP to rebind and chase referrals
974 * Called by OpenLDAP when it receives a referral and has to rebind.
976 * @param handle to rebind.
977 * @param url to bind to.
978 * @param request that triggered the rebind.
979 * @param msgid that triggered the rebind.
980 * @param ctx rlm_ldap configuration.
982 static int rlm_ldap_rebind(LDAP *handle, LDAP_CONST char *url, UNUSED ber_tag_t request, UNUSED ber_int_t msgid,
986 ldap_handle_t *conn = ctx;
990 conn->referred = true;
991 conn->rebound = true; /* not really, but oh well... */
992 rad_assert(handle == conn->handle);
994 DEBUG("rlm_ldap (%s): Rebinding to URL %s", conn->inst->xlat_name, url);
996 status = rlm_ldap_bind(conn->inst, NULL, &conn, conn->inst->admin_dn, conn->inst->password, false);
997 if (status != LDAP_PROC_SUCCESS) {
998 ldap_get_option(handle, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
1004 return LDAP_SUCCESS;
1008 /** Create and return a new connection
1010 * Create a new ldap connection and allocate memory for a new rlm_handle_t
1012 * @param instance rlm_ldap instance.
1013 * @return A new connection handle or NULL on error.
1015 void *mod_conn_create(void *instance)
1017 ldap_rcode_t status;
1019 int ldap_errno, ldap_version;
1022 ldap_instance_t *inst = instance;
1023 LDAP *handle = NULL;
1024 ldap_handle_t *conn = NULL;
1026 #ifdef HAVE_LDAP_INITIALIZE
1028 DEBUG("rlm_ldap (%s): Connecting to %s", inst->xlat_name, inst->server);
1030 ldap_errno = ldap_initialize(&handle, inst->server);
1031 if (ldap_errno != LDAP_SUCCESS) {
1032 LDAP_ERR("ldap_initialize failed: %s", ldap_err2string(ldap_errno));
1038 DEBUG("rlm_ldap (%s): Connecting to %s:%d", inst->xlat_name, inst->server, inst->port);
1040 handle = ldap_init(inst->server, inst->port);
1042 LDAP_ERR("ldap_init() failed");
1048 * We now have a connection structure, but no actual TCP connection.
1050 * Set a bunch of LDAP options, using common code.
1052 #define do_ldap_option(_option, _name, _value) \
1053 if (ldap_set_option(handle, _option, _value) != LDAP_OPT_SUCCESS) { \
1054 ldap_get_option(handle, LDAP_OPT_ERROR_NUMBER, &ldap_errno); \
1055 LDAP_ERR("Could not set %s: %s", _name, ldap_err2string(ldap_errno)); \
1058 if (inst->ldap_debug) {
1059 do_ldap_option(LDAP_OPT_DEBUG_LEVEL, "ldap_debug", &(inst->ldap_debug));
1063 * Leave "chase_referrals" unset to use the OpenLDAP default.
1065 if (inst->chase_referrals != 2) {
1066 if (inst->chase_referrals) {
1067 do_ldap_option(LDAP_OPT_REFERRALS, "chase_referrals", LDAP_OPT_ON);
1069 if (inst->rebind == true) {
1070 #if LDAP_SET_REBIND_PROC_ARGS == 3
1071 ldap_set_rebind_proc(handle, rlm_ldap_rebind, inst);
1075 do_ldap_option(LDAP_OPT_REFERRALS, "chase_referrals", LDAP_OPT_OFF);
1079 memset(&tv, 0, sizeof(tv));
1080 tv.tv_sec = inst->net_timeout;
1082 do_ldap_option(LDAP_OPT_NETWORK_TIMEOUT, "net_timeout", &tv);
1084 do_ldap_option(LDAP_OPT_TIMELIMIT, "srv_timelimit", &(inst->srv_timelimit));
1086 ldap_version = LDAP_VERSION3;
1087 do_ldap_option(LDAP_OPT_PROTOCOL_VERSION, "ldap_version", &ldap_version);
1089 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
1090 do_ldap_option(LDAP_OPT_X_KEEPALIVE_IDLE, "keepalive idle", &(inst->keepalive_idle));
1093 #ifdef LDAP_OPT_X_KEEPALIVE_PROBES
1094 do_ldap_option(LDAP_OPT_X_KEEPALIVE_PROBES, "keepalive probes", &(inst->keepalive_probes));
1097 #ifdef LDAP_OPT_X_KEEPALIVE_INTERVAL
1098 do_ldap_option(LDAP_OPT_X_KEEPALIVE_INTERVAL, "keepalive interval", &(inst->keepalive_interval));
1101 #ifdef HAVE_LDAP_START_TLS
1103 * Set all of the TLS options
1106 # ifdef LDAP_OPT_X_TLS_NEWCTX
1108 /* Always use the new TLS configuration context */
1110 do_ldap_option(LDAP_OPT_X_TLS_NEWCTX, "new TLS context", &is_server);
1115 if (inst->tls_mode) {
1116 do_ldap_option(LDAP_OPT_X_TLS, "tls_mode", &(inst->tls_mode));
1119 # define maybe_ldap_option(_option, _name, _value) \
1120 if (_value) do_ldap_option(_option, _name, _value)
1122 maybe_ldap_option(LDAP_OPT_X_TLS_CACERTFILE, "cacertfile", inst->tls_cacertfile);
1123 maybe_ldap_option(LDAP_OPT_X_TLS_CACERTDIR, "cacertdir", inst->tls_cacertdir);
1127 * Set certificate options
1129 maybe_ldap_option(LDAP_OPT_X_TLS_CERTFILE, "certfile", inst->tls_certfile);
1130 maybe_ldap_option(LDAP_OPT_X_TLS_KEYFILE, "keyfile", inst->tls_keyfile);
1131 maybe_ldap_option(LDAP_OPT_X_TLS_RANDOM_FILE, "randfile", inst->tls_randfile);
1133 # ifdef LDAP_OPT_X_TLS_NEVER
1134 if (inst->tls_require_cert_str) {
1135 do_ldap_option(LDAP_OPT_X_TLS_REQUIRE_CERT, "tls_require_cert", &inst->tls_require_cert);
1140 * And finally start the TLS code.
1142 if (inst->start_tls) {
1143 if (inst->port == 636) {
1144 WDEBUG("Told to Start TLS on LDAPS port this will probably fail, please correct the "
1148 if (ldap_start_tls_s(handle, NULL, NULL) != LDAP_SUCCESS) {
1149 ldap_get_option(handle, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
1151 LDAP_ERR("Could not start TLS: %s", ldap_err2string(ldap_errno));
1155 #endif /* HAVE_LDAP_START_TLS */
1158 * Allocate memory for the handle.
1160 conn = talloc_zero(instance, ldap_handle_t);
1162 conn->handle = handle;
1163 conn->rebound = false;
1164 conn->referred = false;
1166 status = rlm_ldap_bind(inst, NULL, &conn, inst->admin_dn, inst->password, false);
1167 if (status != LDAP_PROC_SUCCESS) {
1174 if (handle) ldap_unbind_s(handle);
1175 if (conn) talloc_free(conn);
1181 /** Close and delete a connection
1183 * Unbinds the LDAP connection, informing the server and freeing any memory, then releases the memory used by the
1184 * connection handle.
1186 * @param instance rlm_ldap instance.
1187 * @param handle to destroy.
1188 * @return always indicates success.
1190 int mod_conn_delete(UNUSED void *instance, void *handle)
1192 ldap_handle_t *conn = handle;
1194 ldap_unbind_s(conn->handle);
1201 /** Gets an LDAP socket from the connection pool
1203 * Retrieve a socket from the connection pool, or NULL on error (of if no sockets are available).
1205 * @param inst rlm_ldap configuration.
1206 * @param request Current request (may be NULL).
1208 ldap_handle_t *rlm_ldap_get_socket(ldap_instance_t const *inst, REQUEST *request)
1210 ldap_handle_t *conn;
1212 conn = fr_connection_get(inst->pool);
1214 REDEBUG("All ldap connections are in use");
1223 /** Frees an LDAP socket back to the connection pool
1225 * If the socket was rebound chasing a referral onto another server then we destroy it.
1226 * If the socket was rebound to another user on the same server, we let the next caller rebind it.
1228 * @param inst rlm_ldap configuration.
1229 * @param conn to release.
1231 void rlm_ldap_release_socket(ldap_instance_t const *inst, ldap_handle_t *conn)
1234 * Could have already been free'd due to a previous error.
1239 * We chased a referral to another server.
1241 * This connection is no longer part of the pool which is connected to and bound to the configured server.
1244 * Note that we do NOT close it if it was bound to another user. Instead, we let the next caller do the
1247 if (conn->referred) {
1248 fr_connection_del(inst->pool, conn);
1252 fr_connection_release(inst->pool, conn);