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 const char *default_cafile; 49 50 static void mod_vhostdb_dbconf_free (void *vdata) 51 { 52 vhostdb_config *dbconf = (vhostdb_config *)vdata; 53 if (!dbconf) return; 54 if (NULL != dbconf->ldap) ldap_unbind_ext_s(dbconf->ldap, NULL, NULL); 55 free(dbconf); 56 } 57 58 /*(copied from mod_authn_ldap.c)*/ 59 static void mod_vhostdb_dbconf_add_scheme (server *srv, buffer *host) 60 { 61 if (!buffer_string_is_empty(host)) { 62 /* reformat hostname(s) as LDAP URIs (scheme://host:port) */ 63 static const char *schemes[] = { 64 "ldap://", "ldaps://", "ldapi://", "cldap://" 65 }; 66 char *b, *e = host->ptr; 67 buffer * const tb = srv->tmp_buf; 68 buffer_clear(tb); 69 while (*(b = e)) { 70 unsigned int j; 71 while (*b==' '||*b=='\t'||*b=='\r'||*b=='\n'||*b==',') ++b; 72 if (*b == '\0') break; 73 e = b; 74 while (*e!=' '&&*e!='\t'&&*e!='\r'&&*e!='\n'&&*e!=','&&*e!='\0') 75 ++e; 76 if (!buffer_string_is_empty(tb)) 77 buffer_append_string_len(tb, CONST_STR_LEN(",")); 78 for (j = 0; j < sizeof(schemes)/sizeof(char *); ++j) { 79 if (buffer_eq_icase_ssn(b, schemes[j], strlen(schemes[j]))) { 80 break; 81 } 82 } 83 if (j == sizeof(schemes)/sizeof(char *)) 84 buffer_append_string_len(tb, CONST_STR_LEN("ldap://")); 85 buffer_append_string_len(tb, b, (size_t)(e - b)); 86 } 87 buffer_copy_buffer(host, tb); 88 } 89 } 90 91 static int mod_vhostdb_dbconf_setup (server *srv, const array *opts, void **vdata) 92 { 93 const buffer *filter = NULL; 94 const char *attr = "documentRoot"; 95 const char *basedn=NULL,*binddn=NULL,*bindpw=NULL,*host=NULL,*cafile=NULL; 96 unsigned short starttls = 0; 97 long timeout = 2000000; /* set 2 sec default timeout (instead of infinite) */ 98 99 for (size_t i = 0; i < opts->used; ++i) { 100 data_string *ds = (data_string *)opts->data[i]; 101 if (ds->type == TYPE_STRING) { 102 if (buffer_is_equal_caseless_string(&ds->key, CONST_STR_LEN("filter"))) { 103 filter = &ds->value; 104 } else if (buffer_is_equal_caseless_string(&ds->key, CONST_STR_LEN("attr"))) { 105 if (!buffer_string_is_empty(&ds->value)) attr = ds->value.ptr; 106 } else if (buffer_is_equal_caseless_string(&ds->key, CONST_STR_LEN("host"))) { 107 mod_vhostdb_dbconf_add_scheme(srv, &ds->value); 108 host = ds->value.ptr; 109 } else if (buffer_is_equal_caseless_string(&ds->key, CONST_STR_LEN("base-dn"))) { 110 if (!buffer_string_is_empty(&ds->value)) basedn = ds->value.ptr; 111 } else if (buffer_is_equal_caseless_string(&ds->key, CONST_STR_LEN("bind-dn"))) { 112 if (!buffer_string_is_empty(&ds->value)) binddn = ds->value.ptr; 113 } else if (buffer_is_equal_caseless_string(&ds->key, CONST_STR_LEN("bind-pw"))) { 114 bindpw = ds->value.ptr; 115 } else if (buffer_is_equal_caseless_string(&ds->key, CONST_STR_LEN("ca-file"))) { 116 if (!buffer_string_is_empty(&ds->value)) cafile = ds->value.ptr; 117 } else if (buffer_is_equal_caseless_string(&ds->key, CONST_STR_LEN("starttls"))) { 118 starttls = config_plugin_value_tobool((data_unset *)ds, 1); 119 } else if (buffer_is_equal_caseless_string(&ds->key, CONST_STR_LEN("timeout"))) { 120 timeout = strtol(ds->value.ptr, NULL, 10); 121 } 122 } 123 } 124 125 /* required: 126 * - host 127 * - filter (LDAP query) 128 * - base-dn 129 * 130 * optional: 131 * - attr (LDAP attribute with docroot; default "documentRoot") 132 * - bind-dn 133 * - bind-pw 134 * - ca-file 135 * - starttls 136 */ 137 138 if (!buffer_string_is_empty(filter) && NULL != host && NULL != basedn) { 139 vhostdb_config *dbconf; 140 141 if (NULL == strchr(filter->ptr, '?')) { 142 log_error(srv->errh, __FILE__, __LINE__, 143 "ldap: filter is missing a replace-operator '?'"); 144 return -1; 145 } 146 147 /* openldap sets FD_CLOEXEC on database socket descriptors 148 * (still race between creation of socket and fcntl FD_CLOEXEC) 149 * (YMMV with other LDAP client libraries) */ 150 151 dbconf = (vhostdb_config *)calloc(1, sizeof(*dbconf)); 152 dbconf->ldap = NULL; 153 dbconf->filter = filter; 154 dbconf->attr = attr; 155 dbconf->host = host; 156 dbconf->basedn = basedn; 157 dbconf->binddn = binddn; 158 dbconf->bindpw = bindpw; 159 dbconf->cafile = cafile; 160 dbconf->starttls = starttls; 161 dbconf->timeout.tv_sec = timeout / 1000000; 162 dbconf->timeout.tv_usec = timeout % 1000000; 163 *vdata = dbconf; 164 } 165 166 return 0; 167 } 168 169 /* 170 * Note: a large portion of the LDAP code is copied verbatim from mod_authn_ldap 171 * with only changes being use of vhostdb_config instead of plugin_config struct 172 * and (const char *) strings in vhostdb_config instead of (buffer *). 173 */ 174 175 __attribute_cold__ 176 static void mod_authn_ldap_err(log_error_st *errh, const char *file, unsigned long line, const char *fn, int err) 177 { 178 log_error(errh, file, line, "ldap: %s: %s", fn, ldap_err2string(err)); 179 } 180 181 __attribute_cold__ 182 static void mod_authn_ldap_opt_err(log_error_st *errh, const char *file, unsigned long line, const char *fn, LDAP *ld) 183 { 184 int err; 185 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &err); 186 mod_authn_ldap_err(errh, file, line, fn, err); 187 } 188 189 static void mod_authn_append_ldap_filter_escape(buffer * const filter, const buffer * const raw) { 190 /* [RFC4515] 3. String Search Filter Definition 191 * 192 * [...] 193 * 194 * The <valueencoding> rule ensures that the entire filter string is a 195 * valid UTF-8 string and provides that the octets that represent the 196 * ASCII characters "*" (ASCII 0x2a), "(" (ASCII 0x28), ")" (ASCII 197 * 0x29), "\" (ASCII 0x5c), and NUL (ASCII 0x00) are represented as a 198 * backslash "\" (ASCII 0x5c) followed by the two hexadecimal digits 199 * representing the value of the encoded octet. 200 * 201 * [...] 202 * 203 * As indicated by the <valueencoding> rule, implementations MUST escape 204 * all octets greater than 0x7F that are not part of a valid UTF-8 205 * encoding sequence when they generate a string representation of a 206 * search filter. Implementations SHOULD accept as input strings that 207 * are not valid UTF-8 strings. This is necessary because RFC 2254 did 208 * not clearly define the term "string representation" (and in 209 * particular did not mention that the string representation of an LDAP 210 * search filter is a string of UTF-8-encoded Unicode characters). 211 * 212 * 213 * https://www.ldap.com/ldap-filters 214 * Although not required, you may escape any other characters that you want 215 * in the assertion value (or substring component) of a filter. This may be 216 * accomplished by prefixing the hexadecimal representation of each byte of 217 * the UTF-8 encoding of the character to escape with a backslash character. 218 */ 219 const char * const b = raw->ptr; 220 const size_t rlen = buffer_string_length(raw); 221 for (size_t i = 0; i < rlen; ++i) { 222 size_t len = i; 223 char *f; 224 do { 225 /* encode all UTF-8 chars with high bit set 226 * (instead of validating UTF-8 and escaping only invalid UTF-8) */ 227 if (((unsigned char *)b)[len] > 0x7f) 228 break; 229 switch (b[len]) { 230 default: 231 continue; 232 case '\0': case '(': case ')': case '*': case '\\': 233 break; 234 } 235 break; 236 } while (++len < rlen); 237 len -= i; 238 239 if (len) { 240 buffer_append_string_len(filter, b+i, len); 241 if ((i += len) == rlen) break; 242 } 243 244 /* escape * ( ) \ NUL ('\0') (and all UTF-8 chars with high bit set) */ 245 f = buffer_extend(filter, 3); 246 f[0] = '\\'; 247 f[1] = "0123456789abcdef"[(((unsigned char *)b)[i] >> 4) & 0xf]; 248 f[2] = "0123456789abcdef"[(((unsigned char *)b)[i] ) & 0xf]; 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 && (!default_cafile || 0 != strcmp(s->cafile, default_cafile))) { 286 ret = ldap_set_option(ld, 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 default_cafile = NULL; 500 } 501 502 static void mod_vhostdb_merge_config_cpv(plugin_config * const pconf, const config_plugin_value_t * const cpv) { 503 switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */ 504 case 0: /* vhostdb.<db> */ 505 if (cpv->vtype == T_CONFIG_LOCAL) 506 pconf->vdata = cpv->v.v; 507 break; 508 default:/* should not happen */ 509 return; 510 } 511 } 512 513 static void mod_vhostdb_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv) { 514 do { 515 mod_vhostdb_merge_config_cpv(pconf, cpv); 516 } while ((++cpv)->k_id != -1); 517 } 518 519 static void mod_vhostdb_patch_config(request_st * const r, plugin_data * const p) { 520 p->conf = p->defaults; /* copy small struct instead of memcpy() */ 521 /*memcpy(&p->conf, &p->defaults, sizeof(plugin_config));*/ 522 for (int i = 1, used = p->nconfig; i < used; ++i) { 523 if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id)) 524 mod_vhostdb_merge_config(&p->conf,p->cvlist + p->cvlist[i].v.u2[0]); 525 } 526 } 527 528 SETDEFAULTS_FUNC(mod_vhostdb_set_defaults) { 529 static const config_plugin_keys_t cpk[] = { 530 { CONST_STR_LEN("vhostdb.ldap"), 531 T_CONFIG_ARRAY_KVSTRING, 532 T_CONFIG_SCOPE_CONNECTION } 533 ,{ NULL, 0, 534 T_CONFIG_UNSET, 535 T_CONFIG_SCOPE_UNSET } 536 }; 537 538 plugin_data * const p = p_d; 539 if (!config_plugin_values_init(srv, p, cpk, "mod_vhostdb_ldap")) 540 return HANDLER_ERROR; 541 542 /* process and validate config directives 543 * (init i to 0 if global context; to 1 to skip empty global context) */ 544 for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) { 545 config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0]; 546 for (; -1 != cpv->k_id; ++cpv) { 547 switch (cpv->k_id) { 548 case 0: /* vhostdb.<db> */ 549 if (cpv->v.a->used) { 550 if (0 != mod_vhostdb_dbconf_setup(srv, cpv->v.a, &cpv->v.v)) 551 return HANDLER_ERROR; 552 if (NULL != cpv->v.v) 553 cpv->vtype = T_CONFIG_LOCAL; 554 } 555 break; 556 default:/* should not happen */ 557 break; 558 } 559 } 560 } 561 562 /* initialize p->defaults from global config context */ 563 if (p->nconfig > 0 && p->cvlist->v.u2[1]) { 564 const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0]; 565 if (-1 != cpv->k_id) 566 mod_vhostdb_merge_config(&p->defaults, cpv); 567 } 568 569 vhostdb_config * const dbconf = (vhostdb_config *)p->defaults.vdata; 570 if (dbconf && dbconf->starttls && dbconf->cafile) { 571 const int ret = 572 ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, dbconf->cafile); 573 if (LDAP_OPT_SUCCESS != ret) { 574 mod_authn_ldap_err(srv->errh, __FILE__, __LINE__, 575 "ldap_set_option(LDAP_OPT_X_TLS_CACERTFILE)", ret); 576 return HANDLER_ERROR; 577 } 578 default_cafile = dbconf->cafile; 579 } 580 581 return HANDLER_GO_ON; 582 } 583 584 585 int mod_vhostdb_ldap_plugin_init (plugin *p); 586 int mod_vhostdb_ldap_plugin_init (plugin *p) 587 { 588 p->version = LIGHTTPD_VERSION_ID; 589 p->name = "vhostdb_ldap"; 590 591 p->init = mod_vhostdb_init; 592 p->cleanup = mod_vhostdb_cleanup; 593 p->set_defaults = mod_vhostdb_set_defaults; 594 595 return 0; 596 } 597