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