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.
9 // ldapsearch -D uid=admin,cn=users,cn=compat,dc=demo1,dc=freeipa,dc=org -w Secret123 -h ipa.demo1.freeipa.org
11 int ctdl_require_ldap_version = 3;
13 #define _GNU_SOURCE // Needed to suppress warning about vasprintf() when running on Linux/Linux
15 #include <libcitadel.h>
16 #include "citserver.h"
17 #include "citadel_ldap.h"
18 #include "ctdl_module.h"
20 #include "internet_addressing.h"
25 // These functions are deprecated and until we change them to the new API we need these declarations to get around compiler warnings.
26 int ldap_simple_bind_s(LDAP *, const char *, const char *);
27 int ldap_unbind(LDAP *);
30 // Utility function, supply a search result and get back the fullname (display name, common name, etc) from the first result
32 // POSIX schema: the display name will be found in "cn" (common name)
33 // Active Directory: the display name will be found in "displayName"
35 void derive_fullname_from_ldap_result(char *fullname, int fullname_size, LDAP *ldserver, LDAPMessage *search_result) {
36 struct berval **values;
38 if (fullname == NULL) return;
39 if (search_result == NULL) return;
40 if (ldserver == NULL) return;
42 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
43 values = ldap_get_values_len(ldserver, search_result, "displayName");
45 if (ldap_count_values_len(values) > 0) {
46 safestrncpy(fullname, values[0]->bv_val, fullname_size);
47 syslog(LOG_DEBUG, "ldap: displayName = %s", fullname);
49 ldap_value_free_len(values);
53 values = ldap_get_values_len(ldserver, search_result, "cn");
55 if (ldap_count_values_len(values) > 0) {
56 safestrncpy(fullname, values[0]->bv_val, fullname_size);
57 syslog(LOG_DEBUG, "ldap: cn = %s", fullname);
59 ldap_value_free_len(values);
65 // Utility function, supply a search result and get back the uid from the first result
67 // POSIX schema: numeric user id will be in the "uidNumber" attribute
68 // Active Directory: we make a uid hashed from "objectGUID"
70 uid_t derive_uid_from_ldap(LDAP *ldserver, LDAPMessage *entry) {
71 struct berval **values;
74 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
75 values = ldap_get_values_len(ldserver, entry, "objectGUID");
77 if (ldap_count_values_len(values) > 0) {
78 uid = abs(HashLittle(values[0]->bv_val, values[0]->bv_len));
80 ldap_value_free_len(values);
84 values = ldap_get_values_len(ldserver, entry, "uidNumber");
86 if (ldap_count_values_len(values) > 0) {
87 uid = atoi(values[0]->bv_val);
89 ldap_value_free_len(values);
93 syslog(LOG_DEBUG, "ldap: uid = %d", uid);
98 // Wrapper function for ldap_initialize() that consistently fills in the correct fields
99 int ctdl_ldap_initialize(LDAP **ld) {
101 char server_url[256];
104 snprintf(server_url, sizeof server_url, "ldap://%s:%d", CtdlGetConfigStr("c_ldap_host"), CtdlGetConfigInt("c_ldap_port"));
105 syslog(LOG_DEBUG, "ldap: initializing server %s", server_url);
106 ret = ldap_initialize(ld, server_url);
107 if (ret != LDAP_SUCCESS) {
108 syslog(LOG_ERR, "ldap: could not connect to %s : %m", server_url);
117 // Bind to the LDAP server and return a working handle
118 LDAP *ctdl_ldap_bind(void) {
119 LDAP *ldserver = NULL;
122 if (ctdl_ldap_initialize(&ldserver) != LDAP_SUCCESS) {
126 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
127 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
129 string_trim(CtdlGetConfigStr("c_ldap_bind_dn"));
130 string_trim(CtdlGetConfigStr("c_ldap_bind_pw"));
131 i = ldap_simple_bind_s(ldserver,
132 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_dn")) ? CtdlGetConfigStr("c_ldap_bind_dn") : NULL),
133 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_pw")) ? CtdlGetConfigStr("c_ldap_bind_pw") : NULL)
135 if (i != LDAP_SUCCESS) {
136 syslog(LOG_ERR, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
144 // Look up a user in the directory to see if this is an account that can be authenticated
146 // POSIX schema: Search all "inetOrgPerson" objects with "uid" set to the supplied username
147 // Active Directory: Look for an account with "sAMAccountName" set to the supplied username
149 int CtdlTryUserLDAP(char *username, char *found_dn, int found_dn_size, char *fullname, int fullname_size, uid_t *uid) {
150 LDAP *ldserver = NULL;
151 LDAPMessage *search_result = NULL;
152 LDAPMessage *entry = NULL;
153 char searchstring[1024];
155 char *user_dn = NULL;
157 ldserver = ctdl_ldap_bind();
158 if (!ldserver) return(-1);
160 if (fullname) safestrncpy(fullname, username, fullname_size);
164 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
165 snprintf(searchstring, sizeof(searchstring), "(sAMAccountName=%s)", username);
168 snprintf(searchstring, sizeof(searchstring), "(&(objectclass=inetOrgPerson)(uid=%s))", username);
171 syslog(LOG_DEBUG, "ldap: search: %s", searchstring);
172 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
174 CtdlGetConfigStr("c_ldap_base_dn"), // base
175 LDAP_SCOPE_SUBTREE, // scope
176 searchstring, // filter
177 NULL, // attrs (all attributes)
178 0, // attrsonly (attrs + values)
179 NULL, // serverctrls (none)
180 NULL, // clientctrls (none)
182 1, // sizelimit (1 result max)
183 &search_result // put the result here
186 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
187 // the search succeeds. Instead, we check to see whether search_result is still NULL.
188 if (search_result == NULL) {
189 syslog(LOG_DEBUG, "ldap: zero search results were returned");
190 ldap_unbind(ldserver);
194 // At this point we've got at least one result from our query. If there are multiple
195 // results, we still only look at the first one.
196 entry = ldap_first_entry(ldserver, search_result);
199 user_dn = ldap_get_dn(ldserver, entry);
201 syslog(LOG_DEBUG, "ldap: dn = %s", user_dn);
204 derive_fullname_from_ldap_result(fullname, fullname_size, ldserver, search_result);
205 *uid = derive_uid_from_ldap(ldserver, search_result);
209 ldap_msgfree(search_result);
211 // unbind so we can go back in as the authenticating user
212 ldap_unbind(ldserver);
215 syslog(LOG_DEBUG, "ldap: No such user was found.");
219 if (found_dn) safestrncpy(found_dn, user_dn, found_dn_size);
220 ldap_memfree(user_dn);
225 // This is an extension of CtdlTryPassword() which gets called when using LDAP authentication.
226 int CtdlTryPasswordLDAP(char *user_dn, const char *password) {
227 LDAP *ldserver = NULL;
230 if (IsEmptyStr(password)) {
231 syslog(LOG_DEBUG, "ldap: empty passwords are not permitted");
235 syslog(LOG_DEBUG, "ldap: trying to bind as %s", user_dn);
236 i = ctdl_ldap_initialize(&ldserver);
237 if (i == LDAP_SUCCESS) {
238 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
239 i = ldap_simple_bind_s(ldserver, user_dn, password);
240 if (i == LDAP_SUCCESS) {
241 syslog(LOG_DEBUG, "ldap: bind succeeded");
244 syslog(LOG_DEBUG, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
246 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
247 ldap_unbind(ldserver);
250 if (i == LDAP_SUCCESS) {
258 // set multiple properties
259 // returns nonzero only if property changed.
260 int vcard_set_props_iff_different(struct vCard *v, char *propname, int numvals, char **vals) {
263 for (i=0; i<numvals; i++) {
264 oldval = vcard_get_prop(v, propname, 0, i, 0);
265 if (oldval == NULL) break;
266 if (strcmp(vals[i],oldval)) break;
269 syslog(LOG_DEBUG, "ldap: vcard property %s, element %d of %d changed from %s to %s", propname, i, numvals, oldval, vals[i]);
270 for (i=0; i<numvals; i++) {
271 vcard_set_prop(v,propname,vals[i],(i==0) ? 0 : 1);
280 // returns nonzero only if property changed.
281 int vcard_set_one_prop_iff_different(struct vCard *v,char *propname, char *newfmt, ...) {
285 va_start(args,newfmt);
286 if (vasprintf(&newvalue, newfmt, args) < 0) {
287 syslog(LOG_ERR, "ldap: out of memory");
290 did_change = vcard_set_props_iff_different(v, propname, 1, &newvalue);
297 // Learn LDAP attributes and stuff them into the vCard.
298 // Returns nonzero if we changed anything.
299 int Ctdl_LDAP_to_vCard(char *ldap_dn, struct vCard *v) {
300 int changed_something = 0;
301 LDAP *ldserver = NULL;
303 LDAPMessage *search_result = NULL;
304 LDAPMessage *entry = NULL;
305 struct berval **givenName;
308 struct berval **initials;
310 struct berval **street;
313 struct berval **postalCode;
314 struct berval **telephoneNumber;
315 struct berval **mobile;
316 struct berval **homePhone;
317 struct berval **facsimileTelephoneNumber;
318 struct berval **mail;
320 struct berval **homeDirectory;
321 struct berval **uidNumber;
322 struct berval **loginShell;
323 struct berval **gidNumber;
325 struct berval **title;
326 struct berval **uuid;
327 char *attrs[] = { "*","+",NULL};
329 if (!ldap_dn) return(0);
332 ldserver = ctdl_ldap_bind();
333 if (!ldserver) return(-1);
338 syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
339 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
342 LDAP_SCOPE_SUBTREE, // scope
344 attrs, // attrs (all attributes)
345 0, // attrsonly (attrs + values)
346 NULL, // serverctrls (none)
347 NULL, // clientctrls (none)
349 1, // sizelimit (1 result max)
350 &search_result // res
353 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
354 // the search succeeds. Instead, we check to see whether search_result is still NULL.
355 if (search_result == NULL) {
356 syslog(LOG_DEBUG, "ldap: zero search results were returned");
357 ldap_unbind(ldserver);
361 // At this point we've got at least one result from our query. If there are multiple
362 // results, we still only look at the first one.
363 entry = ldap_first_entry(ldserver, search_result);
365 syslog(LOG_DEBUG, "ldap: search got user details for vcard.");
366 givenName = ldap_get_values_len(ldserver, search_result, "givenName");
367 sn = ldap_get_values_len(ldserver, search_result, "sn");
368 cn = ldap_get_values_len(ldserver, search_result, "cn");
369 initials = ldap_get_values_len(ldserver, search_result, "initials");
370 title = ldap_get_values_len(ldserver, search_result, "title");
371 o = ldap_get_values_len(ldserver, search_result, "o");
372 street = ldap_get_values_len(ldserver, search_result, "street");
373 l = ldap_get_values_len(ldserver, search_result, "l");
374 st = ldap_get_values_len(ldserver, search_result, "st");
375 postalCode = ldap_get_values_len(ldserver, search_result, "postalCode");
376 telephoneNumber = ldap_get_values_len(ldserver, search_result, "telephoneNumber");
377 mobile = ldap_get_values_len(ldserver, search_result, "mobile");
378 homePhone = ldap_get_values_len(ldserver, search_result, "homePhone");
379 facsimileTelephoneNumber = ldap_get_values_len(ldserver, search_result, "facsimileTelephoneNumber");
380 mail = ldap_get_values_len(ldserver, search_result, "mail");
381 uid = ldap_get_values_len(ldserver, search_result, "uid");
382 homeDirectory = ldap_get_values_len(ldserver, search_result, "homeDirectory");
383 uidNumber = ldap_get_values_len(ldserver, search_result, "uidNumber");
384 loginShell = ldap_get_values_len(ldserver, search_result, "loginShell");
385 gidNumber = ldap_get_values_len(ldserver, search_result, "gidNumber");
386 c = ldap_get_values_len(ldserver, search_result, "c");
387 uuid = ldap_get_values_len(ldserver, search_result, "entryUUID");
389 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);
390 if (telephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;work","%s",telephoneNumber[0]->bv_val);
391 if (facsimileTelephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;fax","%s",facsimileTelephoneNumber[0]->bv_val);
392 if (mobile) changed_something |= vcard_set_one_prop_iff_different(v,"tel;cell","%s",mobile[0]->bv_val);
393 if (homePhone) changed_something |= vcard_set_one_prop_iff_different(v,"tel;home","%s",homePhone[0]->bv_val);
394 if (givenName && sn) {
396 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);
399 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s",sn[0]->bv_val,givenName[0]->bv_val);
403 // FIXME we need a new way to do this.
405 //changed_something |= vcard_set_props_iff_different(v,"email;internet",ldap_count_values_len(mail),mail);
408 if (uuid) changed_something |= vcard_set_one_prop_iff_different(v,"X-uuid","%s",uuid[0]->bv_val);
409 if (o) changed_something |= vcard_set_one_prop_iff_different(v,"org","%s",o[0]->bv_val);
410 if (cn) changed_something |= vcard_set_one_prop_iff_different(v,"fn","%s",cn[0]->bv_val);
411 if (title) changed_something |= vcard_set_one_prop_iff_different(v,"title","%s",title[0]->bv_val);
413 if (givenName) ldap_value_free_len(givenName);
414 if (initials) ldap_value_free_len(initials);
415 if (sn) ldap_value_free_len(sn);
416 if (cn) ldap_value_free_len(cn);
417 if (o) ldap_value_free_len(o);
418 if (street) ldap_value_free_len(street);
419 if (l) ldap_value_free_len(l);
420 if (st) ldap_value_free_len(st);
421 if (postalCode) ldap_value_free_len(postalCode);
422 if (telephoneNumber) ldap_value_free_len(telephoneNumber);
423 if (mobile) ldap_value_free_len(mobile);
424 if (homePhone) ldap_value_free_len(homePhone);
425 if (facsimileTelephoneNumber) ldap_value_free_len(facsimileTelephoneNumber);
426 if (mail) ldap_value_free_len(mail);
427 if (uid) ldap_value_free_len(uid);
428 if (homeDirectory) ldap_value_free_len(homeDirectory);
429 if (uidNumber) ldap_value_free_len(uidNumber);
430 if (loginShell) ldap_value_free_len(loginShell);
431 if (gidNumber) ldap_value_free_len(gidNumber);
432 if (c) ldap_value_free_len(c);
433 if (title) ldap_value_free_len(title);
434 if (uuid) ldap_value_free_len(uuid);
437 ldap_msgfree(search_result);
439 // unbind so we can go back in as the authenticating user
440 ldap_unbind(ldserver);
441 return(changed_something); // tell the caller whether we made any changes
445 // Extract a user's Internet email addresses from LDAP.
446 // Returns zero if we got a valid set of addresses; nonzero for error.
447 int extract_email_addresses_from_ldap(char *ldap_dn, char *emailaddrs) {
448 LDAP *ldserver = NULL;
450 LDAPMessage *search_result = NULL;
451 LDAPMessage *entry = NULL;
452 struct berval **mail;
453 char *attrs[] = { "*","+",NULL };
455 if (!ldap_dn) return(1);
456 if (!emailaddrs) return(1);
458 ldserver = ctdl_ldap_bind();
459 if (!ldserver) return(-1);
464 syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
465 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
468 LDAP_SCOPE_SUBTREE, // scope
470 attrs, // attrs (all attributes)
471 0, // attrsonly (attrs + values)
472 NULL, // serverctrls (none)
473 NULL, // clientctrls (none)
475 1, // sizelimit (1 result max)
476 &search_result // res
479 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
480 // the search succeeds. Instead, we check to see whether search_result is still NULL.
481 if (search_result == NULL) {
482 syslog(LOG_DEBUG, "ldap: zero search results were returned");
483 ldap_unbind(ldserver);
487 // At this point we've got at least one result from our query.
488 // If there are multiple results, we still only look at the first one.
489 emailaddrs[0] = 0; // clear out any previous results
490 entry = ldap_first_entry(ldserver, search_result);
492 syslog(LOG_DEBUG, "ldap: search got user details");
493 mail = ldap_get_values_len(ldserver, search_result, "mail");
496 for (q=0; q<ldap_count_values_len(mail); ++q) {
497 if (IsDirectory(mail[q]->bv_val, 0)) {
498 if ((strlen(emailaddrs) + mail[q]->bv_len + 2) > 512) {
499 syslog(LOG_ERR, "ldap: can't fit all email addresses into user record");
502 if (!IsEmptyStr(emailaddrs)) {
503 strcat(emailaddrs, "|");
505 strcat(emailaddrs, mail[q]->bv_val);
513 ldap_msgfree(search_result);
515 // unbind so we can go back in as the authenticating user
516 ldap_unbind(ldserver);
521 // Remember that a particular user exists in the Citadel database.
522 // As we scan the LDAP tree we will remove users from this list when we find them.
523 // At the end of the scan, any users remaining in this list are stale and should be deleted.
524 void ldap_note_user_in_citadel(char *username, void *data) {
529 // Scan LDAP for users and populate Citadel's user database with everyone
531 // POSIX schema: All objects of class "inetOrgPerson"
532 // Active Directory: Objects that are class "user" and class "person" but NOT class "computer"
534 void CtdlSynchronizeUsersFromLDAP(void) {
535 LDAP *ldserver = NULL;
536 LDAPMessage *search_result = NULL;
537 LDAPMessage *entry = NULL;
538 char *user_dn = NULL;
539 char searchstring[1024];
542 if ((CtdlGetConfigInt("c_auth_mode") != AUTHMODE_LDAP) && (CtdlGetConfigInt("c_auth_mode") != AUTHMODE_LDAP_AD)) {
543 return; // If this site is not running LDAP, stop here.
546 syslog(LOG_INFO, "ldap: synchronizing Citadel user database from LDAP");
548 // first, scan the existing Citadel user list
549 // ForEachUser(ldap_note_user_in_citadel, NULL); // FIXME finish this
551 ldserver = ctdl_ldap_bind();
552 if (!ldserver) return;
557 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
558 snprintf(searchstring, sizeof(searchstring), "(&(objectClass=user)(objectClass=person)(!(objectClass=computer)))");
561 snprintf(searchstring, sizeof(searchstring), "(objectClass=inetOrgPerson)");
564 syslog(LOG_DEBUG, "ldap: search: %s", searchstring);
565 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
567 CtdlGetConfigStr("c_ldap_base_dn"), // base
568 LDAP_SCOPE_SUBTREE, // scope
569 searchstring, // filter
570 NULL, // attrs (all attributes)
571 0, // attrsonly (attrs + values)
572 NULL, // serverctrls (none)
573 NULL, // clientctrls (none)
575 INT_MAX, // sizelimit (max)
576 &search_result // put the result here
579 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
580 // the search succeeds. Instead, we check to see whether search_result is still NULL.
581 if (search_result == NULL) {
582 syslog(LOG_DEBUG, "ldap: zero search results were returned");
583 ldap_unbind(ldserver);
587 syslog(LOG_DEBUG, "ldap: %d entries returned", ldap_count_entries(ldserver, search_result));
588 for (entry=ldap_first_entry(ldserver, search_result); entry!=NULL; entry=ldap_next_entry(ldserver, entry)) {
589 user_dn = ldap_get_dn(ldserver, entry);
591 syslog(LOG_DEBUG, "ldap: found %s", user_dn);
593 int fullname_size = 256;
594 char fullname[256] = { 0 } ;
596 char new_emailaddrs[512] = { 0 } ;
598 uid = derive_uid_from_ldap(ldserver, entry);
599 derive_fullname_from_ldap_result(fullname, fullname_size, ldserver, entry);
600 syslog(LOG_DEBUG, "ldap: display name: <%s> , uid = <%d>", fullname, uid);
602 // now create or update the user
604 struct ctdluser usbuf;
606 found_user = getuserbyuid(&usbuf, uid);
607 if (found_user != 0) {
608 create_user(fullname, CREATE_USER_DO_NOT_BECOME_USER, uid);
609 found_user = getuserbyuid(&usbuf, uid);
610 strcpy(fullname, usbuf.fullname);
613 if (found_user == 0) { // user record exists
614 // now update the account email addresses if necessary
615 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
616 if (extract_email_addresses_from_ldap(user_dn, new_emailaddrs) == 0) {
617 if (strcmp(usbuf.emailaddrs, new_emailaddrs)) { // update only if changed
618 CtdlSetEmailAddressesForUser(usbuf.fullname, new_emailaddrs);
623 ldap_memfree(user_dn);
628 ldap_msgfree(search_result);
630 // unbind so we can go back in as the authenticating user
631 ldap_unbind(ldserver);