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 // 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 ret = ldap_initialize(ld, server_url);
106 if (ret != LDAP_SUCCESS) {
107 syslog(LOG_ERR, "ldap: could not connect to %s : %m", server_url);
116 // Bind to the LDAP server and return a working handle
117 LDAP *ctdl_ldap_bind(void) {
118 LDAP *ldserver = NULL;
121 if (ctdl_ldap_initialize(&ldserver) != LDAP_SUCCESS) {
125 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
126 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
128 striplt(CtdlGetConfigStr("c_ldap_bind_dn"));
129 striplt(CtdlGetConfigStr("c_ldap_bind_pw"));
130 i = ldap_simple_bind_s(ldserver,
131 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_dn")) ? CtdlGetConfigStr("c_ldap_bind_dn") : NULL),
132 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_pw")) ? CtdlGetConfigStr("c_ldap_bind_pw") : NULL)
134 if (i != LDAP_SUCCESS) {
135 syslog(LOG_ERR, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
143 // Look up a user in the directory to see if this is an account that can be authenticated
145 // POSIX schema: Search all "inetOrgPerson" objects with "uid" set to the supplied username
146 // Active Directory: Look for an account with "sAMAccountName" set to the supplied username
148 int CtdlTryUserLDAP(char *username, char *found_dn, int found_dn_size, char *fullname, int fullname_size, uid_t *uid) {
149 LDAP *ldserver = NULL;
150 LDAPMessage *search_result = NULL;
151 LDAPMessage *entry = NULL;
152 char searchstring[1024];
154 char *user_dn = NULL;
156 ldserver = ctdl_ldap_bind();
157 if (!ldserver) return(-1);
159 if (fullname) safestrncpy(fullname, username, fullname_size);
163 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
164 snprintf(searchstring, sizeof(searchstring), "(sAMAccountName=%s)", username);
167 snprintf(searchstring, sizeof(searchstring), "(&(objectclass=inetOrgPerson)(uid=%s))", username);
170 syslog(LOG_DEBUG, "ldap: search: %s", searchstring);
171 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
173 CtdlGetConfigStr("c_ldap_base_dn"), // base
174 LDAP_SCOPE_SUBTREE, // scope
175 searchstring, // filter
176 NULL, // attrs (all attributes)
177 0, // attrsonly (attrs + values)
178 NULL, // serverctrls (none)
179 NULL, // clientctrls (none)
181 1, // sizelimit (1 result max)
182 &search_result // put the result here
185 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
186 // the search succeeds. Instead, we check to see whether search_result is still NULL.
187 if (search_result == NULL) {
188 syslog(LOG_DEBUG, "ldap: zero search results were returned");
189 ldap_unbind(ldserver);
193 // At this point we've got at least one result from our query. If there are multiple
194 // results, we still only look at the first one.
195 entry = ldap_first_entry(ldserver, search_result);
198 user_dn = ldap_get_dn(ldserver, entry);
200 syslog(LOG_DEBUG, "ldap: dn = %s", user_dn);
203 derive_fullname_from_ldap_result(fullname, fullname_size, ldserver, search_result);
204 *uid = derive_uid_from_ldap(ldserver, search_result);
208 ldap_msgfree(search_result);
210 // unbind so we can go back in as the authenticating user
211 ldap_unbind(ldserver);
214 syslog(LOG_DEBUG, "ldap: No such user was found.");
218 if (found_dn) safestrncpy(found_dn, user_dn, found_dn_size);
219 ldap_memfree(user_dn);
224 // This is an extension of CtdlTryPassword() which gets called when using LDAP authentication.
225 int CtdlTryPasswordLDAP(char *user_dn, const char *password) {
226 LDAP *ldserver = NULL;
229 if (IsEmptyStr(password)) {
230 syslog(LOG_DEBUG, "ldap: empty passwords are not permitted");
234 syslog(LOG_DEBUG, "ldap: trying to bind as %s", user_dn);
235 i = ctdl_ldap_initialize(&ldserver);
236 if (i == LDAP_SUCCESS) {
237 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
238 i = ldap_simple_bind_s(ldserver, user_dn, password);
239 if (i == LDAP_SUCCESS) {
240 syslog(LOG_DEBUG, "ldap: bind succeeded");
243 syslog(LOG_DEBUG, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
245 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
246 ldap_unbind(ldserver);
249 if (i == LDAP_SUCCESS) {
257 // set multiple properties
258 // returns nonzero only if property changed.
259 int vcard_set_props_iff_different(struct vCard *v, char *propname, int numvals, char **vals) {
262 for (i=0; i<numvals; i++) {
263 oldval = vcard_get_prop(v, propname, 0, i, 0);
264 if (oldval == NULL) break;
265 if (strcmp(vals[i],oldval)) break;
268 syslog(LOG_DEBUG, "ldap: vcard property %s, element %d of %d changed from %s to %s", propname, i, numvals, oldval, vals[i]);
269 for (i=0; i<numvals; i++) {
270 vcard_set_prop(v,propname,vals[i],(i==0) ? 0 : 1);
279 // returns nonzero only if property changed.
280 int vcard_set_one_prop_iff_different(struct vCard *v,char *propname, char *newfmt, ...) {
284 va_start(args,newfmt);
285 if (vasprintf(&newvalue, newfmt, args) < 0) {
286 syslog(LOG_ERR, "ldap: out of memory");
289 did_change = vcard_set_props_iff_different(v, propname, 1, &newvalue);
296 // Learn LDAP attributes and stuff them into the vCard.
297 // Returns nonzero if we changed anything.
298 int Ctdl_LDAP_to_vCard(char *ldap_dn, struct vCard *v) {
299 int changed_something = 0;
300 LDAP *ldserver = NULL;
302 LDAPMessage *search_result = NULL;
303 LDAPMessage *entry = NULL;
304 struct berval **givenName;
307 struct berval **initials;
309 struct berval **street;
312 struct berval **postalCode;
313 struct berval **telephoneNumber;
314 struct berval **mobile;
315 struct berval **homePhone;
316 struct berval **facsimileTelephoneNumber;
317 struct berval **mail;
319 struct berval **homeDirectory;
320 struct berval **uidNumber;
321 struct berval **loginShell;
322 struct berval **gidNumber;
324 struct berval **title;
325 struct berval **uuid;
326 char *attrs[] = { "*","+",NULL};
328 if (!ldap_dn) return(0);
331 ldserver = ctdl_ldap_bind();
332 if (!ldserver) return(-1);
337 syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
338 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
341 LDAP_SCOPE_SUBTREE, // scope
343 attrs, // attrs (all attributes)
344 0, // attrsonly (attrs + values)
345 NULL, // serverctrls (none)
346 NULL, // clientctrls (none)
348 1, // sizelimit (1 result max)
349 &search_result // res
352 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
353 // the search succeeds. Instead, we check to see whether search_result is still NULL.
354 if (search_result == NULL) {
355 syslog(LOG_DEBUG, "ldap: zero search results were returned");
356 ldap_unbind(ldserver);
360 // At this point we've got at least one result from our query. If there are multiple
361 // results, we still only look at the first one.
362 entry = ldap_first_entry(ldserver, search_result);
364 syslog(LOG_DEBUG, "ldap: search got user details for vcard.");
365 givenName = ldap_get_values_len(ldserver, search_result, "givenName");
366 sn = ldap_get_values_len(ldserver, search_result, "sn");
367 cn = ldap_get_values_len(ldserver, search_result, "cn");
368 initials = ldap_get_values_len(ldserver, search_result, "initials");
369 title = ldap_get_values_len(ldserver, search_result, "title");
370 o = ldap_get_values_len(ldserver, search_result, "o");
371 street = ldap_get_values_len(ldserver, search_result, "street");
372 l = ldap_get_values_len(ldserver, search_result, "l");
373 st = ldap_get_values_len(ldserver, search_result, "st");
374 postalCode = ldap_get_values_len(ldserver, search_result, "postalCode");
375 telephoneNumber = ldap_get_values_len(ldserver, search_result, "telephoneNumber");
376 mobile = ldap_get_values_len(ldserver, search_result, "mobile");
377 homePhone = ldap_get_values_len(ldserver, search_result, "homePhone");
378 facsimileTelephoneNumber = ldap_get_values_len(ldserver, search_result, "facsimileTelephoneNumber");
379 mail = ldap_get_values_len(ldserver, search_result, "mail");
380 uid = ldap_get_values_len(ldserver, search_result, "uid");
381 homeDirectory = ldap_get_values_len(ldserver, search_result, "homeDirectory");
382 uidNumber = ldap_get_values_len(ldserver, search_result, "uidNumber");
383 loginShell = ldap_get_values_len(ldserver, search_result, "loginShell");
384 gidNumber = ldap_get_values_len(ldserver, search_result, "gidNumber");
385 c = ldap_get_values_len(ldserver, search_result, "c");
386 uuid = ldap_get_values_len(ldserver, search_result, "entryUUID");
388 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);
389 if (telephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;work","%s",telephoneNumber[0]->bv_val);
390 if (facsimileTelephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;fax","%s",facsimileTelephoneNumber[0]->bv_val);
391 if (mobile) changed_something |= vcard_set_one_prop_iff_different(v,"tel;cell","%s",mobile[0]->bv_val);
392 if (homePhone) changed_something |= vcard_set_one_prop_iff_different(v,"tel;home","%s",homePhone[0]->bv_val);
393 if (givenName && sn) {
395 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);
398 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s",sn[0]->bv_val,givenName[0]->bv_val);
402 // FIXME we need a new way to do this.
404 //changed_something |= vcard_set_props_iff_different(v,"email;internet",ldap_count_values_len(mail),mail);
407 if (uuid) changed_something |= vcard_set_one_prop_iff_different(v,"X-uuid","%s",uuid[0]->bv_val);
408 if (o) changed_something |= vcard_set_one_prop_iff_different(v,"org","%s",o[0]->bv_val);
409 if (cn) changed_something |= vcard_set_one_prop_iff_different(v,"fn","%s",cn[0]->bv_val);
410 if (title) changed_something |= vcard_set_one_prop_iff_different(v,"title","%s",title[0]->bv_val);
412 if (givenName) ldap_value_free_len(givenName);
413 if (initials) ldap_value_free_len(initials);
414 if (sn) ldap_value_free_len(sn);
415 if (cn) ldap_value_free_len(cn);
416 if (o) ldap_value_free_len(o);
417 if (street) ldap_value_free_len(street);
418 if (l) ldap_value_free_len(l);
419 if (st) ldap_value_free_len(st);
420 if (postalCode) ldap_value_free_len(postalCode);
421 if (telephoneNumber) ldap_value_free_len(telephoneNumber);
422 if (mobile) ldap_value_free_len(mobile);
423 if (homePhone) ldap_value_free_len(homePhone);
424 if (facsimileTelephoneNumber) ldap_value_free_len(facsimileTelephoneNumber);
425 if (mail) ldap_value_free_len(mail);
426 if (uid) ldap_value_free_len(uid);
427 if (homeDirectory) ldap_value_free_len(homeDirectory);
428 if (uidNumber) ldap_value_free_len(uidNumber);
429 if (loginShell) ldap_value_free_len(loginShell);
430 if (gidNumber) ldap_value_free_len(gidNumber);
431 if (c) ldap_value_free_len(c);
432 if (title) ldap_value_free_len(title);
433 if (uuid) ldap_value_free_len(uuid);
436 ldap_msgfree(search_result);
438 // unbind so we can go back in as the authenticating user
439 ldap_unbind(ldserver);
440 return(changed_something); // tell the caller whether we made any changes
444 // Extract a user's Internet email addresses from LDAP.
445 // Returns zero if we got a valid set of addresses; nonzero for error.
446 int extract_email_addresses_from_ldap(char *ldap_dn, char *emailaddrs) {
447 LDAP *ldserver = NULL;
449 LDAPMessage *search_result = NULL;
450 LDAPMessage *entry = NULL;
451 struct berval **mail;
452 char *attrs[] = { "*","+",NULL };
454 if (!ldap_dn) return(1);
455 if (!emailaddrs) return(1);
457 ldserver = ctdl_ldap_bind();
458 if (!ldserver) return(-1);
463 syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
464 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
467 LDAP_SCOPE_SUBTREE, // scope
469 attrs, // attrs (all attributes)
470 0, // attrsonly (attrs + values)
471 NULL, // serverctrls (none)
472 NULL, // clientctrls (none)
474 1, // sizelimit (1 result max)
475 &search_result // res
478 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
479 // the search succeeds. Instead, we check to see whether search_result is still NULL.
480 if (search_result == NULL) {
481 syslog(LOG_DEBUG, "ldap: zero search results were returned");
482 ldap_unbind(ldserver);
486 // At this point we've got at least one result from our query.
487 // If there are multiple results, we still only look at the first one.
488 emailaddrs[0] = 0; // clear out any previous results
489 entry = ldap_first_entry(ldserver, search_result);
491 syslog(LOG_DEBUG, "ldap: search got user details");
492 mail = ldap_get_values_len(ldserver, search_result, "mail");
495 for (q=0; q<ldap_count_values_len(mail); ++q) {
496 if (IsDirectory(mail[q]->bv_val, 0)) {
497 if ((strlen(emailaddrs) + mail[q]->bv_len + 2) > 512) {
498 syslog(LOG_ERR, "ldap: can't fit all email addresses into user record");
501 if (!IsEmptyStr(emailaddrs)) {
502 strcat(emailaddrs, "|");
504 strcat(emailaddrs, mail[q]->bv_val);
512 ldap_msgfree(search_result);
514 // unbind so we can go back in as the authenticating user
515 ldap_unbind(ldserver);
520 // Scan LDAP for users and populate Citadel's user database with everyone
522 // POSIX schema: All objects of class "inetOrgPerson"
523 // Active Directory: Objects that are class "user" and class "person" but NOT class "computer"
525 void CtdlSynchronizeUsersFromLDAP(void) {
526 LDAP *ldserver = NULL;
527 LDAPMessage *search_result = NULL;
528 LDAPMessage *entry = NULL;
529 char *user_dn = NULL;
530 char searchstring[1024];
533 if ((CtdlGetConfigInt("c_auth_mode") != AUTHMODE_LDAP) && (CtdlGetConfigInt("c_auth_mode") != AUTHMODE_LDAP_AD)) {
534 return; // If this site is not running LDAP, stop here.
537 syslog(LOG_INFO, "ldap: synchronizing Citadel user database from LDAP");
539 ldserver = ctdl_ldap_bind();
540 if (!ldserver) return;
545 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
546 snprintf(searchstring, sizeof(searchstring), "(&(objectClass=user)(objectClass=person)(!(objectClass=computer)))");
549 snprintf(searchstring, sizeof(searchstring), "(objectClass=inetOrgPerson)");
552 syslog(LOG_DEBUG, "ldap: search: %s", searchstring);
553 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
555 CtdlGetConfigStr("c_ldap_base_dn"), // base
556 LDAP_SCOPE_SUBTREE, // scope
557 searchstring, // filter
558 NULL, // attrs (all attributes)
559 0, // attrsonly (attrs + values)
560 NULL, // serverctrls (none)
561 NULL, // clientctrls (none)
563 INT_MAX, // sizelimit (max)
564 &search_result // put the result here
567 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
568 // the search succeeds. Instead, we check to see whether search_result is still NULL.
569 if (search_result == NULL) {
570 syslog(LOG_DEBUG, "ldap: zero search results were returned");
571 ldap_unbind(ldserver);
575 syslog(LOG_DEBUG, "ldap: %d entries returned", ldap_count_entries(ldserver, search_result));
576 for (entry=ldap_first_entry(ldserver, search_result); entry!=NULL; entry=ldap_next_entry(ldserver, entry)) {
577 user_dn = ldap_get_dn(ldserver, entry);
579 syslog(LOG_DEBUG, "ldap: found %s", user_dn);
581 int fullname_size = 256;
582 char fullname[256] = { 0 } ;
584 char new_emailaddrs[512] = { 0 } ;
586 uid = derive_uid_from_ldap(ldserver, entry);
587 derive_fullname_from_ldap_result(fullname, fullname_size, ldserver, entry);
588 syslog(LOG_DEBUG, "ldap: display name: <%s> , uid = <%d>", fullname, uid);
590 // now create or update the user
592 struct ctdluser usbuf;
594 found_user = getuserbyuid(&usbuf, uid);
595 if (found_user != 0) {
596 create_user(fullname, CREATE_USER_DO_NOT_BECOME_USER, uid);
597 found_user = getuserbyuid(&usbuf, uid);
598 strcpy(fullname, usbuf.fullname);
601 if (found_user == 0) { // user record exists
602 // now update the account email addresses if necessary
603 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
604 if (extract_email_addresses_from_ldap(user_dn, new_emailaddrs) == 0) {
605 if (strcmp(usbuf.emailaddrs, new_emailaddrs)) { // update only if changed
606 CtdlSetEmailAddressesForUser(usbuf.fullname, new_emailaddrs);
611 ldap_memfree(user_dn);
616 ldap_msgfree(search_result);
618 // unbind so we can go back in as the authenticating user
619 ldap_unbind(ldserver);