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