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