1 /* 2 * request - HTTP request processing 3 * 4 * Fully-rewritten from original EXCEPT for request_check_hostname() 5 * Copyright(c) 2018 Glenn Strauss gstrauss()gluelogic.com All rights reserved 6 * License: BSD 3-clause (same as lighttpd) 7 */ 8 #include "first.h" 9 10 #include "request.h" 11 #include "burl.h" 12 #include "http_header.h" 13 #include "http_kv.h" 14 #include "log.h" 15 #include "sock_addr.h" 16 17 #include <limits.h> 18 #include <stdlib.h> 19 #include <string.h> 20 21 static int request_check_hostname(buffer * const host) { 22 enum { DOMAINLABEL, TOPLABEL } stage = TOPLABEL; 23 size_t i; 24 int label_len = 0; 25 size_t host_len, hostport_len; 26 char *colon; 27 int is_ip = -1; /* -1 don't know yet, 0 no, 1 yes */ 28 int level = 0; 29 30 /* 31 * hostport = host [ ":" port ] 32 * host = hostname | IPv4address | IPv6address 33 * hostname = *( domainlabel "." ) toplabel [ "." ] 34 * domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum 35 * toplabel = alpha | alpha *( alphanum | "-" ) alphanum 36 * IPv4address = 1*digit "." 1*digit "." 1*digit "." 1*digit 37 * IPv6address = "[" ... "]" 38 * port = *digit 39 */ 40 41 /* IPv6 address */ 42 if (host->ptr[0] == '[') { 43 char *c = host->ptr + 1; 44 int colon_cnt = 0; 45 46 /* check the address inside [...] */ 47 for (; *c && *c != ']'; c++) { 48 if (*c == ':') { 49 if (++colon_cnt > 7) { 50 return -1; 51 } 52 } else if (!light_isxdigit(*c) && '.' != *c) { 53 return -1; 54 } 55 } 56 57 /* missing ] */ 58 if (!*c) { 59 return -1; 60 } 61 62 /* check port */ 63 if (*(c+1) == ':') { 64 for (c += 2; *c; c++) { 65 if (!light_isdigit(*c)) { 66 return -1; 67 } 68 } 69 } 70 else if ('\0' != *(c+1)) { 71 /* only a port is allowed to follow [...] */ 72 return -1; 73 } 74 return 0; 75 } 76 77 hostport_len = host_len = buffer_string_length(host); 78 79 if (NULL != (colon = memchr(host->ptr, ':', host_len))) { 80 char *c = colon + 1; 81 82 /* check portnumber */ 83 for (; *c; c++) { 84 if (!light_isdigit(*c)) return -1; 85 } 86 87 /* remove the port from the host-len */ 88 host_len = colon - host->ptr; 89 } 90 91 /* Host is empty */ 92 if (host_len == 0) return -1; 93 94 /* if the hostname ends in a "." strip it */ 95 if (host->ptr[host_len-1] == '.') { 96 /* shift port info one left */ 97 if (NULL != colon) memmove(colon-1, colon, hostport_len - host_len); 98 buffer_string_set_length(host, --hostport_len); 99 if (--host_len == 0) return -1; 100 } 101 102 103 /* scan from the right and skip the \0 */ 104 for (i = host_len; i-- > 0; ) { 105 const char c = host->ptr[i]; 106 107 switch (stage) { 108 case TOPLABEL: 109 if (c == '.') { 110 /* only switch stage, if this is not the last character */ 111 if (i != host_len - 1) { 112 if (label_len == 0) { 113 return -1; 114 } 115 116 /* check the first character at right of the dot */ 117 if (is_ip == 0) { 118 if (!light_isalnum(host->ptr[i+1])) { 119 return -1; 120 } 121 } else if (!light_isdigit(host->ptr[i+1])) { 122 is_ip = 0; 123 } else if ('-' == host->ptr[i+1]) { 124 return -1; 125 } else { 126 /* just digits */ 127 is_ip = 1; 128 } 129 130 stage = DOMAINLABEL; 131 132 label_len = 0; 133 level++; 134 } else if (i == 0) { 135 /* just a dot and nothing else is evil */ 136 return -1; 137 } 138 } else if (i == 0) { 139 /* the first character of the hostname */ 140 if (!light_isalnum(c)) { 141 return -1; 142 } 143 label_len++; 144 } else { 145 if (c != '-' && !light_isalnum(c)) { 146 return -1; 147 } 148 if (is_ip == -1) { 149 if (!light_isdigit(c)) is_ip = 0; 150 } 151 label_len++; 152 } 153 154 break; 155 case DOMAINLABEL: 156 if (is_ip == 1) { 157 if (c == '.') { 158 if (label_len == 0) { 159 return -1; 160 } 161 162 label_len = 0; 163 level++; 164 } else if (!light_isdigit(c)) { 165 return -1; 166 } else { 167 label_len++; 168 } 169 } else { 170 if (c == '.') { 171 if (label_len == 0) { 172 return -1; 173 } 174 175 /* c is either - or alphanum here */ 176 if ('-' == host->ptr[i+1]) { 177 return -1; 178 } 179 180 label_len = 0; 181 level++; 182 } else if (i == 0) { 183 if (!light_isalnum(c)) { 184 return -1; 185 } 186 label_len++; 187 } else { 188 if (c != '-' && !light_isalnum(c)) { 189 return -1; 190 } 191 label_len++; 192 } 193 } 194 195 break; 196 } 197 } 198 199 /* a IP has to consist of 4 parts */ 200 if (is_ip == 1 && level != 3) { 201 return -1; 202 } 203 204 if (label_len == 0) { 205 return -1; 206 } 207 208 return 0; 209 } 210 211 int http_request_host_normalize(buffer * const b, const int scheme_port) { 212 /* 213 * check for and canonicalize numeric IP address and portnum (optional) 214 * (IP address may be followed by ":portnum" (optional)) 215 * - IPv6: "[...]" 216 * - IPv4: "x.x.x.x" 217 * - IPv4: 12345678 (32-bit decimal number) 218 * - IPv4: 012345678 (32-bit octal number) 219 * - IPv4: 0x12345678 (32-bit hex number) 220 * 221 * allow any chars (except ':' and '\0' and stray '[' or ']') 222 * (other code may check chars more strictly or more pedantically) 223 * ':' delimits (optional) port at end of string 224 * "[]" wraps IPv6 address literal 225 * '\0' should have been rejected earlier were it present 226 * 227 * any chars includes, but is not limited to: 228 * - allow '-' any where, even at beginning of word 229 * (security caution: might be confused for cmd flag if passed to shell) 230 * - allow all-digit TLDs 231 * (might be mistaken for IPv4 addr by inet_aton() 232 * unless non-digits appear in subdomain) 233 */ 234 235 /* Note: not using getaddrinfo() since it does not support "[]" around IPv6 236 * and is not as lenient as inet_aton() and inet_addr() for IPv4 strings. 237 * Not using inet_pton() (when available) on IPv4 for similar reasons. */ 238 239 const char * const p = b->ptr; 240 const size_t blen = buffer_string_length(b); 241 long port = 0; 242 243 if (*p != '[') { 244 char * const colon = (char *)memchr(p, ':', blen); 245 if (colon) { 246 if (*p == ':') return -1; /*(empty host then port, or naked IPv6)*/ 247 if (colon[1] != '\0') { 248 char *e; 249 port = strtol(colon+1, &e, 0); /*(allow decimal, octal, hex)*/ 250 if (0 < port && port <= USHRT_MAX && *e == '\0') { 251 /* valid port */ 252 } else { 253 return -1; 254 } 255 } /*(else ignore stray colon at string end)*/ 256 buffer_string_set_length(b, (size_t)(colon - p)); /*(remove port str)*/ 257 } 258 259 if (light_isdigit(*p)) do { 260 /* (IPv4 address literal or domain starting w/ digit (e.g. 3com))*/ 261 /* (check one-element cache of normalized IPv4 address string) */ 262 static struct { char s[INET_ADDRSTRLEN]; size_t n; } laddr; 263 size_t n = colon ? (size_t)(colon - p) : blen; 264 sock_addr addr; 265 if (n == laddr.n && 0 == memcmp(p, laddr.s, n)) break; 266 if (1 == sock_addr_inet_pton(&addr, p, AF_INET, 0)) { 267 sock_addr_inet_ntop_copy_buffer(b, &addr); 268 n = buffer_string_length(b); 269 if (n < sizeof(laddr.s)) memcpy(laddr.s, b->ptr, (laddr.n = n)); 270 } 271 } while (0); 272 } else do { /* IPv6 addr */ 273 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON) 274 275 /* (check one-element cache of normalized IPv4 address string) */ 276 static struct { char s[INET6_ADDRSTRLEN]; size_t n; } laddr; 277 sock_addr addr; 278 char *bracket = b->ptr+blen-1; 279 char *percent = strchr(b->ptr+1, '%'); 280 size_t len; 281 int rc; 282 char buf[INET6_ADDRSTRLEN+16]; /*(+16 for potential %interface name)*/ 283 if (blen <= 2) return -1; /*(invalid "[]")*/ 284 if (*bracket != ']') { 285 bracket = (char *)memchr(b->ptr+1, ']', blen-1); 286 if (NULL == bracket || bracket[1] != ':' || bracket - b->ptr == 1){ 287 return -1; 288 } 289 if (bracket[2] != '\0') { /*(ignore stray colon at string end)*/ 290 char *e; 291 port = strtol(bracket+2, &e, 0); /*(allow decimal, octal, hex)*/ 292 if (0 < port && port <= USHRT_MAX && *e == '\0') { 293 /* valid port */ 294 } else { 295 return -1; 296 } 297 } 298 } 299 300 len = (size_t)((percent ? percent : bracket) - (b->ptr+1)); 301 if (laddr.n == len && 0 == memcmp(laddr.s, b->ptr+1, len)) { 302 /* truncate after ']' and re-add normalized port, if needed */ 303 buffer_string_set_length(b, (size_t)(bracket - b->ptr + 1)); 304 break; 305 } 306 307 *bracket = '\0';/*(terminate IPv6 string)*/ 308 if (percent) *percent = '\0'; /*(remove %interface from address)*/ 309 rc = sock_addr_inet_pton(&addr, b->ptr+1, AF_INET6, 0); 310 if (percent) *percent = '%'; /*(restore %interface)*/ 311 *bracket = ']'; /*(restore bracket)*/ 312 if (1 != rc) return -1; 313 314 sock_addr_inet_ntop(&addr, buf, sizeof(buf)); 315 len = strlen(buf); 316 if (percent) { 317 if (percent > bracket) return -1; 318 if (len + (size_t)(bracket - percent) >= sizeof(buf)) return -1; 319 if (len < sizeof(laddr.s)) memcpy(laddr.s, buf, (laddr.n = len)); 320 memcpy(buf+len, percent, (size_t)(bracket - percent)); 321 len += (size_t)(bracket - percent); 322 } 323 buffer_string_set_length(b, 1); /* truncate after '[' */ 324 buffer_append_string_len(b, buf, len); 325 buffer_append_string_len(b, CONST_STR_LEN("]")); 326 327 #else 328 329 return -1; 330 331 #endif 332 } while (0); 333 334 if (0 != port && port != scheme_port) { 335 buffer_append_string_len(b, CONST_STR_LEN(":")); 336 buffer_append_int(b, (int)port); 337 } 338 339 return 0; 340 } 341 342 int http_request_host_policy (buffer * const b, const unsigned int http_parseopts, const int scheme_port) { 343 return (((http_parseopts & HTTP_PARSEOPT_HOST_STRICT) 344 && 0 != request_check_hostname(b)) 345 || ((http_parseopts & HTTP_PARSEOPT_HOST_NORMALIZE) 346 && 0 != http_request_host_normalize(b, scheme_port))); 347 } 348 349 __attribute_pure__ /*(could be even more strict and use __attribute_const__)*/ 350 static int request_uri_is_valid_char(const unsigned char c) { 351 return (c > 32 && c != 127 && c != 255); 352 } 353 354 __attribute_cold__ 355 __attribute_noinline__ 356 static int http_request_header_line_invalid(request_st * const restrict r, const int status, const char * const restrict msg) { 357 if (r->conf.log_request_header_on_error) { 358 if (msg) log_error(r->conf.errh, __FILE__, __LINE__, "%s", msg); 359 } 360 return status; 361 } 362 363 __attribute_cold__ 364 __attribute_noinline__ 365 static int http_request_header_char_invalid(request_st * const restrict r, const char ch, const char * const restrict msg) { 366 if (r->conf.log_request_header_on_error) { 367 if ((unsigned char)ch > 32 && ch != 127) { 368 log_error(r->conf.errh, __FILE__, __LINE__, "%s ('%c')", msg, ch); 369 } 370 else { 371 log_error(r->conf.errh, __FILE__, __LINE__, "%s (0x%x)", msg, ch); 372 } 373 } 374 return 400; 375 } 376 377 /* add header to list of headers 378 * certain headers are also parsed 379 * might drop a header if deemed unnecessary/broken 380 * 381 * returns 0 on success, HTTP status on error 382 */ 383 static int http_request_parse_single_header(request_st * const restrict r, const enum http_header_e id, const char * const restrict k, const size_t klen, const char * const restrict v, const size_t vlen) { 384 buffer **saveb = NULL; 385 386 /* 387 * Note: k might not be '\0'-terminated 388 * Note: v is not '\0'-terminated, and ends with whitespace 389 * (one of '\r' '\n' ' ' '\t') 390 */ 391 392 switch (id) { 393 /*case HTTP_HEADER_OTHER:*/ 394 default: 395 break; 396 case HTTP_HEADER_HOST: 397 if (!(r->rqst_htags & HTTP_HEADER_HOST)) { 398 saveb = &r->http_host; 399 if (vlen >= 1024) { /*(expecting < 256)*/ 400 return http_request_header_line_invalid(r, 400, "uri-authority too long -> 400"); 401 } 402 } 403 else if (NULL != r->http_host 404 && buffer_is_equal_string(r->http_host, v, vlen)) { 405 /* ignore all Host: headers if match authority in request line */ 406 return 0; /* ignore header */ 407 } 408 else { 409 return http_request_header_line_invalid(r, 400, "duplicate Host header -> 400"); 410 } 411 break; 412 case HTTP_HEADER_CONNECTION: 413 /* "Connection: close" is common case if header is present */ 414 if ((vlen == 5 && buffer_eq_icase_ssn(v, CONST_STR_LEN("close"))) 415 || http_header_str_contains_token(v,vlen,CONST_STR_LEN("close"))) { 416 r->keep_alive = 0; 417 break; 418 } 419 if (http_header_str_contains_token(v,vlen,CONST_STR_LEN("keep-alive"))){ 420 r->keep_alive = 1; 421 break; 422 } 423 break; 424 case HTTP_HEADER_CONTENT_TYPE: 425 if (r->rqst_htags & HTTP_HEADER_CONTENT_TYPE) { 426 return http_request_header_line_invalid(r, 400, "duplicate Content-Type header -> 400"); 427 } 428 break; 429 case HTTP_HEADER_IF_NONE_MATCH: 430 /* if dup, only the first one will survive */ 431 if (r->rqst_htags & HTTP_HEADER_IF_NONE_MATCH) { 432 return 0; /* ignore header */ 433 } 434 break; 435 case HTTP_HEADER_CONTENT_LENGTH: 436 if (!(r->rqst_htags & HTTP_HEADER_CONTENT_LENGTH)) { 437 /*(trailing whitespace was removed from vlen)*/ 438 char *err; 439 off_t clen = strtoll(v, &err, 10); 440 if (clen >= 0 && err == v+vlen && light_isdigit(v[0])) { 441 /* (set only if not set to -1 by Transfer-Encoding: chunked) */ 442 if (0 == r->reqbody_length) r->reqbody_length = clen; 443 } 444 else { 445 return http_request_header_line_invalid(r, 400, "invalid Content-Length header -> 400"); 446 } 447 } 448 else { 449 return http_request_header_line_invalid(r, 400, "duplicate Content-Length header -> 400"); 450 } 451 break; 452 case HTTP_HEADER_HTTP2_SETTINGS: 453 if (r->rqst_htags & HTTP_HEADER_HTTP2_SETTINGS) { 454 return http_request_header_line_invalid(r, 400, "duplicate HTTP2-Settings header -> 400"); 455 } 456 break; 457 case HTTP_HEADER_IF_MODIFIED_SINCE: 458 if (r->rqst_htags & HTTP_HEADER_IF_MODIFIED_SINCE) { 459 /* Proxies sometimes send dup headers 460 * if they are the same we ignore the second 461 * if not, we raise an error */ 462 const buffer *vb = 463 http_header_request_get(r, HTTP_HEADER_IF_MODIFIED_SINCE, 464 CONST_STR_LEN("If-Modified-Since")); 465 if (vb && buffer_is_equal_caseless_string(vb, v, vlen)) { 466 /* ignore it if they are the same */ 467 return 0; /* ignore header */ 468 } 469 else { 470 return http_request_header_line_invalid(r, 400, "duplicate If-Modified-Since header -> 400"); 471 } 472 } 473 break; 474 case HTTP_HEADER_TRANSFER_ENCODING: 475 if (HTTP_VERSION_1_1 != r->http_version) { 476 return http_request_header_line_invalid(r, 400, 477 HTTP_VERSION_1_0 == r->http_version 478 ? "HTTP/1.0 with Transfer-Encoding (bad HTTP/1.0 proxy?) -> 400" 479 : "HTTP/2 with Transfer-Encoding is invalid -> 400"); 480 } 481 482 if (!buffer_eq_icase_ss(v, vlen, CONST_STR_LEN("chunked"))) { 483 /* Transfer-Encoding might contain additional encodings, 484 * which are not currently supported by lighttpd */ 485 return http_request_header_line_invalid(r, 501, NULL); /* Not Implemented */ 486 } 487 r->reqbody_length = -1; 488 489 /* Transfer-Encoding is a hop-by-hop header, 490 * which must not be blindly forwarded to backends */ 491 return 0; /* skip header */ 492 } 493 494 http_header_request_append(r, id, k, klen, v, vlen); 495 496 if (saveb) { 497 *saveb = http_header_request_get(r, id, k, klen); 498 } 499 500 return 0; 501 } 502 503 __attribute_cold__ 504 static int http_request_parse_proto_loose(request_st * const restrict r, const char * const restrict ptr, const size_t len, const unsigned int http_parseopts) { 505 const char * proto = memchr(ptr, ' ', len); 506 if (NULL == proto) 507 return http_request_header_line_invalid(r, 400, "incomplete request line -> 400"); 508 proto = memchr(proto+1, ' ', len - (proto+1 - ptr)); 509 if (NULL == proto) 510 return http_request_header_line_invalid(r, 400, "incomplete request line -> 400"); 511 ++proto; 512 513 if (proto[0]=='H' && proto[1]=='T' && proto[2]=='T' && proto[3]=='P' && proto[4] == '/') { 514 if (proto[5] == '1' && proto[6] == '.' && (proto[7] == '1' || proto[7] == '0')) { 515 /* length already checked before calling this routine */ 516 /* (len != (size_t)(proto - ptr + 8)) */ 517 if (http_parseopts & HTTP_PARSEOPT_HEADER_STRICT) /*(http_header_strict)*/ 518 return http_request_header_line_invalid(r, 400, "incomplete request line -> 400"); 519 r->http_version = (proto[7] == '1') ? HTTP_VERSION_1_1 : HTTP_VERSION_1_0; 520 } 521 else 522 return http_request_header_line_invalid(r, 505, "unknown HTTP version -> 505"); 523 } 524 else 525 return http_request_header_line_invalid(r, 400, "unknown protocol -> 400"); 526 527 /* keep-alive default: HTTP/1.1 -> true; HTTP/1.0 -> false */ 528 r->keep_alive = (HTTP_VERSION_1_0 != r->http_version); 529 530 return 0; 531 } 532 533 __attribute_cold__ 534 static const char * http_request_parse_reqline_uri(request_st * const restrict r, const char * const restrict uri, const size_t len, const unsigned int http_parseopts) { 535 const char *nuri; 536 if ((len > 7 && buffer_eq_icase_ssn(uri, "http://", 7) 537 && NULL != (nuri = memchr(uri + 7, '/', len-7))) 538 || 539 (len > 8 && buffer_eq_icase_ssn(uri, "https://", 8) 540 && NULL != (nuri = memchr(uri + 8, '/', len-8)))) { 541 const char * const host = uri + (uri[4] == ':' ? 7 : 8); 542 const size_t hostlen = nuri - host; 543 if (0 == hostlen || hostlen >= 1024) { /*(expecting < 256)*/ 544 http_request_header_line_invalid(r, 400, "uri-authority empty or too long -> 400"); 545 return NULL; 546 } 547 /* Insert as host header */ 548 http_header_request_set(r, HTTP_HEADER_HOST, CONST_STR_LEN("Host"), host, hostlen); 549 r->http_host = http_header_request_get(r, HTTP_HEADER_HOST, CONST_STR_LEN("Host")); 550 return nuri; 551 } else if (!(http_parseopts & HTTP_PARSEOPT_HEADER_STRICT) /*(!http_header_strict)*/ 552 || (HTTP_METHOD_CONNECT == r->http_method && (uri[0] == ':' || light_isdigit(uri[0]))) 553 || (HTTP_METHOD_OPTIONS == r->http_method && uri[0] == '*' && 1 == len)) { 554 /* (permitted) */ 555 return uri; 556 } else { 557 http_request_header_line_invalid(r, 400, "request-URI parse error -> 400"); 558 return NULL; 559 } 560 } 561 562 static int http_request_parse_pseudohdrs(request_st * const restrict r, const char * const restrict ptr, const unsigned short * const restrict hoff, const unsigned int http_parseopts) { 563 /* HTTP/2 request pseudo-header fields */ 564 const unsigned int http_header_strict = (http_parseopts & HTTP_PARSEOPT_HEADER_STRICT); 565 int scheme = 0; 566 uint32_t ulen = 0, alen = 0; 567 const char *uri = NULL; 568 for (int i = 1; i < hoff[0]; ++i) { 569 const char *k = ptr + ((i > 1) ? hoff[i] : 0); 570 /* one past last line hoff[hoff[0]] is to final "\r\n" */ 571 const char *end = ptr + hoff[i+1]; 572 573 if (*k != ':') 574 break; 575 ++k; 576 const char *colon = memchr(k, ':', end - k); 577 if (NULL == colon) 578 return http_request_header_line_invalid(r, 400, "invalid header missing ':' -> 400"); 579 580 const int klen = (int)(colon - k); 581 if (0 == klen) 582 return http_request_header_line_invalid(r, 400, "invalid header key -> 400"); 583 584 const char *v = colon + 1; 585 /* remove leading whitespace from value */ 586 while (*v == ' ' || *v == '\t') ++v; 587 588 #ifdef __COVERITY__ 589 /*(ptr has at least ::\r\n by now, so end[-2] valid)*/ 590 force_assert(end >= k + 1); 591 #endif 592 /* remove trailing whitespace from value (+ remove '\r\n') */ 593 if (end[-2] == '\r') 594 --end; 595 else if (http_header_strict) 596 return http_request_header_line_invalid(r, 400, "missing CR before LF in header -> 400"); 597 --end; 598 while (v > end && (end[-1] == ' ' || end[-1] == '\t')) --end; 599 600 const int vlen = (int)(end - v); 601 if (vlen <= 0) 602 return http_request_header_line_invalid(r, 400, "invalid pseudo-header -> 400"); 603 604 switch (klen) { 605 case 4: 606 if (0 == memcmp(k, "path", 4)) { 607 if (NULL != uri) 608 return http_request_header_line_invalid(r, 400, "repeated pseudo-header -> 400"); 609 uri = v; 610 ulen = (uint32_t)vlen; 611 continue; 612 } 613 break; 614 case 6: 615 if (0 == memcmp(k, "method", 6)) { 616 if (HTTP_METHOD_UNSET != r->http_method) 617 return http_request_header_line_invalid(r, 400, "repeated pseudo-header -> 400"); 618 r->http_method = get_http_method_key(v, vlen); 619 if (HTTP_METHOD_UNSET >= r->http_method) 620 return http_request_header_line_invalid(r, 501, "unknown http-method -> 501"); 621 continue; 622 } 623 else if (0 == memcmp(k, "scheme", 6)) { 624 if (scheme) 625 return http_request_header_line_invalid(r, 400, "repeated pseudo-header -> 400"); 626 switch (vlen) { /*(validated, but then value is ignored)*/ 627 case 5: /* "https" */ 628 if (v[4]!='s') break; 629 __attribute_fallthrough__ 630 case 4: /* "http" */ 631 if (v[0]=='h' && v[1]=='t' && v[2]=='t' && v[3]=='p') { 632 scheme = 1; 633 continue; 634 } 635 break; 636 default: 637 break; 638 } 639 return http_request_header_line_invalid(r, 400, "unknown pseudo-header scheme -> 400"); 640 } 641 break; 642 case 9: 643 if (0 == memcmp(k, "authority", 9)) { 644 if (r->http_host) 645 return http_request_header_line_invalid(r, 400, "repeated pseudo-header -> 400"); 646 if (vlen >= 1024) /*(expecting < 256)*/ 647 return http_request_header_line_invalid(r, 400, "invalid pseudo-header authority too long -> 400"); 648 alen = (uint32_t)vlen; 649 /* insert as host header */ 650 http_header_request_set(r, HTTP_HEADER_HOST, CONST_STR_LEN("host"), v, vlen); 651 r->http_host = http_header_request_get(r, HTTP_HEADER_HOST, CONST_STR_LEN("Host")); 652 continue; 653 } 654 break; 655 default: 656 break; 657 } 658 return http_request_header_line_invalid(r, 400, "invalid pseudo-header -> 400"); 659 } 660 661 /* :method is required to indicate method 662 * CONNECT method must have :method and :authority 663 * All other methods must have at least :method :scheme :path */ 664 665 if (HTTP_METHOD_UNSET == r->http_method) 666 return http_request_header_line_invalid(r, 400, "missing pseudo-header method -> 400"); 667 668 if (HTTP_METHOD_CONNECT != r->http_method) { 669 if (!scheme) 670 return http_request_header_line_invalid(r, 400, "missing pseudo-header scheme -> 400"); 671 672 if (NULL == uri) 673 return http_request_header_line_invalid(r, 400, "missing pseudo-header path -> 400"); 674 675 if (*uri != '/') { /* (common case: (*uri == '/')) */ 676 if (*uri != '*' || ulen != 1 || HTTP_METHOD_OPTIONS != r->http_method) 677 return http_request_header_line_invalid(r, 400, "invalid pseudo-header path -> 400"); 678 } 679 } 680 else { /* HTTP_METHOD_CONNECT */ 681 if (NULL == r->http_host) 682 return http_request_header_line_invalid(r, 400, "missing pseudo-header authority -> 400"); 683 if (NULL != uri || scheme) 684 return http_request_header_line_invalid(r, 400, "invalid pseudo-header with CONNECT -> 400"); 685 /*(reuse uri and ulen to assign to r->target)*/ 686 uri = r->http_host->ptr; 687 ulen = alen; 688 } 689 690 /* r->http_host, if set, is checked with http_request_host_policy() 691 * in http_request_parse() */ 692 693 /* copied from end of http_request_parse_reqline() */ 694 695 /* check uri for invalid characters */ 696 if (http_header_strict) { 697 if ((http_parseopts & HTTP_PARSEOPT_URL_NORMALIZE_CTRLS_REJECT)) { 698 /* URI will be checked in http_request_parse_target() */ 699 } 700 else { 701 for (uint32_t i = 0; i < ulen; ++i) { 702 if (!request_uri_is_valid_char(uri[i])) 703 return http_request_header_char_invalid(r, uri[i], "invalid character in URI -> 400"); 704 } 705 } 706 } 707 else { 708 /* check entire set of request headers for '\0' */ 709 if (NULL != memchr(ptr, '\0', hoff[hoff[0]])) 710 return http_request_header_char_invalid(r, '\0', "invalid character in header -> 400"); 711 } 712 713 buffer_copy_string_len(&r->target, uri, ulen); 714 buffer_copy_string_len(&r->target_orig, uri, ulen); 715 return 0; 716 } 717 718 static int http_request_parse_reqline(request_st * const restrict r, const char * const restrict ptr, const unsigned short * const restrict hoff, const unsigned int http_parseopts) { 719 size_t len = hoff[2]; 720 721 /* parse the first line of the request 722 * <method> <uri> <protocol>\r\n 723 * */ 724 if (len < 13) /* minimum len with (!http_header_strict): "x x HTTP/1.0\n" */ 725 return http_request_header_line_invalid(r, 400, "invalid request line (too short) -> 400"); 726 if (ptr[len-2] == '\r') 727 len-=2; 728 else if (!(http_parseopts & HTTP_PARSEOPT_HEADER_STRICT)) /*(!http_header_strict)*/ 729 len-=1; 730 else 731 return http_request_header_line_invalid(r, 400, "missing CR before LF in header -> 400"); 732 733 /* 734 * RFC7230: 735 * HTTP-version = HTTP-name "/" DIGIT "." DIGIT 736 * HTTP-name = %x48.54.54.50 ; "HTTP", case-sensitive 737 */ 738 739 /* protocol is expected to be " HTTP/1.1" or " HTTP/1.0" at end of line */ 740 union proto_un { 741 char c[8]; 742 uint64_t u; 743 }; 744 static const union proto_un http_1_1 = {{'H','T','T','P','/','1','.','1'}}; 745 static const union proto_un http_1_0 = {{'H','T','T','P','/','1','.','0'}}; 746 const char *p = ptr + len - 8; 747 union proto_un proto8; 748 proto8.c[0]=p[0]; proto8.c[1]=p[1]; proto8.c[2]=p[2]; proto8.c[3]=p[3]; 749 proto8.c[4]=p[4]; proto8.c[5]=p[5]; proto8.c[6]=p[6]; proto8.c[7]=p[7]; 750 if (p[-1] == ' ' && http_1_1.u == proto8.u) { 751 r->http_version = HTTP_VERSION_1_1; 752 r->keep_alive = 1; /* keep-alive default: HTTP/1.1 -> true */ 753 } 754 else if (p[-1] == ' ' && http_1_0.u == proto8.u) { 755 r->http_version = HTTP_VERSION_1_0; 756 r->keep_alive = 0; /* keep-alive default: HTTP/1.0 -> false */ 757 } 758 else { 759 int status = http_request_parse_proto_loose(r,ptr,len,http_parseopts); 760 if (0 != status) return status; 761 /*(space char must exist if http_request_parse_proto_loose() succeeds)*/ 762 for (p = ptr + len - 9; p[-1] != ' '; --p) ; 763 } 764 765 /* method is expected to be a short string in the general case */ 766 size_t i = 0; 767 while (ptr[i] != ' ') ++i; 768 #if 0 /*(space must exist if protocol was parsed successfully)*/ 769 while (i < len && ptr[i] != ' ') ++i; 770 if (ptr[i] != ' ') 771 return http_request_header_line_invalid(r, 400, "incomplete request line -> 400"); 772 #endif 773 774 r->http_method = get_http_method_key(ptr, i); 775 if (HTTP_METHOD_UNSET >= r->http_method) 776 return http_request_header_line_invalid(r, 501, "unknown http-method -> 501"); 777 778 const char *uri = ptr + i + 1; 779 780 if (uri == p) 781 return http_request_header_line_invalid(r, 400, "no uri specified -> 400"); 782 len = (size_t)(p - uri - 1); 783 784 if (*uri != '/') { /* (common case: (*uri == '/')) */ 785 uri = http_request_parse_reqline_uri(r, uri, len, http_parseopts); 786 if (NULL == uri) return 400; 787 len = (size_t)(p - uri - 1); 788 } 789 790 if (0 == len) 791 return http_request_header_line_invalid(r, 400, "no uri specified -> 400"); 792 793 /* check uri for invalid characters */ 794 if (http_parseopts & HTTP_PARSEOPT_HEADER_STRICT) { /* http_header_strict */ 795 if ((http_parseopts & HTTP_PARSEOPT_URL_NORMALIZE_CTRLS_REJECT)) { 796 /* URI will be checked in http_request_parse_target() */ 797 } 798 else { 799 for (i = 0; i < len; ++i) { 800 if (!request_uri_is_valid_char(uri[i])) 801 return http_request_header_char_invalid(r, uri[i], "invalid character in URI -> 400"); 802 } 803 } 804 } 805 else { 806 /* check entire set of request headers for '\0' */ 807 if (NULL != memchr(ptr, '\0', hoff[hoff[0]])) 808 return http_request_header_char_invalid(r, '\0', "invalid character in header -> 400"); 809 } 810 811 buffer_copy_string_len(&r->target, uri, len); 812 buffer_copy_string_len(&r->target_orig, uri, len); 813 return 0; 814 } 815 816 int http_request_parse_target(request_st * const r, int scheme_port) { 817 /* URI is parsed into components at start of request and may 818 * also be re-parsed upon HANDLER_COMEBACK during the request 819 * r->target is expected to be a "/url-part?query-part" 820 * (and *not* a fully-qualified URI starting https://...) 821 * r->uri.authority is expected to be parsed elsewhere into r->http_host 822 */ 823 824 /** 825 * prepare strings 826 * 827 * - uri.path 828 * - uri.query 829 * 830 */ 831 832 /** 833 * Name according to RFC 2396 834 * 835 * - scheme 836 * - authority 837 * - path 838 * - query 839 * 840 * (scheme)://(authority)(path)?(query)#fragment 841 * 842 */ 843 844 /* take initial scheme value from connection-level state 845 * (request r->uri.scheme can be overwritten for later, 846 * for example by mod_extforward or mod_magnet) */ 847 if (scheme_port == 443) 848 buffer_copy_string_len(&r->uri.scheme, CONST_STR_LEN("https")); 849 else 850 buffer_copy_string_len(&r->uri.scheme, CONST_STR_LEN("http")); 851 852 buffer * const target = &r->target; 853 if (r->http_method == HTTP_METHOD_CONNECT 854 || (r->http_method == HTTP_METHOD_OPTIONS 855 && target->ptr[0] == '*' 856 && target->ptr[1] == '\0')) { 857 /* CONNECT ... (or) OPTIONS * ... */ 858 buffer_copy_buffer(&r->uri.path, target); 859 buffer_clear(&r->uri.query); 860 return 0; 861 } 862 863 char *qstr; 864 if (r->conf.http_parseopts & HTTP_PARSEOPT_URL_NORMALIZE) { 865 /*uint32_t len = (uint32_t)buffer_string_length(target);*/ 866 int qs = burl_normalize(target, r->tmp_buf, r->conf.http_parseopts); 867 if (-2 == qs) { 868 log_error(r->conf.errh, __FILE__, __LINE__, 869 "invalid character in URI -> 400 %s", 870 target->ptr); 871 return 400; /* Bad Request */ 872 } 873 qstr = (-1 == qs) ? NULL : target->ptr+qs; 874 #if 0 /* future: might enable here, or below for all requests */ 875 /* (Note: total header size not recalculated on HANDLER_COMEBACK 876 * even if other request headers changed during processing) 877 * (If (0 != r->loops_per_request), then the generated 878 * request is too large. Should a different error be returned?) */ 879 r->rqst_header_len -= len; 880 len = buffer_string_length(target); 881 r->rqst_header_len += len; 882 if (len > MAX_HTTP_REQUEST_URI) { 883 return 414; /* 414 Request-URI Too Long */ 884 } 885 if (r->rqst_header_len > MAX_HTTP_REQUEST_HEADER) { 886 log_error(r->conf.errh, __FILE__, __LINE__, 887 "request header fields too large: %u -> 431", 888 r->rqst_header_len); 889 return 431; /* Request Header Fields Too Large */ 890 } 891 #endif 892 } 893 else { 894 size_t rlen = buffer_string_length(target); 895 qstr = memchr(target->ptr, '#', rlen);/* discard fragment */ 896 if (qstr) { 897 rlen = (size_t)(qstr - target->ptr); 898 buffer_string_set_length(target, rlen); 899 } 900 qstr = memchr(target->ptr, '?', rlen); 901 } 902 903 /** extract query string from target */ 904 const char * const pstr = target->ptr; 905 const uint32_t rlen = buffer_string_length(target); 906 uint32_t plen; 907 if (NULL != qstr) { 908 plen = (uint32_t)(qstr - pstr); 909 buffer_copy_string_len(&r->uri.query, qstr + 1, rlen - plen - 1); 910 } 911 else { 912 plen = rlen; 913 buffer_clear(&r->uri.query); 914 } 915 buffer_copy_string_len(&r->uri.path, pstr, plen); 916 917 /* decode url to path 918 * 919 * - decode url-encodings (e.g. %20 -> ' ') 920 * - remove path-modifiers (e.g. /../) 921 */ 922 923 buffer_urldecode_path(&r->uri.path); 924 buffer_path_simplify(&r->uri.path, &r->uri.path); 925 if (r->uri.path.ptr[0] != '/') { 926 log_error(r->conf.errh, __FILE__, __LINE__, 927 "uri-path does not begin with '/': %s -> 400", r->uri.path.ptr); 928 return 400; /* Bad Request */ 929 } 930 931 return 0; 932 } 933 934 __attribute_cold__ 935 __attribute_noinline__ 936 static int http_request_parse_header_other(request_st * const restrict r, const char * const restrict k, const int klen, const unsigned int http_header_strict) { 937 for (int i = 0; i < klen; ++i) { 938 if (light_isalpha(k[i]) || k[i] == '-') continue; /*(common cases)*/ 939 /** 940 * 1*<any CHAR except CTLs or separators> 941 * CTLs == 0-31 + 127, CHAR = 7-bit ascii (0..127) 942 * 943 */ 944 switch(k[i]) { 945 case ' ': 946 case '\t': 947 return http_request_header_line_invalid(r, 400, "WS character in key -> 400"); 948 case '(': 949 case ')': 950 case '<': 951 case '>': 952 case '@': 953 case ',': 954 case ';': 955 case '\\': 956 case '\"': 957 case '/': 958 case '[': 959 case ']': 960 case '?': 961 case '=': 962 case '{': 963 case '}': 964 return http_request_header_char_invalid(r, k[i], "invalid character in header key -> 400"); 965 default: 966 if (http_header_strict ? (k[i] < 32 || ((unsigned char *)k)[i] >= 127) : k[i] == '\0') 967 return http_request_header_char_invalid(r, k[i], "invalid character in header key -> 400"); 968 break; /* ok */ 969 } 970 } 971 return 0; 972 } 973 974 static int http_request_parse_headers(request_st * const restrict r, char * const restrict ptr, const unsigned short * const restrict hoff, const unsigned int http_parseopts) { 975 const unsigned int http_header_strict = (http_parseopts & HTTP_PARSEOPT_HEADER_STRICT); 976 977 #if 0 /*(not checked here; will later result in invalid label for HTTP header)*/ 978 int i = hoff[2]; 979 980 if (ptr[i] == ' ' || ptr[i] == '\t') { 981 return http_request_header_line_invalid(r, 400, "WS at the start of first line -> 400"); 982 } 983 #endif 984 985 int i = 2; 986 if (r->http_version >= HTTP_VERSION_2) { 987 /* CONNECT must have :method and :authority 988 * All other methods must have at least :method :scheme :path */ 989 i += (r->http_method != HTTP_METHOD_CONNECT) ? 2 : 1; 990 while (ptr[hoff[i]] == ':') ++i; 991 } 992 993 for (; i < hoff[0]; ++i) { 994 const char *k = ptr + hoff[i]; 995 /* one past last line hoff[hoff[0]] is to final "\r\n" */ 996 char *end = ptr + hoff[i+1]; 997 998 const char *colon = memchr(k, ':', end - k); 999 if (NULL == colon) 1000 return http_request_header_line_invalid(r, 400, "invalid header missing ':' -> 400"); 1001 1002 const char *v = colon + 1; 1003 1004 /* RFC7230 Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing 1005 * 3.2.4. Field Parsing 1006 * [...] 1007 * No whitespace is allowed between the header field-name and colon. In 1008 * the past, differences in the handling of such whitespace have led to 1009 * security vulnerabilities in request routing and response handling. A 1010 * server MUST reject any received request message that contains 1011 * whitespace between a header field-name and colon with a response code 1012 * of 400 (Bad Request). A proxy MUST remove any such whitespace from a 1013 * response message before forwarding the message downstream. 1014 */ 1015 /* (line k[-1] is always preceded by a '\n', 1016 * including first header after request-line, 1017 * so no need to check colon != k) */ 1018 if (colon[-1] == ' ' || colon[-1] == '\t') { 1019 if (http_header_strict) { 1020 return http_request_header_line_invalid(r, 400, "invalid whitespace between field-name and colon -> 400"); 1021 } 1022 else { 1023 /* remove trailing whitespace from key(if !http_header_strict)*/ 1024 do { --colon; } while (colon[-1] == ' ' || colon[-1] == '\t'); 1025 } 1026 } 1027 1028 const int klen = (int)(colon - k); 1029 if (0 == klen) 1030 return http_request_header_line_invalid(r, 400, "invalid header key -> 400"); 1031 const enum http_header_e id = http_header_hkey_get(k, klen); 1032 1033 if (id == HTTP_HEADER_OTHER) { 1034 for (int j = 0; j < klen; ++j) { 1035 if (light_isalpha(k[j]) || k[j] == '-') continue; /*(common cases)*/ 1036 if (0 != http_request_parse_header_other(r, k+j, klen-j, http_header_strict)) 1037 return 400; 1038 break; 1039 } 1040 } 1041 1042 /* remove leading whitespace from value */ 1043 while (*v == ' ' || *v == '\t') ++v; 1044 1045 for (; i+1 <= hoff[0]; ++i) { 1046 end = ptr + hoff[i+1]; 1047 if (end[0] != ' ' && end[0] != '\t') break; 1048 1049 /* line folding */ 1050 #ifdef __COVERITY__ 1051 force_assert(end - k >= 2); 1052 #endif 1053 if (end[-2] == '\r') 1054 end[-2] = ' '; 1055 else if (http_header_strict) 1056 return http_request_header_line_invalid(r, 400, "missing CR before LF in header -> 400"); 1057 end[-1] = ' '; 1058 } 1059 #ifdef __COVERITY__ 1060 /*(buf holding k has non-zero request-line, so end[-2] valid)*/ 1061 force_assert(end >= k + 2); 1062 #endif 1063 if (end[-2] == '\r') 1064 --end; 1065 else if (http_header_strict) 1066 return http_request_header_line_invalid(r, 400, "missing CR before LF in header -> 400"); 1067 /* remove trailing whitespace from value (+ remove '\r\n') */ 1068 /* (line k[-1] is always preceded by a '\n', 1069 * including first header after request-line, 1070 * so no need to check (end != k)) */ 1071 do { --end; } while (end[-1] == ' ' || end[-1] == '\t'); 1072 1073 const int vlen = (int)(end - v); 1074 /* empty header-fields are not allowed by HTTP-RFC, we just ignore them */ 1075 if (vlen <= 0) continue; /* ignore header */ 1076 1077 if (http_header_strict) { 1078 for (int j = 0; j < vlen; ++j) { 1079 if ((((unsigned char *)v)[j] < 32 && v[j] != '\t') || v[j]==127) 1080 return http_request_header_char_invalid(r, v[j], "invalid character in header -> 400"); 1081 } 1082 } /* else URI already checked in http_request_parse_reqline() for any '\0' */ 1083 1084 int status = http_request_parse_single_header(r, id, k, (size_t)klen, v, (size_t)vlen); 1085 if (0 != status) return status; 1086 } 1087 1088 return 0; 1089 } 1090 1091 1092 static int 1093 http_request_parse (request_st * const restrict r, char * const restrict hdrs, const unsigned short * const restrict hoff, const int scheme_port) 1094 { 1095 /* 1096 * Request: "^(GET|POST|HEAD|...) ([^ ]+(\\?[^ ]+|)) (HTTP/1\\.[01])$" 1097 * Header : "^([-a-zA-Z]+): (.+)$" 1098 * End : "^$" 1099 */ 1100 1101 int status; 1102 const unsigned int http_parseopts = r->conf.http_parseopts; 1103 1104 status = (r->http_version >= HTTP_VERSION_2) 1105 ? http_request_parse_pseudohdrs(r, hdrs, hoff, http_parseopts) 1106 : http_request_parse_reqline(r, hdrs, hoff, http_parseopts); 1107 if (0 != status) return status; 1108 1109 status = http_request_parse_target(r, scheme_port); 1110 if (0 != status) return status; 1111 1112 status = http_request_parse_headers(r, hdrs, hoff, http_parseopts); 1113 if (0 != status) return status; 1114 1115 /*(r->http_host might not be set until after parsing request headers)*/ 1116 buffer_copy_buffer(&r->uri.authority, r->http_host);/*(copy even if empty)*/ 1117 buffer_to_lower(&r->uri.authority); 1118 1119 /* post-processing */ 1120 1121 /* check hostname field if it is set */ 1122 if (r->http_host) { 1123 if (0 != http_request_host_policy(r->http_host, 1124 http_parseopts, scheme_port)) 1125 return http_request_header_line_invalid(r, 400, "Invalid Hostname -> 400"); 1126 } 1127 else { 1128 if (r->http_version >= HTTP_VERSION_1_1) 1129 return http_request_header_line_invalid(r, 400, "HTTP/1.1 but Host missing -> 400"); 1130 } 1131 1132 if (0 == r->reqbody_length) { 1133 /* POST requires Content-Length (or Transfer-Encoding) 1134 * (-1 == r->reqbody_length when Transfer-Encoding: chunked)*/ 1135 if (HTTP_METHOD_POST == r->http_method 1136 && !(r->rqst_htags & HTTP_HEADER_CONTENT_LENGTH)) { 1137 return http_request_header_line_invalid(r, 411, "POST-request, but content-length missing -> 411"); 1138 } 1139 } 1140 else { 1141 /* (-1 == r->reqbody_length when Transfer-Encoding: chunked)*/ 1142 if (-1 == r->reqbody_length 1143 && (r->rqst_htags & HTTP_HEADER_CONTENT_LENGTH)) { 1144 /* RFC7230 Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing 1145 * 3.3.3. Message Body Length 1146 * [...] 1147 * If a message is received with both a Transfer-Encoding and a 1148 * Content-Length header field, the Transfer-Encoding overrides the 1149 * Content-Length. Such a message might indicate an attempt to 1150 * perform request smuggling (Section 9.5) or response splitting 1151 * (Section 9.4) and ought to be handled as an error. A sender MUST 1152 * remove the received Content-Length field prior to forwarding such 1153 * a message downstream. 1154 */ 1155 const unsigned int http_header_strict = 1156 (http_parseopts & HTTP_PARSEOPT_HEADER_STRICT); 1157 if (http_header_strict) { 1158 return http_request_header_line_invalid(r, 400, "invalid Transfer-Encoding + Content-Length -> 400"); 1159 } 1160 else { 1161 /* ignore Content-Length */ 1162 http_header_request_unset(r, HTTP_HEADER_CONTENT_LENGTH, CONST_STR_LEN("Content-Length")); 1163 } 1164 } 1165 if (http_method_get_or_head(r->http_method) 1166 && !(http_parseopts & HTTP_PARSEOPT_METHOD_GET_BODY)) { 1167 return http_request_header_line_invalid(r, 400, "GET/HEAD with content-length -> 400"); 1168 } 1169 } 1170 1171 return 0; 1172 } 1173 1174 1175 void 1176 http_request_headers_process (request_st * const restrict r, char * const restrict hdrs, const unsigned short * const restrict hoff, const int scheme_port) 1177 { 1178 r->http_status = http_request_parse(r, hdrs, hoff, scheme_port); 1179 1180 if (0 == r->http_status) { 1181 #if 0 1182 r->conditional_is_valid = (1 << COMP_SERVER_SOCKET) 1183 | (1 << COMP_HTTP_SCHEME) 1184 | (1 << COMP_HTTP_HOST) 1185 | (1 << COMP_HTTP_REMOTE_IP) 1186 | (1 << COMP_HTTP_REQUEST_METHOD) 1187 | (1 << COMP_HTTP_URL) 1188 | (1 << COMP_HTTP_QUERY_STRING) 1189 | (1 << COMP_HTTP_REQUEST_HEADER); 1190 #else 1191 /* all config conditions are valid after parsing header 1192 * (set all bits; remove dependency on plugin_config.h) */ 1193 r->conditional_is_valid = ~0u; 1194 #endif 1195 } 1196 else { 1197 r->keep_alive = 0; 1198 r->reqbody_length = 0; 1199 1200 if (r->conf.log_request_header_on_error) { 1201 /*(http_request_parse() modifies hdrs only to 1202 * undo line-wrapping in-place using spaces)*/ 1203 log_error(r->conf.errh, __FILE__, __LINE__, 1204 "request-header:\n%.*s", (int)r->rqst_header_len, hdrs); 1205 } 1206 } 1207 } 1208