f7f415a8affe0a3ddbcb7085a1082b2db45f00c9
[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-2014 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
26 #ifdef HAVE_LDAP
27 #define LDAP_DEPRECATED 1       /* Suppress libldap's warning that we are using deprecated API calls */
28 #include <ldap.h>
29
30
31
32 /*
33  * Wrapper function for ldap_initialize() that consistently fills in the correct fields
34  */
35 int ctdl_ldap_initialize(LDAP **ld) {
36
37         char server_url[256];
38         int ret;
39
40         snprintf(server_url, sizeof server_url, "ldap://%s:%d", config.c_ldap_host, config.c_ldap_port);
41         ret = ldap_initialize(ld, server_url);
42         if (ret != LDAP_SUCCESS) {
43                 syslog(LOG_ALERT, "LDAP: Could not connect to %s : %s",
44                         server_url,
45                         strerror(errno)
46                 );
47                 *ld = NULL;
48                 return(errno);
49         }
50
51         return(ret);
52 }
53
54
55
56
57 /*
58  * Look up a user in the directory to see if this is an account that can be authenticated
59  */
60 int CtdlTryUserLDAP(char *username,
61                 char *found_dn, int found_dn_size,
62                 char *fullname, int fullname_size,
63                 uid_t *uid, int lookup_based_on_username)
64 {
65         LDAP *ldserver = NULL;
66         int i;
67         LDAPMessage *search_result = NULL;
68         LDAPMessage *entry = NULL;
69         char searchstring[1024];
70         struct timeval tv;
71         char **values;
72         char *user_dn = NULL;
73
74         if (fullname) safestrncpy(fullname, username, fullname_size);
75
76         if (ctdl_ldap_initialize(&ldserver) != LDAP_SUCCESS) {
77                 return(errno);
78         }
79
80         ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
81         ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
82
83         striplt(config.c_ldap_bind_dn);
84         striplt(config.c_ldap_bind_pw);
85         syslog(LOG_DEBUG, "LDAP bind DN: %s", config.c_ldap_bind_dn);
86         i = ldap_simple_bind_s(ldserver,
87                 (!IsEmptyStr(config.c_ldap_bind_dn) ? config.c_ldap_bind_dn : NULL),
88                 (!IsEmptyStr(config.c_ldap_bind_pw) ? config.c_ldap_bind_pw : NULL)
89         );
90         if (i != LDAP_SUCCESS) {
91                 syslog(LOG_ALERT, "LDAP: Cannot bind: %s (%d)", ldap_err2string(i), i);
92                 return(i);
93         }
94
95         tv.tv_sec = 10;
96         tv.tv_usec = 0;
97
98         if (config.c_auth_mode == AUTHMODE_LDAP_AD) {
99                 if (lookup_based_on_username != 0)
100                         snprintf(searchstring, sizeof(searchstring), "(displayName=%s)",username);
101                 else
102                         snprintf(searchstring, sizeof(searchstring), "(sAMAccountName=%s)", username);
103         }
104         else {
105                 if (lookup_based_on_username != 0)
106                         snprintf(searchstring, sizeof(searchstring), "(cn=%s)",username);
107                 else
108                         snprintf(searchstring, sizeof(searchstring), "(&(objectclass=posixAccount)(uid=%s))", username);
109         }
110
111         syslog(LOG_DEBUG, "LDAP search: %s", searchstring);
112         (void) ldap_search_ext_s(
113                 ldserver,                                       /* ld                           */
114                 config.c_ldap_base_dn,                          /* base                         */
115                 LDAP_SCOPE_SUBTREE,                             /* scope                        */
116                 searchstring,                                   /* filter                       */
117                 NULL,                                           /* attrs (all attributes)       */
118                 0,                                              /* attrsonly (attrs + values)   */
119                 NULL,                                           /* serverctrls (none)           */
120                 NULL,                                           /* clientctrls (none)           */
121                 &tv,                                            /* timeout                      */
122                 1,                                              /* sizelimit (1 result max)     */
123                 &search_result                                  /* res                          */
124         );
125
126         /* Ignore the return value of ldap_search_ext_s().  Sometimes it returns an error even when
127          * the search succeeds.  Instead, we check to see whether search_result is still NULL.
128          */
129         if (search_result == NULL) {
130                 syslog(LOG_DEBUG, "LDAP search: zero results were returned");
131                 ldap_unbind(ldserver);
132                 return(2);
133         }
134
135         /* At this point we've got at least one result from our query.  If there are multiple
136          * results, we still only look at the first one.
137          */
138         entry = ldap_first_entry(ldserver, search_result);
139         if (entry) {
140
141                 user_dn = ldap_get_dn(ldserver, entry);
142                 if (user_dn) {
143                         syslog(LOG_DEBUG, "dn = %s", user_dn);
144                 }
145
146                 if (config.c_auth_mode == AUTHMODE_LDAP_AD) {
147                         values = ldap_get_values(ldserver, search_result, "displayName");
148                         if (values) {
149                                 if (values[0]) {
150                                         if (fullname) safestrncpy(fullname, values[0], fullname_size);
151                                         syslog(LOG_DEBUG, "displayName = %s", values[0]);
152                                 }
153                                 ldap_value_free(values);
154                         }
155                 }
156                 else {
157                         values = ldap_get_values(ldserver, search_result, "cn");
158                         if (values) {
159                                 if (values[0]) {
160                                         if (fullname) safestrncpy(fullname, values[0], fullname_size);
161                                         syslog(LOG_DEBUG, "cn = %s", values[0]);
162                                 }
163                                 ldap_value_free(values);
164                         }
165                 }
166                 /* If we know the username is the CN/displayName, we already set the uid*/
167                 if (lookup_based_on_username==0) {
168                         if (config.c_auth_mode == AUTHMODE_LDAP_AD) {
169                                 values = ldap_get_values(ldserver, search_result, "objectGUID");
170                                 if (values) {
171                                         if (values[0]) {
172                                                 if (uid != NULL) {
173                                                         *uid = abs(HashLittle(values[0], strlen(values[0])));
174                                                         syslog(LOG_DEBUG, "uid hashed from objectGUID = %d", *uid);
175                                                 }
176                                         }
177                                         ldap_value_free(values);
178                                 }
179                         }
180                         else {
181                                 values = ldap_get_values(ldserver, search_result, "uidNumber");
182                                 if (values) {
183                                         if (values[0]) {
184                                                 syslog(LOG_DEBUG, "uidNumber = %s", values[0]);
185                                                 if (uid != NULL) {
186                                                         *uid = atoi(values[0]);
187                                                 }
188                                         }
189                                         ldap_value_free(values);
190                                 }
191                         }
192                 }
193
194         }
195
196         /* free the results */
197         ldap_msgfree(search_result);
198
199         /* unbind so we can go back in as the authenticating user */
200         ldap_unbind(ldserver);
201
202         if (!user_dn) {
203                 syslog(LOG_DEBUG, "No such user was found.");
204                 return(4);
205         }
206
207         if (found_dn) safestrncpy(found_dn, user_dn, found_dn_size);
208         ldap_memfree(user_dn);
209         return(0);
210 }
211
212
213 int CtdlTryPasswordLDAP(char *user_dn, const char *password)
214 {
215         LDAP *ldserver = NULL;
216         int i = (-1);
217
218         if (IsEmptyStr(password)) {
219                 syslog(LOG_DEBUG, "LDAP: empty passwords are not permitted");
220                 return(1);
221         }
222
223         syslog(LOG_DEBUG, "LDAP: trying to bind as %s", user_dn);
224         i = ctdl_ldap_initialize(&ldserver);
225         if (i == LDAP_SUCCESS) {
226                 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
227                 i = ldap_simple_bind_s(ldserver, user_dn, password);
228                 if (i == LDAP_SUCCESS) {
229                         syslog(LOG_DEBUG, "LDAP: bind succeeded");
230                 }
231                 else {
232                         syslog(LOG_DEBUG, "LDAP: Cannot bind: %s (%d)", ldap_err2string(i), i);
233                 }
234                 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
235                 ldap_unbind(ldserver);
236         }
237
238         if (i == LDAP_SUCCESS) {
239                 return(0);
240         }
241
242         return(1);
243 }
244
245 //return !0 iff property changed.
246 int vcard_set_props_iff_different(struct vCard *v,char *propname,int numvals, char **vals) {
247         int i;
248         char *oldval;
249         for(i=0;i<numvals;i++) {
250           oldval = vcard_get_prop(v,propname,0,i,0);
251           if (oldval == NULL) break;
252           if (strcmp(vals[i],oldval)) break;
253         }
254         if (i!=numvals) {
255                 syslog(LOG_DEBUG, "LDAP: vcard property %s, element %d of %d changed from %s to %s\n", propname, i, numvals, oldval, vals[i]);
256                 for(i=0;i<numvals;i++) vcard_set_prop(v,propname,vals[i],(i==0) ? 0 : 1);
257                 return 1;
258         }
259         return 0;
260 }
261
262
263 //return !0 iff property changed.
264 int vcard_set_one_prop_iff_different(struct vCard *v,char *propname, char *newfmt, ...) {
265         va_list args;
266         char *newvalue;
267         int changed_something;
268         va_start(args,newfmt);
269         if (-1==vasprintf(&newvalue,newfmt,args)) {
270                 syslog(LOG_ALERT, "Out of memory!\n");
271                 return 0;
272         }
273         changed_something = vcard_set_props_iff_different(v,propname,1,&newvalue);
274         va_end(args);
275         free(newvalue);
276         return changed_something;
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(config.c_ldap_bind_dn);
326         striplt(config.c_ldap_bind_pw);
327         syslog(LOG_DEBUG, "LDAP bind DN: %s", config.c_ldap_bind_dn);
328         i = ldap_simple_bind_s(ldserver,
329                 (!IsEmptyStr(config.c_ldap_bind_dn) ? config.c_ldap_bind_dn : NULL),
330                 (!IsEmptyStr(config.c_ldap_bind_pw) ? config.c_ldap_bind_pw : NULL)
331         );
332         if (i != LDAP_SUCCESS) {
333                 syslog(LOG_ALERT, "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          
359         if (search_result == NULL) {
360                 syslog(LOG_DEBUG, "LDAP search: zero results were returned");
361                 ldap_unbind(ldserver);
362                 return(0);
363         }
364
365         /* At this point we've got at least one result from our query.  If there are multiple
366          * results, we still only look at the first one.
367          */
368
369         entry = ldap_first_entry(ldserver, search_result);
370         if (entry) {
371                 syslog(LOG_DEBUG, "LDAP search, got user details for vcard.");
372                 givenName=ldap_get_values(ldserver, search_result, "givenName");
373                 sn=ldap_get_values(ldserver, search_result, "sn");
374                 cn=ldap_get_values(ldserver, search_result, "cn");
375                 initials=ldap_get_values(ldserver, search_result, "initials");
376                 title=ldap_get_values(ldserver, search_result, "title");
377                 o=ldap_get_values(ldserver, search_result, "o");
378                 street=ldap_get_values(ldserver, search_result, "street");
379                 l=ldap_get_values(ldserver, search_result, "l");
380                 st=ldap_get_values(ldserver, search_result, "st");
381                 postalCode=ldap_get_values(ldserver, search_result, "postalCode");
382                 telephoneNumber=ldap_get_values(ldserver, search_result, "telephoneNumber");
383                 mobile=ldap_get_values(ldserver, search_result, "mobile");
384                 homePhone=ldap_get_values(ldserver, search_result, "homePhone");
385                 facsimileTelephoneNumber=ldap_get_values(ldserver, search_result, "facsimileTelephoneNumber");
386                 mail=ldap_get_values(ldserver, search_result, "mail");
387                 uid=ldap_get_values(ldserver, search_result, "uid");
388                 homeDirectory=ldap_get_values(ldserver, search_result, "homeDirectory");
389                 uidNumber=ldap_get_values(ldserver, search_result, "uidNumber");
390                 loginShell=ldap_get_values(ldserver, search_result, "loginShell");
391                 gidNumber=ldap_get_values(ldserver, search_result, "gidNumber");
392                 c=ldap_get_values(ldserver, search_result, "c");
393                 uuid=ldap_get_values(ldserver, search_result, "entryUUID");
394
395                 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]);
396                 if (telephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;work","%s",telephoneNumber[0]);
397                 if (facsimileTelephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;fax","%s",facsimileTelephoneNumber[0]);
398                 if (mobile) changed_something |= vcard_set_one_prop_iff_different(v,"tel;cell","%s",mobile[0]);
399                 if (homePhone) changed_something |= vcard_set_one_prop_iff_different(v,"tel;home","%s",homePhone[0]);
400                 if (givenName && sn) {
401                         if (initials) {
402                                 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s;%s",sn[0],givenName[0],initials[0]);
403                         }
404                         else {
405                                 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s",sn[0],givenName[0]);
406                         }
407                 }
408                 if (mail) {
409                         changed_something |= vcard_set_props_iff_different(v,"email;internet",ldap_count_values(mail),mail);
410                 }
411                 if (uuid) changed_something |= vcard_set_one_prop_iff_different(v,"X-uuid","%s",uuid[0]);
412                 if (o) changed_something |= vcard_set_one_prop_iff_different(v,"org","%s",o[0]);
413                 if (cn) changed_something |= vcard_set_one_prop_iff_different(v,"fn","%s",cn[0]);
414                 if (title) changed_something |= vcard_set_one_prop_iff_different(v,"title","%s",title[0]);
415                 
416                 if (givenName) ldap_value_free(givenName);
417                 if (initials) ldap_value_free(initials);
418                 if (sn) ldap_value_free(sn);
419                 if (cn) ldap_value_free(cn);
420                 if (o) ldap_value_free(o);
421                 if (street) ldap_value_free(street);
422                 if (l) ldap_value_free(l);
423                 if (st) ldap_value_free(st);
424                 if (postalCode) ldap_value_free(postalCode);
425                 if (telephoneNumber) ldap_value_free(telephoneNumber);
426                 if (mobile) ldap_value_free(mobile);
427                 if (homePhone) ldap_value_free(homePhone);
428                 if (facsimileTelephoneNumber) ldap_value_free(facsimileTelephoneNumber);
429                 if (mail) ldap_value_free(mail);
430                 if (uid) ldap_value_free(uid);
431                 if (homeDirectory) ldap_value_free(homeDirectory);
432                 if (uidNumber) ldap_value_free(uidNumber);
433                 if (loginShell) ldap_value_free(loginShell);
434                 if (gidNumber) ldap_value_free(gidNumber);
435                 if (c) ldap_value_free(c);
436                 if (title) ldap_value_free(title);
437                 if (uuid) ldap_value_free(uuid);
438         }
439         /* free the results */
440         ldap_msgfree(search_result);
441
442         /* unbind so we can go back in as the authenticating user */
443         ldap_unbind(ldserver);
444         
445         return(changed_something);      /* tell the caller whether we made any changes */
446 }
447
448 #endif /* HAVE_LDAP */