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