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