xref: /lighttpd1.4/src/mod_authn_ldap.c (revision 3392e8fb)
1 /*
2  * mod_authn_ldap - HTTP Auth LDAP backend
3  *
4  * Fully-rewritten from original
5  * Copyright(c) 2016 Glenn Strauss gstrauss()gluelogic.com  All rights reserved
6  * License: BSD 3-clause (same as lighttpd)
7  */
8 #include "first.h"
9 
10 #include <ldap.h>
11 
12 #include "base.h"
13 #include "http_auth.h"
14 #include "log.h"
15 #include "plugin.h"
16 
17 #include <stdlib.h>
18 #include <string.h>
19 
20 typedef struct {
21     LDAP *ldap;
22     log_error_st *errh;
23     const char *auth_ldap_hostname;
24     const char *auth_ldap_binddn;
25     const char *auth_ldap_bindpw;
26     const char *auth_ldap_cafile;
27     int auth_ldap_starttls;
28     struct timeval auth_ldap_timeout;
29 } plugin_config_ldap;
30 
31 typedef struct {
32     plugin_config_ldap *ldc;
33     const char *auth_ldap_basedn;
34     const buffer *auth_ldap_filter;
35     const buffer *auth_ldap_groupmember;
36     int auth_ldap_allow_empty_pw;
37 
38     int auth_ldap_starttls;
39     const char *auth_ldap_binddn;
40     const char *auth_ldap_bindpw;
41     const char *auth_ldap_cafile;
42 } plugin_config;
43 
44 typedef struct {
45     PLUGIN_DATA;
46     plugin_config defaults;
47     plugin_config conf;
48 
49     buffer ldap_filter;
50 } plugin_data;
51 
52 static const char *default_cafile;
53 
54 static handler_t mod_authn_ldap_basic(request_st * const r, void *p_d, const http_auth_require_t *require, const buffer *username, const char *pw);
55 
56 INIT_FUNC(mod_authn_ldap_init) {
57     static http_auth_backend_t http_auth_backend_ldap =
58       { "ldap", mod_authn_ldap_basic, NULL, NULL };
59     plugin_data *p = calloc(1, sizeof(*p));
60 
61     /* register http_auth_backend_ldap */
62     http_auth_backend_ldap.p_d = p;
63     http_auth_backend_set(&http_auth_backend_ldap);
64 
65     return p;
66 }
67 
68 FREE_FUNC(mod_authn_ldap_free) {
69     plugin_data * const p = p_d;
70     if (NULL == p->cvlist) return;
71     /* (init i to 0 if global context; to 1 to skip empty global context) */
72     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
73         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
74         for (; -1 != cpv->k_id; ++cpv) {
75             switch (cpv->k_id) {
76               case 0: /* auth.backend.ldap.hostname */
77                 if (cpv->vtype == T_CONFIG_LOCAL) {
78                     plugin_config_ldap *s = cpv->v.v;
79                     if (NULL != s->ldap) ldap_unbind_ext_s(s->ldap, NULL, NULL);
80                     free(s);
81                 }
82                 break;
83               default:
84                 break;
85             }
86         }
87     }
88 
89     free(p->ldap_filter.ptr);
90     default_cafile = NULL;
91 }
92 
93 static void mod_authn_ldap_merge_config_cpv(plugin_config * const pconf, const config_plugin_value_t * const cpv) {
94     switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
95       case 0: /* auth.backend.ldap.hostname */
96         if (cpv->vtype == T_CONFIG_LOCAL)
97             pconf->ldc = cpv->v.v;
98         break;
99       case 1: /* auth.backend.ldap.base-dn */
100         if (cpv->vtype == T_CONFIG_LOCAL)
101             pconf->auth_ldap_basedn = cpv->v.v;
102         break;
103       case 2: /* auth.backend.ldap.filter */
104         pconf->auth_ldap_filter = cpv->v.v;
105         break;
106       case 3: /* auth.backend.ldap.ca-file */
107         pconf->auth_ldap_cafile = cpv->v.v;
108         break;
109       case 4: /* auth.backend.ldap.starttls */
110         pconf->auth_ldap_starttls = (int)cpv->v.u;
111         break;
112       case 5: /* auth.backend.ldap.bind-dn */
113         pconf->auth_ldap_binddn = cpv->v.v;
114         break;
115       case 6: /* auth.backend.ldap.bind-pw */
116         pconf->auth_ldap_bindpw = cpv->v.v;
117         break;
118       case 7: /* auth.backend.ldap.allow-empty-pw */
119         pconf->auth_ldap_allow_empty_pw = (int)cpv->v.u;
120         break;
121       case 8: /* auth.backend.ldap.groupmember */
122         pconf->auth_ldap_groupmember = cpv->v.b;
123         break;
124       case 9: /* auth.backend.ldap.timeout */
125         /*(not implemented as any-scope override;
126          * supported in same scope as auth.backend.ldap.hostname)*/
127         /*pconf->auth_ldap_timeout = cpv->v.b;*/
128         break;
129       default:/* should not happen */
130         return;
131     }
132 }
133 
134 static void mod_authn_ldap_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv) {
135     do {
136         mod_authn_ldap_merge_config_cpv(pconf, cpv);
137     } while ((++cpv)->k_id != -1);
138 }
139 
140 static void mod_authn_ldap_patch_config(request_st * const r, plugin_data * const p) {
141     memcpy(&p->conf, &p->defaults, sizeof(plugin_config));
142     for (int i = 1, used = p->nconfig; i < used; ++i) {
143         if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
144             mod_authn_ldap_merge_config(&p->conf,
145                                         p->cvlist + p->cvlist[i].v.u2[0]);
146     }
147 }
148 
149 /*(copied from mod_vhostdb_ldap.c)*/
150 static void mod_authn_add_scheme (server *srv, buffer *host)
151 {
152     if (!buffer_string_is_empty(host)) {
153         /* reformat hostname(s) as LDAP URIs (scheme://host:port) */
154         static const char *schemes[] = {
155           "ldap://", "ldaps://", "ldapi://", "cldap://"
156         };
157         char *b, *e = host->ptr;
158         buffer * const tb = srv->tmp_buf;
159         buffer_clear(tb);
160         while (*(b = e)) {
161             unsigned int j;
162             while (*b==' '||*b=='\t'||*b=='\r'||*b=='\n'||*b==',') ++b;
163             if (*b == '\0') break;
164             e = b;
165             while (*e!=' '&&*e!='\t'&&*e!='\r'&&*e!='\n'&&*e!=','&&*e!='\0')
166                 ++e;
167             if (!buffer_string_is_empty(tb))
168                 buffer_append_string_len(tb, CONST_STR_LEN(","));
169             for (j = 0; j < sizeof(schemes)/sizeof(char *); ++j) {
170                 if (buffer_eq_icase_ssn(b, schemes[j], strlen(schemes[j]))) {
171                     break;
172                 }
173             }
174             if (j == sizeof(schemes)/sizeof(char *))
175                 buffer_append_string_len(tb, CONST_STR_LEN("ldap://"));
176             buffer_append_string_len(tb, b, (size_t)(e - b));
177         }
178         buffer_copy_buffer(host, tb);
179     }
180 }
181 
182 __attribute_cold__
183 static void mod_authn_ldap_err(log_error_st *errh, const char *file, unsigned long line, const char *fn, int err);
184 
185 SETDEFAULTS_FUNC(mod_authn_ldap_set_defaults) {
186     static const config_plugin_keys_t cpk[] = {
187       { CONST_STR_LEN("auth.backend.ldap.hostname"),
188         T_CONFIG_STRING,
189         T_CONFIG_SCOPE_CONNECTION }
190      ,{ CONST_STR_LEN("auth.backend.ldap.base-dn"),
191         T_CONFIG_STRING,
192         T_CONFIG_SCOPE_CONNECTION }
193      ,{ CONST_STR_LEN("auth.backend.ldap.filter"),
194         T_CONFIG_STRING,
195         T_CONFIG_SCOPE_CONNECTION }
196      ,{ CONST_STR_LEN("auth.backend.ldap.ca-file"),
197         T_CONFIG_STRING,
198         T_CONFIG_SCOPE_CONNECTION }
199      ,{ CONST_STR_LEN("auth.backend.ldap.starttls"),
200         T_CONFIG_BOOL,
201         T_CONFIG_SCOPE_CONNECTION }
202      ,{ CONST_STR_LEN("auth.backend.ldap.bind-dn"),
203         T_CONFIG_STRING,
204         T_CONFIG_SCOPE_CONNECTION }
205      ,{ CONST_STR_LEN("auth.backend.ldap.bind-pw"),
206         T_CONFIG_STRING,
207         T_CONFIG_SCOPE_CONNECTION }
208      ,{ CONST_STR_LEN("auth.backend.ldap.allow-empty-pw"),
209         T_CONFIG_BOOL,
210         T_CONFIG_SCOPE_CONNECTION }
211      ,{ CONST_STR_LEN("auth.backend.ldap.groupmember"),
212         T_CONFIG_STRING,
213         T_CONFIG_SCOPE_CONNECTION }
214      ,{ CONST_STR_LEN("auth.backend.ldap.timeout"),
215         T_CONFIG_STRING,
216         T_CONFIG_SCOPE_CONNECTION }
217      ,{ NULL, 0,
218         T_CONFIG_UNSET,
219         T_CONFIG_SCOPE_UNSET }
220     };
221 
222     plugin_data * const p = p_d;
223     if (!config_plugin_values_init(srv, p, cpk, "mod_authn_ldap"))
224         return HANDLER_ERROR;
225 
226     /* process and validate config directives
227      * (init i to 0 if global context; to 1 to skip empty global context) */
228     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
229         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
230         plugin_config_ldap *ldc = NULL;
231         char *binddn = NULL, *bindpw = NULL, *cafile = NULL;
232         int starttls = 0;
233         long timeout = 2000000; /* set 2 sec default timeout (not infinite) */
234         for (; -1 != cpv->k_id; ++cpv) {
235             switch (cpv->k_id) {
236               case 0: /* auth.backend.ldap.hostname */
237                 if (!buffer_string_is_empty(cpv->v.b)) {
238                     buffer *b;
239                     *(const buffer **)&b = cpv->v.b;
240                     mod_authn_add_scheme(srv, b);
241                     ldc = calloc(1, sizeof(plugin_config_ldap));
242                     force_assert(ldc);
243                     ldc->errh = srv->errh;
244                     ldc->auth_ldap_hostname = b->ptr;
245                     cpv->v.v = ldc;
246                 }
247                 else {
248                     cpv->v.v = NULL;
249                 }
250                 cpv->vtype = T_CONFIG_LOCAL;
251                 break;
252               case 1: /* auth.backend.ldap.base-dn */
253                 cpv->vtype = T_CONFIG_LOCAL;
254                 cpv->v.v = !buffer_string_is_empty(cpv->v.b)
255                   ? cpv->v.b->ptr
256                   : NULL;
257                 break;
258               case 2: /* auth.backend.ldap.filter */
259                 if (!buffer_string_is_empty(cpv->v.b)) {
260                     buffer *b;
261                     *(const buffer **)&b = cpv->v.b;
262                     if (*b->ptr != ',') {
263                         /*(translate $ to ? for consistency w/ other modules)*/
264                         char *d = b->ptr;
265                         for (; NULL != (d = strchr(d, '$')); ++d) *d = '?';
266                         if (NULL == strchr(b->ptr, '?')) {
267                             log_error(srv->errh, __FILE__, __LINE__,
268                               "ldap: %s is missing a replace-operator '?'",
269                               cpk[cpv->k_id].k);
270                             return HANDLER_ERROR;
271                         }
272                     }
273                     cpv->v.v = b;
274                 }
275                 else {
276                     cpv->v.v = NULL;
277                 }
278                 cpv->vtype = T_CONFIG_LOCAL;
279                 break;
280               case 3: /* auth.backend.ldap.ca-file */
281                 cafile = !buffer_string_is_empty(cpv->v.b)
282                   ? cpv->v.b->ptr
283                   : NULL;
284                 cpv->vtype = T_CONFIG_LOCAL;
285                 cpv->v.v = cafile;
286                 break;
287               case 4: /* auth.backend.ldap.starttls */
288                 starttls = (int)cpv->v.u;
289                 break;
290               case 5: /* auth.backend.ldap.bind-dn */
291                 binddn = !buffer_string_is_empty(cpv->v.b)
292                   ? cpv->v.b->ptr
293                   : NULL;
294                 cpv->vtype = T_CONFIG_LOCAL;
295                 cpv->v.v = binddn;
296                 break;
297               case 6: /* auth.backend.ldap.bind-pw */
298                 cpv->vtype = T_CONFIG_LOCAL;
299                 cpv->v.v = bindpw = cpv->v.b->ptr;
300                 break;
301               case 7: /* auth.backend.ldap.allow-empty-pw */
302               case 8: /* auth.backend.ldap.groupmember */
303                 break;
304               case 9: /* auth.backend.ldap.timeout */
305                 timeout = strtol(cpv->v.b->ptr, NULL, 10);
306                 break;
307               default:/* should not happen */
308                 break;
309             }
310         }
311 
312         if (ldc) {
313             ldc->auth_ldap_binddn = binddn;
314             ldc->auth_ldap_bindpw = bindpw;
315             ldc->auth_ldap_cafile = cafile;
316             ldc->auth_ldap_starttls = starttls;
317             ldc->auth_ldap_timeout.tv_sec  = timeout / 1000000;
318             ldc->auth_ldap_timeout.tv_usec = timeout % 1000000;
319         }
320     }
321 
322     static const struct { const char *ptr; uint32_t used; uint32_t size; }
323       memberUid = { "memberUid", sizeof("memberUid"), 0 };
324     *(const buffer **)&p->defaults.auth_ldap_groupmember =
325       (const buffer *)&memberUid;
326 
327     /* initialize p->defaults from global config context */
328     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
329         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
330         if (-1 != cpv->k_id)
331             mod_authn_ldap_merge_config(&p->defaults, cpv);
332     }
333 
334     if (p->defaults.auth_ldap_starttls && p->defaults.auth_ldap_cafile) {
335         const int ret = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE,
336                                         p->defaults.auth_ldap_cafile);
337         if (LDAP_OPT_SUCCESS != ret) {
338             mod_authn_ldap_err(srv->errh, __FILE__, __LINE__,
339               "ldap_set_option(LDAP_OPT_X_TLS_CACERTFILE)", ret);
340             return HANDLER_ERROR;
341         }
342         default_cafile = p->defaults.auth_ldap_cafile;
343     }
344 
345     return HANDLER_GO_ON;
346 }
347 
348 __attribute_cold__
349 static void mod_authn_ldap_err(log_error_st *errh, const char *file, unsigned long line, const char *fn, int err)
350 {
351     log_error(errh, file, line, "ldap: %s: %s", fn, ldap_err2string(err));
352 }
353 
354 __attribute_cold__
355 static void mod_authn_ldap_opt_err(log_error_st *errh, const char *file, unsigned long line, const char *fn, LDAP *ld)
356 {
357     int err;
358     ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &err);
359     mod_authn_ldap_err(errh, file, line, fn, err);
360 }
361 
362 static void mod_authn_append_ldap_dn_escape(buffer * const filter, const buffer * const raw) {
363     /* [RFC4514] 2.4 Converting an AttributeValue from ASN.1 to a String
364      *
365      * https://www.ldap.com/ldap-dns-and-rdns
366      * http://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx
367      */
368     const char * const b = raw->ptr;
369     const size_t rlen = buffer_string_length(raw);
370     if (0 == rlen) return;
371 
372     if (b[0] == ' ') { /* || b[0] == '#' handled below for MS Active Directory*/
373         /* escape leading ' ' */
374         buffer_append_string_len(filter, CONST_STR_LEN("\\"));
375     }
376 
377     for (size_t i = 0; i < rlen; ++i) {
378         size_t len = i;
379         int bs = 0;
380         do {
381             /* encode all UTF-8 chars with high bit set
382              * (instead of validating UTF-8 and escaping only invalid UTF-8) */
383             if (((unsigned char *)b)[len] > 0x7f)
384                 break;
385             switch (b[len]) {
386               default:
387                 continue;
388               case '"': case '+': case ',': case ';': case '\\':
389               case '<': case '>':
390               case '=': case '#': /* (for MS Active Directory) */
391                 bs = 1;
392                 break;
393               case '\0':
394                 break;
395             }
396             break;
397         } while (++len < rlen);
398         len -= i;
399 
400         if (len) {
401             buffer_append_string_len(filter, b+i, len);
402             if ((i += len) == rlen) break;
403         }
404 
405         if (bs) {
406             buffer_append_string_len(filter, CONST_STR_LEN("\\"));
407             buffer_append_string_len(filter, b+i, 1);
408         }
409         else {
410             /* escape NUL ('\0') (and all UTF-8 chars with high bit set) */
411             char *f;
412             f = buffer_extend(filter, 3);
413             f[0] = '\\';
414             f[1] = "0123456789abcdef"[(((unsigned char *)b)[i] >> 4) & 0xf];
415             f[2] = "0123456789abcdef"[(((unsigned char *)b)[i]     ) & 0xf];
416         }
417     }
418 
419     if (rlen > 1 && b[rlen-1] == ' ') {
420         /* escape trailing ' ' */
421         filter->ptr[buffer_string_length(filter)-1] = '\\';
422         buffer_append_string_len(filter, CONST_STR_LEN(" "));
423     }
424 }
425 
426 static void mod_authn_append_ldap_filter_escape(buffer * const filter, const buffer * const raw) {
427     /* [RFC4515] 3. String Search Filter Definition
428      *
429      * [...]
430      *
431      * The <valueencoding> rule ensures that the entire filter string is a
432      * valid UTF-8 string and provides that the octets that represent the
433      * ASCII characters "*" (ASCII 0x2a), "(" (ASCII 0x28), ")" (ASCII
434      * 0x29), "\" (ASCII 0x5c), and NUL (ASCII 0x00) are represented as a
435      * backslash "\" (ASCII 0x5c) followed by the two hexadecimal digits
436      * representing the value of the encoded octet.
437      *
438      * [...]
439      *
440      * As indicated by the <valueencoding> rule, implementations MUST escape
441      * all octets greater than 0x7F that are not part of a valid UTF-8
442      * encoding sequence when they generate a string representation of a
443      * search filter.  Implementations SHOULD accept as input strings that
444      * are not valid UTF-8 strings.  This is necessary because RFC 2254 did
445      * not clearly define the term "string representation" (and in
446      * particular did not mention that the string representation of an LDAP
447      * search filter is a string of UTF-8-encoded Unicode characters).
448      *
449      *
450      * https://www.ldap.com/ldap-filters
451      * Although not required, you may escape any other characters that you want
452      * in the assertion value (or substring component) of a filter. This may be
453      * accomplished by prefixing the hexadecimal representation of each byte of
454      * the UTF-8 encoding of the character to escape with a backslash character.
455      */
456     const char * const b = raw->ptr;
457     const size_t rlen = buffer_string_length(raw);
458     for (size_t i = 0; i < rlen; ++i) {
459         size_t len = i;
460         char *f;
461         do {
462             /* encode all UTF-8 chars with high bit set
463              * (instead of validating UTF-8 and escaping only invalid UTF-8) */
464             if (((unsigned char *)b)[len] > 0x7f)
465                 break;
466             switch (b[len]) {
467               default:
468                 continue;
469               case '\0': case '(': case ')': case '*': case '\\':
470                 break;
471             }
472             break;
473         } while (++len < rlen);
474         len -= i;
475 
476         if (len) {
477             buffer_append_string_len(filter, b+i, len);
478             if ((i += len) == rlen) break;
479         }
480 
481         /* escape * ( ) \ NUL ('\0') (and all UTF-8 chars with high bit set) */
482         f = buffer_extend(filter, 3);
483         f[0] = '\\';
484         f[1] = "0123456789abcdef"[(((unsigned char *)b)[i] >> 4) & 0xf];
485         f[2] = "0123456789abcdef"[(((unsigned char *)b)[i]     ) & 0xf];
486     }
487 }
488 
489 static LDAP * mod_authn_ldap_host_init(log_error_st *errh, plugin_config_ldap *s) {
490     LDAP *ld;
491     int ret;
492 
493     if (NULL == s->auth_ldap_hostname) return NULL;
494 
495     if (LDAP_SUCCESS != ldap_initialize(&ld, s->auth_ldap_hostname)) {
496         log_perror(errh, __FILE__, __LINE__, "ldap: ldap_initialize()");
497         return NULL;
498     }
499 
500     ret = LDAP_VERSION3;
501     ret = ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &ret);
502     if (LDAP_OPT_SUCCESS != ret) {
503         mod_authn_ldap_err(errh, __FILE__, __LINE__, "ldap_set_option()", ret);
504         ldap_destroy(ld);
505         return NULL;
506     }
507 
508     /* restart ldap functions if interrupted by a signal, e.g. SIGCHLD */
509     ldap_set_option(ld, LDAP_OPT_RESTART, LDAP_OPT_ON);
510 
511   #ifdef LDAP_OPT_NETWORK_TIMEOUT /* OpenLDAP-specific */
512     ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &s->auth_ldap_timeout);
513   #endif
514 
515   #ifdef LDAP_OPT_TIMEOUT /* OpenLDAP-specific; OpenLDAP 2.4+ */
516     ldap_set_option(ld, LDAP_OPT_TIMEOUT, &s->auth_ldap_timeout);
517   #endif
518 
519     if (s->auth_ldap_starttls) {
520         /* if no CA file is given, it is ok, as we will use encryption
521          * if the server requires a CAfile it will tell us */
522         if (s->auth_ldap_cafile
523             && (!default_cafile
524                 || 0 != strcmp(s->auth_ldap_cafile, default_cafile))) {
525             ret = ldap_set_option(ld, LDAP_OPT_X_TLS_CACERTFILE,
526                                   s->auth_ldap_cafile);
527             if (LDAP_OPT_SUCCESS != ret) {
528                 mod_authn_ldap_err(errh, __FILE__, __LINE__,
529                                    "ldap_set_option(LDAP_OPT_X_TLS_CACERTFILE)",
530                                    ret);
531                 ldap_destroy(ld);
532                 return NULL;
533             }
534         }
535 
536         ret = ldap_start_tls_s(ld, NULL,  NULL);
537         if (LDAP_OPT_SUCCESS != ret) {
538             mod_authn_ldap_err(errh,__FILE__,__LINE__,"ldap_start_tls_s()",ret);
539             ldap_destroy(ld);
540             return NULL;
541         }
542     }
543 
544     return ld;
545 }
546 
547 static int mod_authn_ldap_bind(log_error_st *errh, LDAP *ld, const char *dn, const char *pw) {
548     struct berval creds;
549     int ret;
550 
551     if (NULL != pw) {
552         *((const char **)&creds.bv_val) = pw; /*(cast away const)*/
553         creds.bv_len = strlen(pw);
554     } else {
555         creds.bv_val = NULL;
556         creds.bv_len = 0;
557     }
558 
559     /* RFE: add functionality: LDAP_SASL_EXTERNAL (or GSS-SPNEGO, etc.) */
560 
561     ret = ldap_sasl_bind_s(ld,dn,LDAP_SASL_SIMPLE,&creds,NULL,NULL,NULL);
562     if (ret != LDAP_SUCCESS) {
563         mod_authn_ldap_err(errh, __FILE__, __LINE__, "ldap_sasl_bind_s()", ret);
564     }
565 
566     return ret;
567 }
568 
569 static int mod_authn_ldap_rebind_proc (LDAP *ld, LDAP_CONST char *url, ber_tag_t ldap_request, ber_int_t msgid, void *params) {
570     const plugin_config_ldap *s = (const plugin_config_ldap *)params;
571     UNUSED(url);
572     UNUSED(ldap_request);
573     UNUSED(msgid);
574     return s->auth_ldap_binddn
575       ? mod_authn_ldap_bind(s->errh, ld,
576                             s->auth_ldap_binddn,
577                             s->auth_ldap_bindpw)
578       : mod_authn_ldap_bind(s->errh, ld, NULL, NULL);
579 }
580 
581 static LDAPMessage * mod_authn_ldap_search(log_error_st *errh, plugin_config_ldap *s, const char *base, const char *filter) {
582     LDAPMessage *lm = NULL;
583     char *attrs[] = { LDAP_NO_ATTRS, NULL };
584     int ret;
585 
586     /*
587      * 1. connect anonymously (if not already connected)
588      *    (ldap connection is kept open unless connection-level error occurs)
589      * 2. issue search using filter
590      */
591 
592     if (s->ldap != NULL) {
593         ret = ldap_search_ext_s(s->ldap, base, LDAP_SCOPE_SUBTREE, filter,
594                                 attrs, 0, NULL, NULL, NULL, 0, &lm);
595         if (LDAP_SUCCESS == ret) {
596             return lm;
597         } else if (LDAP_SERVER_DOWN != ret) {
598             /* try again (or initial request);
599              * ldap lib sometimes fails for the first call but reconnects */
600             ret = ldap_search_ext_s(s->ldap, base, LDAP_SCOPE_SUBTREE, filter,
601                                     attrs, 0, NULL, NULL, NULL, 0, &lm);
602             if (LDAP_SUCCESS == ret) {
603                 return lm;
604             }
605         }
606 
607         ldap_unbind_ext_s(s->ldap, NULL, NULL);
608     }
609 
610     s->ldap = mod_authn_ldap_host_init(errh, s);
611     if (NULL == s->ldap) {
612         return NULL;
613     }
614 
615     ldap_set_rebind_proc(s->ldap, mod_authn_ldap_rebind_proc, s);
616     ret = mod_authn_ldap_rebind_proc(s->ldap, NULL, 0, 0, s);
617     if (LDAP_SUCCESS != ret) {
618         ldap_destroy(s->ldap);
619         s->ldap = NULL;
620         return NULL;
621     }
622 
623     ret = ldap_search_ext_s(s->ldap, base, LDAP_SCOPE_SUBTREE, filter,
624                             attrs, 0, NULL, NULL, NULL, 0, &lm);
625     if (LDAP_SUCCESS != ret) {
626         log_error(errh, __FILE__, __LINE__,
627           "ldap: %s; filter: %s", ldap_err2string(ret), filter);
628         ldap_unbind_ext_s(s->ldap, NULL, NULL);
629         s->ldap = NULL;
630         return NULL;
631     }
632 
633     return lm;
634 }
635 
636 static char * mod_authn_ldap_get_dn(log_error_st *errh, plugin_config_ldap *s, const char *base, const char *filter) {
637     LDAP *ld;
638     LDAPMessage *lm, *first;
639     char *dn;
640     int count;
641 
642     lm = mod_authn_ldap_search(errh, s, base, filter);
643     if (NULL == lm) {
644         return NULL;
645     }
646 
647     ld = s->ldap; /*(must be after mod_authn_ldap_search(); might reconnect)*/
648 
649     count = ldap_count_entries(ld, lm);
650     if (0 == count) { /*(no entries found)*/
651         ldap_msgfree(lm);
652         return NULL;
653     } else if (count > 1) {
654         log_error(errh, __FILE__, __LINE__,
655           "ldap: more than one record returned.  "
656           "you might have to refine the filter: %s", filter);
657     }
658 
659     if (NULL == (first = ldap_first_entry(ld, lm))) {
660         mod_authn_ldap_opt_err(errh,__FILE__,__LINE__,"ldap_first_entry()",ld);
661         ldap_msgfree(lm);
662         return NULL;
663     }
664 
665     if (NULL == (dn = ldap_get_dn(ld, first))) {
666         mod_authn_ldap_opt_err(errh,__FILE__,__LINE__,"ldap_get_dn()",ld);
667         ldap_msgfree(lm);
668         return NULL;
669     }
670 
671     ldap_msgfree(lm);
672     return dn;
673 }
674 
675 static handler_t mod_authn_ldap_memberOf(log_error_st *errh, plugin_config *s, const http_auth_require_t *require, const buffer *username, const char *userdn) {
676     const array *groups = &require->group;
677     buffer *filter = buffer_init();
678     handler_t rc = HANDLER_ERROR;
679 
680     buffer_copy_string_len(filter, CONST_STR_LEN("("));
681     buffer_append_string_buffer(filter, s->auth_ldap_groupmember);
682     buffer_append_string_len(filter, CONST_STR_LEN("="));
683     if (buffer_is_equal_string(s->auth_ldap_groupmember,
684                                CONST_STR_LEN("member"))) {
685         buffer_append_string(filter, userdn);
686     } else { /*(assume "memberUid"; consider validating in SETDEFAULTS_FUNC)*/
687         mod_authn_append_ldap_filter_escape(filter, username);
688     }
689     buffer_append_string_len(filter, CONST_STR_LEN(")"));
690 
691     plugin_config_ldap * const ldc = s->ldc;
692     for (size_t i = 0; i < groups->used; ++i) {
693         const char *base = groups->data[i]->key.ptr;
694         LDAPMessage *lm = mod_authn_ldap_search(errh, ldc, base, filter->ptr);
695         if (NULL != lm) {
696             int count = ldap_count_entries(ldc->ldap, lm);
697             ldap_msgfree(lm);
698             if (count > 0) {
699                 rc = HANDLER_GO_ON;
700                 break;
701             }
702         }
703     }
704 
705     buffer_free(filter);
706     return rc;
707 }
708 
709 static handler_t mod_authn_ldap_basic(request_st * const r, void *p_d, const http_auth_require_t * const require, const buffer * const username, const char * const pw) {
710     plugin_data *p = (plugin_data *)p_d;
711     LDAP *ld;
712     char *dn;
713 
714     mod_authn_ldap_patch_config(r, p);
715 
716     if (pw[0] == '\0' && !p->conf.auth_ldap_allow_empty_pw)
717         return HANDLER_ERROR;
718 
719     const buffer * const template = p->conf.auth_ldap_filter;
720     if (NULL == template)
721         return HANDLER_ERROR;
722 
723     log_error_st * const errh = r->conf.errh;
724 
725     /* build filter to get DN for uid = username */
726     buffer * const ldap_filter = &p->ldap_filter;
727     buffer_clear(ldap_filter);
728     if (*template->ptr == ',') {
729         /* special-case filter template beginning with ',' to be explicit DN */
730         buffer_append_string_len(ldap_filter, CONST_STR_LEN("uid="));
731         mod_authn_append_ldap_dn_escape(ldap_filter, username);
732         buffer_append_string_buffer(ldap_filter, template);
733         dn = ldap_filter->ptr;
734     }
735     else {
736         for (const char *b = template->ptr, *d; *b; b = d+1) {
737             if (NULL != (d = strchr(b, '?'))) {
738                 buffer_append_string_len(ldap_filter, b, (size_t)(d - b));
739                 mod_authn_append_ldap_filter_escape(ldap_filter, username);
740             }
741             else {
742                 d = template->ptr + buffer_string_length(template);
743                 buffer_append_string_len(ldap_filter, b, (size_t)(d - b));
744                 break;
745             }
746         }
747 
748         /* ldap_search for DN (synchronous; blocking) */
749         dn = mod_authn_ldap_get_dn(errh, p->conf.ldc,
750                                    p->conf.auth_ldap_basedn, ldap_filter->ptr);
751         if (NULL == dn) return HANDLER_ERROR;
752     }
753 
754     /*(Check ldc here rather than further up to preserve historical behavior
755      * where p->conf.ldc above (was p->anon_conf above) is set of directives in
756      * same context as auth_ldap_hostname.  Preference: admin intentions are
757      * clearer if directives are always together in a set in same context)*/
758 
759     plugin_config_ldap * const ldc_base = p->conf.ldc;
760     plugin_config_ldap ldc_custom;
761 
762     if ( p->conf.ldc->auth_ldap_starttls != p->conf.auth_ldap_starttls
763         || p->conf.ldc->auth_ldap_binddn != p->conf.auth_ldap_binddn
764         || p->conf.ldc->auth_ldap_bindpw != p->conf.auth_ldap_bindpw
765         || p->conf.ldc->auth_ldap_cafile != p->conf.auth_ldap_cafile ) {
766         ldc_custom.ldap = NULL;
767         ldc_custom.errh = errh;
768         ldc_custom.auth_ldap_hostname = ldc_base->auth_ldap_hostname;
769         ldc_custom.auth_ldap_starttls = p->conf.auth_ldap_starttls;
770         ldc_custom.auth_ldap_binddn = p->conf.auth_ldap_binddn;
771         ldc_custom.auth_ldap_bindpw = p->conf.auth_ldap_bindpw;
772         ldc_custom.auth_ldap_cafile = p->conf.auth_ldap_cafile;
773         ldc_custom.auth_ldap_timeout= ldc_base->auth_ldap_timeout;
774         p->conf.ldc = &ldc_custom;
775     }
776 
777     handler_t rc = HANDLER_ERROR;
778     do {
779         /* auth against LDAP server (synchronous; blocking) */
780 
781         ld = mod_authn_ldap_host_init(errh, p->conf.ldc);
782         if (NULL == ld)
783             break;
784 
785         /* Disable referral tracking; target user should be in provided scope */
786         int ret = ldap_set_option(ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
787         if (LDAP_OPT_SUCCESS != ret) {
788             mod_authn_ldap_err(errh,__FILE__,__LINE__,"ldap_set_option()",ret);
789             break;
790         }
791 
792         if (LDAP_SUCCESS != mod_authn_ldap_bind(errh, ld, dn, pw))
793             break;
794 
795         ldap_unbind_ext_s(ld, NULL, NULL); /* disconnect */
796         ld = NULL;
797 
798         if (http_auth_match_rules(require, username->ptr, NULL, NULL)) {
799             rc = HANDLER_GO_ON; /* access granted */
800         }
801         else if (require->group.used) {
802             /*(must not re-use ldap_filter, since it might be used for dn)*/
803             rc = mod_authn_ldap_memberOf(errh,&p->conf,require,username,dn);
804         }
805     } while (0);
806 
807     if (NULL != ld) ldap_destroy(ld);
808     if (ldc_base != p->conf.ldc && NULL != p->conf.ldc->ldap)
809         ldap_unbind_ext_s(p->conf.ldc->ldap, NULL, NULL);
810     if (dn != ldap_filter->ptr) ldap_memfree(dn);
811     return rc;
812 }
813 
814 int mod_authn_ldap_plugin_init(plugin *p);
815 int mod_authn_ldap_plugin_init(plugin *p) {
816     p->version     = LIGHTTPD_VERSION_ID;
817     p->name        = "authn_ldap";
818     p->init        = mod_authn_ldap_init;
819     p->set_defaults = mod_authn_ldap_set_defaults;
820     p->cleanup     = mod_authn_ldap_free;
821 
822     return 0;
823 }
824