xref: /lighttpd1.4/src/mod_vhostdb_ldap.c (revision 49e9f0ac)
1 #include "first.h"
2 
3 #include <ldap.h>
4 
5 #include <errno.h>
6 #include <string.h>
7 #include <stdlib.h>
8 
9 #include "base.h"
10 #include "http_vhostdb.h"
11 #include "log.h"
12 #include "plugin.h"
13 
14 /*
15  * virtual host plugin using LDAP for domain to directory lookups
16  */
17 
18 typedef struct {
19     LDAP *ldap;
20     buffer *filter;
21     server *srv;
22 
23     const char *attr;
24     const char *host;
25     const char *basedn;
26     const char *binddn;
27     const char *bindpw;
28     const char *cafile;
29     unsigned short starttls;
30 } vhostdb_config;
31 
32 typedef struct {
33     void *vdata;
34     array *options;
35 } plugin_config;
36 
37 typedef struct {
38     PLUGIN_DATA;
39     plugin_config **config_storage;
40     plugin_config conf;
41 } plugin_data;
42 
43 static void mod_vhostdb_dbconf_free (void *vdata)
44 {
45     vhostdb_config *dbconf = (vhostdb_config *)vdata;
46     if (!dbconf) return;
47     if (NULL != dbconf->ldap) ldap_unbind_ext_s(dbconf->ldap, NULL, NULL);
48     free(dbconf);
49 }
50 
51 /*(copied from mod_authn_ldap.c)*/
52 static void mod_vhostdb_dbconf_add_scheme (server *srv, buffer *host)
53 {
54     if (!buffer_string_is_empty(host)) {
55         /* reformat hostname(s) as LDAP URIs (scheme://host:port) */
56         static const char *schemes[] = {
57           "ldap://", "ldaps://", "ldapi://", "cldap://"
58         };
59         char *b, *e = host->ptr;
60         buffer_clear(srv->tmp_buf);
61         while (*(b = e)) {
62             unsigned int j;
63             while (*b==' '||*b=='\t'||*b=='\r'||*b=='\n'||*b==',') ++b;
64             if (*b == '\0') break;
65             e = b;
66             while (*e!=' '&&*e!='\t'&&*e!='\r'&&*e!='\n'&&*e!=','&&*e!='\0')
67                 ++e;
68             if (!buffer_string_is_empty(srv->tmp_buf))
69                 buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN(","));
70             for (j = 0; j < sizeof(schemes)/sizeof(char *); ++j) {
71                 if (0 == strncasecmp(b, schemes[j], strlen(schemes[j]))) {
72                     break;
73                 }
74             }
75             if (j == sizeof(schemes)/sizeof(char *))
76                 buffer_append_string_len(srv->tmp_buf,
77                                          CONST_STR_LEN("ldap://"));
78             buffer_append_string_len(srv->tmp_buf, b, (size_t)(e - b));
79         }
80         buffer_copy_buffer(host, srv->tmp_buf);
81     }
82 }
83 
84 static int mod_vhostdb_dbconf_setup (server *srv, array *opts, void **vdata)
85 {
86     buffer *filter = NULL;
87     const char *attr = "documentRoot";
88     const char *basedn=NULL,*binddn=NULL,*bindpw=NULL,*host=NULL,*cafile=NULL;
89     unsigned short starttls = 0;
90 
91     for (size_t i = 0; i < opts->used; ++i) {
92         const data_string *ds = (data_string *)opts->data[i];
93         if (ds->type == TYPE_STRING) {
94             if (buffer_is_equal_caseless_string(ds->key, CONST_STR_LEN("filter"))) {
95                 filter = ds->value;
96             } else if (buffer_is_equal_caseless_string(ds->key, CONST_STR_LEN("attr"))) {
97                 if (!buffer_string_is_empty(ds->value)) attr   = ds->value->ptr;
98             } else if (buffer_is_equal_caseless_string(ds->key, CONST_STR_LEN("host"))) {
99                 mod_vhostdb_dbconf_add_scheme(srv, ds->value);
100                 host   = ds->value->ptr;
101             } else if (buffer_is_equal_caseless_string(ds->key, CONST_STR_LEN("base-dn"))) {
102                 if (!buffer_string_is_empty(ds->value)) basedn = ds->value->ptr;
103             } else if (buffer_is_equal_caseless_string(ds->key, CONST_STR_LEN("bind-dn"))) {
104                 if (!buffer_string_is_empty(ds->value)) binddn = ds->value->ptr;
105             } else if (buffer_is_equal_caseless_string(ds->key, CONST_STR_LEN("bind-pw"))) {
106                 bindpw = ds->value->ptr;
107             } else if (buffer_is_equal_caseless_string(ds->key, CONST_STR_LEN("ca-file"))) {
108                 if (!buffer_string_is_empty(ds->value)) cafile = ds->value->ptr;
109             } else if (buffer_is_equal_caseless_string(ds->key, CONST_STR_LEN("starttls"))) {
110                 starttls = !buffer_is_equal_string(ds->value, CONST_STR_LEN("disable"))
111                         && !buffer_is_equal_string(ds->value, CONST_STR_LEN("0"));
112             }
113         }
114     }
115 
116     /* required:
117      * - host
118      * - filter (LDAP query)
119      * - base-dn
120      *
121      * optional:
122      * - attr   (LDAP attribute with docroot; default "documentRoot")
123      * - bind-dn
124      * - bind-pw
125      * - ca-file
126      * - starttls
127      */
128 
129     if (!buffer_string_is_empty(filter) && NULL != host && NULL != basedn) {
130         vhostdb_config *dbconf;
131 
132         if (NULL == strchr(filter->ptr, '?')) {
133             log_error_write(srv, __FILE__, __LINE__, "s",
134                             "ldap: filter is missing a replace-operator '?'");
135             return -1;
136         }
137 
138         /* openldap sets FD_CLOEXEC on database socket descriptors
139          * (still race between creation of socket and fcntl FD_CLOEXEC)
140          * (YMMV with other LDAP client libraries) */
141 
142         dbconf = (vhostdb_config *)calloc(1, sizeof(*dbconf));
143         dbconf->ldap     = NULL;
144         dbconf->filter   = filter;
145         dbconf->attr     = attr;
146         dbconf->host     = host;
147         dbconf->basedn   = basedn;
148         dbconf->binddn   = binddn;
149         dbconf->bindpw   = bindpw;
150         dbconf->cafile   = cafile;
151         dbconf->starttls = starttls;
152         *vdata = dbconf;
153     }
154     return 0;
155 }
156 
157 /*
158  * Note: a large portion of the LDAP code is copied verbatim from mod_authn_ldap
159  * with only changes being use of vhostdb_config instead of plugin_config struct
160  * and (const char *) strings in vhostdb_config instead of (buffer *).
161  */
162 
163 static void mod_authn_ldap_err(server *srv, const char *file, unsigned long line, const char *fn, int err)
164 {
165     log_error_write(srv,file,line,"sSss","ldap:",fn,":",ldap_err2string(err));
166 }
167 
168 static void mod_authn_ldap_opt_err(server *srv, const char *file, unsigned long line, const char *fn, LDAP *ld)
169 {
170     int err;
171     ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &err);
172     mod_authn_ldap_err(srv, file, line, fn, err);
173 }
174 
175 static void mod_authn_append_ldap_filter_escape(buffer * const filter, const buffer * const raw) {
176     /* [RFC4515] 3. String Search Filter Definition
177      *
178      * [...]
179      *
180      * The <valueencoding> rule ensures that the entire filter string is a
181      * valid UTF-8 string and provides that the octets that represent the
182      * ASCII characters "*" (ASCII 0x2a), "(" (ASCII 0x28), ")" (ASCII
183      * 0x29), "\" (ASCII 0x5c), and NUL (ASCII 0x00) are represented as a
184      * backslash "\" (ASCII 0x5c) followed by the two hexadecimal digits
185      * representing the value of the encoded octet.
186      *
187      * [...]
188      *
189      * As indicated by the <valueencoding> rule, implementations MUST escape
190      * all octets greater than 0x7F that are not part of a valid UTF-8
191      * encoding sequence when they generate a string representation of a
192      * search filter.  Implementations SHOULD accept as input strings that
193      * are not valid UTF-8 strings.  This is necessary because RFC 2254 did
194      * not clearly define the term "string representation" (and in
195      * particular did not mention that the string representation of an LDAP
196      * search filter is a string of UTF-8-encoded Unicode characters).
197      *
198      *
199      * https://www.ldap.com/ldap-filters
200      * Although not required, you may escape any other characters that you want
201      * in the assertion value (or substring component) of a filter. This may be
202      * accomplished by prefixing the hexadecimal representation of each byte of
203      * the UTF-8 encoding of the character to escape with a backslash character.
204      */
205     const char * const b = raw->ptr;
206     const size_t rlen = buffer_string_length(raw);
207     for (size_t i = 0; i < rlen; ++i) {
208         size_t len = i;
209         char *f;
210         do {
211             /* encode all UTF-8 chars with high bit set
212              * (instead of validating UTF-8 and escaping only invalid UTF-8) */
213             if (((unsigned char *)b)[len] > 0x7f)
214                 break;
215             switch (b[len]) {
216               default:
217                 continue;
218               case '\0': case '(': case ')': case '*': case '\\':
219                 break;
220             }
221             break;
222         } while (++len < rlen);
223         len -= i;
224 
225         if (len) {
226             buffer_append_string_len(filter, b+i, len);
227             if ((i += len) == rlen) break;
228         }
229 
230         /* escape * ( ) \ NUL ('\0') (and all UTF-8 chars with high bit set) */
231         buffer_string_prepare_append(filter, 3);
232         f = filter->ptr + buffer_string_length(filter);
233         f[0] = '\\';
234         f[1] = "0123456789abcdef"[(((unsigned char *)b)[i] >> 4) & 0xf];
235         f[2] = "0123456789abcdef"[(((unsigned char *)b)[i]     ) & 0xf];
236         buffer_commit(filter, 3);
237     }
238 }
239 
240 static LDAP * mod_authn_ldap_host_init(server *srv, vhostdb_config *s) {
241     LDAP *ld;
242     int ret;
243 
244     ret = ldap_initialize(&ld, s->host);
245     if (LDAP_SUCCESS != ret) {
246         log_error_write(srv, __FILE__, __LINE__, "sss", "ldap:",
247                         "ldap_initialize():", strerror(errno));
248         return NULL;
249     }
250 
251     ret = LDAP_VERSION3;
252     ret = ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &ret);
253     if (LDAP_OPT_SUCCESS != ret) {
254         mod_authn_ldap_err(srv, __FILE__, __LINE__, "ldap_set_options()", ret);
255         ldap_destroy(ld);
256         return NULL;
257     }
258 
259     if (s->starttls) {
260         /* if no CA file is given, it is ok, as we will use encryption
261          * if the server requires a CAfile it will tell us */
262         if (s->cafile) {
263             ret = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, s->cafile);
264             if (LDAP_OPT_SUCCESS != ret) {
265                 mod_authn_ldap_err(srv, __FILE__, __LINE__,
266                                    "ldap_set_option(LDAP_OPT_X_TLS_CACERTFILE)",
267                                    ret);
268                 ldap_destroy(ld);
269                 return NULL;
270             }
271         }
272 
273         ret = ldap_start_tls_s(ld, NULL,  NULL);
274         if (LDAP_OPT_SUCCESS != ret) {
275             mod_authn_ldap_err(srv,__FILE__,__LINE__,"ldap_start_tls_s()",ret);
276             ldap_destroy(ld);
277             return NULL;
278         }
279     }
280 
281     return ld;
282 }
283 
284 static int mod_authn_ldap_bind(server *srv, LDAP *ld, const char *dn, const char *pw) {
285     struct berval creds;
286     int ret;
287 
288     if (NULL != pw) {
289         *((const char **)&creds.bv_val) = pw; /*(cast away const)*/
290         creds.bv_len = strlen(pw);
291     } else {
292         creds.bv_val = NULL;
293         creds.bv_len = 0;
294     }
295 
296     /* RFE: add functionality: LDAP_SASL_EXTERNAL (or GSS-SPNEGO, etc.) */
297 
298     ret = ldap_sasl_bind_s(ld,dn,LDAP_SASL_SIMPLE,&creds,NULL,NULL,NULL);
299     if (ret != LDAP_SUCCESS) {
300         mod_authn_ldap_err(srv, __FILE__, __LINE__, "ldap_sasl_bind_s()", ret);
301     }
302 
303     return ret;
304 }
305 
306 static int mod_authn_ldap_rebind_proc (LDAP *ld, LDAP_CONST char *url, ber_tag_t ldap_request, ber_int_t msgid, void *params) {
307     vhostdb_config *s = (vhostdb_config *)params;
308     UNUSED(url);
309     UNUSED(ldap_request);
310     UNUSED(msgid);
311     return mod_authn_ldap_bind(s->srv, ld, s->binddn, s->bindpw);
312 }
313 
314 static LDAPMessage * mod_authn_ldap_search(server *srv, vhostdb_config *s, char *base, char *filter) {
315     LDAPMessage *lm = NULL;
316     char *attrs[] = { LDAP_NO_ATTRS, NULL };
317     int ret;
318 
319     /*
320      * 1. connect anonymously (if not already connected)
321      *    (ldap connection is kept open unless connection-level error occurs)
322      * 2. issue search using filter
323      */
324 
325     if (s->ldap != NULL) {
326         ret = ldap_search_ext_s(s->ldap, base, LDAP_SCOPE_SUBTREE, filter,
327                                 attrs, 0, NULL, NULL, NULL, 0, &lm);
328         if (LDAP_SUCCESS == ret) {
329             return lm;
330         } else if (LDAP_SERVER_DOWN != ret) {
331             /* try again (or initial request);
332              * ldap lib sometimes fails for the first call but reconnects */
333             ret = ldap_search_ext_s(s->ldap, base, LDAP_SCOPE_SUBTREE, filter,
334                                     attrs, 0, NULL, NULL, NULL, 0, &lm);
335             if (LDAP_SUCCESS == ret) {
336                 return lm;
337             }
338         }
339 
340         ldap_unbind_ext_s(s->ldap, NULL, NULL);
341     }
342 
343     s->ldap = mod_authn_ldap_host_init(srv, s);
344     if (NULL == s->ldap) {
345         return NULL;
346     }
347 
348     ldap_set_rebind_proc(s->ldap, mod_authn_ldap_rebind_proc, s);
349     ret = mod_authn_ldap_bind(srv, s->ldap, s->binddn, s->bindpw);
350     if (LDAP_SUCCESS != ret) {
351         ldap_destroy(s->ldap);
352         s->ldap = NULL;
353         return NULL;
354     }
355 
356     ret = ldap_search_ext_s(s->ldap, base, LDAP_SCOPE_SUBTREE, filter,
357                             attrs, 0, NULL, NULL, NULL, 0, &lm);
358     if (LDAP_SUCCESS != ret) {
359         log_error_write(srv, __FILE__, __LINE__, "sSss",
360                         "ldap:", ldap_err2string(ret), "; filter:", filter);
361         ldap_unbind_ext_s(s->ldap, NULL, NULL);
362         s->ldap = NULL;
363         return NULL;
364     }
365 
366     return lm;
367 }
368 
369 static void mod_vhostdb_patch_connection (server *srv, connection *con, plugin_data *p);
370 
371 static int mod_vhostdb_ldap_query(server *srv, connection *con, void *p_d, buffer *docroot)
372 {
373     plugin_data *p = (plugin_data *)p_d;
374     vhostdb_config *dbconf;
375     LDAP *ld;
376     LDAPMessage *lm, *first;
377     struct berval **vals;
378     int count;
379     char *basedn;
380     buffer *template;
381 
382     /*(reuse buffer for ldap query before generating docroot result)*/
383     buffer *filter = docroot;
384     buffer_clear(filter); /*(also resets docroot (alias))*/
385 
386     mod_vhostdb_patch_connection(srv, con, p);
387     if (NULL == p->conf.vdata) return 0; /*(after resetting docroot)*/
388     dbconf = (vhostdb_config *)p->conf.vdata;
389     dbconf->srv = srv;
390 
391     template = dbconf->filter;
392     for (char *b = template->ptr, *d; *b; b = d+1) {
393         if (NULL != (d = strchr(b, '?'))) {
394             buffer_append_string_len(filter, b, (size_t)(d - b));
395             mod_authn_append_ldap_filter_escape(filter, con->uri.authority);
396         } else {
397             d = template->ptr + buffer_string_length(template);
398             buffer_append_string_len(filter, b, (size_t)(d - b));
399             break;
400         }
401     }
402 
403     /* (cast away const for poor LDAP ldap_search_ext_s() prototype) */
404     *(const char **)&basedn = dbconf->basedn;
405 
406     /* ldap_search (synchronous; blocking) */
407     lm = mod_authn_ldap_search(srv, dbconf, basedn, filter->ptr);
408     if (NULL == lm) {
409         return -1;
410     }
411 
412     /*(must be after mod_authn_ldap_search(); might reconnect)*/
413     ld = dbconf->ldap;
414 
415     count = ldap_count_entries(ld, lm);
416     if (count > 1) {
417         log_error_write(srv, __FILE__, __LINE__, "ssb",
418                         "ldap:", "more than one record returned.  "
419                         "you might have to refine the filter:", filter);
420     }
421 
422     buffer_clear(docroot); /*(reset buffer to store result)*/
423 
424     if (0 == count) { /*(no entries found)*/
425         ldap_msgfree(lm);
426         return 0;
427     }
428 
429     if (NULL == (first = ldap_first_entry(ld, lm))) {
430         mod_authn_ldap_opt_err(srv,__FILE__,__LINE__,"ldap_first_entry()",ld);
431         ldap_msgfree(lm);
432         return -1;
433     }
434 
435     if (NULL != (vals = ldap_get_values_len(ld, first, dbconf->attr))) {
436         buffer_copy_string_len(docroot, vals[0]->bv_val, vals[0]->bv_len);
437         ldap_value_free_len(vals);
438     }
439 
440     ldap_msgfree(lm);
441     return 0;
442 }
443 
444 
445 
446 
447 INIT_FUNC(mod_vhostdb_init) {
448     static http_vhostdb_backend_t http_vhostdb_backend_ldap =
449       { "ldap", mod_vhostdb_ldap_query, NULL };
450     plugin_data *p = calloc(1, sizeof(*p));
451 
452     /* register http_vhostdb_backend_ldap */
453     http_vhostdb_backend_ldap.p_d = p;
454     http_vhostdb_backend_set(&http_vhostdb_backend_ldap);
455 
456     return p;
457 }
458 
459 FREE_FUNC(mod_vhostdb_cleanup) {
460     plugin_data *p = p_d;
461     if (!p) return HANDLER_GO_ON;
462 
463     if (p->config_storage) {
464         for (size_t i = 0; i < srv->config_context->used; i++) {
465             plugin_config *s = p->config_storage[i];
466             if (!s) continue;
467             mod_vhostdb_dbconf_free(s->vdata);
468             array_free(s->options);
469             free(s);
470         }
471         free(p->config_storage);
472     }
473     free(p);
474 
475     UNUSED(srv);
476     return HANDLER_GO_ON;
477 }
478 
479 SETDEFAULTS_FUNC(mod_vhostdb_set_defaults) {
480     plugin_data *p = p_d;
481 
482     config_values_t cv[] = {
483         { "vhostdb.ldap",  NULL, T_CONFIG_ARRAY,  T_CONFIG_SCOPE_CONNECTION },
484         { NULL,            NULL, T_CONFIG_UNSET,  T_CONFIG_SCOPE_UNSET }
485     };
486 
487     p->config_storage = calloc(srv->config_context->used, sizeof(plugin_config *));
488 
489     for (size_t i = 0; i < srv->config_context->used; ++i) {
490         data_config const *config = (data_config const*)srv->config_context->data[i];
491         plugin_config *s = calloc(1, sizeof(plugin_config));
492 
493         s->options = array_init();
494         cv[0].destination = s->options;
495 
496         p->config_storage[i] = s;
497 
498         if (config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
499             return HANDLER_ERROR;
500         }
501 
502 	if (!array_is_kvstring(s->options)) {
503 		log_error_write(srv, __FILE__, __LINE__, "s",
504 				"unexpected value for vhostdb.ldap; expected list of \"option\" => \"value\"");
505 		return HANDLER_ERROR;
506 	}
507 
508         if (s->options->used
509             && 0 != mod_vhostdb_dbconf_setup(srv, s->options, &s->vdata)) {
510             return HANDLER_ERROR;
511         }
512     }
513 
514     return HANDLER_GO_ON;
515 }
516 
517 #define PATCH(x) \
518     p->conf.x = s->x;
519 static void mod_vhostdb_patch_connection (server *srv, connection *con, plugin_data *p)
520 {
521     plugin_config *s = p->config_storage[0];
522     PATCH(vdata);
523 
524     /* skip the first, the global context */
525     for (size_t i = 1; i < srv->config_context->used; ++i) {
526         data_config *dc = (data_config *)srv->config_context->data[i];
527         s = p->config_storage[i];
528 
529         /* condition didn't match */
530         if (!config_check_cond(srv, con, dc)) continue;
531 
532         /* merge config */
533         for (size_t j = 0; j < dc->value->used; ++j) {
534             data_unset *du = dc->value->data[j];
535 
536             if (buffer_is_equal_string(du->key,CONST_STR_LEN("vhostdb.ldap"))) {
537                 PATCH(vdata);
538             }
539         }
540     }
541 }
542 #undef PATCH
543 
544 /* this function is called at dlopen() time and inits the callbacks */
545 int mod_vhostdb_ldap_plugin_init (plugin *p);
546 int mod_vhostdb_ldap_plugin_init (plugin *p)
547 {
548     p->version          = LIGHTTPD_VERSION_ID;
549     p->name             = buffer_init_string("vhostdb_ldap");
550 
551     p->init             = mod_vhostdb_init;
552     p->cleanup          = mod_vhostdb_cleanup;
553     p->set_defaults     = mod_vhostdb_set_defaults;
554 
555     return 0;
556 }
557