]> arthur.barton.de Git - netatalk.git/blob - libatalk/acl/ldap.c
8743bafeabcd90b7f0e16afd6fa79bf3738b332a
[netatalk.git] / libatalk / acl / ldap.c
1 /*
2   Copyright (c) 2008,2009 Frank Lahm <franklahm@gmail.com>
3
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License as published by
6   the Free Software Foundation; either version 2 of the License, or
7   (at your option) any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   GNU General Public License for more details.
13 */
14
15 #ifdef HAVE_CONFIG_H
16 #include "config.h"
17 #endif /* HAVE_CONFIG_H */
18
19 #ifdef HAVE_LDAP
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <sys/time.h>
24 #include <string.h>
25 #include <errno.h>
26 #define LDAP_DEPRECATED 1
27 #include <ldap.h>
28
29 #include <atalk/logger.h>
30 #include <atalk/afp.h>
31 #include <atalk/uuid.h>
32 #include <atalk/ldapconfig.h>   /* For struct ldap_pref */
33
34 typedef enum {
35     KEEPALIVE = 1
36 } ldapcon_t;
37
38 /********************************************************
39  * LDAP config stuff. Filled by libatalk/acl/ldap_config.c
40  ********************************************************/
41 int ldap_config_valid;
42
43 char *ldap_server;
44 int  ldap_auth_method;
45 char *ldap_auth_dn;
46 char *ldap_auth_pw;
47 char *ldap_userbase;
48 int  ldap_userscope;
49 char *ldap_groupbase;
50 int  ldap_groupscope;
51 char *ldap_uuid_attr;
52 char *ldap_uuid_string;
53 char *ldap_name_attr;
54 char *ldap_group_attr;
55 char *ldap_uid_attr;
56 int  ldap_uuid_encoding;
57
58 struct ldap_pref ldap_prefs[] = {
59     {&ldap_server,     "ldap server",      0, 0, -1},
60     {&ldap_auth_method,"ldap auth method", 1, 1, -1},
61     {&ldap_auth_dn,    "ldap auth dn",     0, 0,  0},
62     {&ldap_auth_pw,    "ldap auth pw",     0, 0,  0},
63     {&ldap_userbase,   "ldap userbase",    0, 0, -1},
64     {&ldap_userscope,  "ldap userscope",   1 ,1, -1},
65     {&ldap_groupbase,  "ldap groupbase",   0, 0, -1},
66     {&ldap_groupscope, "ldap groupscope",  1 ,1, -1},
67     {&ldap_uuid_attr,  "ldap uuid attr",   0, 0, -1},
68     {&ldap_uuid_string,"ldap uuid string", 0, 0,  0},
69     {&ldap_name_attr,  "ldap name attr",   0, 0, -1},
70     {&ldap_group_attr, "ldap group attr",  0, 0, -1},
71     {&ldap_uid_attr,   "ldap uid attr",    0, 0,  0},
72     {&ldap_uuid_encoding,"ldap uuid encoding", 1, 1,  0},
73     {NULL,             NULL,               0, 0, -1}
74 };
75
76 struct pref_array prefs_array[] = {
77     {"ldap auth method", "none",   LDAP_AUTH_NONE},
78     {"ldap auth method", "simple", LDAP_AUTH_SIMPLE},
79     {"ldap auth method", "sasl",   LDAP_AUTH_SASL},
80     {"ldap userscope",   "base",   LDAP_SCOPE_BASE},
81     {"ldap userscope",   "one",    LDAP_SCOPE_ONELEVEL},
82     {"ldap userscope",   "sub",    LDAP_SCOPE_SUBTREE},
83     {"ldap groupscope",  "base",   LDAP_SCOPE_BASE},
84     {"ldap groupscope",  "one",    LDAP_SCOPE_ONELEVEL},
85     {"ldap groupscope",  "sub",    LDAP_SCOPE_SUBTREE},
86     {"ldap uuid encoding", "ms-guid",    LDAP_UUID_ENCODING_MSGUID},
87     {"ldap uuid encoding", "string", LDAP_UUID_ENCODING_STRING},
88     {NULL,               NULL,     0}
89 };
90
91 /********************************************************
92  * Static helper function
93  ********************************************************/
94
95 /*
96  * ldap_getattr_fromfilter_withbase_scope():
97  *   conflags: KEEPALIVE
98  *   scope: LDAP_SCOPE_BASE, LDAP_SCOPE_ONELEVEL, LDAP_SCOPE_SUBTREE
99  *   result: return unique search result here, allocated here, caller must free
100  *
101  * returns: -1 on error
102  *           0 nothing found
103  *           1 successfull search, result int 'result'
104  *
105  * All connection managment to the LDAP server is done here. Just set KEEPALIVE if you know
106  * you will be dispatching more than one search in a row, then don't set it with the last search.
107  * You MUST dispatch the queries timely, otherwise the LDAP handle might timeout.
108  */
109 static int ldap_getattr_fromfilter_withbase_scope( const char *searchbase,
110                                                    const char *filter,
111                                                    char *attributes[],
112                                                    int scope,
113                                                    ldapcon_t conflags,
114                                                    char **result) {
115     int ret;
116     int ldaperr;
117     int retrycount = 0;
118     int desired_version  = LDAP_VERSION3;
119     static int ldapconnected = 0;
120     static LDAP *ld     = NULL;
121     LDAPMessage* msg    = NULL;
122     LDAPMessage* entry  = NULL;
123     struct berval **attribute_values = NULL;
124     struct timeval timeout;
125
126     LOG(log_maxdebug, logtype_afpd,"ldap: BEGIN");
127
128     timeout.tv_sec = 3;
129     timeout.tv_usec = 0;
130
131     /* init LDAP if necessary */
132 retry:
133     ret = 0;
134
135     if (ld == NULL) {
136         LOG(log_maxdebug, logtype_default, "ldap: server: \"%s\"",
137             ldap_server);
138         if ((ld = ldap_init(ldap_server, LDAP_PORT)) == NULL ) {
139             LOG(log_error, logtype_default, "ldap: ldap_init error: %s",
140                 strerror(errno));
141             return -1;
142         }
143         if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &desired_version) != 0) {
144             /* LDAP_OPT_SUCCESS is not in the proposed standard, so we check for 0
145                http://tools.ietf.org/id/draft-ietf-ldapext-ldap-c-api-05.txt */
146             LOG(log_error, logtype_default, "ldap: ldap_set_option failed!");
147             free(ld);
148             ld = NULL;
149             return -1;
150         }
151     }
152
153     /* connect */
154     if (!ldapconnected) {
155         if (LDAP_AUTH_NONE == ldap_auth_method) {
156             if (ldap_bind_s(ld, "", "", LDAP_AUTH_SIMPLE) != LDAP_SUCCESS ) {
157                 LOG(log_error, logtype_default, "ldap: ldap_bind failed, auth_method: \'%d\'",
158                     ldap_auth_method);
159                 free(ld);
160                 ld = NULL;
161                 return -1;
162             }
163             ldapconnected = 1;
164
165         } else if (LDAP_AUTH_SIMPLE == ldap_auth_method) {
166             if (ldap_bind_s(ld, ldap_auth_dn, ldap_auth_pw, ldap_auth_method) != LDAP_SUCCESS ) {
167                 LOG(log_error, logtype_default,
168                     "ldap: ldap_bind failed: ldap_auth_dn: \'%s\', ldap_auth_pw: \'%s\', ldap_auth_method: \'%d\'",
169                     ldap_auth_dn, ldap_auth_pw, ldap_auth_method);
170                 free(ld);
171                 ld = NULL;
172                 return -1;
173             }
174             ldapconnected = 1;
175         }
176     }
177
178     LOG(log_maxdebug, logtype_afpd, "ldap: start search: base: %s, filter: %s, attr: %s",
179         searchbase, filter, attributes[0]);
180
181     /* start LDAP search */
182     ldaperr = ldap_search_st(ld, searchbase, scope, filter, attributes, 0, &timeout, &msg);
183     LOG(log_maxdebug, logtype_default, "ldap: ldap_search_st returned: %s",
184         ldap_err2string(ldaperr));
185     if (ldaperr != LDAP_SUCCESS) {
186         LOG(log_error, logtype_default, "ldap: ldap_search_st failed: %s, retrycount: %i",
187             ldap_err2string(ldaperr), retrycount);
188         ret = -1;
189         goto cleanup;
190     }
191
192     /* parse search result */
193     LOG(log_maxdebug, logtype_default, "ldap: got %d entries from ldap search",
194         ldap_count_entries(ld, msg));
195     if ((ret = ldap_count_entries(ld, msg)) != 1) {
196         ret = 0;
197         goto cleanup;
198     }
199
200     entry = ldap_first_entry(ld, msg);
201     if (entry == NULL) {
202         LOG(log_error, logtype_default, "ldap: ldap_first_entry error");
203         ret = -1;
204         goto cleanup;
205     }
206
207     attribute_values = ldap_get_values_len(ld, entry, attributes[0]);
208     if (attribute_values == NULL) {
209         LOG(log_error, logtype_default, "ldap: ldap_get_values_len error");
210         ret = -1;
211         goto cleanup;
212     }
213
214     LOG(log_maxdebug, logtype_afpd,"ldap: search result: %s: %s",
215         attributes[0], attribute_values[0]->bv_val);
216
217     /* allocate and copy result */
218     *result = calloc(1, attribute_values[0]->bv_len + 1);
219     memcpy(*result, attribute_values[0]->bv_val, attribute_values[0]->bv_len + 1);
220
221     if (*result == NULL) {
222         LOG(log_error, logtype_default, "ldap: memcopy error: %s", strerror(errno));
223         ret = -1;
224         goto cleanup;
225     }
226
227 cleanup:
228     if (attribute_values)
229         ldap_value_free_len(attribute_values);
230     /* FIXME: is there another way to free entry ? */
231     while (entry != NULL)
232         entry = ldap_next_entry(ld, entry);
233     if (msg)
234         ldap_msgfree(msg);
235
236     if (ldapconnected) {
237         if ((ret == -1) || !(conflags & KEEPALIVE)) {
238             LOG(log_maxdebug, logtype_default,"ldap: unbind");
239             if (ldap_unbind_s(ld) != 0) {
240                 LOG(log_error, logtype_default, "ldap: unbind: %s\n", ldap_err2string(ldaperr));
241                 return -1;
242             }
243             ld = NULL;
244             ldapconnected = 0;
245
246             /* In case of error we try twice */
247             if (ret == -1) {
248                 retrycount++;
249                 if (retrycount < 2)
250                     goto retry;
251             }
252         }
253     }
254     return ret;
255 }
256
257 /********************************************************
258  * Interface
259  ********************************************************/
260
261 /*! 
262  * Search UUID for name in LDAP
263  *
264  * Caller must free uuid_string when done with it
265  *
266  * @param name        (r) name to search
267  * @param type        (r) type of USER or GROUP
268  * @param uuid_string (w) result as pointer to allocated UUID-string
269  *
270  * @returns 0 on success, -1 on error or not found
271  */
272 int ldap_getuuidfromname( const char *name, uuidtype_t type, char **uuid_string) {
273     int ret;
274     int len;
275     char filter[256];           /* this should really be enough. we dont want to malloc everything! */
276     char *attributes[]  = { ldap_uuid_attr, NULL};
277     char *ldap_attr;
278
279     if (!ldap_config_valid)
280         return -1;
281
282     /* make filter */
283     if (type == UUID_GROUP)
284         ldap_attr = ldap_group_attr;
285     else /* type hopefully == UUID_USER */
286         ldap_attr = ldap_name_attr;
287     len = snprintf( filter, 256, "%s=%s", ldap_attr, name);
288     if (len >= 256 || len == -1) {
289         LOG(log_error, logtype_default, "ldap_getnamefromuuid: filter error:%d, \"%s\"", len, filter);
290         return -1;
291     }
292
293     if (type == UUID_GROUP) {
294         ret = ldap_getattr_fromfilter_withbase_scope( ldap_groupbase, filter, attributes, ldap_groupscope, KEEPALIVE, uuid_string);
295     } else  { /* type hopefully == UUID_USER */
296         ret = ldap_getattr_fromfilter_withbase_scope( ldap_userbase, filter, attributes, ldap_userscope, KEEPALIVE, uuid_string);
297     }
298
299     if (ret != 1)
300         return -1;
301
302     if(ldap_uuid_encoding == LDAP_UUID_ENCODING_MSGUID) {
303         /* Convert byte array to UUID string (no dashes) */
304         unsigned char* uuid_bytes = (unsigned char*) *uuid_string;
305         *uuid_string = malloc(37);
306         snprintf(*uuid_string, 37,
307             "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
308             uuid_bytes[3], uuid_bytes[2], uuid_bytes[1], uuid_bytes[0], /* Data1 */
309             uuid_bytes[5], uuid_bytes[4], /* Data2 */
310             uuid_bytes[7], uuid_bytes[6], /* Data3 */
311             uuid_bytes[8], uuid_bytes[9], /* Data4 - High Bytes */
312             uuid_bytes[10], uuid_bytes[11], uuid_bytes[12], /* Data4 - Low Bytes */
313             uuid_bytes[13], uuid_bytes[14], uuid_bytes[15]);
314         free(uuid_bytes);
315         LOG(log_error, logtype_default, "ldap_getnamefromuuid: uuid_string: %s", *uuid_string);
316     }
317
318     return 0;
319 }
320
321 /*
322  * LDAP search wrapper
323  * returns allocated storage in name, caller must free it
324  * returns 0 on success, -1 on error or not found
325  * 
326  * @param uuidstr  (r) uuid to search as ascii string
327  * @param name     (w) return pointer to name as allocated string
328  * @param type     (w) return type: USER or GROUP
329  *
330  * returns 0 on success, -1 on errror
331  */
332 int ldap_getnamefromuuid( const char *uuidstr, char **name, uuidtype_t *type) {
333     int ret;
334     int len;
335     char filter[256];       /* this should really be enough. we dont want to malloc everything! */
336     char *attributes[]  = { NULL, NULL};
337
338     if (!ldap_config_valid)
339         return -1;
340
341     if(ldap_uuid_encoding == LDAP_UUID_ENCODING_MSGUID) {
342         /* Convert to LDAP-safe binary encoding for direct query of AD objectGUID attribute */
343         char* stripped = malloc(strlen(uuidstr));
344
345         int i = 0;
346         int s = 0;
347         char c;
348         while(c = uuidstr[i]) {
349             if((c >='a' && c <= 'f')
350                 || (c >= 'A' && c <= 'F')
351                 || (c >= '0' && c <= '9')) {
352                 stripped[s++] = toupper(c);
353             }
354             i++;
355         }
356
357         /* LDAP Binary Notation is \XX * 16 bytes of UUID + terminator = 49 */
358         char* ldap_bytes = malloc(49);
359         snprintf(ldap_bytes, 49,
360             "\\%c%c\\%c%c\\%c%c\\%c%c\\%c%c\\%c%c\\%c%c\\%c%c"
361             "\\%c%c\\%c%c\\%c%c\\%c%c\\%c%c\\%c%c\\%c%c\\%c%c",
362             /* Data1 (uint32) */
363             stripped[6], stripped[7], stripped[4], stripped[5],
364             stripped[2], stripped[3], stripped[0], stripped[1],
365             /* Data2 (uint16) */
366             stripped[10], stripped[11], stripped[8], stripped[9],
367             /* Data3 (uint16) */
368             stripped[14], stripped[15], stripped[12], stripped[13],
369             /* Data4 (uint64) */
370             stripped[16], stripped[17], stripped[18], stripped[19],
371             stripped[20], stripped[21], stripped[22], stripped[23],
372             stripped[24], stripped[25], stripped[26], stripped[27],
373             stripped[28], stripped[29], stripped[30], stripped[31]);
374         len = snprintf( filter, 256, "%s=%s", ldap_uuid_attr, ldap_bytes);
375
376         free(ldap_bytes);
377         free(stripped);
378     } else {
379         len = snprintf( filter, 256, "%s=%s", ldap_uuid_attr, uuidstr);
380     }
381
382     if (len >= 256 || len == -1) {
383         LOG(log_error, logtype_default, "ldap_getnamefromuuid: filter overflow:%d, \"%s\"", len, filter);
384         return -1;
385     }
386     /* search groups first. group acls are probably used more often */
387     attributes[0] = ldap_group_attr;
388     ret = ldap_getattr_fromfilter_withbase_scope( ldap_groupbase, filter, attributes, ldap_groupscope, KEEPALIVE, name);
389     if (ret == -1)
390         return -1;
391     if (ret == 1) {
392         *type = UUID_GROUP;
393         return 0;
394     }
395
396     attributes[0] = ldap_name_attr;
397     ret = ldap_getattr_fromfilter_withbase_scope( ldap_userbase, filter, attributes, ldap_userscope, KEEPALIVE, name);
398     if (ret == 1) {
399         *type = UUID_USER;
400         return 0;
401     }
402
403     return -1;
404 }
405 #endif  /* HAVE_LDAP */