1 // These functions implement the portions of AUTHMODE_LDAP and AUTHMODE_LDAP_AD which
2 // actually speak to the LDAP server.
4 // Copyright (c) 2011-2022 by the citadel.org development team.
6 // This program is open source software; you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License, version 3.
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // ldapsearch -D uid=admin,cn=users,cn=compat,dc=demo1,dc=freeipa,dc=org -w Secret123 -h ipa.demo1.freeipa.org
16 int ctdl_require_ldap_version = 3;
18 #define _GNU_SOURCE // Needed to suppress warning about vasprintf() when running on Linux/Linux
20 #include <libcitadel.h>
21 #include "citserver.h"
22 #include "citadel_ldap.h"
23 #include "ctdl_module.h"
25 #include "internet_addressing.h"
30 // These functions are deprecated and until we change them to the new API we need these declarations to get around compiler warnings.
31 int ldap_simple_bind_s(LDAP *, const char *, const char *);
32 int ldap_unbind(LDAP *);
35 // Utility function, supply a search result and get back the fullname (display name, common name, etc) from the first result
37 // POSIX schema: the display name will be found in "cn" (common name)
38 // Active Directory: the display name will be found in "displayName"
40 void derive_fullname_from_ldap_result(char *fullname, int fullname_size, LDAP *ldserver, LDAPMessage *search_result) {
41 struct berval **values;
43 if (fullname == NULL) return;
44 if (search_result == NULL) return;
45 if (ldserver == NULL) return;
47 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
48 values = ldap_get_values_len(ldserver, search_result, "displayName");
50 if (ldap_count_values_len(values) > 0) {
51 safestrncpy(fullname, values[0]->bv_val, fullname_size);
52 syslog(LOG_DEBUG, "ldap: displayName = %s", fullname);
54 ldap_value_free_len(values);
58 values = ldap_get_values_len(ldserver, search_result, "cn");
60 if (ldap_count_values_len(values) > 0) {
61 safestrncpy(fullname, values[0]->bv_val, fullname_size);
62 syslog(LOG_DEBUG, "ldap: cn = %s", fullname);
64 ldap_value_free_len(values);
70 // Utility function, supply a search result and get back the uid from the first result
72 // POSIX schema: numeric user id will be in the "uidNumber" attribute
73 // Active Directory: we make a uid hashed from "objectGUID"
75 uid_t derive_uid_from_ldap(LDAP *ldserver, LDAPMessage *entry) {
76 struct berval **values;
79 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
80 values = ldap_get_values_len(ldserver, entry, "objectGUID");
82 if (ldap_count_values_len(values) > 0) {
83 uid = abs(HashLittle(values[0]->bv_val, values[0]->bv_len));
85 ldap_value_free_len(values);
89 values = ldap_get_values_len(ldserver, entry, "uidNumber");
91 if (ldap_count_values_len(values) > 0) {
92 uid = atoi(values[0]->bv_val);
94 ldap_value_free_len(values);
98 syslog(LOG_DEBUG, "ldap: uid = %d", uid);
103 // Wrapper function for ldap_initialize() that consistently fills in the correct fields
104 int ctdl_ldap_initialize(LDAP **ld) {
106 char server_url[256];
109 snprintf(server_url, sizeof server_url, "ldap://%s:%d", CtdlGetConfigStr("c_ldap_host"), CtdlGetConfigInt("c_ldap_port"));
110 syslog(LOG_DEBUG, "ldap: initializing server %s", server_url);
111 ret = ldap_initialize(ld, server_url);
112 if (ret != LDAP_SUCCESS) {
113 syslog(LOG_ERR, "ldap: could not connect to %s : %m", server_url);
122 // Bind to the LDAP server and return a working handle
123 LDAP *ctdl_ldap_bind(void) {
124 LDAP *ldserver = NULL;
127 if (ctdl_ldap_initialize(&ldserver) != LDAP_SUCCESS) {
131 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
132 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
134 striplt(CtdlGetConfigStr("c_ldap_bind_dn"));
135 striplt(CtdlGetConfigStr("c_ldap_bind_pw"));
136 i = ldap_simple_bind_s(ldserver,
137 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_dn")) ? CtdlGetConfigStr("c_ldap_bind_dn") : NULL),
138 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_pw")) ? CtdlGetConfigStr("c_ldap_bind_pw") : NULL)
140 if (i != LDAP_SUCCESS) {
141 syslog(LOG_ERR, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
149 // Look up a user in the directory to see if this is an account that can be authenticated
151 // POSIX schema: Search all "inetOrgPerson" objects with "uid" set to the supplied username
152 // Active Directory: Look for an account with "sAMAccountName" set to the supplied username
154 int CtdlTryUserLDAP(char *username, char *found_dn, int found_dn_size, char *fullname, int fullname_size, uid_t *uid) {
155 LDAP *ldserver = NULL;
156 LDAPMessage *search_result = NULL;
157 LDAPMessage *entry = NULL;
158 char searchstring[1024];
160 char *user_dn = NULL;
162 ldserver = ctdl_ldap_bind();
163 if (!ldserver) return(-1);
165 if (fullname) safestrncpy(fullname, username, fullname_size);
169 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
170 snprintf(searchstring, sizeof(searchstring), "(sAMAccountName=%s)", username);
173 snprintf(searchstring, sizeof(searchstring), "(&(objectclass=inetOrgPerson)(uid=%s))", username);
176 syslog(LOG_DEBUG, "ldap: search: %s", searchstring);
177 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
179 CtdlGetConfigStr("c_ldap_base_dn"), // base
180 LDAP_SCOPE_SUBTREE, // scope
181 searchstring, // filter
182 NULL, // attrs (all attributes)
183 0, // attrsonly (attrs + values)
184 NULL, // serverctrls (none)
185 NULL, // clientctrls (none)
187 1, // sizelimit (1 result max)
188 &search_result // put the result here
191 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
192 // the search succeeds. Instead, we check to see whether search_result is still NULL.
193 if (search_result == NULL) {
194 syslog(LOG_DEBUG, "ldap: zero search results were returned");
195 ldap_unbind(ldserver);
199 // At this point we've got at least one result from our query. If there are multiple
200 // results, we still only look at the first one.
201 entry = ldap_first_entry(ldserver, search_result);
204 user_dn = ldap_get_dn(ldserver, entry);
206 syslog(LOG_DEBUG, "ldap: dn = %s", user_dn);
209 derive_fullname_from_ldap_result(fullname, fullname_size, ldserver, search_result);
210 *uid = derive_uid_from_ldap(ldserver, search_result);
214 ldap_msgfree(search_result);
216 // unbind so we can go back in as the authenticating user
217 ldap_unbind(ldserver);
220 syslog(LOG_DEBUG, "ldap: No such user was found.");
224 if (found_dn) safestrncpy(found_dn, user_dn, found_dn_size);
225 ldap_memfree(user_dn);
230 // This is an extension of CtdlTryPassword() which gets called when using LDAP authentication.
231 int CtdlTryPasswordLDAP(char *user_dn, const char *password) {
232 LDAP *ldserver = NULL;
235 if (IsEmptyStr(password)) {
236 syslog(LOG_DEBUG, "ldap: empty passwords are not permitted");
240 syslog(LOG_DEBUG, "ldap: trying to bind as %s", user_dn);
241 i = ctdl_ldap_initialize(&ldserver);
242 if (i == LDAP_SUCCESS) {
243 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
244 i = ldap_simple_bind_s(ldserver, user_dn, password);
245 if (i == LDAP_SUCCESS) {
246 syslog(LOG_DEBUG, "ldap: bind succeeded");
249 syslog(LOG_DEBUG, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
251 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
252 ldap_unbind(ldserver);
255 if (i == LDAP_SUCCESS) {
263 // set multiple properties
264 // returns nonzero only if property changed.
265 int vcard_set_props_iff_different(struct vCard *v, char *propname, int numvals, char **vals) {
268 for (i=0; i<numvals; i++) {
269 oldval = vcard_get_prop(v, propname, 0, i, 0);
270 if (oldval == NULL) break;
271 if (strcmp(vals[i],oldval)) break;
274 syslog(LOG_DEBUG, "ldap: vcard property %s, element %d of %d changed from %s to %s", propname, i, numvals, oldval, vals[i]);
275 for (i=0; i<numvals; i++) {
276 vcard_set_prop(v,propname,vals[i],(i==0) ? 0 : 1);
285 // returns nonzero only if property changed.
286 int vcard_set_one_prop_iff_different(struct vCard *v,char *propname, char *newfmt, ...) {
290 va_start(args,newfmt);
291 if (vasprintf(&newvalue, newfmt, args) < 0) {
292 syslog(LOG_ERR, "ldap: out of memory");
295 did_change = vcard_set_props_iff_different(v, propname, 1, &newvalue);
302 // Learn LDAP attributes and stuff them into the vCard.
303 // Returns nonzero if we changed anything.
304 int Ctdl_LDAP_to_vCard(char *ldap_dn, struct vCard *v) {
305 int changed_something = 0;
306 LDAP *ldserver = NULL;
308 LDAPMessage *search_result = NULL;
309 LDAPMessage *entry = NULL;
310 struct berval **givenName;
313 struct berval **initials;
315 struct berval **street;
318 struct berval **postalCode;
319 struct berval **telephoneNumber;
320 struct berval **mobile;
321 struct berval **homePhone;
322 struct berval **facsimileTelephoneNumber;
323 struct berval **mail;
325 struct berval **homeDirectory;
326 struct berval **uidNumber;
327 struct berval **loginShell;
328 struct berval **gidNumber;
330 struct berval **title;
331 struct berval **uuid;
332 char *attrs[] = { "*","+",NULL};
334 if (!ldap_dn) return(0);
337 ldserver = ctdl_ldap_bind();
338 if (!ldserver) return(-1);
343 syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
344 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
347 LDAP_SCOPE_SUBTREE, // scope
349 attrs, // attrs (all attributes)
350 0, // attrsonly (attrs + values)
351 NULL, // serverctrls (none)
352 NULL, // clientctrls (none)
354 1, // sizelimit (1 result max)
355 &search_result // res
358 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
359 // the search succeeds. Instead, we check to see whether search_result is still NULL.
360 if (search_result == NULL) {
361 syslog(LOG_DEBUG, "ldap: zero search results were returned");
362 ldap_unbind(ldserver);
366 // At this point we've got at least one result from our query. If there are multiple
367 // results, we still only look at the first one.
368 entry = ldap_first_entry(ldserver, search_result);
370 syslog(LOG_DEBUG, "ldap: search got user details for vcard.");
371 givenName = ldap_get_values_len(ldserver, search_result, "givenName");
372 sn = ldap_get_values_len(ldserver, search_result, "sn");
373 cn = ldap_get_values_len(ldserver, search_result, "cn");
374 initials = ldap_get_values_len(ldserver, search_result, "initials");
375 title = ldap_get_values_len(ldserver, search_result, "title");
376 o = ldap_get_values_len(ldserver, search_result, "o");
377 street = ldap_get_values_len(ldserver, search_result, "street");
378 l = ldap_get_values_len(ldserver, search_result, "l");
379 st = ldap_get_values_len(ldserver, search_result, "st");
380 postalCode = ldap_get_values_len(ldserver, search_result, "postalCode");
381 telephoneNumber = ldap_get_values_len(ldserver, search_result, "telephoneNumber");
382 mobile = ldap_get_values_len(ldserver, search_result, "mobile");
383 homePhone = ldap_get_values_len(ldserver, search_result, "homePhone");
384 facsimileTelephoneNumber = ldap_get_values_len(ldserver, search_result, "facsimileTelephoneNumber");
385 mail = ldap_get_values_len(ldserver, search_result, "mail");
386 uid = ldap_get_values_len(ldserver, search_result, "uid");
387 homeDirectory = ldap_get_values_len(ldserver, search_result, "homeDirectory");
388 uidNumber = ldap_get_values_len(ldserver, search_result, "uidNumber");
389 loginShell = ldap_get_values_len(ldserver, search_result, "loginShell");
390 gidNumber = ldap_get_values_len(ldserver, search_result, "gidNumber");
391 c = ldap_get_values_len(ldserver, search_result, "c");
392 uuid = ldap_get_values_len(ldserver, search_result, "entryUUID");
394 if (street && l && st && postalCode && c) changed_something |= vcard_set_one_prop_iff_different(v,"adr",";;%s;%s;%s;%s;%s",street[0]->bv_val,l[0]->bv_val,st[0]->bv_val,postalCode[0]->bv_val,c[0]->bv_val);
395 if (telephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;work","%s",telephoneNumber[0]->bv_val);
396 if (facsimileTelephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;fax","%s",facsimileTelephoneNumber[0]->bv_val);
397 if (mobile) changed_something |= vcard_set_one_prop_iff_different(v,"tel;cell","%s",mobile[0]->bv_val);
398 if (homePhone) changed_something |= vcard_set_one_prop_iff_different(v,"tel;home","%s",homePhone[0]->bv_val);
399 if (givenName && sn) {
401 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s;%s",sn[0]->bv_val,givenName[0]->bv_val,initials[0]->bv_val);
404 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s",sn[0]->bv_val,givenName[0]->bv_val);
408 // FIXME we need a new way to do this.
410 //changed_something |= vcard_set_props_iff_different(v,"email;internet",ldap_count_values_len(mail),mail);
413 if (uuid) changed_something |= vcard_set_one_prop_iff_different(v,"X-uuid","%s",uuid[0]->bv_val);
414 if (o) changed_something |= vcard_set_one_prop_iff_different(v,"org","%s",o[0]->bv_val);
415 if (cn) changed_something |= vcard_set_one_prop_iff_different(v,"fn","%s",cn[0]->bv_val);
416 if (title) changed_something |= vcard_set_one_prop_iff_different(v,"title","%s",title[0]->bv_val);
418 if (givenName) ldap_value_free_len(givenName);
419 if (initials) ldap_value_free_len(initials);
420 if (sn) ldap_value_free_len(sn);
421 if (cn) ldap_value_free_len(cn);
422 if (o) ldap_value_free_len(o);
423 if (street) ldap_value_free_len(street);
424 if (l) ldap_value_free_len(l);
425 if (st) ldap_value_free_len(st);
426 if (postalCode) ldap_value_free_len(postalCode);
427 if (telephoneNumber) ldap_value_free_len(telephoneNumber);
428 if (mobile) ldap_value_free_len(mobile);
429 if (homePhone) ldap_value_free_len(homePhone);
430 if (facsimileTelephoneNumber) ldap_value_free_len(facsimileTelephoneNumber);
431 if (mail) ldap_value_free_len(mail);
432 if (uid) ldap_value_free_len(uid);
433 if (homeDirectory) ldap_value_free_len(homeDirectory);
434 if (uidNumber) ldap_value_free_len(uidNumber);
435 if (loginShell) ldap_value_free_len(loginShell);
436 if (gidNumber) ldap_value_free_len(gidNumber);
437 if (c) ldap_value_free_len(c);
438 if (title) ldap_value_free_len(title);
439 if (uuid) ldap_value_free_len(uuid);
442 ldap_msgfree(search_result);
444 // unbind so we can go back in as the authenticating user
445 ldap_unbind(ldserver);
446 return(changed_something); // tell the caller whether we made any changes
450 // Extract a user's Internet email addresses from LDAP.
451 // Returns zero if we got a valid set of addresses; nonzero for error.
452 int extract_email_addresses_from_ldap(char *ldap_dn, char *emailaddrs) {
453 LDAP *ldserver = NULL;
455 LDAPMessage *search_result = NULL;
456 LDAPMessage *entry = NULL;
457 struct berval **mail;
458 char *attrs[] = { "*","+",NULL };
460 if (!ldap_dn) return(1);
461 if (!emailaddrs) return(1);
463 ldserver = ctdl_ldap_bind();
464 if (!ldserver) return(-1);
469 syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
470 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
473 LDAP_SCOPE_SUBTREE, // scope
475 attrs, // attrs (all attributes)
476 0, // attrsonly (attrs + values)
477 NULL, // serverctrls (none)
478 NULL, // clientctrls (none)
480 1, // sizelimit (1 result max)
481 &search_result // res
484 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
485 // the search succeeds. Instead, we check to see whether search_result is still NULL.
486 if (search_result == NULL) {
487 syslog(LOG_DEBUG, "ldap: zero search results were returned");
488 ldap_unbind(ldserver);
492 // At this point we've got at least one result from our query.
493 // If there are multiple results, we still only look at the first one.
494 emailaddrs[0] = 0; // clear out any previous results
495 entry = ldap_first_entry(ldserver, search_result);
497 syslog(LOG_DEBUG, "ldap: search got user details");
498 mail = ldap_get_values_len(ldserver, search_result, "mail");
501 for (q=0; q<ldap_count_values_len(mail); ++q) {
502 if (IsDirectory(mail[q]->bv_val, 0)) {
503 if ((strlen(emailaddrs) + mail[q]->bv_len + 2) > 512) {
504 syslog(LOG_ERR, "ldap: can't fit all email addresses into user record");
507 if (!IsEmptyStr(emailaddrs)) {
508 strcat(emailaddrs, "|");
510 strcat(emailaddrs, mail[q]->bv_val);
518 ldap_msgfree(search_result);
520 // unbind so we can go back in as the authenticating user
521 ldap_unbind(ldserver);
526 // Remember that a particular user exists in the Citadel database.
527 // As we scan the LDAP tree we will remove users from this list when we find them.
528 // At the end of the scan, any users remaining in this list are stale and should be deleted.
529 void ldap_note_user_in_citadel(char *username, void *data) {
534 // Scan LDAP for users and populate Citadel's user database with everyone
536 // POSIX schema: All objects of class "inetOrgPerson"
537 // Active Directory: Objects that are class "user" and class "person" but NOT class "computer"
539 void CtdlSynchronizeUsersFromLDAP(void) {
540 LDAP *ldserver = NULL;
541 LDAPMessage *search_result = NULL;
542 LDAPMessage *entry = NULL;
543 char *user_dn = NULL;
544 char searchstring[1024];
547 if ((CtdlGetConfigInt("c_auth_mode") != AUTHMODE_LDAP) && (CtdlGetConfigInt("c_auth_mode") != AUTHMODE_LDAP_AD)) {
548 return; // If this site is not running LDAP, stop here.
551 syslog(LOG_INFO, "ldap: synchronizing Citadel user database from LDAP");
553 // first, scan the existing Citadel user list
554 // ForEachUser(ldap_note_user_in_citadel, NULL); // FIXME finish this
556 ldserver = ctdl_ldap_bind();
557 if (!ldserver) return;
562 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
563 snprintf(searchstring, sizeof(searchstring), "(&(objectClass=user)(objectClass=person)(!(objectClass=computer)))");
566 snprintf(searchstring, sizeof(searchstring), "(objectClass=inetOrgPerson)");
569 syslog(LOG_DEBUG, "ldap: search: %s", searchstring);
570 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
572 CtdlGetConfigStr("c_ldap_base_dn"), // base
573 LDAP_SCOPE_SUBTREE, // scope
574 searchstring, // filter
575 NULL, // attrs (all attributes)
576 0, // attrsonly (attrs + values)
577 NULL, // serverctrls (none)
578 NULL, // clientctrls (none)
580 INT_MAX, // sizelimit (max)
581 &search_result // put the result here
584 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
585 // the search succeeds. Instead, we check to see whether search_result is still NULL.
586 if (search_result == NULL) {
587 syslog(LOG_DEBUG, "ldap: zero search results were returned");
588 ldap_unbind(ldserver);
592 syslog(LOG_DEBUG, "ldap: %d entries returned", ldap_count_entries(ldserver, search_result));
593 for (entry=ldap_first_entry(ldserver, search_result); entry!=NULL; entry=ldap_next_entry(ldserver, entry)) {
594 user_dn = ldap_get_dn(ldserver, entry);
596 syslog(LOG_DEBUG, "ldap: found %s", user_dn);
598 int fullname_size = 256;
599 char fullname[256] = { 0 } ;
601 char new_emailaddrs[512] = { 0 } ;
603 uid = derive_uid_from_ldap(ldserver, entry);
604 derive_fullname_from_ldap_result(fullname, fullname_size, ldserver, entry);
605 syslog(LOG_DEBUG, "ldap: display name: <%s> , uid = <%d>", fullname, uid);
607 // now create or update the user
609 struct ctdluser usbuf;
611 found_user = getuserbyuid(&usbuf, uid);
612 if (found_user != 0) {
613 create_user(fullname, CREATE_USER_DO_NOT_BECOME_USER, uid);
614 found_user = getuserbyuid(&usbuf, uid);
615 strcpy(fullname, usbuf.fullname);
618 if (found_user == 0) { // user record exists
619 // now update the account email addresses if necessary
620 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
621 if (extract_email_addresses_from_ldap(user_dn, new_emailaddrs) == 0) {
622 if (strcmp(usbuf.emailaddrs, new_emailaddrs)) { // update only if changed
623 CtdlSetEmailAddressesForUser(usbuf.fullname, new_emailaddrs);
628 ldap_memfree(user_dn);
633 ldap_msgfree(search_result);
635 // unbind so we can go back in as the authenticating user
636 ldap_unbind(ldserver);