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