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, const char *in, UNUSED void *arg)
53 static const char encode[] = ",+\"\\<>;*=()";
54 static const char 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(const char *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(const char *full, const char *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) {
138 for (i = 0; i < p_len; i++) {
139 if (part[p_len - i] != full[f_len - i]) {
144 return f_len - p_len;
147 /** Parse response from LDAP server dealing with any errors
149 * Should be called after an LDAP operation. Will check result of operation and if it was successful, then attempt
150 * to retrieve and parse the result.
152 * Will also produce extended error output including any messages the server sent, and information about partial
155 * @param[in] inst of LDAP module.
156 * @param[in] conn Current connection.
157 * @param[in] msgid returned from last operation.
158 * @param[in] dn Last search or bind DN.
159 * @param[out] result Where to write result, if NULL result will be freed.
160 * @param[out] error Where to write the error string, may be NULL, must not be freed.
161 * @param[out] extra Where to write additional error string to, may be NULL (faster) or must be freed
162 * (with talloc_free).
163 * @return One of the LDAP_PROC_* codes.
165 static ldap_rcode_t rlm_ldap_result(const ldap_instance_t *inst, const ldap_handle_t *conn, int msgid, const char *dn,
166 LDAPMessage **result, const char **error, char **extra)
168 ldap_rcode_t status = LDAP_PROC_SUCCESS;
170 int lib_errno = LDAP_SUCCESS; //!< errno returned by the library.
171 int srv_errno = LDAP_SUCCESS; //!< errno in the result message.
173 char *part_dn = NULL; //!< Partial DN match.
174 char *our_err = NULL; //!< Our extended error message.
175 char *srv_err = NULL; //!< Server's extended error message.
178 int freeit = FALSE; //!< Whether the message should
179 //!< be freed after being processed.
182 struct timeval tv; //!< Holds timeout values.
184 LDAPMessage *tmp_msg; //!< Temporary message pointer storage
185 //!< if we weren't provided with one.
187 const char *tmp_err; //!< Temporary error pointer storage
188 //!< if we weren't provided with one.
200 * We always need the result, but our caller may not
208 * Check if there was an error sending the request
210 ldap_get_option(conn->handle, LDAP_OPT_ERROR_NUMBER,
212 if (lib_errno != LDAP_SUCCESS) {
216 tv.tv_sec = inst->timeout;
220 * Now retrieve the result and check for errors
221 * ldap_result returns -1 on error, and 0 on timeout
223 lib_errno = ldap_result(conn->handle, msgid, 1, &tv, result);
224 if (lib_errno == 0) {
225 lib_errno = LDAP_TIMEOUT;
230 if (lib_errno == -1) {
231 ldap_get_option(conn->handle, LDAP_OPT_ERROR_NUMBER,
237 * Parse the result and check for errors sent by the server
239 lib_errno = ldap_parse_result(conn->handle, *result,
241 extra ? &part_dn : NULL,
242 extra ? extra : NULL,
245 if (lib_errno != LDAP_SUCCESS) {
246 ldap_get_option(conn->handle, LDAP_OPT_ERROR_NUMBER,
253 if ((lib_errno == LDAP_SUCCESS) && (srv_errno != LDAP_SUCCESS)) {
254 lib_errno = srv_errno;
255 } else if ((lib_errno != LDAP_SUCCESS) && (srv_errno == LDAP_SUCCESS)) {
256 srv_errno = lib_errno;
265 case LDAP_NO_SUCH_OBJECT:
266 *error = "The specified object wasn't found, check basedn and admin dn";
268 status = LDAP_PROC_BAD_DN;
273 * Build our own internal diagnostic string
275 len = rlm_ldap_common_dn(dn, part_dn);
278 our_err = talloc_asprintf(conn, "Match stopped here: [%.*s]%s", len, part_dn, part_dn ? part_dn : "");
282 case LDAP_INSUFFICIENT_ACCESS:
283 *error = "Insufficient access. Check the identity and password configuration directives";
285 status = LDAP_PROC_NOT_PERMITTED;
288 case LDAP_UNWILLING_TO_PERFORM:
289 *error = "Server was unwilling to perform";
291 status = LDAP_PROC_NOT_PERMITTED;
295 exec_trigger(NULL, inst->cs, "modules.ldap.timeout", TRUE);
297 *error = "Timed out while waiting for server to respond";
299 status = LDAP_PROC_ERROR;
302 case LDAP_FILTER_ERROR:
303 *error = "Bad search filter";
305 status = LDAP_PROC_ERROR;
308 case LDAP_TIMELIMIT_EXCEEDED:
309 exec_trigger(NULL, inst->cs, "modules.ldap.timeout", TRUE);
311 *error = "Time limit exceeded";
315 case LDAP_UNAVAILABLE:
316 case LDAP_SERVER_DOWN:
317 status = LDAP_PROC_RETRY;
321 case LDAP_INVALID_CREDENTIALS:
322 case LDAP_CONSTRAINT_VIOLATION:
323 status = LDAP_PROC_REJECT;
327 case LDAP_OPERATIONS_ERROR:
328 *error = "Please set 'chase_referrals=yes' and 'rebind=yes'. See the ldap module configuration "
333 status = LDAP_PROC_ERROR;
338 *error = ldap_err2string(lib_errno);
341 if (!extra || ((lib_errno == srv_errno) && !our_err && !srv_err)) {
346 * Output the error codes from the library and server
348 p = talloc_strdup(conn, "");
351 if (lib_errno != srv_errno) {
352 a = talloc_asprintf_append(p, "LDAP lib error: %s (%u), srv error: %s (%u)",
353 ldap_err2string(lib_errno), lib_errno,
354 ldap_err2string(srv_errno), srv_errno);
364 a = talloc_asprintf_append_buffer(p,". %s", our_err);
374 a = talloc_asprintf_append_buffer(p, ". Server said: %s", srv_err);
392 ldap_memfree(srv_err);
396 ldap_memfree(part_dn);
400 talloc_free(our_err);
403 if ((lib_errno || srv_errno) && *result) {
404 ldap_msgfree(*result);
411 /** Bind to the LDAP directory as a user
413 * Performs a simple bind to the LDAP directory, and handles any errors that
416 * @param inst rlm_ldap configuration.
417 * @param request Current request, this may be NULL, in which case all debug logging is done with radlog.
418 * @param pconn to use. May change as this function auto re-connects. Caller must check that pconn is not NULL after
419 * calling this function.
420 * @param dn The DN of the user, may be NULL to bind anonymously.
421 * @param password May be NULL if no password is specified.
422 * @param retry if the server is down.
423 * @return one of the RLM_MODULE_* values.
425 rlm_rcode_t rlm_ldap_bind(const ldap_instance_t *inst, REQUEST *request, ldap_handle_t **pconn, const char *dn,
426 const char *password, int retry)
428 rlm_rcode_t rcode = RLM_MODULE_OK;
433 const char *error = NULL;
437 * Bind as anonymous user
442 msgid = ldap_bind((*pconn)->handle, dn, password, LDAP_AUTH_SIMPLE);
443 /* We got a valid message ID */
446 RDEBUG2("Waiting for bind result...");
448 DEBUG2("rlm_ldap (%s): Waiting for bind result...", inst->xlat_name);
452 status = rlm_ldap_result(inst, *pconn, msgid, dn, NULL, &error, &extra);
454 case LDAP_PROC_SUCCESS:
456 case LDAP_PROC_NOT_PERMITTED:
457 rcode = RLM_MODULE_USERLOCK;
459 LDAP_ERR_REQ("Bind was not permitted: %s", error);
464 case LDAP_PROC_REJECT:
465 rcode = RLM_MODULE_REJECT;
467 LDAP_ERR_REQ("Bind credentials incorrect: %s", error);
472 case LDAP_PROC_RETRY:
474 *pconn = fr_connection_reconnect(inst->pool, *pconn);
476 LDAP_DBGW_REQ("Bind with %s to %s:%d failed: %s. Got new socket, retrying...",
477 dn, inst->server, inst->port, error);
479 talloc_free(extra); /* don't leak debug info */
486 * Were not allowed to retry, or there are no more
487 * sockets, treat this as a hard failure.
492 rcode = RLM_MODULE_FAIL;
493 #ifdef HAVE_LDAP_INITIALIZE
495 LDAP_ERR_REQ("Bind with %s to %s failed: %s", dn, inst->server, error);
499 LDAP_ERR_REQ("Bind with %s to %s:%d failed: %s", dn, inst->server,
507 if (extra) talloc_free(extra);
509 return rcode; /* caller closes the connection */
513 /** Search for something in the LDAP directory
515 * Binds as the administrative user and performs a search, dealing with any
518 * @param inst rlm_ldap configuration.
519 * @param request Current request.
520 * @param pconn to use. May change as this function auto re-connects. Caller must check that pconn is not NULL
521 * after calling this function.
523 * @param scope to use.
524 * @param filter to use.
525 * @param attrs to retrieve.
526 * @param result Where to store the result. Must be freed with ldap_msgfree.
527 * may be NULL in which case result will be automatically freed after use.
528 * @return One of the LDAP_PROC_* values.
530 ldap_rcode_t rlm_ldap_search(const ldap_instance_t *inst, REQUEST *request, ldap_handle_t **pconn,
531 const char *dn, int scope, const char *filter, const char * const *attrs,
532 LDAPMessage **result)
536 int msgid; //!< Message id returned by
537 //!< ldap_search_ext.
539 int count = 0; //!< Number of results we got.
541 struct timeval tv; //!< Holds timeout values.
543 const char *error = NULL;
547 * OpenLDAP library doesn't declare attrs array as const, but
548 * it really should be *sigh*.
551 memcpy(&search_attrs, &attrs, sizeof(attrs));
554 * Do all searches as the admin user.
556 if ((*pconn)->rebound) {
557 if (rlm_ldap_bind(inst, request, pconn, inst->login, inst->password, TRUE) != RLM_MODULE_OK) {
558 return LDAP_PROC_ERROR;
563 (*pconn)->rebound = FALSE;
566 RDEBUG2("Performing search in '%s' with filter '%s'", dn, filter);
569 * If LDAP search produced an error it should also be logged
570 * to the ld. result should pick it up without us
571 * having to pass it explicitly.
573 tv.tv_sec = inst->timeout;
576 (void) ldap_search_ext((*pconn)->handle, dn, scope, filter, search_attrs, 0, NULL, NULL, &tv, 0, &msgid);
578 RDEBUG2("Waiting for search result...");
579 status = rlm_ldap_result(inst, *pconn, msgid, dn, result, &error, &extra);
581 case LDAP_PROC_SUCCESS:
583 case LDAP_PROC_RETRY:
584 *pconn = fr_connection_reconnect(inst->pool, *pconn);
586 RDEBUGW("Search failed: %s. Got new socket, retrying...", error);
588 talloc_free(extra); /* don't leak debug info */
593 status = LDAP_PROC_ERROR;
597 RDEBUGE("Failed performing search: %s", error);
598 RDEBUGE("%s", extra);
604 count = ldap_count_entries((*pconn)->handle, *result);
606 ldap_msgfree(*result);
609 RDEBUG("Search returned no results");
611 status = LDAP_PROC_NO_RESULT;
616 if (extra) talloc_free(extra);
621 /** Modify something in the LDAP directory
623 * Binds as the administrative user and attempts to modify an LDAP object.
625 * @param inst rlm_ldap configuration.
626 * @param request Current request.
627 * @param pconn to use. May change as this function auto re-connects. Caller must check that pconn is not NULL after
628 * calling this function.
629 * @param dn to modify.
630 * @param mods to make.
631 * @return One of the LDAP_PROC_* values.
633 ldap_rcode_t rlm_ldap_modify(const ldap_instance_t *inst, REQUEST *request, ldap_handle_t **pconn,
634 const char *dn, LDAPMod *mods[])
638 int msgid; //!< Message id returned by
639 //!< ldap_search_ext.
641 const char *error = NULL;
645 * Perform all modifications as the admin user.
647 if ((*pconn)->rebound) {
648 if (rlm_ldap_bind(inst, request, pconn, inst->login, inst->password, TRUE) != RLM_MODULE_OK) {
649 return LDAP_PROC_ERROR;
654 (*pconn)->rebound = FALSE;
657 RDEBUG2("Modifying object with DN \"%s\"", dn);
659 (void) ldap_modify_ext((*pconn)->handle, dn, mods, NULL, NULL, &msgid);
661 RDEBUG2("Waiting for modify result...");
662 status = rlm_ldap_result(inst, *pconn, msgid, dn, NULL, &error, &extra);
664 case LDAP_PROC_SUCCESS:
666 case LDAP_PROC_RETRY:
667 *pconn = fr_connection_reconnect(inst->pool, *pconn);
669 RDEBUGW("Modify failed: %s. Got new socket, retrying...", error);
671 talloc_free(extra); /* don't leak debug info */
676 status = LDAP_PROC_ERROR;
680 RDEBUGE("Failed modifying object: %s", error);
681 RDEBUGE("%s", extra);
687 if (extra) talloc_free(extra);
692 /** Retrieve the DN of a user object
694 * Retrieves the DN of a user and adds it to the control list as LDAP-UserDN. Will also retrieve any attributes
695 * passed and return the result in *result.
697 * This potentially allows for all authorization and authentication checks to be performed in one ldap search
698 * operation, which is a big bonus given the number of crappy, slow *cough*AD*cough* LDAP directory servers out there.
700 * @param[in] inst rlm_ldap configuration.
701 * @param[in] request Current request.
702 * @param[in,out] pconn to use. May change as this function auto re-connects. Caller must check that pconn is not NULL
703 * after calling this function.
704 * @param[in] attrs Additional attributes to retrieve, may be NULL.
705 * @param[in] force Query even if the User-DN already exists.
706 * @param[out] result Where to write the result, may be NULL in which case result is discarded.
707 * @param[out] rcode The status of the operation, one of the RLM_MODULE_* codes.
708 * @return The user's DN or NULL on error.
710 const char *rlm_ldap_find_user(const ldap_instance_t *inst, REQUEST *request, ldap_handle_t **pconn,
711 const char *attrs[], int force, LDAPMessage **result, rlm_rcode_t *rcode)
713 static const char *tmp_attrs[] = { NULL };
716 VALUE_PAIR *vp = NULL;
717 LDAPMessage *tmp_msg = NULL, *entry = NULL;
720 char filter[LDAP_MAX_FILTER_STR_LEN];
721 char basedn[LDAP_MAX_FILTER_STR_LEN];
723 int freeit = FALSE; //!< Whether the message should
724 //!< be freed after being processed.
726 *rcode = RLM_MODULE_FAIL;
735 memset(&attrs, 0, sizeof(tmp_attrs));
739 * If the caller isn't looking for the result we can just return the current userdn value.
742 vp = pairfind(request->config_items, PW_LDAP_USERDN, 0, TAG_ANY);
744 RDEBUG("Using user DN from request \"%s\"", vp->vp_strvalue);
745 *rcode = RLM_MODULE_OK;
746 return vp->vp_strvalue;
751 * Perform all searches as the admin user.
753 if ((*pconn)->rebound) {
754 if (rlm_ldap_bind(inst, request, pconn, inst->login, inst->password, TRUE) != RLM_MODULE_OK) {
755 *rcode = RLM_MODULE_FAIL;
761 (*pconn)->rebound = FALSE;
765 if (!radius_xlat(filter, sizeof(filter), inst->filter, request, rlm_ldap_escape_func, NULL)) {
766 RDEBUGE("Unable to create filter");
768 *rcode = RLM_MODULE_INVALID;
772 if (!radius_xlat(basedn, sizeof(basedn), inst->basedn, request, rlm_ldap_escape_func, NULL)) {
773 RDEBUGE("Unable to create basedn");
775 *rcode = RLM_MODULE_INVALID;
779 status = rlm_ldap_search(inst, request, pconn, basedn, LDAP_SCOPE_SUBTREE, filter, attrs, result);
781 case LDAP_PROC_SUCCESS:
783 case LDAP_PROC_NO_RESULT:
784 *rcode = RLM_MODULE_NOTFOUND;
787 *rcode = RLM_MODULE_FAIL;
793 entry = ldap_first_entry((*pconn)->handle, *result);
795 ldap_get_option((*pconn)->handle, LDAP_OPT_RESULT_CODE, &ldap_errno);
796 RDEBUGE("Failed retrieving entry: %s",
797 ldap_err2string(ldap_errno));
802 dn = ldap_get_dn((*pconn)->handle, entry);
804 ldap_get_option((*pconn)->handle, LDAP_OPT_RESULT_CODE, &ldap_errno);
806 RDEBUGE("Retrieving object DN from entry failed: %s",
807 ldap_err2string(ldap_errno));
812 RDEBUG("User object found at DN \"%s\"", dn);
813 vp = pairmake(request, &request->config_items, "LDAP-UserDn", dn, T_OP_EQ);
815 *rcode = RLM_MODULE_OK;
821 if ((freeit || (*rcode != RLM_MODULE_OK)) && *result) {
822 ldap_msgfree(*result);
826 return vp ? vp->vp_strvalue : NULL;
829 rlm_rcode_t rlm_ldap_apply_profile(const ldap_instance_t *inst, REQUEST *request, ldap_handle_t **pconn,
830 const char *profile, const rlm_ldap_map_xlat_t *expanded)
832 rlm_rcode_t rcode = RLM_MODULE_OK;
834 LDAPMessage *result = NULL, *entry = NULL;
836 LDAP *handle = (*pconn)->handle;
837 char filter[LDAP_MAX_FILTER_STR_LEN];
839 if (!profile || !*profile) {
840 return RLM_MODULE_NOOP;
842 strlcpy(filter, inst->base_filter, sizeof(filter));
844 status = rlm_ldap_search(inst, request, pconn, profile, LDAP_SCOPE_BASE, filter, expanded->attrs, &result);
846 case LDAP_PROC_SUCCESS:
848 case LDAP_PROC_NO_RESULT:
849 RDEBUG("Profile \"%s\" not found", profile);
850 return RLM_MODULE_NOTFOUND;
852 return RLM_MODULE_FAIL;
858 entry = ldap_first_entry(handle, result);
860 ldap_get_option(handle, LDAP_OPT_RESULT_CODE, &ldap_errno);
861 RDEBUGE("Failed retrieving entry: %s", ldap_err2string(ldap_errno));
863 rcode = RLM_MODULE_NOTFOUND;
868 rlm_ldap_map_do(inst, request, handle, expanded, entry);
871 ldap_msgfree(result);
876 /** Check for presence of access attribute in result
878 * @param inst rlm_ldap configuration.
879 * @param request Current request.
880 * @param conn used to retrieve entry.
881 * @param entry retrieved by rlm_ldap_find_user or rlm_ldap_search.
882 * @return RLM_MODULE_USERLOCK if the user was denied access, else RLM_MODULE_OK.
884 rlm_rcode_t rlm_ldap_check_access(const ldap_instance_t *inst, REQUEST *request, const ldap_handle_t *conn,
887 rlm_rcode_t rcode = RLM_MODULE_OK;
890 vals = ldap_get_values(conn->handle, entry, inst->userobj_access_attr);
892 if (inst->access_positive && (strncmp(vals[0], "FALSE", 5) == 0)) {
893 RDEBUG("\"%s\" attribute exists but is set to 'false' - user locked out");
894 rcode = RLM_MODULE_USERLOCK;
896 RDEBUG("\"%s\" attribute exists - user locked out", inst->userobj_access_attr);
897 rcode = RLM_MODULE_USERLOCK;
900 ldap_value_free(vals);
901 } else if (inst->access_positive) {
902 RDEBUG("No \"%s\" attribute - user locked out", inst->userobj_access_attr);
903 rcode = RLM_MODULE_USERLOCK;
909 /** Verify we got a password from the search
911 * Checks to see if after the LDAP to RADIUS mapping has been completed that a reference password.
913 * @param inst rlm_ldap configuration.
914 * @param request Current request.
916 void rlm_ldap_check_reply(const ldap_instance_t *inst, REQUEST *request)
919 * More warning messages for people who can't be bothered to read the documentation.
921 * Expect_password is set when we process the mapping, and is only true if there was a mapping between
922 * an LDAP attribute and a password reference attribute in the control list.
924 if (inst->expect_password && (debug_flag > 1)) {
925 if (!pairfind(request->config_items, PW_CLEARTEXT_PASSWORD, 0, TAG_ANY) &&
926 !pairfind(request->config_items, PW_NT_PASSWORD, 0, TAG_ANY) &&
927 !pairfind(request->config_items, PW_USER_PASSWORD, 0, TAG_ANY) &&
928 !pairfind(request->config_items, PW_PASSWORD_WITH_HEADER, 0, TAG_ANY) &&
929 !pairfind(request->config_items, PW_CRYPT_PASSWORD, 0, TAG_ANY)) {
930 RDEBUGW("No \"reference\" password added. Ensure the admin user has permission to "
931 "read the password attribute");
932 RDEBUGW("PAP authentication will *NOT* work with Active Directory (if that is what you "
933 "were trying to configure)");
938 #if LDAP_SET_REBIND_PROC_ARGS == 3
939 /** Callback for OpenLDAP to rebind and chase referrals
941 * Called by OpenLDAP when it receives a referral and has to rebind.
943 * @param handle to rebind.
944 * @param url to bind to.
945 * @param request that triggered the rebind.
946 * @param msgid that triggered the rebind.
947 * @param ctx rlm_ldap configuration.
949 static int rlm_ldap_rebind(LDAP *handle, LDAP_CONST char *url, UNUSED ber_tag_t request, UNUSED ber_int_t msgid,
953 ldap_handle_t *conn = ctx;
957 conn->referred = TRUE;
958 conn->rebound = TRUE; /* not really, but oh well... */
959 rad_assert(handle == conn->handle);
961 DEBUG("rlm_ldap (%s): Rebinding to URL %s", conn->inst->xlat_name, url);
963 rcode = rlm_ldap_bind(conn->inst, NULL, &conn, conn->inst->login, conn->inst->password, FALSE);
965 if (rcode == RLM_MODULE_OK) {
969 ldap_get_option(handle, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
975 /** Create and return a new connection
977 * Create a new ldap connection and allocate memory for a new rlm_handle_t
979 * @param ctx rlm_ldap instance.
980 * @return A new connection handle or NULL on error.
982 void *rlm_ldap_conn_create(void *ctx)
986 int ldap_errno, ldap_version;
989 ldap_instance_t *inst = ctx;
991 ldap_handle_t *conn = NULL;
993 #ifdef HAVE_LDAP_INITIALIZE
995 DEBUG("rlm_ldap (%s): Connecting to %s", inst->xlat_name, inst->server);
997 ldap_errno = ldap_initialize(&handle, inst->server);
998 if (ldap_errno != LDAP_SUCCESS) {
999 LDAP_ERR("ldap_initialize failed: %s", ldap_err2string(ldap_errno));
1005 DEBUG("rlm_ldap (%s): Connecting to %s:%d", inst->xlat_name, inst->server, inst->port);
1007 handle = ldap_init(inst->server, inst->port);
1009 LDAP_ERR("ldap_init() failed");
1015 * We now have a connection structure, but no actual TCP connection.
1017 * Set a bunch of LDAP options, using common code.
1019 #define do_ldap_option(_option, _name, _value) \
1020 if (ldap_set_option(handle, _option, _value) != LDAP_OPT_SUCCESS) { \
1021 ldap_get_option(handle, LDAP_OPT_ERROR_NUMBER, &ldap_errno); \
1022 LDAP_ERR("Could not set %s: %s", _name, ldap_err2string(ldap_errno)); \
1025 if (inst->ldap_debug) {
1026 do_ldap_option(LDAP_OPT_DEBUG_LEVEL, "ldap_debug", &(inst->ldap_debug));
1030 * Leave "chase_referrals" unset to use the OpenLDAP default.
1032 if (inst->chase_referrals != 2) {
1033 if (inst->chase_referrals) {
1034 do_ldap_option(LDAP_OPT_REFERRALS, "chase_referrals", LDAP_OPT_ON);
1036 if (inst->rebind == 1) {
1037 #if LDAP_SET_REBIND_PROC_ARGS == 3
1038 ldap_set_rebind_proc(handle, rlm_ldap_rebind, inst);
1040 DEBUGW("The flag 'rebind = yes' is not supported by the system LDAP library. "
1045 do_ldap_option(LDAP_OPT_REFERRALS, "chase_referrals", LDAP_OPT_OFF);
1049 tv.tv_sec = inst->net_timeout;
1051 do_ldap_option(LDAP_OPT_NETWORK_TIMEOUT, "net_timeout", &tv);
1053 do_ldap_option(LDAP_OPT_TIMELIMIT, "timelimit", &(inst->timelimit));
1055 ldap_version = LDAP_VERSION3;
1056 do_ldap_option(LDAP_OPT_PROTOCOL_VERSION, "ldap_version", &ldap_version);
1058 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
1059 do_ldap_option(LDAP_OPT_X_KEEPALIVE_IDLE, "keepalive idle", &(inst->keepalive_idle));
1062 #ifdef LDAP_OPT_X_KEEPALIVE_PROBES
1063 do_ldap_option(LDAP_OPT_X_KEEPALIVE_PROBES, "keepalive probes", &(inst->keepalive_probes));
1066 #ifdef LDAP_OPT_X_KEEPALIVE_INTERVAL
1067 do_ldap_option(LDAP_OPT_X_KEEPALIVE_INTERVAL, "keepalive interval", &(inst->keepalive_interval));
1070 #ifdef HAVE_LDAP_START_TLS
1072 * Set all of the TLS options
1074 if (inst->tls_mode) {
1075 do_ldap_option(LDAP_OPT_X_TLS, "tls_mode", &(inst->tls_mode));
1078 # define maybe_ldap_option(_option, _name, _value) \
1079 if (_value) do_ldap_option(_option, _name, _value)
1081 maybe_ldap_option(LDAP_OPT_X_TLS_CACERTFILE, "cacertfile", inst->tls_cacertfile);
1082 maybe_ldap_option(LDAP_OPT_X_TLS_CACERTDIR, "cacertdir", inst->tls_cacertdir);
1084 # ifdef HAVE_LDAP_INT_TLS_CONFIG
1085 if (ldap_int_tls_config(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, inst->tls_require_cert) != LDAP_OPT_SUCCESS) {
1086 ldap_get_option(handle, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
1088 LDAP_ERR("Could not set LDAP_OPT_X_TLS_REQUIRE_CERT option to %s: %s", inst->tls_require_cert,
1089 ldap_err2string(ldap_errno));
1094 * Set certificate options
1096 maybe_ldap_option(LDAP_OPT_X_TLS_CERTFILE, "certfile", inst->tls_certfile);
1097 maybe_ldap_option(LDAP_OPT_X_TLS_KEYFILE, "keyfile", inst->tls_keyfile);
1098 maybe_ldap_option(LDAP_OPT_X_TLS_RANDOM_FILE, "randfile", inst->tls_randfile);
1101 * And finally start the TLS code.
1103 if (inst->start_tls) {
1104 if (inst->port == 636) {
1105 DEBUGW("Told to Start TLS on LDAPS port this will probably fail, please correct the "
1109 if (ldap_start_tls_s(handle, NULL, NULL) != LDAP_SUCCESS) {
1110 ldap_get_option(handle, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
1112 LDAP_ERR("Could not start TLS: %s", ldap_err2string(ldap_errno));
1116 #endif /* HAVE_LDAP_START_TLS */
1119 * Allocate memory for the handle.
1121 conn = talloc_zero(ctx, ldap_handle_t);
1123 conn->handle = handle;
1124 conn->rebound = FALSE;
1125 conn->referred = FALSE;
1127 rcode = rlm_ldap_bind(inst, NULL, &conn, inst->login, inst->password, FALSE);
1128 if (rcode != RLM_MODULE_OK) {
1135 if (handle) ldap_unbind_s(handle);
1136 if (conn) talloc_free(conn);
1142 /** Close and delete a connection
1144 * Unbinds the LDAP connection, informing the server and freeing any memory, then releases the memory used by the
1145 * connection handle.
1147 * @param ctx unused.
1148 * @param connection to destroy.
1149 * @return always indicates success.
1151 int rlm_ldap_conn_delete(UNUSED void *ctx, void *connection)
1153 ldap_handle_t *conn = connection;
1155 ldap_unbind_s(conn->handle);
1162 /** Gets an LDAP socket from the connection pool
1164 * Retrieve a socket from the connection pool, or NULL on error (of if no sockets are available).
1166 * @param inst rlm_ldap configuration.
1167 * @param request Current request.
1169 ldap_handle_t *rlm_ldap_get_socket(const ldap_instance_t *inst, REQUEST *request)
1171 ldap_handle_t *conn;
1173 conn = fr_connection_get(inst->pool);
1175 RDEBUGE("All ldap connections are in use");
1183 /** Frees an LDAP socket back to the connection pool
1185 * If the socket was rebound chasing a referral onto another server then we destroy it.
1186 * If the socket was rebound to another user on the same server, we let the next caller rebind it.
1188 * @param inst rlm_ldap configuration.
1189 * @param conn to release.
1191 void rlm_ldap_release_socket(const ldap_instance_t *inst, ldap_handle_t *conn)
1194 * Could have already been free'd due to a previous error.
1199 * We chased a referral to another server.
1201 * This connection is no longer part of the pool which is connected to and bound to the configured server.
1204 * Note that we do NOT close it if it was bound to another user. Instead, we let the next caller do the
1207 if (conn->referred) {
1208 fr_connection_del(inst->pool, conn);
1212 fr_connection_release(inst->pool, conn);