6fd3fd3093afcd2925cd57bbba12c9bb2880a4f3
[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)
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                 snprintf(searchstring, sizeof(searchstring), "(sAMAccountName=%s)", username);
100         }
101         else {
102                 snprintf(searchstring, sizeof(searchstring), "(&(objectclass=posixAccount)(uid=%s))", username);
103         }
104
105         syslog(LOG_DEBUG, "LDAP search: %s", searchstring);
106         (void) ldap_search_ext_s(
107                 ldserver,                                       /* ld                           */
108                 config.c_ldap_base_dn,                          /* base                         */
109                 LDAP_SCOPE_SUBTREE,                             /* scope                        */
110                 searchstring,                                   /* filter                       */
111                 NULL,                                           /* attrs (all attributes)       */
112                 0,                                              /* attrsonly (attrs + values)   */
113                 NULL,                                           /* serverctrls (none)           */
114                 NULL,                                           /* clientctrls (none)           */
115                 &tv,                                            /* timeout                      */
116                 1,                                              /* sizelimit (1 result max)     */
117                 &search_result                                  /* res                          */
118         );
119
120         /* Ignore the return value of ldap_search_ext_s().  Sometimes it returns an error even when
121          * the search succeeds.  Instead, we check to see whether search_result is still NULL.
122          */
123         if (search_result == NULL) {
124                 syslog(LOG_DEBUG, "LDAP search: zero results were returned");
125                 ldap_unbind(ldserver);
126                 return(2);
127         }
128
129         /* At this point we've got at least one result from our query.  If there are multiple
130          * results, we still only look at the first one.
131          */
132         entry = ldap_first_entry(ldserver, search_result);
133         if (entry) {
134
135                 user_dn = ldap_get_dn(ldserver, entry);
136                 if (user_dn) {
137                         syslog(LOG_DEBUG, "dn = %s", user_dn);
138                 }
139
140                 if (config.c_auth_mode == AUTHMODE_LDAP_AD) {
141                         values = ldap_get_values(ldserver, search_result, "displayName");
142                         if (values) {
143                                 if (values[0]) {
144                                         if (fullname) safestrncpy(fullname, values[0], fullname_size);
145                                         syslog(LOG_DEBUG, "displayName = %s", values[0]);
146                                 }
147                                 ldap_value_free(values);
148                         }
149                 }
150                 else {
151                         values = ldap_get_values(ldserver, search_result, "cn");
152                         if (values) {
153                                 if (values[0]) {
154                                         if (fullname) safestrncpy(fullname, values[0], fullname_size);
155                                         syslog(LOG_DEBUG, "cn = %s", values[0]);
156                                 }
157                                 ldap_value_free(values);
158                         }
159                 }
160
161                 if (config.c_auth_mode == AUTHMODE_LDAP_AD) {
162                         values = ldap_get_values(ldserver, search_result, "objectGUID");
163                         if (values) {
164                                 if (values[0]) {
165                                         if (uid != NULL) {
166                                                 *uid = abs(HashLittle(values[0], strlen(values[0])));
167                                                 syslog(LOG_DEBUG, "uid hashed from objectGUID = %d", *uid);
168                                         }
169                                 }
170                                 ldap_value_free(values);
171                         }
172                 }
173                 else {
174                         values = ldap_get_values(ldserver, search_result, "uidNumber");
175                         if (values) {
176                                 if (values[0]) {
177                                         syslog(LOG_DEBUG, "uidNumber = %s", values[0]);
178                                         if (uid != NULL) {
179                                                 *uid = atoi(values[0]);
180                                         }
181                                 }
182                                 ldap_value_free(values);
183                         }
184                 }
185
186         }
187
188         /* free the results */
189         ldap_msgfree(search_result);
190
191         /* unbind so we can go back in as the authenticating user */
192         ldap_unbind(ldserver);
193
194         if (!user_dn) {
195                 syslog(LOG_DEBUG, "No such user was found.");
196                 return(4);
197         }
198
199         if (found_dn) safestrncpy(found_dn, user_dn, found_dn_size);
200         ldap_memfree(user_dn);
201         return(0);
202 }
203
204
205 int CtdlTryPasswordLDAP(char *user_dn, const char *password)
206 {
207         LDAP *ldserver = NULL;
208         int i = (-1);
209
210         if (IsEmptyStr(password)) {
211                 syslog(LOG_DEBUG, "LDAP: empty passwords are not permitted");
212                 return(1);
213         }
214
215         syslog(LOG_DEBUG, "LDAP: trying to bind as %s", user_dn);
216         i = ctdl_ldap_initialize(&ldserver);
217         if (i == LDAP_SUCCESS) {
218                 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
219                 i = ldap_simple_bind_s(ldserver, user_dn, password);
220                 if (i == LDAP_SUCCESS) {
221                         syslog(LOG_DEBUG, "LDAP: bind succeeded");
222                 }
223                 else {
224                         syslog(LOG_DEBUG, "LDAP: Cannot bind: %s (%d)", ldap_err2string(i), i);
225                 }
226                 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
227                 ldap_unbind(ldserver);
228         }
229
230         if (i == LDAP_SUCCESS) {
231                 return(0);
232         }
233
234         return(1);
235 }
236
237 //return !0 iff property changed.
238 int vcard_set_props_iff_different(struct vCard *v,char *propname,int numvals, char **vals) {
239         int i;
240         char *oldval;
241         for(i=0;i<numvals;i++) {
242           oldval = vcard_get_prop(v,propname,0,i,0);
243           if (oldval == NULL) break;
244           if (strcmp(vals[i],oldval)) break;
245         }
246         if (i!=numvals) {
247                 for(i=0;i<numvals;i++) vcard_set_prop(v,propname,vals[i],(i==0) ? 0 : 1);
248                 return 1;
249         }
250         return 0;
251 }
252
253
254 //return !0 iff property changed.
255 int vcard_set_one_prop_iff_different(struct vCard *v,char *propname, char *newfmt, ...) {
256         va_list args;
257         char *newvalue;
258         int changed_something;
259         va_start(args,newfmt);
260         if (-1==vasprintf(&newvalue,newfmt,args)) {
261                 syslog(LOG_ALERT, "Out of memory!\n");
262                 return 0;
263         }
264         changed_something = vcard_set_props_iff_different(v,propname,1,&newvalue);
265         va_end(args);
266         free(newvalue);
267         return changed_something;
268 }
269
270 /*
271  * Learn LDAP attributes and stuff them into the vCard.
272  * Returns nonzero if we changed anything.
273  */
274 int Ctdl_LDAP_to_vCard(char *ldap_dn, struct vCard *v)
275 {
276         int changed_something = 0;
277         LDAP *ldserver = NULL;
278         int i;
279         struct timeval tv;
280         LDAPMessage *search_result = NULL;
281         LDAPMessage *entry = NULL;
282         char **givenName;
283         char **sn;
284         char **cn;
285         char **initials;
286         char **o;
287         char **street;
288         char **l;
289         char **st;
290         char **postalCode;
291         char **telephoneNumber;
292         char **mobile;
293         char **homePhone;
294         char **facsimileTelephoneNumber;
295         char **mail;
296         char **uid;
297         char **homeDirectory;
298         char **uidNumber;
299         char **loginShell;
300         char **gidNumber;
301         char **c;
302         char **title;
303         char **uuid;
304         char *attrs[] = { "*","+",NULL};
305
306         if (!ldap_dn) return(0);
307         if (!v) return(0);
308
309         if (ctdl_ldap_initialize(&ldserver) != LDAP_SUCCESS) {
310                 return(0);
311         }
312
313         ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
314         ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
315
316         striplt(config.c_ldap_bind_dn);
317         striplt(config.c_ldap_bind_pw);
318         syslog(LOG_DEBUG, "LDAP bind DN: %s", config.c_ldap_bind_dn);
319         i = ldap_simple_bind_s(ldserver,
320                 (!IsEmptyStr(config.c_ldap_bind_dn) ? config.c_ldap_bind_dn : NULL),
321                 (!IsEmptyStr(config.c_ldap_bind_pw) ? config.c_ldap_bind_pw : NULL)
322         );
323         if (i != LDAP_SUCCESS) {
324                 syslog(LOG_ALERT, "LDAP: Cannot bind: %s (%d)", ldap_err2string(i), i);
325                 return(0);
326         }
327
328         tv.tv_sec = 10;
329         tv.tv_usec = 0;
330
331         syslog(LOG_DEBUG, "LDAP search: %s", ldap_dn);
332         (void) ldap_search_ext_s(
333                 ldserver,                               /* ld                           */
334                 ldap_dn,                                /* base                         */
335                 LDAP_SCOPE_SUBTREE,             /* scope                        */
336                 NULL,                                   /* filter                       */
337                 attrs,                                  /* attrs (all attributes)       */
338                 0,                                              /* attrsonly (attrs + values)   */
339                 NULL,                                   /* serverctrls (none)           */
340                 NULL,                                   /* clientctrls (none)           */
341                 &tv,                                    /* timeout                      */
342                 1,                                              /* sizelimit (1 result max)     */
343                 &search_result                  /* res                          */
344         );
345         
346         /* Ignore the return value of ldap_search_ext_s().  Sometimes it returns an error even when
347          * the search succeeds.  Instead, we check to see whether search_result is still NULL.
348          */
349          
350         if (search_result == NULL) {
351                 syslog(LOG_DEBUG, "LDAP search: zero results were returned");
352                 ldap_unbind(ldserver);
353                 return(0);
354         }
355
356         /* At this point we've got at least one result from our query.  If there are multiple
357          * results, we still only look at the first one.
358          */
359
360         entry = ldap_first_entry(ldserver, search_result);
361         if (entry) {
362                 syslog(LOG_DEBUG, "LDAP search, got user details for vcard.");
363                 givenName=ldap_get_values(ldserver, search_result, "givenName");
364                 sn=ldap_get_values(ldserver, search_result, "sn");
365                 cn=ldap_get_values(ldserver, search_result, "cn");
366                 initials=ldap_get_values(ldserver, search_result, "initials");
367                 title=ldap_get_values(ldserver, search_result, "title");
368                 o=ldap_get_values(ldserver, search_result, "o");
369                 street=ldap_get_values(ldserver, search_result, "street");
370                 l=ldap_get_values(ldserver, search_result, "l");
371                 st=ldap_get_values(ldserver, search_result, "st");
372                 postalCode=ldap_get_values(ldserver, search_result, "postalCode");
373                 telephoneNumber=ldap_get_values(ldserver, search_result, "telephoneNumber");
374                 mobile=ldap_get_values(ldserver, search_result, "mobile");
375                 homePhone=ldap_get_values(ldserver, search_result, "homePhone");
376                 facsimileTelephoneNumber=ldap_get_values(ldserver, search_result, "facsimileTelephoneNumber");
377                 mail=ldap_get_values(ldserver, search_result, "mail");
378                 uid=ldap_get_values(ldserver, search_result, "uid");
379                 homeDirectory=ldap_get_values(ldserver, search_result, "homeDirectory");
380                 uidNumber=ldap_get_values(ldserver, search_result, "uidNumber");
381                 loginShell=ldap_get_values(ldserver, search_result, "loginShell");
382                 gidNumber=ldap_get_values(ldserver, search_result, "gidNumber");
383                 c=ldap_get_values(ldserver, search_result, "c");
384                 uuid=ldap_get_values(ldserver, search_result, "entryUUID");
385
386                 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]);
387                 if (telephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;work","%s",telephoneNumber[0]);
388                 if (facsimileTelephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;fax","%s",facsimileTelephoneNumber[0]);
389                 if (mobile) changed_something |= vcard_set_one_prop_iff_different(v,"tel;cell","%s",mobile[0]);
390                 if (homePhone) changed_something |= vcard_set_one_prop_iff_different(v,"tel;home","%s",homePhone[0]);
391                 if (givenName && sn) {
392                         if (initials) {
393                                 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s;%s",sn[0],givenName[0],initials[0]);
394                         }
395                         else {
396                                 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s",sn[0],givenName[0]);
397                         }
398                 }
399                 if (mail) {
400                         changed_something |= vcard_set_props_iff_different(v,"email;internet",ldap_count_values(mail),mail);
401                 }
402                 if (uuid) changed_something |= vcard_set_one_prop_iff_different(v,"uid","%s",uuid[0]);
403                 if (o) changed_something |= vcard_set_one_prop_iff_different(v,"org","%s",o[0]);
404                 if (cn) changed_something |= vcard_set_one_prop_iff_different(v,"fn","%s",cn[0]);
405                 if (title) changed_something |= vcard_set_one_prop_iff_different(v,"title","%s",title[0]);
406                 
407                 if (givenName) ldap_value_free(givenName);
408                 if (initials) ldap_value_free(initials);
409                 if (sn) ldap_value_free(sn);
410                 if (cn) ldap_value_free(cn);
411                 if (o) ldap_value_free(o);
412                 if (street) ldap_value_free(street);
413                 if (l) ldap_value_free(l);
414                 if (st) ldap_value_free(st);
415                 if (postalCode) ldap_value_free(postalCode);
416                 if (telephoneNumber) ldap_value_free(telephoneNumber);
417                 if (mobile) ldap_value_free(mobile);
418                 if (homePhone) ldap_value_free(homePhone);
419                 if (facsimileTelephoneNumber) ldap_value_free(facsimileTelephoneNumber);
420                 if (mail) ldap_value_free(mail);
421                 if (uid) ldap_value_free(uid);
422                 if (homeDirectory) ldap_value_free(homeDirectory);
423                 if (uidNumber) ldap_value_free(uidNumber);
424                 if (loginShell) ldap_value_free(loginShell);
425                 if (gidNumber) ldap_value_free(gidNumber);
426                 if (c) ldap_value_free(c);
427                 if (title) ldap_value_free(title);
428                 if (uuid) ldap_value_free(uuid);
429         }
430         /* free the results */
431         ldap_msgfree(search_result);
432
433         /* unbind so we can go back in as the authenticating user */
434         ldap_unbind(ldserver);
435         
436         return(changed_something);      /* tell the caller whether we made any changes */
437 }
438
439 #endif /* HAVE_LDAP */