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 int ctdl_require_ldap_version = 3;
16 #define _GNU_SOURCE // Needed to suppress warning about vasprintf() when running on Linux/Linux
18 #include <libcitadel.h>
19 #include "citserver.h"
20 #include "citadel_ldap.h"
21 #include "ctdl_module.h"
23 #include "internet_addressing.h"
28 // Utility function, supply a search result and get back the fullname (display name, common name, etc) from the first result
29 void derive_fullname_from_ldap_result(char *fullname, int fullname_size, LDAP *ldserver, LDAPMessage *search_result) {
32 if (fullname == NULL) return;
33 if (search_result == NULL) return;
34 if (ldserver == NULL) return;
36 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
37 values = ldap_get_values(ldserver, search_result, "displayName");
40 if (fullname) safestrncpy(fullname, values[0], fullname_size);
41 syslog(LOG_DEBUG, "ldap: displayName = %s", values[0]);
43 ldap_value_free(values);
47 values = ldap_get_values(ldserver, search_result, "cn");
50 if (fullname) safestrncpy(fullname, values[0], fullname_size);
51 syslog(LOG_DEBUG, "ldap: cn = %s", values[0]);
53 ldap_value_free(values);
59 // Utility function, supply a search result and get back the uid from the first result
60 uid_t derive_uid_from_ldap(LDAP *ldserver, LDAPMessage *entry) {
61 struct berval **values;
64 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
65 values = ldap_get_values_len(ldserver, entry, "objectGUID"); // AD schema: uid hashed from objectGUID
67 if (ldap_count_values_len(values) > 0) {
68 uid = abs(HashLittle(values[0]->bv_val, values[0]->bv_len));
70 ldap_value_free(Xvalues);
74 values = ldap_get_values_len(ldserver, entry, "uidNumber"); // POSIX schema: uid = uidNumber
76 if (ldap_count_values_len(values) > 0) {
77 uid = atoi(values[0]->bv_val);
79 ldap_value_free_len(values);
83 syslog(LOG_DEBUG, "ldap: uid = %d", uid);
88 // Wrapper function for ldap_initialize() that consistently fills in the correct fields
89 int ctdl_ldap_initialize(LDAP **ld) {
94 snprintf(server_url, sizeof server_url, "ldap://%s:%d", CtdlGetConfigStr("c_ldap_host"), CtdlGetConfigInt("c_ldap_port"));
95 ret = ldap_initialize(ld, server_url);
96 if (ret != LDAP_SUCCESS) {
97 syslog(LOG_ERR, "ldap: could not connect to %s : %m", server_url);
106 // Bind to the LDAP server and return a working handle
107 LDAP *ctdl_ldap_bind(void) {
108 LDAP *ldserver = NULL;
111 if (ctdl_ldap_initialize(&ldserver) != LDAP_SUCCESS) {
115 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
116 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
118 striplt(CtdlGetConfigStr("c_ldap_bind_dn"));
119 striplt(CtdlGetConfigStr("c_ldap_bind_pw"));
120 i = ldap_simple_bind_s(ldserver,
121 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_dn")) ? CtdlGetConfigStr("c_ldap_bind_dn") : NULL),
122 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_pw")) ? CtdlGetConfigStr("c_ldap_bind_pw") : NULL)
124 if (i != LDAP_SUCCESS) {
125 syslog(LOG_ERR, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
133 // Look up a user in the directory to see if this is an account that can be authenticated
134 int CtdlTryUserLDAP(char *username, char *found_dn, int found_dn_size, char *fullname, int fullname_size, uid_t *uid) {
135 LDAP *ldserver = NULL;
136 LDAPMessage *search_result = NULL;
137 LDAPMessage *entry = NULL;
138 char searchstring[1024];
140 char *user_dn = NULL;
142 ldserver = ctdl_ldap_bind();
143 if (!ldserver) return(-1);
145 if (fullname) safestrncpy(fullname, username, fullname_size);
149 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
150 snprintf(searchstring, sizeof(searchstring), "(sAMAccountName=%s)", username);
153 snprintf(searchstring, sizeof(searchstring), "(&(objectclass=posixAccount)(cn=%s))", username);
154 // snprintf(searchstring, sizeof(searchstring), "(&(objectclass=posixAccount)(uid=%s))", username);
157 syslog(LOG_DEBUG, "ldap: search: %s", searchstring);
158 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
160 CtdlGetConfigStr("c_ldap_base_dn"), // base
161 LDAP_SCOPE_SUBTREE, // scope
162 searchstring, // filter
163 NULL, // attrs (all attributes)
164 0, // attrsonly (attrs + values)
165 NULL, // serverctrls (none)
166 NULL, // clientctrls (none)
168 1, // sizelimit (1 result max)
169 &search_result // res
172 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
173 // the search succeeds. Instead, we check to see whether search_result is still NULL.
174 if (search_result == NULL) {
175 syslog(LOG_DEBUG, "ldap: zero search results were returned");
176 ldap_unbind(ldserver);
180 // At this point we've got at least one result from our query. If there are multiple
181 // results, we still only look at the first one.
182 entry = ldap_first_entry(ldserver, search_result);
185 user_dn = ldap_get_dn(ldserver, entry);
187 syslog(LOG_DEBUG, "ldap: dn = %s", user_dn);
190 derive_fullname_from_ldap_result(fullname, fullname_size, ldserver, search_result);
191 *uid = derive_uid_from_ldap(ldserver, search_result);
195 ldap_msgfree(search_result);
197 // unbind so we can go back in as the authenticating user
198 ldap_unbind(ldserver);
201 syslog(LOG_DEBUG, "ldap: No such user was found.");
205 if (found_dn) safestrncpy(found_dn, user_dn, found_dn_size);
206 ldap_memfree(user_dn);
211 int CtdlTryPasswordLDAP(char *user_dn, const char *password) {
212 LDAP *ldserver = NULL;
215 if (IsEmptyStr(password)) {
216 syslog(LOG_DEBUG, "ldap: empty passwords are not permitted");
220 syslog(LOG_DEBUG, "ldap: trying to bind as %s", user_dn);
221 i = ctdl_ldap_initialize(&ldserver);
222 if (i == LDAP_SUCCESS) {
223 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
224 i = ldap_simple_bind_s(ldserver, user_dn, password);
225 if (i == LDAP_SUCCESS) {
226 syslog(LOG_DEBUG, "ldap: bind succeeded");
229 syslog(LOG_DEBUG, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
231 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
232 ldap_unbind(ldserver);
235 if (i == LDAP_SUCCESS) {
243 //return !0 iff property changed.
244 int vcard_set_props_iff_different(struct vCard *v,char *propname,int numvals, char **vals) {
247 for(i=0;i<numvals;i++) {
248 oldval = vcard_get_prop(v,propname,0,i,0);
249 if (oldval == NULL) break;
250 if (strcmp(vals[i],oldval)) break;
253 syslog(LOG_DEBUG, "ldap: vcard property %s, element %d of %d changed from %s to %s\n", propname, i, numvals, oldval, vals[i]);
254 for(i=0;i<numvals;i++) vcard_set_prop(v,propname,vals[i],(i==0) ? 0 : 1);
261 //return !0 iff property changed.
262 int vcard_set_one_prop_iff_different(struct vCard *v,char *propname, char *newfmt, ...) {
265 int changed_something;
266 va_start(args,newfmt);
267 if (-1==vasprintf(&newvalue,newfmt,args)) {
268 syslog(LOG_ERR, "ldap: out of memory!");
271 changed_something = vcard_set_props_iff_different(v,propname,1,&newvalue);
274 return changed_something;
278 // Learn LDAP attributes and stuff them into the vCard.
279 // Returns nonzero if we changed anything.
280 int Ctdl_LDAP_to_vCard(char *ldap_dn, struct vCard *v) {
281 int changed_something = 0;
282 LDAP *ldserver = NULL;
284 LDAPMessage *search_result = NULL;
285 LDAPMessage *entry = NULL;
295 char **telephoneNumber;
298 char **facsimileTelephoneNumber;
301 char **homeDirectory;
308 char *attrs[] = { "*","+",NULL};
310 if (!ldap_dn) return(0);
313 ldserver = ctdl_ldap_bind();
314 if (!ldserver) return(-1);
319 syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
320 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
323 LDAP_SCOPE_SUBTREE, // scope
325 attrs, // attrs (all attributes)
326 0, // attrsonly (attrs + values)
327 NULL, // serverctrls (none)
328 NULL, // clientctrls (none)
330 1, // sizelimit (1 result max)
331 &search_result // res
334 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
335 // the search succeeds. Instead, we check to see whether search_result is still NULL.
336 if (search_result == NULL) {
337 syslog(LOG_DEBUG, "ldap: zero search results were returned");
338 ldap_unbind(ldserver);
342 // At this point we've got at least one result from our query. If there are multiple
343 // results, we still only look at the first one.
344 entry = ldap_first_entry(ldserver, search_result);
346 syslog(LOG_DEBUG, "ldap: search got user details for vcard.");
347 givenName=ldap_get_values(ldserver, search_result, "givenName");
348 sn=ldap_get_values(ldserver, search_result, "sn");
349 cn=ldap_get_values(ldserver, search_result, "cn");
350 initials=ldap_get_values(ldserver, search_result, "initials");
351 title=ldap_get_values(ldserver, search_result, "title");
352 o=ldap_get_values(ldserver, search_result, "o");
353 street=ldap_get_values(ldserver, search_result, "street");
354 l=ldap_get_values(ldserver, search_result, "l");
355 st=ldap_get_values(ldserver, search_result, "st");
356 postalCode=ldap_get_values(ldserver, search_result, "postalCode");
357 telephoneNumber=ldap_get_values(ldserver, search_result, "telephoneNumber");
358 mobile=ldap_get_values(ldserver, search_result, "mobile");
359 homePhone=ldap_get_values(ldserver, search_result, "homePhone");
360 facsimileTelephoneNumber=ldap_get_values(ldserver, search_result, "facsimileTelephoneNumber");
361 mail=ldap_get_values(ldserver, search_result, "mail");
362 uid=ldap_get_values(ldserver, search_result, "uid");
363 homeDirectory=ldap_get_values(ldserver, search_result, "homeDirectory");
364 uidNumber=ldap_get_values(ldserver, search_result, "uidNumber");
365 loginShell=ldap_get_values(ldserver, search_result, "loginShell");
366 gidNumber=ldap_get_values(ldserver, search_result, "gidNumber");
367 c=ldap_get_values(ldserver, search_result, "c");
368 uuid=ldap_get_values(ldserver, search_result, "entryUUID");
370 if (street && l && st && postalCode && c) changed_something |= vcard_set_one_prop_iff_different(v,"adr",";;%s;%s;%s;%s;%s",street[0],l[0],st[0],postalCode[0],c[0]);
371 if (telephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;work","%s",telephoneNumber[0]);
372 if (facsimileTelephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;fax","%s",facsimileTelephoneNumber[0]);
373 if (mobile) changed_something |= vcard_set_one_prop_iff_different(v,"tel;cell","%s",mobile[0]);
374 if (homePhone) changed_something |= vcard_set_one_prop_iff_different(v,"tel;home","%s",homePhone[0]);
375 if (givenName && sn) {
377 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s;%s",sn[0],givenName[0],initials[0]);
380 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s",sn[0],givenName[0]);
384 changed_something |= vcard_set_props_iff_different(v,"email;internet",ldap_count_values(mail),mail);
386 if (uuid) changed_something |= vcard_set_one_prop_iff_different(v,"X-uuid","%s",uuid[0]);
387 if (o) changed_something |= vcard_set_one_prop_iff_different(v,"org","%s",o[0]);
388 if (cn) changed_something |= vcard_set_one_prop_iff_different(v,"fn","%s",cn[0]);
389 if (title) changed_something |= vcard_set_one_prop_iff_different(v,"title","%s",title[0]);
391 if (givenName) ldap_value_free(givenName);
392 if (initials) ldap_value_free(initials);
393 if (sn) ldap_value_free(sn);
394 if (cn) ldap_value_free(cn);
395 if (o) ldap_value_free(o);
396 if (street) ldap_value_free(street);
397 if (l) ldap_value_free(l);
398 if (st) ldap_value_free(st);
399 if (postalCode) ldap_value_free(postalCode);
400 if (telephoneNumber) ldap_value_free(telephoneNumber);
401 if (mobile) ldap_value_free(mobile);
402 if (homePhone) ldap_value_free(homePhone);
403 if (facsimileTelephoneNumber) ldap_value_free(facsimileTelephoneNumber);
404 if (mail) ldap_value_free(mail);
405 if (uid) ldap_value_free(uid);
406 if (homeDirectory) ldap_value_free(homeDirectory);
407 if (uidNumber) ldap_value_free(uidNumber);
408 if (loginShell) ldap_value_free(loginShell);
409 if (gidNumber) ldap_value_free(gidNumber);
410 if (c) ldap_value_free(c);
411 if (title) ldap_value_free(title);
412 if (uuid) ldap_value_free(uuid);
415 ldap_msgfree(search_result);
417 // unbind so we can go back in as the authenticating user
418 ldap_unbind(ldserver);
419 return(changed_something); // tell the caller whether we made any changes
423 // Extract a user's Internet email addresses from LDAP.
424 // Returns zero if we got a valid set of addresses; nonzero for error.
425 int extract_email_addresses_from_ldap(char *ldap_dn, char *emailaddrs) {
426 LDAP *ldserver = NULL;
428 LDAPMessage *search_result = NULL;
429 LDAPMessage *entry = NULL;
431 char *attrs[] = { "*","+",NULL};
433 if (!ldap_dn) return(1);
434 if (!emailaddrs) return(1);
436 ldserver = ctdl_ldap_bind();
437 if (!ldserver) return(-1);
442 syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
443 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
446 LDAP_SCOPE_SUBTREE, // scope
448 attrs, // attrs (all attributes)
449 0, // attrsonly (attrs + values)
450 NULL, // serverctrls (none)
451 NULL, // clientctrls (none)
453 1, // sizelimit (1 result max)
454 &search_result // res
457 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
458 // the search succeeds. Instead, we check to see whether search_result is still NULL.
459 if (search_result == NULL) {
460 syslog(LOG_DEBUG, "ldap: zero search results were returned");
461 ldap_unbind(ldserver);
465 // At this point we've got at least one result from our query. If there are multiple
466 // results, we still only look at the first one.
467 emailaddrs[0] = 0; // clear out any previous results
468 entry = ldap_first_entry(ldserver, search_result);
470 syslog(LOG_DEBUG, "ldap: search got user details");
471 mail = ldap_get_values(ldserver, search_result, "mail");
475 for (q=0; q<ldap_count_values(mail); ++q) {
476 if (IsDirectory(mail[q], 0)) {
477 if ((strlen(emailaddrs) + strlen(mail[q]) + 2) > 512) {
478 syslog(LOG_ERR, "ldap: can't fit all email addresses into user record");
481 if (!IsEmptyStr(emailaddrs)) {
482 strcat(emailaddrs, "|");
484 strcat(emailaddrs, mail[q]);
492 ldap_msgfree(search_result);
494 // unbind so we can go back in as the authenticating user
495 ldap_unbind(ldserver);
500 // Scan LDAP for users and populate Citadel's user database with everyone
501 void CtdlSynchronizeUsersFromLDAP(void) {
502 LDAP *ldserver = NULL;
503 LDAPMessage *search_result = NULL;
504 LDAPMessage *entry = NULL;
505 char *user_dn = NULL;
506 char searchstring[1024];
509 if ((CtdlGetConfigInt("c_auth_mode") != AUTHMODE_LDAP) && (CtdlGetConfigInt("c_auth_mode") != AUTHMODE_LDAP_AD)) {
510 return; // not running LDAP
513 syslog(LOG_INFO, "ldap: synchronizing Citadel user database from LDAP");
515 ldserver = ctdl_ldap_bind();
516 if (!ldserver) return;
521 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
522 snprintf(searchstring, sizeof(searchstring), "(&(objectClass=user)(objectClass=person)(!(objectClass=computer)))");
525 snprintf(searchstring, sizeof(searchstring), "(objectClass=inetOrgPerson)");
528 syslog(LOG_DEBUG, "ldap: search: %s", searchstring);
529 syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
531 CtdlGetConfigStr("c_ldap_base_dn"), // base
532 LDAP_SCOPE_SUBTREE, // scope
533 searchstring, // filter
534 NULL, // attrs (all attributes)
535 0, // attrsonly (attrs + values)
536 NULL, // serverctrls (none)
537 NULL, // clientctrls (none)
539 INT_MAX, // sizelimit (max)
540 &search_result // result
543 // Ignore the return value of ldap_search_ext_s(). Sometimes it returns an error even when
544 // the search succeeds. Instead, we check to see whether search_result is still NULL.
545 if (search_result == NULL) {
546 syslog(LOG_DEBUG, "ldap: zero search results were returned");
547 ldap_unbind(ldserver);
551 syslog(LOG_DEBUG, "ldap: %d entries returned", ldap_count_entries(ldserver, search_result));
552 for (entry=ldap_first_entry(ldserver, search_result); entry!=NULL; entry=ldap_next_entry(ldserver, entry)) {
553 user_dn = ldap_get_dn(ldserver, entry);
555 syslog(LOG_DEBUG, "ldap: found %s", user_dn);
557 int fullname_size = 256;
558 char fullname[256] = { 0 } ;
560 char new_emailaddrs[512] = { 0 } ;
562 uid = derive_uid_from_ldap(ldserver, entry);
563 derive_fullname_from_ldap_result(fullname, fullname_size, ldserver, entry);
564 syslog(LOG_DEBUG, "ldap: display name: <%s> , uid = <%d>", fullname, uid);
566 // now create or update the user
568 struct ctdluser usbuf;
570 found_user = getuserbyuid(&usbuf, uid);
571 if (found_user != 0) {
572 create_user(fullname, CREATE_USER_DO_NOT_BECOME_USER, uid);
573 found_user = getuserbyuid(&usbuf, uid);
574 strcpy(fullname, usbuf.fullname);
577 if (found_user == 0) { // user record exists
578 // now update the account email addresses if necessary
579 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
580 if (extract_email_addresses_from_ldap(user_dn, new_emailaddrs) == 0) {
581 if (strcmp(usbuf.emailaddrs, new_emailaddrs)) { // update only if changed
582 CtdlSetEmailAddressesForUser(usbuf.fullname, new_emailaddrs);
587 ldap_memfree(user_dn);
592 ldap_msgfree(search_result);
594 // unbind so we can go back in as the authenticating user
595 ldap_unbind(ldserver);