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