started working on code for extracting email addresses from ldap
[citadel.git] / citadel / ldap.c
1 /*
2  * These functions implement the portions of AUTHMODE_LDAP and AUTHMODE_LDAP_AD which
3  * actually speak to the LDAP server.
4  *
5  * Copyright (c) 2011-2017 by the citadel.org development team.
6  *
7  * This program is open source software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License, version 3.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  */
15
16 int ctdl_require_ldap_version = 3;
17
18 #define _GNU_SOURCE             // Needed to suppress warning about vasprintf() when running on Linux/Linux
19 #include <stdio.h>
20 #include <libcitadel.h>
21 #include "citserver.h"
22 #include "citadel_ldap.h"
23 #include "ctdl_module.h"
24 #include "user_ops.h"
25 #include "internet_addressing.h"
26 #include "config.h"
27
28 #ifdef HAVE_LDAP
29 #define LDAP_DEPRECATED 1       // Suppress libldap's warning that we are using deprecated API calls
30 #include <ldap.h>
31
32
33 /*
34  * Wrapper function for ldap_initialize() that consistently fills in the correct fields
35  */
36 int ctdl_ldap_initialize(LDAP **ld) {
37
38         char server_url[256];
39         int ret;
40
41         snprintf(server_url, sizeof server_url, "ldap://%s:%d", CtdlGetConfigStr("c_ldap_host"), CtdlGetConfigInt("c_ldap_port"));
42         ret = ldap_initialize(ld, server_url);
43         if (ret != LDAP_SUCCESS) {
44                 syslog(LOG_ERR, "ldap: could not connect to %s : %m", server_url);
45                 *ld = NULL;
46                 return(errno);
47         }
48
49         return(ret);
50 }
51
52
53 /*
54  * Look up a user in the directory to see if this is an account that can be authenticated
55  */
56 int CtdlTryUserLDAP(char *username,
57                 char *found_dn, int found_dn_size,
58                 char *fullname, int fullname_size,
59                 uid_t *uid, int lookup_based_on_username)
60 {
61         LDAP *ldserver = NULL;
62         int i;
63         LDAPMessage *search_result = NULL;
64         LDAPMessage *entry = NULL;
65         char searchstring[1024];
66         struct timeval tv;
67         char **values;
68         char *user_dn = NULL;
69
70         if (fullname) safestrncpy(fullname, username, fullname_size);
71
72         if (ctdl_ldap_initialize(&ldserver) != LDAP_SUCCESS) {
73                 return(errno);
74         }
75
76         ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
77         ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
78
79         striplt(CtdlGetConfigStr("c_ldap_bind_dn"));
80         striplt(CtdlGetConfigStr("c_ldap_bind_pw"));
81         syslog(LOG_DEBUG, "ldap: bind DN: %s", CtdlGetConfigStr("c_ldap_bind_dn"));
82         i = ldap_simple_bind_s(ldserver,
83                 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_dn")) ? CtdlGetConfigStr("c_ldap_bind_dn") : NULL),
84                 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_pw")) ? CtdlGetConfigStr("c_ldap_bind_pw") : NULL)
85         );
86         if (i != LDAP_SUCCESS) {
87                 syslog(LOG_ERR, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
88                 return(i);
89         }
90
91         tv.tv_sec = 10;
92         tv.tv_usec = 0;
93
94         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
95                 if (lookup_based_on_username != 0)
96                         snprintf(searchstring, sizeof(searchstring), "(displayName=%s)",username);
97                 else
98                         snprintf(searchstring, sizeof(searchstring), "(sAMAccountName=%s)", username);
99         }
100         else {
101                 if (lookup_based_on_username != 0) {
102                         snprintf(searchstring, sizeof(searchstring), "(cn=%s)",username);
103                 }
104                 else {
105                         snprintf(searchstring, sizeof(searchstring), "(&(objectclass=posixAccount)(uid=%s))", username);
106                 }
107         }
108
109         syslog(LOG_DEBUG, "ldap: search: %s", searchstring);
110         (void) ldap_search_ext_s(
111                 ldserver,                                       /* ld                           */
112                 CtdlGetConfigStr("c_ldap_base_dn"),             /* base                         */
113                 LDAP_SCOPE_SUBTREE,                             /* scope                        */
114                 searchstring,                                   /* filter                       */
115                 NULL,                                           /* attrs (all attributes)       */
116                 0,                                              /* attrsonly (attrs + values)   */
117                 NULL,                                           /* serverctrls (none)           */
118                 NULL,                                           /* clientctrls (none)           */
119                 &tv,                                            /* timeout                      */
120                 1,                                              /* sizelimit (1 result max)     */
121                 &search_result                                  /* res                          */
122         );
123
124         /* Ignore the return value of ldap_search_ext_s().  Sometimes it returns an error even when
125          * the search succeeds.  Instead, we check to see whether search_result is still NULL.
126          */
127         if (search_result == NULL) {
128                 syslog(LOG_DEBUG, "ldap: zero search results were returned");
129                 ldap_unbind(ldserver);
130                 return(2);
131         }
132
133         /* At this point we've got at least one result from our query.  If there are multiple
134          * results, we still only look at the first one.
135          */
136         entry = ldap_first_entry(ldserver, search_result);
137         if (entry) {
138
139                 user_dn = ldap_get_dn(ldserver, entry);
140                 if (user_dn) {
141                         syslog(LOG_DEBUG, "ldap: dn = %s", user_dn);
142                 }
143
144                 if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
145                         values = ldap_get_values(ldserver, search_result, "displayName");
146                         if (values) {
147                                 if (values[0]) {
148                                         if (fullname) safestrncpy(fullname, values[0], fullname_size);
149                                         syslog(LOG_DEBUG, "ldap: displayName = %s", values[0]);
150                                 }
151                                 ldap_value_free(values);
152                         }
153                 }
154                 else {
155                         values = ldap_get_values(ldserver, search_result, "cn");
156                         if (values) {
157                                 if (values[0]) {
158                                         if (fullname) safestrncpy(fullname, values[0], fullname_size);
159                                         syslog(LOG_DEBUG, "ldap: cn = %s", values[0]);
160                                 }
161                                 ldap_value_free(values);
162                         }
163                 }
164                 /* If we know the username is the CN/displayName, we already set the uid*/
165                 if (lookup_based_on_username==0) {
166                         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
167                                 values = ldap_get_values(ldserver, search_result, "objectGUID");
168                                 if (values) {
169                                         if (values[0]) {
170                                                 if (uid != NULL) {
171                                                         *uid = abs(HashLittle(values[0], strlen(values[0])));
172                                                         syslog(LOG_DEBUG, "ldap: uid hashed from objectGUID = %d", *uid);
173                                                 }
174                                         }
175                                         ldap_value_free(values);
176                                 }
177                         }
178                         else {
179                                 values = ldap_get_values(ldserver, search_result, "uidNumber");
180                                 if (values) {
181                                         if (values[0]) {
182                                                 syslog(LOG_DEBUG, "ldap: uidNumber = %s", values[0]);
183                                                 if (uid != NULL) {
184                                                         *uid = atoi(values[0]);
185                                                 }
186                                         }
187                                         ldap_value_free(values);
188                                 }
189                         }
190                 }
191
192         }
193
194         /* free the results */
195         ldap_msgfree(search_result);
196
197         /* unbind so we can go back in as the authenticating user */
198         ldap_unbind(ldserver);
199
200         if (!user_dn) {
201                 syslog(LOG_DEBUG, "ldap: No such user was found.");
202                 return(4);
203         }
204
205         if (found_dn) safestrncpy(found_dn, user_dn, found_dn_size);
206         ldap_memfree(user_dn);
207         return(0);
208 }
209
210
211 int CtdlTryPasswordLDAP(char *user_dn, const char *password)
212 {
213         LDAP *ldserver = NULL;
214         int i = (-1);
215
216         if (IsEmptyStr(password)) {
217                 syslog(LOG_DEBUG, "ldap: empty passwords are not permitted");
218                 return(1);
219         }
220
221         syslog(LOG_DEBUG, "ldap: trying to bind as %s", user_dn);
222         i = ctdl_ldap_initialize(&ldserver);
223         if (i == LDAP_SUCCESS) {
224                 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
225                 i = ldap_simple_bind_s(ldserver, user_dn, password);
226                 if (i == LDAP_SUCCESS) {
227                         syslog(LOG_DEBUG, "ldap: bind succeeded");
228                 }
229                 else {
230                         syslog(LOG_DEBUG, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
231                 }
232                 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
233                 ldap_unbind(ldserver);
234         }
235
236         if (i == LDAP_SUCCESS) {
237                 return(0);
238         }
239
240         return(1);
241 }
242
243
244 //return !0 iff property changed.
245 int vcard_set_props_iff_different(struct vCard *v,char *propname,int numvals, char **vals) {
246         int i;
247         char *oldval = "";
248         for(i=0;i<numvals;i++) {
249           oldval = vcard_get_prop(v,propname,0,i,0);
250           if (oldval == NULL) break;
251           if (strcmp(vals[i],oldval)) break;
252         }
253         if (i!=numvals) {
254                 syslog(LOG_DEBUG, "ldap: vcard property %s, element %d of %d changed from %s to %s\n", propname, i, numvals, oldval, vals[i]);
255                 for(i=0;i<numvals;i++) vcard_set_prop(v,propname,vals[i],(i==0) ? 0 : 1);
256                 return 1;
257         }
258         return 0;
259 }
260
261
262 //return !0 iff property changed.
263 int vcard_set_one_prop_iff_different(struct vCard *v,char *propname, char *newfmt, ...) {
264         va_list args;
265         char *newvalue;
266         int changed_something;
267         va_start(args,newfmt);
268         if (-1==vasprintf(&newvalue,newfmt,args)) {
269                 syslog(LOG_ERR, "ldap: out of memory!");
270                 return 0;
271         }
272         changed_something = vcard_set_props_iff_different(v,propname,1,&newvalue);
273         va_end(args);
274         free(newvalue);
275         return changed_something;
276 }
277
278
279 /*
280  * Learn LDAP attributes and stuff them into the vCard.
281  * Returns nonzero if we changed anything.
282  */
283 int Ctdl_LDAP_to_vCard(char *ldap_dn, struct vCard *v)
284 {
285         int changed_something = 0;
286         LDAP *ldserver = NULL;
287         int i;
288         struct timeval tv;
289         LDAPMessage *search_result = NULL;
290         LDAPMessage *entry = NULL;
291         char **givenName;
292         char **sn;
293         char **cn;
294         char **initials;
295         char **o;
296         char **street;
297         char **l;
298         char **st;
299         char **postalCode;
300         char **telephoneNumber;
301         char **mobile;
302         char **homePhone;
303         char **facsimileTelephoneNumber;
304         char **mail;
305         char **uid;
306         char **homeDirectory;
307         char **uidNumber;
308         char **loginShell;
309         char **gidNumber;
310         char **c;
311         char **title;
312         char **uuid;
313         char *attrs[] = { "*","+",NULL};
314
315         if (!ldap_dn) return(0);
316         if (!v) return(0);
317
318         if (ctdl_ldap_initialize(&ldserver) != LDAP_SUCCESS) {
319                 return(0);
320         }
321
322         ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
323         ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
324
325         striplt(CtdlGetConfigStr("c_ldap_bind_dn"));
326         striplt(CtdlGetConfigStr("c_ldap_bind_pw"));
327         syslog(LOG_DEBUG, "ldap: bind DN: %s", CtdlGetConfigStr("c_ldap_bind_dn"));
328         i = ldap_simple_bind_s(ldserver,
329                 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_dn")) ? CtdlGetConfigStr("c_ldap_bind_dn") : NULL),
330                 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_pw")) ? CtdlGetConfigStr("c_ldap_bind_pw") : NULL)
331         );
332         if (i != LDAP_SUCCESS) {
333                 syslog(LOG_ERR, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
334                 return(0);
335         }
336
337         tv.tv_sec = 10;
338         tv.tv_usec = 0;
339
340         syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
341         (void) ldap_search_ext_s(
342                 ldserver,                               // ld
343                 ldap_dn,                                // base
344                 LDAP_SCOPE_SUBTREE,                     // scope
345                 NULL,                                   // filter
346                 attrs,                                  // attrs (all attributes)
347                 0,                                      // attrsonly (attrs + values)
348                 NULL,                                   // serverctrls (none)
349                 NULL,                                   // clientctrls (none)
350                 &tv,                                    // timeout
351                 1,                                      // sizelimit (1 result max)
352                 &search_result                          // res
353         );
354         
355         /* Ignore the return value of ldap_search_ext_s().  Sometimes it returns an error even when
356          * the search succeeds.  Instead, we check to see whether search_result is still NULL.
357          */
358         if (search_result == NULL) {
359                 syslog(LOG_DEBUG, "ldap: zero search results were returned");
360                 ldap_unbind(ldserver);
361                 return(0);
362         }
363
364         /* At this point we've got at least one result from our query.  If there are multiple
365          * results, we still only look at the first one.
366          */
367         entry = ldap_first_entry(ldserver, search_result);
368         if (entry) {
369                 syslog(LOG_DEBUG, "ldap: search got user details for vcard.");
370                 givenName=ldap_get_values(ldserver, search_result, "givenName");
371                 sn=ldap_get_values(ldserver, search_result, "sn");
372                 cn=ldap_get_values(ldserver, search_result, "cn");
373                 initials=ldap_get_values(ldserver, search_result, "initials");
374                 title=ldap_get_values(ldserver, search_result, "title");
375                 o=ldap_get_values(ldserver, search_result, "o");
376                 street=ldap_get_values(ldserver, search_result, "street");
377                 l=ldap_get_values(ldserver, search_result, "l");
378                 st=ldap_get_values(ldserver, search_result, "st");
379                 postalCode=ldap_get_values(ldserver, search_result, "postalCode");
380                 telephoneNumber=ldap_get_values(ldserver, search_result, "telephoneNumber");
381                 mobile=ldap_get_values(ldserver, search_result, "mobile");
382                 homePhone=ldap_get_values(ldserver, search_result, "homePhone");
383                 facsimileTelephoneNumber=ldap_get_values(ldserver, search_result, "facsimileTelephoneNumber");
384                 mail=ldap_get_values(ldserver, search_result, "mail");
385                 uid=ldap_get_values(ldserver, search_result, "uid");
386                 homeDirectory=ldap_get_values(ldserver, search_result, "homeDirectory");
387                 uidNumber=ldap_get_values(ldserver, search_result, "uidNumber");
388                 loginShell=ldap_get_values(ldserver, search_result, "loginShell");
389                 gidNumber=ldap_get_values(ldserver, search_result, "gidNumber");
390                 c=ldap_get_values(ldserver, search_result, "c");
391                 uuid=ldap_get_values(ldserver, search_result, "entryUUID");
392
393                 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]);
394                 if (telephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;work","%s",telephoneNumber[0]);
395                 if (facsimileTelephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;fax","%s",facsimileTelephoneNumber[0]);
396                 if (mobile) changed_something |= vcard_set_one_prop_iff_different(v,"tel;cell","%s",mobile[0]);
397                 if (homePhone) changed_something |= vcard_set_one_prop_iff_different(v,"tel;home","%s",homePhone[0]);
398                 if (givenName && sn) {
399                         if (initials) {
400                                 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s;%s",sn[0],givenName[0],initials[0]);
401                         }
402                         else {
403                                 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s",sn[0],givenName[0]);
404                         }
405                 }
406                 if (mail) {
407                         changed_something |= vcard_set_props_iff_different(v,"email;internet",ldap_count_values(mail),mail);
408                 }
409                 if (uuid) changed_something |= vcard_set_one_prop_iff_different(v,"X-uuid","%s",uuid[0]);
410                 if (o) changed_something |= vcard_set_one_prop_iff_different(v,"org","%s",o[0]);
411                 if (cn) changed_something |= vcard_set_one_prop_iff_different(v,"fn","%s",cn[0]);
412                 if (title) changed_something |= vcard_set_one_prop_iff_different(v,"title","%s",title[0]);
413                 
414                 if (givenName) ldap_value_free(givenName);
415                 if (initials) ldap_value_free(initials);
416                 if (sn) ldap_value_free(sn);
417                 if (cn) ldap_value_free(cn);
418                 if (o) ldap_value_free(o);
419                 if (street) ldap_value_free(street);
420                 if (l) ldap_value_free(l);
421                 if (st) ldap_value_free(st);
422                 if (postalCode) ldap_value_free(postalCode);
423                 if (telephoneNumber) ldap_value_free(telephoneNumber);
424                 if (mobile) ldap_value_free(mobile);
425                 if (homePhone) ldap_value_free(homePhone);
426                 if (facsimileTelephoneNumber) ldap_value_free(facsimileTelephoneNumber);
427                 if (mail) ldap_value_free(mail);
428                 if (uid) ldap_value_free(uid);
429                 if (homeDirectory) ldap_value_free(homeDirectory);
430                 if (uidNumber) ldap_value_free(uidNumber);
431                 if (loginShell) ldap_value_free(loginShell);
432                 if (gidNumber) ldap_value_free(gidNumber);
433                 if (c) ldap_value_free(c);
434                 if (title) ldap_value_free(title);
435                 if (uuid) ldap_value_free(uuid);
436         }
437         /* free the results */
438         ldap_msgfree(search_result);
439
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 */
443 }
444
445
446 /*
447  * Extract a user's Internet email addresses from LDAP.
448  * Returns zero if we got a valid set of addresses; nonzero for error.
449  */
450 int extract_email_addresses_from_ldap(char *ldap_dn, char *emailaddrs)
451 {
452         LDAP *ldserver = NULL;
453         int i;
454         struct timeval tv;
455         LDAPMessage *search_result = NULL;
456         LDAPMessage *entry = NULL;
457         char **mail;
458         char *attrs[] = { "*","+",NULL};
459
460         if (!ldap_dn) return(1);
461         if (!emailaddrs) return(1);
462
463         if (ctdl_ldap_initialize(&ldserver) != LDAP_SUCCESS) {
464                 return(2);
465         }
466
467         ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
468         ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
469
470         striplt(CtdlGetConfigStr("c_ldap_bind_dn"));
471         striplt(CtdlGetConfigStr("c_ldap_bind_pw"));
472         syslog(LOG_DEBUG, "ldap: bind DN: %s", CtdlGetConfigStr("c_ldap_bind_dn"));
473         i = ldap_simple_bind_s(ldserver,
474                 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_dn")) ? CtdlGetConfigStr("c_ldap_bind_dn") : NULL),
475                 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_pw")) ? CtdlGetConfigStr("c_ldap_bind_pw") : NULL)
476         );
477         if (i != LDAP_SUCCESS) {
478                 syslog(LOG_ERR, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
479                 return(3);
480         }
481
482         tv.tv_sec = 10;
483         tv.tv_usec = 0;
484
485         syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
486         (void) ldap_search_ext_s(
487                 ldserver,                               // ld
488                 ldap_dn,                                // base
489                 LDAP_SCOPE_SUBTREE,                     // scope
490                 NULL,                                   // filter
491                 attrs,                                  // attrs (all attributes)
492                 0,                                      // attrsonly (attrs + values)
493                 NULL,                                   // serverctrls (none)
494                 NULL,                                   // clientctrls (none)
495                 &tv,                                    // timeout
496                 1,                                      // sizelimit (1 result max)
497                 &search_result                          // res
498         );
499         
500         /* Ignore the return value of ldap_search_ext_s().  Sometimes it returns an error even when
501          * the search succeeds.  Instead, we check to see whether search_result is still NULL.
502          */
503         if (search_result == NULL) {
504                 syslog(LOG_DEBUG, "ldap: zero search results were returned");
505                 ldap_unbind(ldserver);
506                 return(4);
507         }
508
509         /* At this point we've got at least one result from our query.  If there are multiple
510          * results, we still only look at the first one.
511          */
512         emailaddrs[0] = 0;      /* clear out any previous results */
513         entry = ldap_first_entry(ldserver, search_result);
514         if (entry) {
515                 syslog(LOG_DEBUG, "ldap: search got user details");
516                 mail=ldap_get_values(ldserver, search_result, "mail");
517
518                 if (mail) {
519                         int q;
520                         for (q=0; q<ldap_count_values(mail); ++q) {
521                                 if (IsDirectory(mail[q], 0)) {
522                                         syslog(LOG_DEBUG, "\035FIXME YES DIRECTORY %s\033[0m", mail[q]);
523                                         if ((strlen(emailaddrs) + strlen(mail[q]) + 2) > 512) {
524                                                 syslog(LOG_ERR, "ldap: can't fit all email addresses into user record");
525                                         }
526                                         else {
527                                                 if (!IsEmptyStr(emailaddrs)) {
528                                                         strcat(emailaddrs, "|");
529                                                 }
530                                                 strcat(emailaddrs, mail[q]);
531                                         }
532                                 }
533                         }
534                 }
535         }
536
537         /* free the results */
538         ldap_msgfree(search_result);
539
540         /* unbind so we can go back in as the authenticating user */
541         ldap_unbind(ldserver);
542         return(0);
543 }
544
545 #endif /* HAVE_LDAP */