1 #include "first.h" 2 3 #include "network.h" 4 #include "fdevent.h" 5 #include "log.h" 6 #include "connections.h" 7 #include "plugin.h" 8 #include "joblist.h" 9 #include "configfile.h" 10 11 #include "network_backends.h" 12 #include "sys-mmap.h" 13 #include "sys-socket.h" 14 15 #include <sys/types.h> 16 #include <sys/stat.h> 17 #include <sys/time.h> 18 19 #include <errno.h> 20 #include <fcntl.h> 21 #include <unistd.h> 22 #include <string.h> 23 #include <stdlib.h> 24 #include <assert.h> 25 26 #ifdef USE_OPENSSL 27 # include <openssl/ssl.h> 28 # include <openssl/err.h> 29 # include <openssl/rand.h> 30 # ifndef OPENSSL_NO_DH 31 # include <openssl/dh.h> 32 # endif 33 # include <openssl/bn.h> 34 35 # if OPENSSL_VERSION_NUMBER >= 0x0090800fL 36 # ifndef OPENSSL_NO_ECDH 37 # include <openssl/ecdh.h> 38 # endif 39 # endif 40 #endif 41 42 #ifdef USE_OPENSSL 43 static void ssl_info_callback(const SSL *ssl, int where, int ret) { 44 UNUSED(ret); 45 46 if (0 != (where & SSL_CB_HANDSHAKE_START)) { 47 connection *con = SSL_get_app_data(ssl); 48 ++con->renegotiations; 49 } 50 } 51 #endif 52 53 static handler_t network_server_handle_fdevent(server *srv, void *context, int revents) { 54 server_socket *srv_socket = (server_socket *)context; 55 connection *con; 56 int loops = 0; 57 58 UNUSED(context); 59 60 if (0 == (revents & FDEVENT_IN)) { 61 log_error_write(srv, __FILE__, __LINE__, "sdd", 62 "strange event for server socket", 63 srv_socket->fd, 64 revents); 65 return HANDLER_ERROR; 66 } 67 68 /* accept()s at most 100 connections directly 69 * 70 * we jump out after 100 to give the waiting connections a chance */ 71 for (loops = 0; loops < 100 && NULL != (con = connection_accept(srv, srv_socket)); loops++) { 72 connection_state_machine(srv, con); 73 } 74 return HANDLER_GO_ON; 75 } 76 77 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT 78 static int network_ssl_servername_callback(SSL *ssl, int *al, server *srv) { 79 const char *servername; 80 connection *con = (connection *) SSL_get_app_data(ssl); 81 UNUSED(al); 82 83 buffer_copy_string(con->uri.scheme, "https"); 84 85 if (NULL == (servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name))) { 86 #if 0 87 /* this "error" just means the client didn't support it */ 88 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:", 89 "failed to get TLS server name"); 90 #endif 91 return SSL_TLSEXT_ERR_NOACK; 92 } 93 buffer_copy_string(con->tlsext_server_name, servername); 94 buffer_to_lower(con->tlsext_server_name); 95 96 /* Sometimes this is still set, confusing COMP_HTTP_HOST */ 97 buffer_reset(con->uri.authority); 98 99 config_cond_cache_reset(srv, con); 100 config_setup_connection(srv, con); 101 102 con->conditional_is_valid[COMP_SERVER_SOCKET] = 1; 103 con->conditional_is_valid[COMP_HTTP_SCHEME] = 1; 104 con->conditional_is_valid[COMP_HTTP_HOST] = 1; 105 config_patch_connection(srv, con); 106 107 if (NULL == con->conf.ssl_pemfile_x509 || NULL == con->conf.ssl_pemfile_pkey) { 108 /* x509/pkey available <=> pemfile was set <=> pemfile got patched: so this should never happen, unless you nest $SERVER["socket"] */ 109 log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:", 110 "no certificate/private key for TLS server name", con->tlsext_server_name); 111 return SSL_TLSEXT_ERR_ALERT_FATAL; 112 } 113 114 /* first set certificate! setting private key checks whether certificate matches it */ 115 if (!SSL_use_certificate(ssl, con->conf.ssl_pemfile_x509)) { 116 log_error_write(srv, __FILE__, __LINE__, "ssb:s", "SSL:", 117 "failed to set certificate for TLS server name", con->tlsext_server_name, 118 ERR_error_string(ERR_get_error(), NULL)); 119 return SSL_TLSEXT_ERR_ALERT_FATAL; 120 } 121 122 if (!SSL_use_PrivateKey(ssl, con->conf.ssl_pemfile_pkey)) { 123 log_error_write(srv, __FILE__, __LINE__, "ssb:s", "SSL:", 124 "failed to set private key for TLS server name", con->tlsext_server_name, 125 ERR_error_string(ERR_get_error(), NULL)); 126 return SSL_TLSEXT_ERR_ALERT_FATAL; 127 } 128 129 if (con->conf.ssl_verifyclient) { 130 if (NULL == con->conf.ssl_ca_file_cert_names) { 131 log_error_write(srv, __FILE__, __LINE__, "ssb:s", "SSL:", 132 "can't verify client without ssl.ca-file for TLS server name", con->tlsext_server_name, 133 ERR_error_string(ERR_get_error(), NULL)); 134 return SSL_TLSEXT_ERR_ALERT_FATAL; 135 } 136 137 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(con->conf.ssl_ca_file_cert_names)); 138 /* forcing verification here is really not that useful - a client could just connect without SNI */ 139 SSL_set_verify( 140 ssl, 141 SSL_VERIFY_PEER | (con->conf.ssl_verifyclient_enforce ? SSL_VERIFY_FAIL_IF_NO_PEER_CERT : 0), 142 NULL 143 ); 144 SSL_set_verify_depth(ssl, con->conf.ssl_verifyclient_depth); 145 } else { 146 SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL); 147 } 148 149 return SSL_TLSEXT_ERR_OK; 150 } 151 #endif 152 153 static int network_server_init(server *srv, buffer *host_token, specific_config *s) { 154 int val; 155 socklen_t addr_len; 156 server_socket *srv_socket; 157 unsigned int port = 0; 158 const char *host; 159 buffer *b; 160 int err; 161 162 #ifdef __WIN32 163 WORD wVersionRequested; 164 WSADATA wsaData; 165 166 wVersionRequested = MAKEWORD( 2, 2 ); 167 168 err = WSAStartup( wVersionRequested, &wsaData ); 169 if ( err != 0 ) { 170 /* Tell the user that we could not find a usable */ 171 /* WinSock DLL. */ 172 return -1; 173 } 174 #endif 175 err = -1; 176 177 srv_socket = calloc(1, sizeof(*srv_socket)); 178 force_assert(NULL != srv_socket); 179 srv_socket->addr.plain.sa_family = AF_INET; /* default */ 180 srv_socket->fd = -1; 181 srv_socket->fde_ndx = -1; 182 183 srv_socket->srv_token = buffer_init(); 184 buffer_copy_buffer(srv_socket->srv_token, host_token); 185 186 b = buffer_init(); 187 buffer_copy_buffer(b, host_token); 188 189 host = b->ptr; 190 191 if (host[0] == '/') { 192 /* host is a unix-domain-socket */ 193 #ifdef HAVE_SYS_UN_H 194 srv_socket->addr.plain.sa_family = AF_UNIX; 195 #else 196 log_error_write(srv, __FILE__, __LINE__, "s", 197 "ERROR: Unix Domain sockets are not supported."); 198 goto error_free_socket; 199 #endif 200 } else { 201 /* ipv4:port 202 * [ipv6]:port 203 */ 204 size_t len = buffer_string_length(b); 205 char *sp = NULL; 206 if (0 == len) { 207 log_error_write(srv, __FILE__, __LINE__, "s", "value of $SERVER[\"socket\"] must not be empty"); 208 goto error_free_socket; 209 } 210 if ((b->ptr[0] == '[' && b->ptr[len-1] == ']') || NULL == (sp = strrchr(b->ptr, ':'))) { 211 /* use server.port if set in config, or else default from config_set_defaults() */ 212 port = srv->srvconf.port; 213 sp = b->ptr + len; /* point to '\0' at end of string so end of IPv6 address can be found below */ 214 } else { 215 /* found ip:port separator at *sp; port doesn't end in ']', so *sp hopefully doesn't split an IPv6 address */ 216 *sp = '\0'; 217 port = strtol(sp+1, NULL, 10); 218 } 219 220 /* check for [ and ] */ 221 if (b->ptr[0] == '[' && *(sp-1) == ']') { 222 *(sp-1) = '\0'; 223 host++; 224 225 s->use_ipv6 = 1; 226 } 227 228 if (port == 0 || port > 65535) { 229 log_error_write(srv, __FILE__, __LINE__, "sd", "port not set or out of range:", port); 230 231 goto error_free_socket; 232 } 233 } 234 235 if (*host == '\0') host = NULL; 236 237 #ifdef HAVE_IPV6 238 if (s->use_ipv6) { 239 srv_socket->addr.plain.sa_family = AF_INET6; 240 } 241 #endif 242 243 switch(srv_socket->addr.plain.sa_family) { 244 #ifdef HAVE_IPV6 245 case AF_INET6: 246 memset(&srv_socket->addr, 0, sizeof(struct sockaddr_in6)); 247 srv_socket->addr.ipv6.sin6_family = AF_INET6; 248 if (host == NULL) { 249 srv_socket->addr.ipv6.sin6_addr = in6addr_any; 250 log_error_write(srv, __FILE__, __LINE__, "s", "warning: please use server.use-ipv6 only for hostnames, not without server.bind / empty address; your config will break if the kernel default for IPV6_V6ONLY changes"); 251 } else { 252 struct addrinfo hints, *res; 253 int r; 254 255 memset(&hints, 0, sizeof(hints)); 256 257 hints.ai_family = AF_INET6; 258 hints.ai_socktype = SOCK_STREAM; 259 hints.ai_protocol = IPPROTO_TCP; 260 261 if (0 != (r = getaddrinfo(host, NULL, &hints, &res))) { 262 log_error_write(srv, __FILE__, __LINE__, 263 "sssss", "getaddrinfo failed: ", 264 gai_strerror(r), "'", host, "'"); 265 266 goto error_free_socket; 267 } 268 269 memcpy(&(srv_socket->addr), res->ai_addr, res->ai_addrlen); 270 271 freeaddrinfo(res); 272 } 273 srv_socket->addr.ipv6.sin6_port = htons(port); 274 addr_len = sizeof(struct sockaddr_in6); 275 break; 276 #endif 277 case AF_INET: 278 memset(&srv_socket->addr, 0, sizeof(struct sockaddr_in)); 279 srv_socket->addr.ipv4.sin_family = AF_INET; 280 if (host == NULL) { 281 srv_socket->addr.ipv4.sin_addr.s_addr = htonl(INADDR_ANY); 282 } else { 283 struct hostent *he; 284 if (NULL == (he = gethostbyname(host))) { 285 log_error_write(srv, __FILE__, __LINE__, 286 "sds", "gethostbyname failed: ", 287 h_errno, host); 288 goto error_free_socket; 289 } 290 291 if (he->h_addrtype != AF_INET) { 292 log_error_write(srv, __FILE__, __LINE__, "sd", "addr-type != AF_INET: ", he->h_addrtype); 293 goto error_free_socket; 294 } 295 296 if (he->h_length != sizeof(struct in_addr)) { 297 log_error_write(srv, __FILE__, __LINE__, "sd", "addr-length != sizeof(in_addr): ", he->h_length); 298 goto error_free_socket; 299 } 300 301 memcpy(&(srv_socket->addr.ipv4.sin_addr.s_addr), he->h_addr_list[0], he->h_length); 302 } 303 srv_socket->addr.ipv4.sin_port = htons(port); 304 addr_len = sizeof(struct sockaddr_in); 305 break; 306 #ifdef HAVE_SYS_UN_H 307 case AF_UNIX: 308 memset(&srv_socket->addr, 0, sizeof(struct sockaddr_un)); 309 srv_socket->addr.un.sun_family = AF_UNIX; 310 { 311 size_t hostlen = strlen(host) + 1; 312 if (hostlen > sizeof(srv_socket->addr.un.sun_path)) { 313 log_error_write(srv, __FILE__, __LINE__, "sS", "unix socket filename too long:", host); 314 goto error_free_socket; 315 } 316 memcpy(srv_socket->addr.un.sun_path, host, hostlen); 317 318 #if defined(SUN_LEN) 319 addr_len = SUN_LEN(&srv_socket->addr.un); 320 #else 321 /* stevens says: */ 322 addr_len = hostlen + sizeof(srv_socket->addr.un.sun_family); 323 #endif 324 } 325 326 break; 327 #endif 328 default: 329 goto error_free_socket; 330 } 331 332 if (srv->srvconf.preflight_check) { 333 err = 0; 334 goto error_free_socket; 335 } 336 337 if (srv->sockets_disabled) { /* lighttpd -1 (one-shot mode) */ 338 #ifdef USE_OPENSSL 339 if (s->ssl_enabled) srv_socket->ssl_ctx = s->ssl_ctx; 340 #endif 341 goto srv_sockets_append; 342 } 343 344 #ifdef HAVE_SYS_UN_H 345 if (AF_UNIX == srv_socket->addr.plain.sa_family) { 346 /* check if the socket exists and try to connect to it. */ 347 if (-1 == (srv_socket->fd = socket(srv_socket->addr.plain.sa_family, SOCK_STREAM, 0))) { 348 log_error_write(srv, __FILE__, __LINE__, "ss", "socket failed:", strerror(errno)); 349 goto error_free_socket; 350 } 351 if (0 == connect(srv_socket->fd, (struct sockaddr *) &(srv_socket->addr), addr_len)) { 352 log_error_write(srv, __FILE__, __LINE__, "ss", 353 "server socket is still in use:", 354 host); 355 356 357 goto error_free_socket; 358 } 359 360 /* connect failed */ 361 switch(errno) { 362 case ECONNREFUSED: 363 unlink(host); 364 break; 365 case ENOENT: 366 break; 367 default: 368 log_error_write(srv, __FILE__, __LINE__, "sds", 369 "testing socket failed:", 370 host, strerror(errno)); 371 372 goto error_free_socket; 373 } 374 } else 375 #endif 376 { 377 if (-1 == (srv_socket->fd = socket(srv_socket->addr.plain.sa_family, SOCK_STREAM, IPPROTO_TCP))) { 378 log_error_write(srv, __FILE__, __LINE__, "ss", "socket failed:", strerror(errno)); 379 goto error_free_socket; 380 } 381 382 #ifdef HAVE_IPV6 383 if (AF_INET6 == srv_socket->addr.plain.sa_family 384 && host != NULL) { 385 if (s->set_v6only) { 386 val = 1; 387 if (-1 == setsockopt(srv_socket->fd, IPPROTO_IPV6, IPV6_V6ONLY, &val, sizeof(val))) { 388 log_error_write(srv, __FILE__, __LINE__, "ss", "socketsockopt(IPV6_V6ONLY) failed:", strerror(errno)); 389 goto error_free_socket; 390 } 391 } else { 392 log_error_write(srv, __FILE__, __LINE__, "s", "warning: server.set-v6only will be removed soon, update your config to have different sockets for ipv4 and ipv6"); 393 } 394 } 395 #endif 396 } 397 398 /* set FD_CLOEXEC now, fdevent_fcntl_set is called later; needed for pipe-logger forks */ 399 fd_close_on_exec(srv_socket->fd); 400 401 /* */ 402 srv->cur_fds = srv_socket->fd; 403 404 val = 1; 405 if (setsockopt(srv_socket->fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0) { 406 log_error_write(srv, __FILE__, __LINE__, "ss", "socketsockopt(SO_REUSEADDR) failed:", strerror(errno)); 407 goto error_free_socket; 408 } 409 410 if (0 != bind(srv_socket->fd, (struct sockaddr *) &(srv_socket->addr), addr_len)) { 411 switch(srv_socket->addr.plain.sa_family) { 412 case AF_UNIX: 413 log_error_write(srv, __FILE__, __LINE__, "sds", 414 "can't bind to socket:", 415 host, strerror(errno)); 416 break; 417 default: 418 log_error_write(srv, __FILE__, __LINE__, "ssds", 419 "can't bind to port:", 420 host, port, strerror(errno)); 421 break; 422 } 423 goto error_free_socket; 424 } 425 426 if (-1 == listen(srv_socket->fd, s->listen_backlog)) { 427 log_error_write(srv, __FILE__, __LINE__, "ss", "listen failed: ", strerror(errno)); 428 goto error_free_socket; 429 } 430 431 if (s->ssl_enabled) { 432 #ifdef USE_OPENSSL 433 if (NULL == (srv_socket->ssl_ctx = s->ssl_ctx)) { 434 log_error_write(srv, __FILE__, __LINE__, "s", "ssl.pemfile has to be set"); 435 goto error_free_socket; 436 } 437 #else 438 439 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:", 440 "ssl requested but openssl support is not compiled in"); 441 442 goto error_free_socket; 443 #endif 444 #ifdef TCP_DEFER_ACCEPT 445 } else if (s->defer_accept) { 446 int v = s->defer_accept; 447 if (-1 == setsockopt(srv_socket->fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &v, sizeof(v))) { 448 log_error_write(srv, __FILE__, __LINE__, "ss", "can't set TCP_DEFER_ACCEPT: ", strerror(errno)); 449 } 450 #endif 451 #if defined(__FreeBSD__) || defined(__NetBSD__) \ 452 || defined(__OpenBSD__) || defined(__DragonflyBSD__) 453 } else if (!buffer_is_empty(s->bsd_accept_filter) 454 && (buffer_is_equal_string(s->bsd_accept_filter, CONST_STR_LEN("httpready")) 455 || buffer_is_equal_string(s->bsd_accept_filter, CONST_STR_LEN("dataready")))) { 456 #ifdef SO_ACCEPTFILTER 457 /* FreeBSD accf_http filter */ 458 struct accept_filter_arg afa; 459 memset(&afa, 0, sizeof(afa)); 460 strncpy(afa.af_name, s->bsd_accept_filter->ptr, sizeof(afa.af_name)); 461 if (setsockopt(srv_socket->fd, SOL_SOCKET, SO_ACCEPTFILTER, &afa, sizeof(afa)) < 0) { 462 if (errno != ENOENT) { 463 log_error_write(srv, __FILE__, __LINE__, "SBss", "can't set accept-filter '", s->bsd_accept_filter, "':", strerror(errno)); 464 } 465 } 466 #endif 467 #endif 468 } 469 470 srv_sockets_append: 471 srv_socket->is_ssl = s->ssl_enabled; 472 473 if (srv->srv_sockets.size == 0) { 474 srv->srv_sockets.size = 4; 475 srv->srv_sockets.used = 0; 476 srv->srv_sockets.ptr = malloc(srv->srv_sockets.size * sizeof(server_socket*)); 477 force_assert(NULL != srv->srv_sockets.ptr); 478 } else if (srv->srv_sockets.used == srv->srv_sockets.size) { 479 srv->srv_sockets.size += 4; 480 srv->srv_sockets.ptr = realloc(srv->srv_sockets.ptr, srv->srv_sockets.size * sizeof(server_socket*)); 481 force_assert(NULL != srv->srv_sockets.ptr); 482 } 483 484 srv->srv_sockets.ptr[srv->srv_sockets.used++] = srv_socket; 485 486 buffer_free(b); 487 488 return 0; 489 490 error_free_socket: 491 if (srv_socket->fd != -1) { 492 /* check if server fd are already registered */ 493 if (srv_socket->fde_ndx != -1) { 494 fdevent_event_del(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd); 495 fdevent_unregister(srv->ev, srv_socket->fd); 496 } 497 498 close(srv_socket->fd); 499 } 500 buffer_free(srv_socket->srv_token); 501 free(srv_socket); 502 503 buffer_free(b); 504 505 return err; /* -1 if error; 0 if srv->srvconf.preflight_check successful */ 506 } 507 508 int network_close(server *srv) { 509 size_t i; 510 for (i = 0; i < srv->srv_sockets.used; i++) { 511 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 512 513 if (srv_socket->fd != -1) { 514 /* check if server fd are already registered */ 515 if (srv_socket->fde_ndx != -1) { 516 fdevent_event_del(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd); 517 fdevent_unregister(srv->ev, srv_socket->fd); 518 } 519 520 close(srv_socket->fd); 521 } 522 523 buffer_free(srv_socket->srv_token); 524 525 free(srv_socket); 526 } 527 528 free(srv->srv_sockets.ptr); 529 530 return 0; 531 } 532 533 typedef enum { 534 NETWORK_BACKEND_UNSET, 535 NETWORK_BACKEND_WRITE, 536 NETWORK_BACKEND_WRITEV, 537 NETWORK_BACKEND_SENDFILE, 538 } network_backend_t; 539 540 #ifdef USE_OPENSSL 541 static X509* x509_load_pem_file(server *srv, const char *file) { 542 BIO *in; 543 X509 *x = NULL; 544 545 in = BIO_new(BIO_s_file()); 546 if (NULL == in) { 547 log_error_write(srv, __FILE__, __LINE__, "S", "SSL: BIO_new(BIO_s_file()) failed"); 548 goto error; 549 } 550 551 if (BIO_read_filename(in,file) <= 0) { 552 log_error_write(srv, __FILE__, __LINE__, "SSS", "SSL: BIO_read_filename('", file,"') failed"); 553 goto error; 554 } 555 x = PEM_read_bio_X509(in, NULL, NULL, NULL); 556 557 if (NULL == x) { 558 log_error_write(srv, __FILE__, __LINE__, "SSS", "SSL: couldn't read X509 certificate from '", file,"'"); 559 goto error; 560 } 561 562 BIO_free(in); 563 return x; 564 565 error: 566 if (NULL != in) BIO_free(in); 567 return NULL; 568 } 569 570 static EVP_PKEY* evp_pkey_load_pem_file(server *srv, const char *file) { 571 BIO *in; 572 EVP_PKEY *x = NULL; 573 574 in=BIO_new(BIO_s_file()); 575 if (NULL == in) { 576 log_error_write(srv, __FILE__, __LINE__, "s", "SSL: BIO_new(BIO_s_file()) failed"); 577 goto error; 578 } 579 580 if (BIO_read_filename(in,file) <= 0) { 581 log_error_write(srv, __FILE__, __LINE__, "SSS", "SSL: BIO_read_filename('", file,"') failed"); 582 goto error; 583 } 584 x = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL); 585 586 if (NULL == x) { 587 log_error_write(srv, __FILE__, __LINE__, "SSS", "SSL: couldn't read private key from '", file,"'"); 588 goto error; 589 } 590 591 BIO_free(in); 592 return x; 593 594 error: 595 if (NULL != in) BIO_free(in); 596 return NULL; 597 } 598 599 static int network_openssl_load_pemfile(server *srv, size_t ndx) { 600 specific_config *s = srv->config_storage[ndx]; 601 602 #ifdef OPENSSL_NO_TLSEXT 603 { 604 data_config *dc = (data_config *)srv->config_context->data[ndx]; 605 if ((ndx > 0 && (COMP_SERVER_SOCKET != dc->comp || dc->cond != CONFIG_COND_EQ)) 606 || !s->ssl_enabled) { 607 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:", 608 "ssl.pemfile only works in SSL socket binding context as openssl version does not support TLS extensions"); 609 return -1; 610 } 611 } 612 #endif 613 614 if (NULL == (s->ssl_pemfile_x509 = x509_load_pem_file(srv, s->ssl_pemfile->ptr))) return -1; 615 if (NULL == (s->ssl_pemfile_pkey = evp_pkey_load_pem_file(srv, s->ssl_pemfile->ptr))) return -1; 616 617 if (!X509_check_private_key(s->ssl_pemfile_x509, s->ssl_pemfile_pkey)) { 618 log_error_write(srv, __FILE__, __LINE__, "sssb", "SSL:", 619 "Private key does not match the certificate public key, reason:", 620 ERR_error_string(ERR_get_error(), NULL), 621 s->ssl_pemfile); 622 return -1; 623 } 624 625 return 0; 626 } 627 #endif 628 629 int network_init(server *srv) { 630 buffer *b; 631 size_t i, j; 632 network_backend_t backend; 633 634 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL 635 #ifndef OPENSSL_NO_ECDH 636 EC_KEY *ecdh; 637 int nid; 638 #endif 639 #endif 640 641 #ifdef USE_OPENSSL 642 # ifndef OPENSSL_NO_DH 643 DH *dh; 644 # endif 645 BIO *bio; 646 647 /* 1024-bit MODP Group with 160-bit prime order subgroup (RFC5114) 648 * -----BEGIN DH PARAMETERS----- 649 * MIIBDAKBgQCxC4+WoIDgHd6S3l6uXVTsUsmfvPsGo8aaap3KUtI7YWBz4oZ1oj0Y 650 * mDjvHi7mUsAT7LSuqQYRIySXXDzUm4O/rMvdfZDEvXCYSI6cIZpzck7/1vrlZEc4 651 * +qMaT/VbzMChUa9fDci0vUW/N982XBpl5oz9p21NpwjfH7K8LkpDcQKBgQCk0cvV 652 * w/00EmdlpELvuZkF+BBN0lisUH/WQGz/FCZtMSZv6h5cQVZLd35pD1UE8hMWAhe0 653 * sBuIal6RVH+eJ0n01/vX07mpLuGQnQ0iY/gKdqaiTAh6CR9THb8KAWm2oorWYqTR 654 * jnOvoy13nVkY0IvIhY9Nzvl8KiSFXm7rIrOy5QICAKA= 655 * -----END DH PARAMETERS----- 656 */ 657 658 static const unsigned char dh1024_p[]={ 659 0xB1,0x0B,0x8F,0x96,0xA0,0x80,0xE0,0x1D,0xDE,0x92,0xDE,0x5E, 660 0xAE,0x5D,0x54,0xEC,0x52,0xC9,0x9F,0xBC,0xFB,0x06,0xA3,0xC6, 661 0x9A,0x6A,0x9D,0xCA,0x52,0xD2,0x3B,0x61,0x60,0x73,0xE2,0x86, 662 0x75,0xA2,0x3D,0x18,0x98,0x38,0xEF,0x1E,0x2E,0xE6,0x52,0xC0, 663 0x13,0xEC,0xB4,0xAE,0xA9,0x06,0x11,0x23,0x24,0x97,0x5C,0x3C, 664 0xD4,0x9B,0x83,0xBF,0xAC,0xCB,0xDD,0x7D,0x90,0xC4,0xBD,0x70, 665 0x98,0x48,0x8E,0x9C,0x21,0x9A,0x73,0x72,0x4E,0xFF,0xD6,0xFA, 666 0xE5,0x64,0x47,0x38,0xFA,0xA3,0x1A,0x4F,0xF5,0x5B,0xCC,0xC0, 667 0xA1,0x51,0xAF,0x5F,0x0D,0xC8,0xB4,0xBD,0x45,0xBF,0x37,0xDF, 668 0x36,0x5C,0x1A,0x65,0xE6,0x8C,0xFD,0xA7,0x6D,0x4D,0xA7,0x08, 669 0xDF,0x1F,0xB2,0xBC,0x2E,0x4A,0x43,0x71, 670 }; 671 672 static const unsigned char dh1024_g[]={ 673 0xA4,0xD1,0xCB,0xD5,0xC3,0xFD,0x34,0x12,0x67,0x65,0xA4,0x42, 674 0xEF,0xB9,0x99,0x05,0xF8,0x10,0x4D,0xD2,0x58,0xAC,0x50,0x7F, 675 0xD6,0x40,0x6C,0xFF,0x14,0x26,0x6D,0x31,0x26,0x6F,0xEA,0x1E, 676 0x5C,0x41,0x56,0x4B,0x77,0x7E,0x69,0x0F,0x55,0x04,0xF2,0x13, 677 0x16,0x02,0x17,0xB4,0xB0,0x1B,0x88,0x6A,0x5E,0x91,0x54,0x7F, 678 0x9E,0x27,0x49,0xF4,0xD7,0xFB,0xD7,0xD3,0xB9,0xA9,0x2E,0xE1, 679 0x90,0x9D,0x0D,0x22,0x63,0xF8,0x0A,0x76,0xA6,0xA2,0x4C,0x08, 680 0x7A,0x09,0x1F,0x53,0x1D,0xBF,0x0A,0x01,0x69,0xB6,0xA2,0x8A, 681 0xD6,0x62,0xA4,0xD1,0x8E,0x73,0xAF,0xA3,0x2D,0x77,0x9D,0x59, 682 0x18,0xD0,0x8B,0xC8,0x85,0x8F,0x4D,0xCE,0xF9,0x7C,0x2A,0x24, 683 0x85,0x5E,0x6E,0xEB,0x22,0xB3,0xB2,0xE5, 684 }; 685 #endif 686 687 struct nb_map { 688 network_backend_t nb; 689 const char *name; 690 } network_backends[] = { 691 /* lowest id wins */ 692 #if defined USE_SENDFILE 693 { NETWORK_BACKEND_SENDFILE, "sendfile" }, 694 #endif 695 #if defined USE_LINUX_SENDFILE 696 { NETWORK_BACKEND_SENDFILE, "linux-sendfile" }, 697 #endif 698 #if defined USE_FREEBSD_SENDFILE 699 { NETWORK_BACKEND_SENDFILE, "freebsd-sendfile" }, 700 #endif 701 #if defined USE_SOLARIS_SENDFILEV 702 { NETWORK_BACKEND_SENDFILE, "solaris-sendfilev" }, 703 #endif 704 #if defined USE_WRITEV 705 { NETWORK_BACKEND_WRITEV, "writev" }, 706 #endif 707 { NETWORK_BACKEND_WRITE, "write" }, 708 { NETWORK_BACKEND_UNSET, NULL } 709 }; 710 711 #ifdef USE_OPENSSL 712 /* load SSL certificates */ 713 for (i = 0; i < srv->config_context->used; i++) { 714 specific_config *s = srv->config_storage[i]; 715 #ifndef SSL_OP_NO_COMPRESSION 716 # define SSL_OP_NO_COMPRESSION 0 717 #endif 718 long ssloptions = 719 SSL_OP_ALL | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | SSL_OP_NO_COMPRESSION; 720 721 if (buffer_string_is_empty(s->ssl_pemfile) && buffer_string_is_empty(s->ssl_ca_file)) continue; 722 723 if (srv->ssl_is_init == 0) { 724 SSL_load_error_strings(); 725 SSL_library_init(); 726 OpenSSL_add_all_algorithms(); 727 srv->ssl_is_init = 1; 728 729 if (0 == RAND_status()) { 730 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:", 731 "not enough entropy in the pool"); 732 return -1; 733 } 734 } 735 736 if (!buffer_string_is_empty(s->ssl_pemfile)) { 737 #ifdef OPENSSL_NO_TLSEXT 738 data_config *dc = (data_config *)srv->config_context->data[i]; 739 if (COMP_HTTP_HOST == dc->comp) { 740 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:", 741 "can't use ssl.pemfile with $HTTP[\"host\"], openssl version does not support TLS extensions"); 742 return -1; 743 } 744 #endif 745 if (network_openssl_load_pemfile(srv, i)) return -1; 746 } 747 748 749 if (!buffer_string_is_empty(s->ssl_ca_file)) { 750 s->ssl_ca_file_cert_names = SSL_load_client_CA_file(s->ssl_ca_file->ptr); 751 if (NULL == s->ssl_ca_file_cert_names) { 752 log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:", 753 ERR_error_string(ERR_get_error(), NULL), s->ssl_ca_file); 754 } 755 } 756 757 if (buffer_string_is_empty(s->ssl_pemfile) || !s->ssl_enabled) continue; 758 759 if (NULL == (s->ssl_ctx = SSL_CTX_new(SSLv23_server_method()))) { 760 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:", 761 ERR_error_string(ERR_get_error(), NULL)); 762 return -1; 763 } 764 765 /* completely useless identifier; required for client cert verification to work with sessions */ 766 if (0 == SSL_CTX_set_session_id_context(s->ssl_ctx, (const unsigned char*) CONST_STR_LEN("lighttpd"))) { 767 log_error_write(srv, __FILE__, __LINE__, "ss:s", "SSL:", 768 "failed to set session context", 769 ERR_error_string(ERR_get_error(), NULL)); 770 return -1; 771 } 772 773 if (s->ssl_empty_fragments) { 774 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS 775 ssloptions &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; 776 #else 777 ssloptions &= ~0x00000800L; /* hardcode constant */ 778 log_error_write(srv, __FILE__, __LINE__, "ss", "WARNING: SSL:", 779 "'insert empty fragments' not supported by the openssl version used to compile lighttpd with"); 780 #endif 781 } 782 783 SSL_CTX_set_options(s->ssl_ctx, ssloptions); 784 SSL_CTX_set_info_callback(s->ssl_ctx, ssl_info_callback); 785 786 if (!s->ssl_use_sslv2) { 787 /* disable SSLv2 */ 788 if ((SSL_OP_NO_SSLv2 & SSL_CTX_set_options(s->ssl_ctx, SSL_OP_NO_SSLv2)) != SSL_OP_NO_SSLv2) { 789 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:", 790 ERR_error_string(ERR_get_error(), NULL)); 791 return -1; 792 } 793 } 794 795 if (!s->ssl_use_sslv3) { 796 /* disable SSLv3 */ 797 if ((SSL_OP_NO_SSLv3 & SSL_CTX_set_options(s->ssl_ctx, SSL_OP_NO_SSLv3)) != SSL_OP_NO_SSLv3) { 798 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:", 799 ERR_error_string(ERR_get_error(), NULL)); 800 return -1; 801 } 802 } 803 804 if (!buffer_string_is_empty(s->ssl_cipher_list)) { 805 /* Disable support for low encryption ciphers */ 806 if (SSL_CTX_set_cipher_list(s->ssl_ctx, s->ssl_cipher_list->ptr) != 1) { 807 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:", 808 ERR_error_string(ERR_get_error(), NULL)); 809 return -1; 810 } 811 812 if (s->ssl_honor_cipher_order) { 813 SSL_CTX_set_options(s->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); 814 } 815 } 816 817 #ifndef OPENSSL_NO_DH 818 /* Support for Diffie-Hellman key exchange */ 819 if (!buffer_string_is_empty(s->ssl_dh_file)) { 820 /* DH parameters from file */ 821 bio = BIO_new_file((char *) s->ssl_dh_file->ptr, "r"); 822 if (bio == NULL) { 823 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL: Unable to open file", s->ssl_dh_file->ptr); 824 return -1; 825 } 826 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); 827 BIO_free(bio); 828 if (dh == NULL) { 829 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL: PEM_read_bio_DHparams failed", s->ssl_dh_file->ptr); 830 return -1; 831 } 832 } else { 833 BIGNUM *dh_p, *dh_g; 834 /* Default DH parameters from RFC5114 */ 835 dh = DH_new(); 836 if (dh == NULL) { 837 log_error_write(srv, __FILE__, __LINE__, "s", "SSL: DH_new () failed"); 838 return -1; 839 } 840 dh_p = BN_bin2bn(dh1024_p,sizeof(dh1024_p), NULL); 841 dh_g = BN_bin2bn(dh1024_g,sizeof(dh1024_g), NULL); 842 if ((dh_p == NULL) || (dh_g == NULL)) { 843 DH_free(dh); 844 log_error_write(srv, __FILE__, __LINE__, "s", "SSL: BN_bin2bn () failed"); 845 return -1; 846 } 847 #if OPENSSL_VERSION_NUMBER < 0x10100000L \ 848 || defined(LIBRESSL_VERSION_NUMBER) 849 dh->p = dh_p; 850 dh->g = dh_g; 851 dh->length = 160; 852 #else 853 DH_set0_pqg(dh, dh_p, NULL, dh_g); 854 DH_set_length(dh, 160); 855 #endif 856 } 857 SSL_CTX_set_tmp_dh(s->ssl_ctx,dh); 858 SSL_CTX_set_options(s->ssl_ctx,SSL_OP_SINGLE_DH_USE); 859 DH_free(dh); 860 #else 861 if (!buffer_string_is_empty(s->ssl_dh_file)) { 862 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL: openssl compiled without DH support, can't load parameters from", s->ssl_dh_file->ptr); 863 } 864 #endif 865 866 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL 867 #ifndef OPENSSL_NO_ECDH 868 /* Support for Elliptic-Curve Diffie-Hellman key exchange */ 869 if (!buffer_string_is_empty(s->ssl_ec_curve)) { 870 /* OpenSSL only supports the "named curves" from RFC 4492, section 5.1.1. */ 871 nid = OBJ_sn2nid((char *) s->ssl_ec_curve->ptr); 872 if (nid == 0) { 873 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL: Unknown curve name", s->ssl_ec_curve->ptr); 874 return -1; 875 } 876 } else { 877 /* Default curve */ 878 nid = OBJ_sn2nid("prime256v1"); 879 } 880 ecdh = EC_KEY_new_by_curve_name(nid); 881 if (ecdh == NULL) { 882 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL: Unable to create curve", s->ssl_ec_curve->ptr); 883 return -1; 884 } 885 SSL_CTX_set_tmp_ecdh(s->ssl_ctx,ecdh); 886 SSL_CTX_set_options(s->ssl_ctx,SSL_OP_SINGLE_ECDH_USE); 887 EC_KEY_free(ecdh); 888 #endif 889 #endif 890 891 /* load all ssl.ca-files specified in the config into each SSL_CTX to be prepared for SNI */ 892 for (j = 0; j < srv->config_context->used; j++) { 893 specific_config *s1 = srv->config_storage[j]; 894 895 if (!buffer_string_is_empty(s1->ssl_ca_file)) { 896 if (1 != SSL_CTX_load_verify_locations(s->ssl_ctx, s1->ssl_ca_file->ptr, NULL)) { 897 log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:", 898 ERR_error_string(ERR_get_error(), NULL), s1->ssl_ca_file); 899 return -1; 900 } 901 } 902 } 903 904 if (s->ssl_verifyclient) { 905 if (NULL == s->ssl_ca_file_cert_names) { 906 log_error_write(srv, __FILE__, __LINE__, "s", 907 "SSL: You specified ssl.verifyclient.activate but no ca_file" 908 ); 909 return -1; 910 } 911 SSL_CTX_set_client_CA_list(s->ssl_ctx, SSL_dup_CA_list(s->ssl_ca_file_cert_names)); 912 SSL_CTX_set_verify( 913 s->ssl_ctx, 914 SSL_VERIFY_PEER | (s->ssl_verifyclient_enforce ? SSL_VERIFY_FAIL_IF_NO_PEER_CERT : 0), 915 NULL 916 ); 917 SSL_CTX_set_verify_depth(s->ssl_ctx, s->ssl_verifyclient_depth); 918 } 919 920 if (SSL_CTX_use_certificate(s->ssl_ctx, s->ssl_pemfile_x509) < 0) { 921 log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:", 922 ERR_error_string(ERR_get_error(), NULL), s->ssl_pemfile); 923 return -1; 924 } 925 926 if (SSL_CTX_use_PrivateKey(s->ssl_ctx, s->ssl_pemfile_pkey) < 0) { 927 log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:", 928 ERR_error_string(ERR_get_error(), NULL), s->ssl_pemfile); 929 return -1; 930 } 931 932 if (SSL_CTX_check_private_key(s->ssl_ctx) != 1) { 933 log_error_write(srv, __FILE__, __LINE__, "sssb", "SSL:", 934 "Private key does not match the certificate public key, reason:", 935 ERR_error_string(ERR_get_error(), NULL), 936 s->ssl_pemfile); 937 return -1; 938 } 939 SSL_CTX_set_default_read_ahead(s->ssl_ctx, 1); 940 SSL_CTX_set_mode(s->ssl_ctx, SSL_CTX_get_mode(s->ssl_ctx) | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); 941 942 # ifndef OPENSSL_NO_TLSEXT 943 if (!SSL_CTX_set_tlsext_servername_callback(s->ssl_ctx, network_ssl_servername_callback) || 944 !SSL_CTX_set_tlsext_servername_arg(s->ssl_ctx, srv)) { 945 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:", 946 "failed to initialize TLS servername callback, openssl library does not support TLS servername extension"); 947 return -1; 948 } 949 # endif 950 } 951 #endif 952 953 b = buffer_init(); 954 955 buffer_copy_buffer(b, srv->srvconf.bindhost); 956 buffer_append_string_len(b, CONST_STR_LEN(":")); 957 buffer_append_int(b, srv->srvconf.port); 958 959 if (0 != network_server_init(srv, b, srv->config_storage[0])) { 960 buffer_free(b); 961 return -1; 962 } 963 buffer_free(b); 964 965 #ifdef USE_OPENSSL 966 srv->network_ssl_backend_write = network_write_chunkqueue_openssl; 967 #endif 968 969 /* get a usefull default */ 970 backend = network_backends[0].nb; 971 972 /* match name against known types */ 973 if (!buffer_string_is_empty(srv->srvconf.network_backend)) { 974 for (i = 0; network_backends[i].name; i++) { 975 /**/ 976 if (buffer_is_equal_string(srv->srvconf.network_backend, network_backends[i].name, strlen(network_backends[i].name))) { 977 backend = network_backends[i].nb; 978 break; 979 } 980 } 981 if (NULL == network_backends[i].name) { 982 /* we don't know it */ 983 984 log_error_write(srv, __FILE__, __LINE__, "sb", 985 "server.network-backend has a unknown value:", 986 srv->srvconf.network_backend); 987 988 return -1; 989 } 990 } 991 992 switch(backend) { 993 case NETWORK_BACKEND_WRITE: 994 srv->network_backend_write = network_write_chunkqueue_write; 995 break; 996 #if defined(USE_WRITEV) 997 case NETWORK_BACKEND_WRITEV: 998 srv->network_backend_write = network_write_chunkqueue_writev; 999 break; 1000 #endif 1001 #if defined(USE_SENDFILE) 1002 case NETWORK_BACKEND_SENDFILE: 1003 srv->network_backend_write = network_write_chunkqueue_sendfile; 1004 break; 1005 #endif 1006 default: 1007 return -1; 1008 } 1009 1010 /* check for $SERVER["socket"] */ 1011 for (i = 1; i < srv->config_context->used; i++) { 1012 data_config *dc = (data_config *)srv->config_context->data[i]; 1013 specific_config *s = srv->config_storage[i]; 1014 1015 /* not our stage */ 1016 if (COMP_SERVER_SOCKET != dc->comp) continue; 1017 1018 if (dc->cond != CONFIG_COND_EQ) continue; 1019 1020 /* check if we already know this socket, 1021 * if yes, don't init it */ 1022 for (j = 0; j < srv->srv_sockets.used; j++) { 1023 if (buffer_is_equal(srv->srv_sockets.ptr[j]->srv_token, dc->string)) { 1024 break; 1025 } 1026 } 1027 1028 if (j == srv->srv_sockets.used) { 1029 if (0 != network_server_init(srv, dc->string, s)) return -1; 1030 } 1031 } 1032 1033 return 0; 1034 } 1035 1036 int network_register_fdevents(server *srv) { 1037 size_t i; 1038 1039 if (-1 == fdevent_reset(srv->ev)) { 1040 return -1; 1041 } 1042 1043 if (srv->sockets_disabled) return 0; /* lighttpd -1 (one-shot mode) */ 1044 1045 /* register fdevents after reset */ 1046 for (i = 0; i < srv->srv_sockets.used; i++) { 1047 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 1048 1049 fdevent_register(srv->ev, srv_socket->fd, network_server_handle_fdevent, srv_socket); 1050 fdevent_event_set(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd, FDEVENT_IN); 1051 } 1052 return 0; 1053 } 1054 1055 int network_write_chunkqueue(server *srv, connection *con, chunkqueue *cq, off_t max_bytes) { 1056 int ret = -1; 1057 off_t written = 0; 1058 #ifdef TCP_CORK 1059 int corked = 0; 1060 #endif 1061 server_socket *srv_socket = con->srv_socket; 1062 1063 if (con->conf.global_kbytes_per_second) { 1064 off_t limit = con->conf.global_kbytes_per_second * 1024 - *(con->conf.global_bytes_per_second_cnt_ptr); 1065 if (limit <= 0) { 1066 /* we reached the global traffic limit */ 1067 1068 con->traffic_limit_reached = 1; 1069 joblist_append(srv, con); 1070 1071 return 1; 1072 } else { 1073 if (max_bytes > limit) max_bytes = limit; 1074 } 1075 } 1076 1077 if (con->conf.kbytes_per_second) { 1078 off_t limit = con->conf.kbytes_per_second * 1024 - con->bytes_written_cur_second; 1079 if (limit <= 0) { 1080 /* we reached the traffic limit */ 1081 1082 con->traffic_limit_reached = 1; 1083 joblist_append(srv, con); 1084 1085 return 1; 1086 } else { 1087 if (max_bytes > limit) max_bytes = limit; 1088 } 1089 } 1090 1091 written = cq->bytes_out; 1092 1093 #ifdef TCP_CORK 1094 /* Linux: put a cork into the socket as we want to combine the write() calls 1095 * but only if we really have multiple chunks 1096 */ 1097 if (cq->first && cq->first->next) { 1098 corked = 1; 1099 setsockopt(con->fd, IPPROTO_TCP, TCP_CORK, &corked, sizeof(corked)); 1100 } 1101 #endif 1102 1103 if (srv_socket->is_ssl) { 1104 #ifdef USE_OPENSSL 1105 ret = srv->network_ssl_backend_write(srv, con, con->ssl, cq, max_bytes); 1106 #endif 1107 } else { 1108 ret = srv->network_backend_write(srv, con, con->fd, cq, max_bytes); 1109 } 1110 1111 if (ret >= 0) { 1112 chunkqueue_remove_finished_chunks(cq); 1113 ret = chunkqueue_is_empty(cq) ? 0 : 1; 1114 } 1115 1116 #ifdef TCP_CORK 1117 if (corked) { 1118 corked = 0; 1119 setsockopt(con->fd, IPPROTO_TCP, TCP_CORK, &corked, sizeof(corked)); 1120 } 1121 #endif 1122 1123 written = cq->bytes_out - written; 1124 con->bytes_written += written; 1125 con->bytes_written_cur_second += written; 1126 1127 *(con->conf.global_bytes_per_second_cnt_ptr) += written; 1128 1129 return ret; 1130 } 1131