CtdlTryPasswordLDAP() migrated to ctdl_ldap_initialize()
[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         ldserver = ldap_init(config.c_ldap_host, config.c_ldap_port);
77         if (ctdl_ldap_initialize(&ldserver) != LDAP_SUCCESS) {
78                 return(errno);
79         }
80
81         ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
82         ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
83
84         striplt(config.c_ldap_bind_dn);
85         striplt(config.c_ldap_bind_pw);
86         syslog(LOG_DEBUG, "LDAP bind DN: %s", config.c_ldap_bind_dn);
87         i = ldap_simple_bind_s(ldserver,
88                 (!IsEmptyStr(config.c_ldap_bind_dn) ? config.c_ldap_bind_dn : NULL),
89                 (!IsEmptyStr(config.c_ldap_bind_pw) ? config.c_ldap_bind_pw : NULL)
90         );
91         if (i != LDAP_SUCCESS) {
92                 syslog(LOG_ALERT, "LDAP: Cannot bind: %s (%d)", ldap_err2string(i), i);
93                 return(i);
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
219         i = ctdl_ldap_initialize(&ldserver);
220         if (i == LDAP_SUCCESS) {
221                 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
222                 i = ldap_simple_bind_s(ldserver, user_dn, password);
223                 if (i == LDAP_SUCCESS) {
224                         syslog(LOG_DEBUG, "LDAP: bind succeeded");
225                 }
226                 else {
227                         syslog(LOG_DEBUG, "LDAP: Cannot bind: %s (%d)", ldap_err2string(i), i);
228                 }
229                 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
230                 ldap_unbind(ldserver);
231         }
232
233         if (i == LDAP_SUCCESS) {
234                 return(0);
235         }
236
237         return(1);
238 }
239
240 //return !0 iff property changed.
241 int vcard_set_props_iff_different(struct vCard *v,char *propname,int numvals, char **vals) {
242         int i;
243         char *oldval;
244         for(i=0;i<numvals;i++) {
245           oldval = vcard_get_prop(v,propname,0,i,0);
246           if (oldval == NULL) break;
247           if (strcmp(vals[i],oldval)) break;
248         }
249         if (i!=numvals) {
250                 for(i=0;i<numvals;i++) vcard_set_prop(v,propname,vals[i],(i==0) ? 0 : 1);
251                 return 1;
252         }
253         return 0;
254 }
255
256
257 //return !0 iff property changed.
258 int vcard_set_one_prop_iff_different(struct vCard *v,char *propname, char *newfmt, ...) {
259         va_list args;
260         char *newvalue;
261         int changed_something;
262         va_start(args,newfmt);
263         if (-1==vasprintf(&newvalue,newfmt,args)) {
264                 syslog(LOG_ALERT, "Out of memory!\n");
265                 return 0;
266         }
267         changed_something = vcard_set_props_iff_different(v,propname,1,&newvalue);
268         va_end(args);
269         free(newvalue);
270         return changed_something;
271 }
272
273 /*
274  * Learn LDAP attributes and stuff them into the vCard.
275  * Returns nonzero if we changed anything.
276  */
277 int Ctdl_LDAP_to_vCard(char *ldap_dn, struct vCard *v)
278 {
279         int changed_something = 0;
280         LDAP *ldserver = NULL;
281         int i;
282         struct timeval tv;
283         LDAPMessage *search_result = NULL;
284         LDAPMessage *entry = NULL;
285         char **givenName;
286         char **sn;
287         char **cn;
288         char **initials;
289         char **o;
290         char **street;
291         char **l;
292         char **st;
293         char **postalCode;
294         char **telephoneNumber;
295         char **mobile;
296         char **homePhone;
297         char **facsimileTelephoneNumber;
298         char **mail;
299         char **uid;
300         char **homeDirectory;
301         char **uidNumber;
302         char **loginShell;
303         char **gidNumber;
304         char **c;
305         char **title;
306         char **uuid;
307         char *attrs[] = { "*","+",NULL};
308
309         if (!ldap_dn) return(0);
310         if (!v) return(0);
311         ldserver = ldap_init(config.c_ldap_host, config.c_ldap_port);
312         if (ldserver == NULL) {
313                 syslog(LOG_ALERT, "LDAP: Could not connect to %s:%d : %s",
314                         config.c_ldap_host, config.c_ldap_port,
315                         strerror(errno)
316                 );
317                 return(0);
318         }
319
320         ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
321         ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
322
323         striplt(config.c_ldap_bind_dn);
324         striplt(config.c_ldap_bind_pw);
325         syslog(LOG_DEBUG, "LDAP bind DN: %s", config.c_ldap_bind_dn);
326         i = ldap_simple_bind_s(ldserver,
327                 (!IsEmptyStr(config.c_ldap_bind_dn) ? config.c_ldap_bind_dn : NULL),
328                 (!IsEmptyStr(config.c_ldap_bind_pw) ? config.c_ldap_bind_pw : NULL)
329         );
330         if (i != LDAP_SUCCESS) {
331                 syslog(LOG_ALERT, "LDAP: Cannot bind: %s (%d)", ldap_err2string(i), i);
332                 return(0);
333         }
334
335         tv.tv_sec = 10;
336         tv.tv_usec = 0;
337
338         syslog(LOG_DEBUG, "LDAP search: %s", ldap_dn);
339         (void) ldap_search_ext_s(
340                 ldserver,                               /* ld                           */
341                 ldap_dn,                                /* base                         */
342                 LDAP_SCOPE_SUBTREE,             /* scope                        */
343                 NULL,                                   /* filter                       */
344                 attrs,                                  /* attrs (all attributes)       */
345                 0,                                              /* attrsonly (attrs + values)   */
346                 NULL,                                   /* serverctrls (none)           */
347                 NULL,                                   /* clientctrls (none)           */
348                 &tv,                                    /* timeout                      */
349                 1,                                              /* sizelimit (1 result max)     */
350                 &search_result                  /* res                          */
351         );
352         
353         /* Ignore the return value of ldap_search_ext_s().  Sometimes it returns an error even when
354          * the search succeeds.  Instead, we check to see whether search_result is still NULL.
355          */
356          
357         if (search_result == NULL) {
358                 syslog(LOG_DEBUG, "LDAP search: zero results were returned");
359                 ldap_unbind(ldserver);
360                 return(0);
361         }
362
363         /* At this point we've got at least one result from our query.  If there are multiple
364          * results, we still only look at the first one.
365          */
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,"uid","%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         
443         return(changed_something);      /* tell the caller whether we made any changes */
444 }
445
446 #endif /* HAVE_LDAP */