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