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 // res
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 int CtdlTryPasswordLDAP(char *user_dn, const char *password) {
225 LDAP *ldserver = NULL;
228 if (IsEmptyStr(password)) {
229 syslog(LOG_DEBUG, "ldap: empty passwords are not permitted");
233 syslog(LOG_DEBUG, "ldap: trying to bind as %s", user_dn);
234 i = ctdl_ldap_initialize(&ldserver);
235 if (i == LDAP_SUCCESS) {
236 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
237 i = ldap_simple_bind_s(ldserver, user_dn, password);
238 if (i == LDAP_SUCCESS) {
239 syslog(LOG_DEBUG, "ldap: bind succeeded");
242 syslog(LOG_DEBUG, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
244 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
245 ldap_unbind(ldserver);
248 if (i == LDAP_SUCCESS) {
256 // set multiple properties
257 // returns nonzero only if property changed.
258 int vcard_set_props_iff_different(struct vCard *v, char *propname, int numvals, char **vals) {
261 for (i=0; i<numvals; i++) {
262 oldval = vcard_get_prop(v, propname, 0, i, 0);
263 if (oldval == NULL) break;
264 if (strcmp(vals[i],oldval)) break;
267 syslog(LOG_DEBUG, "ldap: vcard property %s, element %d of %d changed from %s to %s", propname, i, numvals, oldval, vals[i]);
268 for (i=0; i<numvals; i++) {
269 vcard_set_prop(v,propname,vals[i],(i==0) ? 0 : 1);
278 // returns nonzero only if property changed.
279 int vcard_set_one_prop_iff_different(struct vCard *v,char *propname, char *newfmt, ...) {
283 va_start(args,newfmt);
284 if (vasprintf(&newvalue, newfmt, args) < 0) {
285 syslog(LOG_ERR, "ldap: out of memory");
288 did_change = vcard_set_props_iff_different(v, propname, 1, &newvalue);
295 // Learn LDAP attributes and stuff them into the vCard.
296 // Returns nonzero if we changed anything.
297 int Ctdl_LDAP_to_vCard(char *ldap_dn, struct vCard *v) {
298 int changed_something = 0;
299 LDAP *ldserver = NULL;
301 LDAPMessage *search_result = NULL;
302 LDAPMessage *entry = NULL;
303 struct berval **givenName;
306 struct berval **initials;
308 struct berval **street;
311 struct berval **postalCode;
312 struct berval **telephoneNumber;
313 struct berval **mobile;
314 struct berval **homePhone;
315 struct berval **facsimileTelephoneNumber;
316 struct berval **mail;
318 struct berval **homeDirectory;
319 struct berval **uidNumber;
320 struct berval **loginShell;
321 struct berval **gidNumber;
323 struct berval **title;
324 struct berval **uuid;
325 char *attrs[] = { "*","+",NULL};
327 if (!ldap_dn) return(0);
330 ldserver = ctdl_ldap_bind();
331 if (!ldserver) return(-1);
336 syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
337 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
340 LDAP_SCOPE_SUBTREE, // scope
342 attrs, // attrs (all attributes)
343 0, // attrsonly (attrs + values)
344 NULL, // serverctrls (none)
345 NULL, // clientctrls (none)
347 1, // sizelimit (1 result max)
348 &search_result // res
351 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
352 // the search succeeds. Instead, we check to see whether search_result is still NULL.
353 if (search_result == NULL) {
354 syslog(LOG_DEBUG, "ldap: zero search results were returned");
355 ldap_unbind(ldserver);
359 // At this point we've got at least one result from our query. If there are multiple
360 // results, we still only look at the first one.
361 entry = ldap_first_entry(ldserver, search_result);
363 syslog(LOG_DEBUG, "ldap: search got user details for vcard.");
364 givenName = ldap_get_values_len(ldserver, search_result, "givenName");
365 sn = ldap_get_values_len(ldserver, search_result, "sn");
366 cn = ldap_get_values_len(ldserver, search_result, "cn");
367 initials = ldap_get_values_len(ldserver, search_result, "initials");
368 title = ldap_get_values_len(ldserver, search_result, "title");
369 o = ldap_get_values_len(ldserver, search_result, "o");
370 street = ldap_get_values_len(ldserver, search_result, "street");
371 l = ldap_get_values_len(ldserver, search_result, "l");
372 st = ldap_get_values_len(ldserver, search_result, "st");
373 postalCode = ldap_get_values_len(ldserver, search_result, "postalCode");
374 telephoneNumber = ldap_get_values_len(ldserver, search_result, "telephoneNumber");
375 mobile = ldap_get_values_len(ldserver, search_result, "mobile");
376 homePhone = ldap_get_values_len(ldserver, search_result, "homePhone");
377 facsimileTelephoneNumber = ldap_get_values_len(ldserver, search_result, "facsimileTelephoneNumber");
378 mail = ldap_get_values_len(ldserver, search_result, "mail");
379 uid = ldap_get_values_len(ldserver, search_result, "uid");
380 homeDirectory = ldap_get_values_len(ldserver, search_result, "homeDirectory");
381 uidNumber = ldap_get_values_len(ldserver, search_result, "uidNumber");
382 loginShell = ldap_get_values_len(ldserver, search_result, "loginShell");
383 gidNumber = ldap_get_values_len(ldserver, search_result, "gidNumber");
384 c = ldap_get_values_len(ldserver, search_result, "c");
385 uuid = ldap_get_values_len(ldserver, search_result, "entryUUID");
387 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);
388 if (telephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;work","%s",telephoneNumber[0]->bv_val);
389 if (facsimileTelephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;fax","%s",facsimileTelephoneNumber[0]->bv_val);
390 if (mobile) changed_something |= vcard_set_one_prop_iff_different(v,"tel;cell","%s",mobile[0]->bv_val);
391 if (homePhone) changed_something |= vcard_set_one_prop_iff_different(v,"tel;home","%s",homePhone[0]->bv_val);
392 if (givenName && sn) {
394 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);
397 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s",sn[0]->bv_val,givenName[0]->bv_val);
401 // FIXME we need a new way to do this.
403 //changed_something |= vcard_set_props_iff_different(v,"email;internet",ldap_count_values_len(mail),mail);
406 if (uuid) changed_something |= vcard_set_one_prop_iff_different(v,"X-uuid","%s",uuid[0]->bv_val);
407 if (o) changed_something |= vcard_set_one_prop_iff_different(v,"org","%s",o[0]->bv_val);
408 if (cn) changed_something |= vcard_set_one_prop_iff_different(v,"fn","%s",cn[0]->bv_val);
409 if (title) changed_something |= vcard_set_one_prop_iff_different(v,"title","%s",title[0]->bv_val);
411 if (givenName) ldap_value_free_len(givenName);
412 if (initials) ldap_value_free_len(initials);
413 if (sn) ldap_value_free_len(sn);
414 if (cn) ldap_value_free_len(cn);
415 if (o) ldap_value_free_len(o);
416 if (street) ldap_value_free_len(street);
417 if (l) ldap_value_free_len(l);
418 if (st) ldap_value_free_len(st);
419 if (postalCode) ldap_value_free_len(postalCode);
420 if (telephoneNumber) ldap_value_free_len(telephoneNumber);
421 if (mobile) ldap_value_free_len(mobile);
422 if (homePhone) ldap_value_free_len(homePhone);
423 if (facsimileTelephoneNumber) ldap_value_free_len(facsimileTelephoneNumber);
424 if (mail) ldap_value_free_len(mail);
425 if (uid) ldap_value_free_len(uid);
426 if (homeDirectory) ldap_value_free_len(homeDirectory);
427 if (uidNumber) ldap_value_free_len(uidNumber);
428 if (loginShell) ldap_value_free_len(loginShell);
429 if (gidNumber) ldap_value_free_len(gidNumber);
430 if (c) ldap_value_free_len(c);
431 if (title) ldap_value_free_len(title);
432 if (uuid) ldap_value_free_len(uuid);
435 ldap_msgfree(search_result);
437 // unbind so we can go back in as the authenticating user
438 ldap_unbind(ldserver);
439 return(changed_something); // tell the caller whether we made any changes
443 // Extract a user's Internet email addresses from LDAP.
444 // Returns zero if we got a valid set of addresses; nonzero for error.
445 int extract_email_addresses_from_ldap(char *ldap_dn, char *emailaddrs) {
446 LDAP *ldserver = NULL;
448 LDAPMessage *search_result = NULL;
449 LDAPMessage *entry = NULL;
450 struct berval **mail;
451 char *attrs[] = { "*","+",NULL };
453 if (!ldap_dn) return(1);
454 if (!emailaddrs) return(1);
456 ldserver = ctdl_ldap_bind();
457 if (!ldserver) return(-1);
462 syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
463 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
466 LDAP_SCOPE_SUBTREE, // scope
468 attrs, // attrs (all attributes)
469 0, // attrsonly (attrs + values)
470 NULL, // serverctrls (none)
471 NULL, // clientctrls (none)
473 1, // sizelimit (1 result max)
474 &search_result // res
477 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
478 // the search succeeds. Instead, we check to see whether search_result is still NULL.
479 if (search_result == NULL) {
480 syslog(LOG_DEBUG, "ldap: zero search results were returned");
481 ldap_unbind(ldserver);
485 // At this point we've got at least one result from our query.
486 // If there are multiple results, we still only look at the first one.
487 emailaddrs[0] = 0; // clear out any previous results
488 entry = ldap_first_entry(ldserver, search_result);
490 syslog(LOG_DEBUG, "ldap: search got user details");
491 mail = ldap_get_values_len(ldserver, search_result, "mail");
494 for (q=0; q<ldap_count_values_len(mail); ++q) {
495 if (IsDirectory(mail[q]->bv_val, 0)) {
496 if ((strlen(emailaddrs) + mail[q]->bv_len + 2) > 512) {
497 syslog(LOG_ERR, "ldap: can't fit all email addresses into user record");
500 if (!IsEmptyStr(emailaddrs)) {
501 strcat(emailaddrs, "|");
503 strcat(emailaddrs, mail[q]->bv_val);
511 ldap_msgfree(search_result);
513 // unbind so we can go back in as the authenticating user
514 ldap_unbind(ldserver);
519 // Scan LDAP for users and populate Citadel's user database with everyone
521 // POSIX schema: All objects of class "inetOrgPerson"
522 // Active Directory: Objects that are class "user" and class "person" but NOT class "computer"
524 void CtdlSynchronizeUsersFromLDAP(void) {
525 LDAP *ldserver = NULL;
526 LDAPMessage *search_result = NULL;
527 LDAPMessage *entry = NULL;
528 char *user_dn = NULL;
529 char searchstring[1024];
532 if ((CtdlGetConfigInt("c_auth_mode") != AUTHMODE_LDAP) && (CtdlGetConfigInt("c_auth_mode") != AUTHMODE_LDAP_AD)) {
533 return; // This site is not running LDAP. Stop here.
536 syslog(LOG_INFO, "ldap: synchronizing Citadel user database from LDAP");
538 ldserver = ctdl_ldap_bind();
539 if (!ldserver) return;
544 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
545 snprintf(searchstring, sizeof(searchstring), "(&(objectClass=user)(objectClass=person)(!(objectClass=computer)))");
548 snprintf(searchstring, sizeof(searchstring), "(objectClass=inetOrgPerson)");
551 syslog(LOG_DEBUG, "ldap: search: %s", searchstring);
552 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
554 CtdlGetConfigStr("c_ldap_base_dn"), // base
555 LDAP_SCOPE_SUBTREE, // scope
556 searchstring, // filter
557 NULL, // attrs (all attributes)
558 0, // attrsonly (attrs + values)
559 NULL, // serverctrls (none)
560 NULL, // clientctrls (none)
562 INT_MAX, // sizelimit (max)
563 &search_result // result
566 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
567 // the search succeeds. Instead, we check to see whether search_result is still NULL.
568 if (search_result == NULL) {
569 syslog(LOG_DEBUG, "ldap: zero search results were returned");
570 ldap_unbind(ldserver);
574 syslog(LOG_DEBUG, "ldap: %d entries returned", ldap_count_entries(ldserver, search_result));
575 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);
617 ldap_msgfree(search_result);
619 // unbind so we can go back in as the authenticating user
620 ldap_unbind(ldserver);