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. Use, duplication, or disclosure
7 // is subject to the terms of the GNU General Public License, version 3.
8 // The program is distributed without any warranty, expressed or implied.
10 // ldapsearch -D uid=admin,cn=users,cn=compat,dc=demo1,dc=freeipa,dc=org -w Secret123 -h ipa.demo1.freeipa.org
12 int ctdl_require_ldap_version = 3;
14 #define _GNU_SOURCE // Needed to suppress warning about vasprintf() when running on Linux/Linux
16 #include <libcitadel.h>
17 #include "citserver.h"
18 #include "citadel_ldap.h"
19 #include "ctdl_module.h"
21 #include "internet_addressing.h"
26 // These functions are deprecated and until we change them to the new API we need these declarations to get around compiler warnings.
27 int ldap_simple_bind_s(LDAP *, const char *, const char *);
28 int ldap_unbind(LDAP *);
31 // Utility function, supply a search result and get back the fullname (display name, common name, etc) from the first result
33 // POSIX schema: the display name will be found in "cn" (common name)
34 // Active Directory: the display name will be found in "displayName"
36 void derive_fullname_from_ldap_result(char *fullname, int fullname_size, LDAP *ldserver, LDAPMessage *search_result) {
37 struct berval **values;
39 if (fullname == NULL) return;
40 if (search_result == NULL) return;
41 if (ldserver == NULL) return;
43 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
44 values = ldap_get_values_len(ldserver, search_result, "displayName");
46 if (ldap_count_values_len(values) > 0) {
47 safestrncpy(fullname, values[0]->bv_val, fullname_size);
48 syslog(LOG_DEBUG, "ldap: displayName = %s", fullname);
50 ldap_value_free_len(values);
54 values = ldap_get_values_len(ldserver, search_result, "cn");
56 if (ldap_count_values_len(values) > 0) {
57 safestrncpy(fullname, values[0]->bv_val, fullname_size);
58 syslog(LOG_DEBUG, "ldap: cn = %s", fullname);
60 ldap_value_free_len(values);
66 // Utility function, supply a search result and get back the uid from the first result
68 // POSIX schema: numeric user id will be in the "uidNumber" attribute
69 // Active Directory: we make a uid hashed from "objectGUID"
71 uid_t derive_uid_from_ldap(LDAP *ldserver, LDAPMessage *entry) {
72 struct berval **values;
75 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
76 values = ldap_get_values_len(ldserver, entry, "objectGUID");
78 if (ldap_count_values_len(values) > 0) {
79 uid = abs(HashLittle(values[0]->bv_val, values[0]->bv_len));
81 ldap_value_free_len(values);
85 values = ldap_get_values_len(ldserver, entry, "uidNumber");
87 if (ldap_count_values_len(values) > 0) {
88 uid = atoi(values[0]->bv_val);
90 ldap_value_free_len(values);
94 syslog(LOG_DEBUG, "ldap: uid = %d", uid);
99 // Wrapper function for ldap_initialize() that consistently fills in the correct fields
100 int ctdl_ldap_initialize(LDAP **ld) {
102 char server_url[256];
105 snprintf(server_url, sizeof server_url, "ldap://%s:%d", CtdlGetConfigStr("c_ldap_host"), CtdlGetConfigInt("c_ldap_port"));
106 syslog(LOG_DEBUG, "ldap: initializing server %s", server_url);
107 ret = ldap_initialize(ld, server_url);
108 if (ret != LDAP_SUCCESS) {
109 syslog(LOG_ERR, "ldap: could not connect to %s : %m", server_url);
118 // Bind to the LDAP server and return a working handle
119 LDAP *ctdl_ldap_bind(void) {
120 LDAP *ldserver = NULL;
123 if (ctdl_ldap_initialize(&ldserver) != LDAP_SUCCESS) {
127 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
128 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
130 striplt(CtdlGetConfigStr("c_ldap_bind_dn"));
131 striplt(CtdlGetConfigStr("c_ldap_bind_pw"));
132 i = ldap_simple_bind_s(ldserver,
133 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_dn")) ? CtdlGetConfigStr("c_ldap_bind_dn") : NULL),
134 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_pw")) ? CtdlGetConfigStr("c_ldap_bind_pw") : NULL)
136 if (i != LDAP_SUCCESS) {
137 syslog(LOG_ERR, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
145 // Look up a user in the directory to see if this is an account that can be authenticated
147 // POSIX schema: Search all "inetOrgPerson" objects with "uid" set to the supplied username
148 // Active Directory: Look for an account with "sAMAccountName" set to the supplied username
150 int CtdlTryUserLDAP(char *username, char *found_dn, int found_dn_size, char *fullname, int fullname_size, uid_t *uid) {
151 LDAP *ldserver = NULL;
152 LDAPMessage *search_result = NULL;
153 LDAPMessage *entry = NULL;
154 char searchstring[1024];
156 char *user_dn = NULL;
158 ldserver = ctdl_ldap_bind();
159 if (!ldserver) return(-1);
161 if (fullname) safestrncpy(fullname, username, fullname_size);
165 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
166 snprintf(searchstring, sizeof(searchstring), "(sAMAccountName=%s)", username);
169 snprintf(searchstring, sizeof(searchstring), "(&(objectclass=inetOrgPerson)(uid=%s))", username);
172 syslog(LOG_DEBUG, "ldap: search: %s", searchstring);
173 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
175 CtdlGetConfigStr("c_ldap_base_dn"), // base
176 LDAP_SCOPE_SUBTREE, // scope
177 searchstring, // filter
178 NULL, // attrs (all attributes)
179 0, // attrsonly (attrs + values)
180 NULL, // serverctrls (none)
181 NULL, // clientctrls (none)
183 1, // sizelimit (1 result max)
184 &search_result // put the result here
187 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
188 // the search succeeds. Instead, we check to see whether search_result is still NULL.
189 if (search_result == NULL) {
190 syslog(LOG_DEBUG, "ldap: zero search results were returned");
191 ldap_unbind(ldserver);
195 // At this point we've got at least one result from our query. If there are multiple
196 // results, we still only look at the first one.
197 entry = ldap_first_entry(ldserver, search_result);
200 user_dn = ldap_get_dn(ldserver, entry);
202 syslog(LOG_DEBUG, "ldap: dn = %s", user_dn);
205 derive_fullname_from_ldap_result(fullname, fullname_size, ldserver, search_result);
206 *uid = derive_uid_from_ldap(ldserver, search_result);
210 ldap_msgfree(search_result);
212 // unbind so we can go back in as the authenticating user
213 ldap_unbind(ldserver);
216 syslog(LOG_DEBUG, "ldap: No such user was found.");
220 if (found_dn) safestrncpy(found_dn, user_dn, found_dn_size);
221 ldap_memfree(user_dn);
226 // This is an extension of CtdlTryPassword() which gets called when using LDAP authentication.
227 int CtdlTryPasswordLDAP(char *user_dn, const char *password) {
228 LDAP *ldserver = NULL;
231 if (IsEmptyStr(password)) {
232 syslog(LOG_DEBUG, "ldap: empty passwords are not permitted");
236 syslog(LOG_DEBUG, "ldap: trying to bind as %s", user_dn);
237 i = ctdl_ldap_initialize(&ldserver);
238 if (i == LDAP_SUCCESS) {
239 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
240 i = ldap_simple_bind_s(ldserver, user_dn, password);
241 if (i == LDAP_SUCCESS) {
242 syslog(LOG_DEBUG, "ldap: bind succeeded");
245 syslog(LOG_DEBUG, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
247 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
248 ldap_unbind(ldserver);
251 if (i == LDAP_SUCCESS) {
259 // set multiple properties
260 // returns nonzero only if property changed.
261 int vcard_set_props_iff_different(struct vCard *v, char *propname, int numvals, char **vals) {
264 for (i=0; i<numvals; i++) {
265 oldval = vcard_get_prop(v, propname, 0, i, 0);
266 if (oldval == NULL) break;
267 if (strcmp(vals[i],oldval)) break;
270 syslog(LOG_DEBUG, "ldap: vcard property %s, element %d of %d changed from %s to %s", propname, i, numvals, oldval, vals[i]);
271 for (i=0; i<numvals; i++) {
272 vcard_set_prop(v,propname,vals[i],(i==0) ? 0 : 1);
281 // returns nonzero only if property changed.
282 int vcard_set_one_prop_iff_different(struct vCard *v,char *propname, char *newfmt, ...) {
286 va_start(args,newfmt);
287 if (vasprintf(&newvalue, newfmt, args) < 0) {
288 syslog(LOG_ERR, "ldap: out of memory");
291 did_change = vcard_set_props_iff_different(v, propname, 1, &newvalue);
298 // Learn LDAP attributes and stuff them into the vCard.
299 // Returns nonzero if we changed anything.
300 int Ctdl_LDAP_to_vCard(char *ldap_dn, struct vCard *v) {
301 int changed_something = 0;
302 LDAP *ldserver = NULL;
304 LDAPMessage *search_result = NULL;
305 LDAPMessage *entry = NULL;
306 struct berval **givenName;
309 struct berval **initials;
311 struct berval **street;
314 struct berval **postalCode;
315 struct berval **telephoneNumber;
316 struct berval **mobile;
317 struct berval **homePhone;
318 struct berval **facsimileTelephoneNumber;
319 struct berval **mail;
321 struct berval **homeDirectory;
322 struct berval **uidNumber;
323 struct berval **loginShell;
324 struct berval **gidNumber;
326 struct berval **title;
327 struct berval **uuid;
328 char *attrs[] = { "*","+",NULL};
330 if (!ldap_dn) return(0);
333 ldserver = ctdl_ldap_bind();
334 if (!ldserver) return(-1);
339 syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
340 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
343 LDAP_SCOPE_SUBTREE, // scope
345 attrs, // attrs (all attributes)
346 0, // attrsonly (attrs + values)
347 NULL, // serverctrls (none)
348 NULL, // clientctrls (none)
350 1, // sizelimit (1 result max)
351 &search_result // res
354 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
355 // the search succeeds. Instead, we check to see whether search_result is still NULL.
356 if (search_result == NULL) {
357 syslog(LOG_DEBUG, "ldap: zero search results were returned");
358 ldap_unbind(ldserver);
362 // At this point we've got at least one result from our query. If there are multiple
363 // results, we still only look at the first one.
364 entry = ldap_first_entry(ldserver, search_result);
366 syslog(LOG_DEBUG, "ldap: search got user details for vcard.");
367 givenName = ldap_get_values_len(ldserver, search_result, "givenName");
368 sn = ldap_get_values_len(ldserver, search_result, "sn");
369 cn = ldap_get_values_len(ldserver, search_result, "cn");
370 initials = ldap_get_values_len(ldserver, search_result, "initials");
371 title = ldap_get_values_len(ldserver, search_result, "title");
372 o = ldap_get_values_len(ldserver, search_result, "o");
373 street = ldap_get_values_len(ldserver, search_result, "street");
374 l = ldap_get_values_len(ldserver, search_result, "l");
375 st = ldap_get_values_len(ldserver, search_result, "st");
376 postalCode = ldap_get_values_len(ldserver, search_result, "postalCode");
377 telephoneNumber = ldap_get_values_len(ldserver, search_result, "telephoneNumber");
378 mobile = ldap_get_values_len(ldserver, search_result, "mobile");
379 homePhone = ldap_get_values_len(ldserver, search_result, "homePhone");
380 facsimileTelephoneNumber = ldap_get_values_len(ldserver, search_result, "facsimileTelephoneNumber");
381 mail = ldap_get_values_len(ldserver, search_result, "mail");
382 uid = ldap_get_values_len(ldserver, search_result, "uid");
383 homeDirectory = ldap_get_values_len(ldserver, search_result, "homeDirectory");
384 uidNumber = ldap_get_values_len(ldserver, search_result, "uidNumber");
385 loginShell = ldap_get_values_len(ldserver, search_result, "loginShell");
386 gidNumber = ldap_get_values_len(ldserver, search_result, "gidNumber");
387 c = ldap_get_values_len(ldserver, search_result, "c");
388 uuid = ldap_get_values_len(ldserver, search_result, "entryUUID");
390 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);
391 if (telephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;work","%s",telephoneNumber[0]->bv_val);
392 if (facsimileTelephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;fax","%s",facsimileTelephoneNumber[0]->bv_val);
393 if (mobile) changed_something |= vcard_set_one_prop_iff_different(v,"tel;cell","%s",mobile[0]->bv_val);
394 if (homePhone) changed_something |= vcard_set_one_prop_iff_different(v,"tel;home","%s",homePhone[0]->bv_val);
395 if (givenName && sn) {
397 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);
400 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s",sn[0]->bv_val,givenName[0]->bv_val);
404 // FIXME we need a new way to do this.
406 //changed_something |= vcard_set_props_iff_different(v,"email;internet",ldap_count_values_len(mail),mail);
409 if (uuid) changed_something |= vcard_set_one_prop_iff_different(v,"X-uuid","%s",uuid[0]->bv_val);
410 if (o) changed_something |= vcard_set_one_prop_iff_different(v,"org","%s",o[0]->bv_val);
411 if (cn) changed_something |= vcard_set_one_prop_iff_different(v,"fn","%s",cn[0]->bv_val);
412 if (title) changed_something |= vcard_set_one_prop_iff_different(v,"title","%s",title[0]->bv_val);
414 if (givenName) ldap_value_free_len(givenName);
415 if (initials) ldap_value_free_len(initials);
416 if (sn) ldap_value_free_len(sn);
417 if (cn) ldap_value_free_len(cn);
418 if (o) ldap_value_free_len(o);
419 if (street) ldap_value_free_len(street);
420 if (l) ldap_value_free_len(l);
421 if (st) ldap_value_free_len(st);
422 if (postalCode) ldap_value_free_len(postalCode);
423 if (telephoneNumber) ldap_value_free_len(telephoneNumber);
424 if (mobile) ldap_value_free_len(mobile);
425 if (homePhone) ldap_value_free_len(homePhone);
426 if (facsimileTelephoneNumber) ldap_value_free_len(facsimileTelephoneNumber);
427 if (mail) ldap_value_free_len(mail);
428 if (uid) ldap_value_free_len(uid);
429 if (homeDirectory) ldap_value_free_len(homeDirectory);
430 if (uidNumber) ldap_value_free_len(uidNumber);
431 if (loginShell) ldap_value_free_len(loginShell);
432 if (gidNumber) ldap_value_free_len(gidNumber);
433 if (c) ldap_value_free_len(c);
434 if (title) ldap_value_free_len(title);
435 if (uuid) ldap_value_free_len(uuid);
438 ldap_msgfree(search_result);
440 // unbind so we can go back in as the authenticating user
441 ldap_unbind(ldserver);
442 return(changed_something); // tell the caller whether we made any changes
446 // Extract a user's Internet email addresses from LDAP.
447 // Returns zero if we got a valid set of addresses; nonzero for error.
448 int extract_email_addresses_from_ldap(char *ldap_dn, char *emailaddrs) {
449 LDAP *ldserver = NULL;
451 LDAPMessage *search_result = NULL;
452 LDAPMessage *entry = NULL;
453 struct berval **mail;
454 char *attrs[] = { "*","+",NULL };
456 if (!ldap_dn) return(1);
457 if (!emailaddrs) return(1);
459 ldserver = ctdl_ldap_bind();
460 if (!ldserver) return(-1);
465 syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
466 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
469 LDAP_SCOPE_SUBTREE, // scope
471 attrs, // attrs (all attributes)
472 0, // attrsonly (attrs + values)
473 NULL, // serverctrls (none)
474 NULL, // clientctrls (none)
476 1, // sizelimit (1 result max)
477 &search_result // res
480 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
481 // the search succeeds. Instead, we check to see whether search_result is still NULL.
482 if (search_result == NULL) {
483 syslog(LOG_DEBUG, "ldap: zero search results were returned");
484 ldap_unbind(ldserver);
488 // At this point we've got at least one result from our query.
489 // If there are multiple results, we still only look at the first one.
490 emailaddrs[0] = 0; // clear out any previous results
491 entry = ldap_first_entry(ldserver, search_result);
493 syslog(LOG_DEBUG, "ldap: search got user details");
494 mail = ldap_get_values_len(ldserver, search_result, "mail");
497 for (q=0; q<ldap_count_values_len(mail); ++q) {
498 if (IsDirectory(mail[q]->bv_val, 0)) {
499 if ((strlen(emailaddrs) + mail[q]->bv_len + 2) > 512) {
500 syslog(LOG_ERR, "ldap: can't fit all email addresses into user record");
503 if (!IsEmptyStr(emailaddrs)) {
504 strcat(emailaddrs, "|");
506 strcat(emailaddrs, mail[q]->bv_val);
514 ldap_msgfree(search_result);
516 // unbind so we can go back in as the authenticating user
517 ldap_unbind(ldserver);
522 // Remember that a particular user exists in the Citadel database.
523 // As we scan the LDAP tree we will remove users from this list when we find them.
524 // At the end of the scan, any users remaining in this list are stale and should be deleted.
525 void ldap_note_user_in_citadel(char *username, void *data) {
530 // Scan LDAP for users and populate Citadel's user database with everyone
532 // POSIX schema: All objects of class "inetOrgPerson"
533 // Active Directory: Objects that are class "user" and class "person" but NOT class "computer"
535 void CtdlSynchronizeUsersFromLDAP(void) {
536 LDAP *ldserver = NULL;
537 LDAPMessage *search_result = NULL;
538 LDAPMessage *entry = NULL;
539 char *user_dn = NULL;
540 char searchstring[1024];
543 if ((CtdlGetConfigInt("c_auth_mode") != AUTHMODE_LDAP) && (CtdlGetConfigInt("c_auth_mode") != AUTHMODE_LDAP_AD)) {
544 return; // If this site is not running LDAP, stop here.
547 syslog(LOG_INFO, "ldap: synchronizing Citadel user database from LDAP");
549 // first, scan the existing Citadel user list
550 // ForEachUser(ldap_note_user_in_citadel, NULL); // FIXME finish this
552 ldserver = ctdl_ldap_bind();
553 if (!ldserver) return;
558 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
559 snprintf(searchstring, sizeof(searchstring), "(&(objectClass=user)(objectClass=person)(!(objectClass=computer)))");
562 snprintf(searchstring, sizeof(searchstring), "(objectClass=inetOrgPerson)");
565 syslog(LOG_DEBUG, "ldap: search: %s", searchstring);
566 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
568 CtdlGetConfigStr("c_ldap_base_dn"), // base
569 LDAP_SCOPE_SUBTREE, // scope
570 searchstring, // filter
571 NULL, // attrs (all attributes)
572 0, // attrsonly (attrs + values)
573 NULL, // serverctrls (none)
574 NULL, // clientctrls (none)
576 INT_MAX, // sizelimit (max)
577 &search_result // put the result here
580 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
581 // the search succeeds. Instead, we check to see whether search_result is still NULL.
582 if (search_result == NULL) {
583 syslog(LOG_DEBUG, "ldap: zero search results were returned");
584 ldap_unbind(ldserver);
588 syslog(LOG_DEBUG, "ldap: %d entries returned", ldap_count_entries(ldserver, search_result));
589 for (entry=ldap_first_entry(ldserver, search_result); entry!=NULL; entry=ldap_next_entry(ldserver, entry)) {
590 user_dn = ldap_get_dn(ldserver, entry);
592 syslog(LOG_DEBUG, "ldap: found %s", user_dn);
594 int fullname_size = 256;
595 char fullname[256] = { 0 } ;
597 char new_emailaddrs[512] = { 0 } ;
599 uid = derive_uid_from_ldap(ldserver, entry);
600 derive_fullname_from_ldap_result(fullname, fullname_size, ldserver, entry);
601 syslog(LOG_DEBUG, "ldap: display name: <%s> , uid = <%d>", fullname, uid);
603 // now create or update the user
605 struct ctdluser usbuf;
607 found_user = getuserbyuid(&usbuf, uid);
608 if (found_user != 0) {
609 create_user(fullname, CREATE_USER_DO_NOT_BECOME_USER, uid);
610 found_user = getuserbyuid(&usbuf, uid);
611 strcpy(fullname, usbuf.fullname);
614 if (found_user == 0) { // user record exists
615 // now update the account email addresses if necessary
616 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
617 if (extract_email_addresses_from_ldap(user_dn, new_emailaddrs) == 0) {
618 if (strcmp(usbuf.emailaddrs, new_emailaddrs)) { // update only if changed
619 CtdlSetEmailAddressesForUser(usbuf.fullname, new_emailaddrs);
624 ldap_memfree(user_dn);
629 ldap_msgfree(search_result);
631 // unbind so we can go back in as the authenticating user
632 ldap_unbind(ldserver);