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