1 /* $OpenBSD: constraint.c,v 1.33 2016/10/18 21:57:19 rzalamena Exp $ */ 2 3 /* 4 * Copyright (c) 2015 Reyk Floeter <reyk@openbsd.org> 5 * 6 * Permission to use, copy, modify, and distribute this software for any 7 * purpose with or without fee is hereby granted, provided that the above 8 * copyright notice and this permission notice appear in all copies. 9 * 10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 */ 18 19 #include <sys/queue.h> 20 #include <sys/socket.h> 21 #include <sys/time.h> 22 #include <sys/types.h> 23 #include <sys/wait.h> 24 #include <sys/resource.h> 25 #include <sys/uio.h> 26 27 #include <netinet/in.h> 28 #include <arpa/inet.h> 29 30 #include <errno.h> 31 #include <stdio.h> 32 #include <stdlib.h> 33 #include <fcntl.h> 34 #include <imsg.h> 35 #include <netdb.h> 36 #include <poll.h> 37 #include <signal.h> 38 #include <string.h> 39 #include <unistd.h> 40 #include <time.h> 41 #include <ctype.h> 42 #include <tls.h> 43 #include <pwd.h> 44 45 #include "ntpd.h" 46 47 int constraint_addr_init(struct constraint *); 48 struct constraint * 49 constraint_byid(u_int32_t); 50 struct constraint * 51 constraint_byfd(int); 52 struct constraint * 53 constraint_bypid(pid_t); 54 int constraint_close(u_int32_t); 55 void constraint_update(void); 56 void constraint_reset(void); 57 int constraint_cmp(const void *, const void *); 58 59 void priv_constraint_close(int, int); 60 void priv_constraint_readquery(struct constraint *, struct ntp_addr_msg *, 61 uint8_t **); 62 63 struct httpsdate * 64 httpsdate_init(const char *, const char *, const char *, 65 const char *, const u_int8_t *, size_t); 66 void httpsdate_free(void *); 67 int httpsdate_request(struct httpsdate *, struct timeval *); 68 void *httpsdate_query(const char *, const char *, const char *, 69 const char *, const u_int8_t *, size_t, 70 struct timeval *, struct timeval *); 71 72 char *tls_readline(struct tls *, size_t *, size_t *, struct timeval *); 73 74 u_int constraint_cnt; 75 extern u_int peer_cnt; 76 extern struct imsgbuf *ibuf; /* priv */ 77 extern struct imsgbuf *ibuf_main; /* chld */ 78 79 struct httpsdate { 80 char *tls_addr; 81 char *tls_port; 82 char *tls_hostname; 83 char *tls_path; 84 char *tls_request; 85 struct tls_config *tls_config; 86 struct tls *tls_ctx; 87 struct tm tls_tm; 88 }; 89 90 int 91 constraint_init(struct constraint *cstr) 92 { 93 cstr->state = STATE_NONE; 94 cstr->fd = -1; 95 cstr->last = getmonotime(); 96 cstr->constraint = 0; 97 cstr->senderrors = 0; 98 99 return (constraint_addr_init(cstr)); 100 } 101 102 int 103 constraint_addr_init(struct constraint *cstr) 104 { 105 struct sockaddr_in *sa_in; 106 struct sockaddr_in6 *sa_in6; 107 struct ntp_addr *h; 108 109 if (cstr->state == STATE_DNS_INPROGRESS) 110 return (0); 111 112 if (cstr->addr_head.a == NULL) { 113 priv_dns(IMSG_CONSTRAINT_DNS, cstr->addr_head.name, cstr->id); 114 cstr->state = STATE_DNS_INPROGRESS; 115 return (0); 116 } 117 118 h = cstr->addr; 119 switch (h->ss.ss_family) { 120 case AF_INET: 121 sa_in = (struct sockaddr_in *)&h->ss; 122 if (ntohs(sa_in->sin_port) == 0) 123 sa_in->sin_port = htons(443); 124 cstr->state = STATE_DNS_DONE; 125 break; 126 case AF_INET6: 127 sa_in6 = (struct sockaddr_in6 *)&h->ss; 128 if (ntohs(sa_in6->sin6_port) == 0) 129 sa_in6->sin6_port = htons(443); 130 cstr->state = STATE_DNS_DONE; 131 break; 132 default: 133 /* XXX king bula sez it? */ 134 fatalx("wrong AF in constraint_addr_init"); 135 /* NOTREACHED */ 136 } 137 138 return (1); 139 } 140 141 int 142 constraint_query(struct constraint *cstr) 143 { 144 time_t now; 145 struct ntp_addr_msg am; 146 struct iovec iov[3]; 147 int iov_cnt = 0; 148 149 now = getmonotime(); 150 151 switch (cstr->state) { 152 case STATE_DNS_DONE: 153 /* Proceed and query the time */ 154 break; 155 case STATE_DNS_TEMPFAIL: 156 /* Retry resolving the address */ 157 constraint_init(cstr); 158 return (-1); 159 case STATE_QUERY_SENT: 160 if (cstr->last + CONSTRAINT_SCAN_TIMEOUT > now) { 161 /* The caller should expect a reply */ 162 return (0); 163 } 164 165 /* Timeout, just kill the process to reset it. */ 166 imsg_compose(ibuf_main, IMSG_CONSTRAINT_KILL, 167 cstr->id, 0, -1, NULL, 0); 168 169 cstr->state = STATE_TIMEOUT; 170 return (-1); 171 case STATE_INVALID: 172 if (cstr->last + CONSTRAINT_SCAN_INTERVAL > now) { 173 /* Nothing to do */ 174 return (-1); 175 } 176 177 /* Reset and retry */ 178 cstr->senderrors = 0; 179 constraint_close(cstr->id); 180 break; 181 case STATE_REPLY_RECEIVED: 182 default: 183 /* Nothing to do */ 184 return (-1); 185 } 186 187 cstr->last = now; 188 cstr->state = STATE_QUERY_SENT; 189 190 memset(&am, 0, sizeof(am)); 191 memcpy(&am.a, cstr->addr, sizeof(am.a)); 192 193 iov[iov_cnt].iov_base = &am; 194 iov[iov_cnt++].iov_len = sizeof(am); 195 if (cstr->addr_head.name) { 196 am.namelen = strlen(cstr->addr_head.name) + 1; 197 iov[iov_cnt].iov_base = cstr->addr_head.name; 198 iov[iov_cnt++].iov_len = am.namelen; 199 } 200 if (cstr->addr_head.path) { 201 am.pathlen = strlen(cstr->addr_head.path) + 1; 202 iov[iov_cnt].iov_base = cstr->addr_head.path; 203 iov[iov_cnt++].iov_len = am.pathlen; 204 } 205 206 imsg_composev(ibuf_main, IMSG_CONSTRAINT_QUERY, 207 cstr->id, 0, -1, iov, iov_cnt); 208 209 return (0); 210 } 211 212 void 213 priv_constraint_msg(u_int32_t id, u_int8_t *data, size_t len, int argc, 214 char **argv) 215 { 216 struct ntp_addr_msg am; 217 struct ntp_addr *h; 218 struct constraint *cstr; 219 int pipes[2]; 220 221 if ((cstr = constraint_byid(id)) != NULL) { 222 log_warnx("IMSG_CONSTRAINT_QUERY repeated for id %d", id); 223 return; 224 } 225 226 if (len < sizeof(am)) { 227 log_warnx("invalid IMSG_CONSTRAINT_QUERY received"); 228 return; 229 } 230 memcpy(&am, data, sizeof(am)); 231 if (len != (sizeof(am) + am.namelen + am.pathlen)) { 232 log_warnx("invalid IMSG_CONSTRAINT_QUERY received"); 233 return; 234 } 235 /* Additional imsg data is obtained in the unpriv child */ 236 237 if ((h = calloc(1, sizeof(*h))) == NULL) 238 fatal("calloc ntp_addr"); 239 memcpy(h, &am.a, sizeof(*h)); 240 h->next = NULL; 241 242 cstr = new_constraint(); 243 cstr->id = id; 244 cstr->addr = h; 245 cstr->addr_head.a = h; 246 constraint_add(cstr); 247 constraint_cnt++; 248 249 if (socketpair(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, AF_UNSPEC, 250 pipes) == -1) 251 fatal("%s pipes", __func__); 252 253 /* Prepare and send constraint data to child. */ 254 cstr->fd = pipes[0]; 255 imsg_init(&cstr->ibuf, cstr->fd); 256 if (imsg_compose(&cstr->ibuf, IMSG_CONSTRAINT_QUERY, id, 0, -1, 257 data, len) == -1) 258 fatal("%s: imsg_compose", __func__); 259 if (imsg_flush(&cstr->ibuf) == -1) 260 fatal("%s: imsg_flush", __func__); 261 262 /* 263 * Fork child handlers and make sure to do any sensitive work in the 264 * the (unprivileged) child. The parent should not do any parsing, 265 * certificate loading etc. 266 */ 267 cstr->pid = start_child(CONSTRAINT_PROC_NAME, pipes[1], argc, argv); 268 } 269 270 void 271 priv_constraint_readquery(struct constraint *cstr, struct ntp_addr_msg *am, 272 uint8_t **data) 273 { 274 struct ntp_addr *h; 275 uint8_t *dptr; 276 int n; 277 struct imsg imsg; 278 size_t mlen; 279 280 /* Read the message our parent left us. */ 281 if (((n = imsg_read(&cstr->ibuf)) == -1 && errno != EAGAIN) || n == 0) 282 fatal("%s: imsg_read", __func__); 283 if (((n = imsg_get(&cstr->ibuf, &imsg)) == -1) || n == 0) 284 fatal("%s: imsg_get", __func__); 285 if (imsg.hdr.type != IMSG_CONSTRAINT_QUERY) 286 fatalx("%s: invalid message type", __func__); 287 288 /* 289 * Copy the message contents just like our father: 290 * priv_constraint_msg(). 291 */ 292 mlen = imsg.hdr.len - IMSG_HEADER_SIZE; 293 if (mlen < sizeof(*am)) 294 fatalx("%s: mlen < sizeof(*am)", __func__); 295 296 memcpy(am, imsg.data, sizeof(*am)); 297 if (mlen != (sizeof(*am) + am->namelen + am->pathlen)) 298 fatalx("%s: mlen < sizeof(*am) + am->namelen + am->pathlen", 299 __func__); 300 301 if ((h = calloc(1, sizeof(*h))) == NULL || 302 (*data = calloc(1, mlen)) == NULL) 303 fatal("%s: calloc", __func__); 304 305 memcpy(h, &am->a, sizeof(*h)); 306 h->next = NULL; 307 308 cstr->id = imsg.hdr.peerid; 309 cstr->addr = h; 310 cstr->addr_head.a = h; 311 312 dptr = imsg.data; 313 memcpy(*data, dptr + sizeof(*am), mlen - sizeof(*am)); 314 imsg_free(&imsg); 315 } 316 317 void 318 priv_constraint_child(const char *pw_dir, uid_t pw_uid, gid_t pw_gid) 319 { 320 struct constraint *cstr; 321 struct ntp_addr_msg *am; 322 uint8_t *data; 323 static char addr[NI_MAXHOST]; 324 struct timeval rectv, xmttv; 325 struct sigaction sa; 326 void *ctx; 327 struct iovec iov[2]; 328 int i; 329 330 log_procinit("constraint"); 331 332 if (setpriority(PRIO_PROCESS, 0, 0) == -1) 333 log_warn("could not set priority"); 334 335 if ((cstr = calloc(1, sizeof(*cstr))) == NULL || 336 (am = calloc(1, sizeof(*am))) == NULL) 337 fatal("%s: calloc", __func__); 338 339 /* Init TLS and load CA certs before chroot() */ 340 if (tls_init() == -1) 341 fatalx("tls_init"); 342 if ((conf->ca = tls_load_file(CONSTRAINT_CA, 343 &conf->ca_len, NULL)) == NULL) 344 fatalx("failed to load constraint ca"); 345 346 if (chroot(pw_dir) == -1) 347 fatal("chroot"); 348 if (chdir("/") == -1) 349 fatal("chdir(\"/\")"); 350 351 if (setgroups(1, &pw_gid) || 352 setresgid(pw_gid, pw_gid, pw_gid) || 353 setresuid(pw_uid, pw_uid, pw_uid)) 354 fatal("can't drop privileges"); 355 356 /* Reset all signal handlers */ 357 memset(&sa, 0, sizeof(sa)); 358 sigemptyset(&sa.sa_mask); 359 sa.sa_flags = SA_RESTART; 360 sa.sa_handler = SIG_DFL; 361 for (i = 1; i < _NSIG; i++) 362 sigaction(i, &sa, NULL); 363 364 if (pledge("stdio inet", NULL) == -1) 365 fatal("pledge"); 366 367 cstr->fd = CONSTRAINT_PASSFD; 368 imsg_init(&cstr->ibuf, cstr->fd); 369 priv_constraint_readquery(cstr, am, &data); 370 371 /* 372 * Get the IP address as name and set the process title accordingly. 373 * This only converts an address into a string and does not trigger 374 * any DNS operation, so it is safe to be called without the dns 375 * pledge. 376 */ 377 if (getnameinfo((struct sockaddr *)&cstr->addr->ss, 378 SA_LEN((struct sockaddr *)&cstr->addr->ss), 379 addr, sizeof(addr), NULL, 0, 380 NI_NUMERICHOST) != 0) 381 fatalx("%s getnameinfo", __func__); 382 383 log_debug("constraint request to %s", addr); 384 setproctitle("constraint from %s", addr); 385 (void)closefrom(CONSTRAINT_PASSFD + 1); 386 387 /* 388 * Set the close-on-exec flag to prevent leaking the communication 389 * channel to any exec'ed child. In theory this could never happen, 390 * constraints don't exec children and pledge() prevents it, 391 * but we keep it as a safety belt; especially for portability. 392 */ 393 if (fcntl(CONSTRAINT_PASSFD, F_SETFD, FD_CLOEXEC) == -1) 394 fatal("%s fcntl F_SETFD", __func__); 395 396 /* Get remaining data from imsg in the unpriv child */ 397 if (am->namelen) { 398 if ((cstr->addr_head.name = 399 get_string(data, am->namelen)) == NULL) 400 fatalx("invalid IMSG_CONSTRAINT_QUERY name"); 401 data += am->namelen; 402 } 403 if (am->pathlen) { 404 if ((cstr->addr_head.path = 405 get_string(data, am->pathlen)) == NULL) 406 fatalx("invalid IMSG_CONSTRAINT_QUERY path"); 407 } 408 409 /* Run! */ 410 if ((ctx = httpsdate_query(addr, 411 CONSTRAINT_PORT, cstr->addr_head.name, cstr->addr_head.path, 412 conf->ca, conf->ca_len, &rectv, &xmttv)) == NULL) { 413 /* Abort with failure but without warning */ 414 exit(1); 415 } 416 417 iov[0].iov_base = &rectv; 418 iov[0].iov_len = sizeof(rectv); 419 iov[1].iov_base = &xmttv; 420 iov[1].iov_len = sizeof(xmttv); 421 imsg_composev(&cstr->ibuf, 422 IMSG_CONSTRAINT_RESULT, 0, 0, -1, iov, 2); 423 imsg_flush(&cstr->ibuf); 424 425 /* Tear down the TLS connection after sending the result */ 426 httpsdate_free(ctx); 427 428 exit(0); 429 } 430 431 void 432 priv_constraint_check_child(pid_t pid, int status) 433 { 434 struct constraint *cstr; 435 int fail, sig; 436 char *signame; 437 438 fail = sig = 0; 439 if (WIFSIGNALED(status)) { 440 sig = WTERMSIG(status); 441 } else if (WIFEXITED(status)) { 442 if (WEXITSTATUS(status) != 0) 443 fail = 1; 444 } else 445 fatalx("unexpected cause of SIGCHLD"); 446 447 if ((cstr = constraint_bypid(pid)) != NULL) { 448 if (sig) { 449 if (sig != SIGTERM) { 450 signame = strsignal(sig) ? 451 strsignal(sig) : "unknown"; 452 log_warnx("constraint %s; " 453 "terminated with signal %d (%s)", 454 log_sockaddr((struct sockaddr *) 455 &cstr->addr->ss), sig, signame); 456 } 457 fail = 1; 458 } 459 460 priv_constraint_close(cstr->fd, fail); 461 } 462 } 463 464 void 465 priv_constraint_kill(u_int32_t id) 466 { 467 struct constraint *cstr; 468 469 if ((cstr = constraint_byid(id)) == NULL) { 470 log_warnx("IMSG_CONSTRAINT_KILL for invalid id %d", id); 471 return; 472 } 473 474 kill(cstr->pid, SIGTERM); 475 } 476 477 struct constraint * 478 constraint_byid(u_int32_t id) 479 { 480 struct constraint *cstr; 481 482 TAILQ_FOREACH(cstr, &conf->constraints, entry) { 483 if (cstr->id == id) 484 return (cstr); 485 } 486 487 return (NULL); 488 } 489 490 struct constraint * 491 constraint_byfd(int fd) 492 { 493 struct constraint *cstr; 494 495 TAILQ_FOREACH(cstr, &conf->constraints, entry) { 496 if (cstr->fd == fd) 497 return (cstr); 498 } 499 500 return (NULL); 501 } 502 503 struct constraint * 504 constraint_bypid(pid_t pid) 505 { 506 struct constraint *cstr; 507 508 TAILQ_FOREACH(cstr, &conf->constraints, entry) { 509 if (cstr->pid == pid) 510 return (cstr); 511 } 512 513 return (NULL); 514 } 515 516 int 517 constraint_close(u_int32_t id) 518 { 519 struct constraint *cstr; 520 521 if ((cstr = constraint_byid(id)) == NULL) { 522 log_warn("%s: id %d: not found", __func__, id); 523 return (0); 524 } 525 526 cstr->last = getmonotime(); 527 528 if (cstr->addr == NULL || (cstr->addr = cstr->addr->next) == NULL) { 529 /* Either a pool or all addresses have been tried */ 530 cstr->addr = cstr->addr_head.a; 531 if (cstr->senderrors) 532 cstr->state = STATE_INVALID; 533 else if (cstr->state >= STATE_QUERY_SENT) 534 cstr->state = STATE_DNS_DONE; 535 536 return (1); 537 } 538 539 /* Go on and try the next resolved address for this constraint */ 540 return (constraint_init(cstr)); 541 } 542 543 void 544 priv_constraint_close(int fd, int fail) 545 { 546 struct constraint *cstr; 547 u_int32_t id; 548 549 if ((cstr = constraint_byfd(fd)) == NULL) { 550 log_warn("%s: fd %d: not found", __func__, fd); 551 return; 552 } 553 554 id = cstr->id; 555 constraint_remove(cstr); 556 constraint_cnt--; 557 558 imsg_compose(ibuf, IMSG_CONSTRAINT_CLOSE, id, 0, -1, 559 &fail, sizeof(fail)); 560 } 561 562 void 563 constraint_add(struct constraint *cstr) 564 { 565 TAILQ_INSERT_TAIL(&conf->constraints, cstr, entry); 566 } 567 568 void 569 constraint_remove(struct constraint *cstr) 570 { 571 TAILQ_REMOVE(&conf->constraints, cstr, entry); 572 573 msgbuf_clear(&cstr->ibuf.w); 574 if (cstr->fd != -1) 575 close(cstr->fd); 576 free(cstr->addr_head.name); 577 free(cstr->addr_head.path); 578 free(cstr->addr); 579 free(cstr); 580 } 581 582 void 583 constraint_purge(void) 584 { 585 struct constraint *cstr, *ncstr; 586 587 TAILQ_FOREACH_SAFE(cstr, &conf->constraints, entry, ncstr) 588 constraint_remove(cstr); 589 } 590 591 int 592 priv_constraint_dispatch(struct pollfd *pfd) 593 { 594 struct imsg imsg; 595 struct constraint *cstr; 596 ssize_t n; 597 struct timeval tv[2]; 598 599 if ((cstr = constraint_byfd(pfd->fd)) == NULL) 600 return (0); 601 602 if (!(pfd->revents & POLLIN)) 603 return (0); 604 605 if (((n = imsg_read(&cstr->ibuf)) == -1 && errno != EAGAIN) || n == 0) { 606 priv_constraint_close(pfd->fd, 1); 607 return (1); 608 } 609 610 for (;;) { 611 if ((n = imsg_get(&cstr->ibuf, &imsg)) == -1) { 612 priv_constraint_close(pfd->fd, 1); 613 return (1); 614 } 615 if (n == 0) 616 break; 617 618 switch (imsg.hdr.type) { 619 case IMSG_CONSTRAINT_RESULT: 620 if (imsg.hdr.len != IMSG_HEADER_SIZE + sizeof(tv)) 621 fatalx("invalid IMSG_CONSTRAINT received"); 622 623 /* forward imsg to ntp child, don't parse it here */ 624 imsg_compose(ibuf, imsg.hdr.type, 625 cstr->id, 0, -1, imsg.data, sizeof(tv)); 626 break; 627 default: 628 break; 629 } 630 imsg_free(&imsg); 631 } 632 633 return (0); 634 } 635 636 void 637 constraint_msg_result(u_int32_t id, u_int8_t *data, size_t len) 638 { 639 struct constraint *cstr; 640 struct timeval tv[2]; 641 double offset; 642 643 if ((cstr = constraint_byid(id)) == NULL) { 644 log_warnx("IMSG_CONSTRAINT_CLOSE with invalid constraint id"); 645 return; 646 } 647 648 if (len != sizeof(tv)) { 649 log_warnx("invalid IMSG_CONSTRAINT received"); 650 return; 651 } 652 653 memcpy(tv, data, len); 654 655 offset = gettime_from_timeval(&tv[0]) - 656 gettime_from_timeval(&tv[1]); 657 658 log_info("constraint reply from %s: offset %f", 659 log_sockaddr((struct sockaddr *)&cstr->addr->ss), 660 offset); 661 662 cstr->state = STATE_REPLY_RECEIVED; 663 cstr->last = getmonotime(); 664 cstr->constraint = tv[0].tv_sec; 665 666 constraint_update(); 667 } 668 669 void 670 constraint_msg_close(u_int32_t id, u_int8_t *data, size_t len) 671 { 672 struct constraint *cstr; 673 int fail; 674 675 if ((cstr = constraint_byid(id)) == NULL) { 676 log_warnx("IMSG_CONSTRAINT_CLOSE with invalid constraint id"); 677 return; 678 } 679 680 if (len != sizeof(int)) { 681 log_warnx("invalid IMSG_CONSTRAINT_CLOSE received"); 682 return; 683 } 684 685 memcpy(&fail, data, len); 686 687 if (fail) { 688 log_debug("no constraint reply from %s" 689 " received in time, next query %ds", 690 log_sockaddr((struct sockaddr *) 691 &cstr->addr->ss), CONSTRAINT_SCAN_INTERVAL); 692 } 693 694 if (fail || cstr->state < STATE_QUERY_SENT) { 695 cstr->senderrors++; 696 constraint_close(cstr->id); 697 } 698 } 699 700 void 701 constraint_msg_dns(u_int32_t id, u_int8_t *data, size_t len) 702 { 703 struct constraint *cstr, *ncstr = NULL; 704 u_int8_t *p; 705 struct ntp_addr *h; 706 707 if ((cstr = constraint_byid(id)) == NULL) { 708 log_warnx("IMSG_CONSTRAINT_DNS with invalid constraint id"); 709 return; 710 } 711 if (cstr->addr != NULL) { 712 log_warnx("IMSG_CONSTRAINT_DNS but addr != NULL!"); 713 return; 714 } 715 if (len == 0) { 716 log_debug("%s FAILED", __func__); 717 cstr->state = STATE_DNS_TEMPFAIL; 718 return; 719 } 720 721 if ((len % sizeof(struct sockaddr_storage)) != 0) 722 fatalx("IMSG_CONSTRAINT_DNS len"); 723 724 p = data; 725 do { 726 if ((h = calloc(1, sizeof(*h))) == NULL) 727 fatal("calloc ntp_addr"); 728 memcpy(&h->ss, p, sizeof(h->ss)); 729 p += sizeof(h->ss); 730 len -= sizeof(h->ss); 731 732 if (ncstr == NULL || cstr->addr_head.pool) { 733 ncstr = new_constraint(); 734 ncstr->addr = h; 735 ncstr->addr_head.a = h; 736 ncstr->addr_head.name = strdup(cstr->addr_head.name); 737 ncstr->addr_head.path = strdup(cstr->addr_head.path); 738 if (ncstr->addr_head.name == NULL || 739 ncstr->addr_head.path == NULL) 740 fatal("calloc name"); 741 ncstr->addr_head.pool = cstr->addr_head.pool; 742 ncstr->state = STATE_DNS_DONE; 743 constraint_add(ncstr); 744 constraint_cnt += constraint_init(ncstr); 745 } else { 746 h->next = ncstr->addr; 747 ncstr->addr = h; 748 ncstr->addr_head.a = h; 749 } 750 } while (len); 751 752 constraint_remove(cstr); 753 } 754 755 int 756 constraint_cmp(const void *a, const void *b) 757 { 758 return (*(const time_t *)a - *(const time_t *)b); 759 } 760 761 void 762 constraint_update(void) 763 { 764 struct constraint *cstr; 765 int cnt, i; 766 time_t *sum; 767 time_t now; 768 769 now = getmonotime(); 770 771 cnt = 0; 772 TAILQ_FOREACH(cstr, &conf->constraints, entry) { 773 if (cstr->state != STATE_REPLY_RECEIVED) 774 continue; 775 cnt++; 776 } 777 778 if ((sum = calloc(cnt, sizeof(time_t))) == NULL) 779 fatal("calloc"); 780 781 i = 0; 782 TAILQ_FOREACH(cstr, &conf->constraints, entry) { 783 if (cstr->state != STATE_REPLY_RECEIVED) 784 continue; 785 sum[i++] = cstr->constraint + (now - cstr->last); 786 } 787 788 qsort(sum, cnt, sizeof(time_t), constraint_cmp); 789 790 /* calculate median */ 791 i = cnt / 2; 792 if (cnt % 2 == 0) 793 if (sum[i - 1] < sum[i]) 794 i -= 1; 795 796 conf->constraint_last = now; 797 conf->constraint_median = sum[i]; 798 799 free(sum); 800 } 801 802 void 803 constraint_reset(void) 804 { 805 struct constraint *cstr; 806 807 TAILQ_FOREACH(cstr, &conf->constraints, entry) { 808 if (cstr->state == STATE_QUERY_SENT) 809 continue; 810 constraint_close(cstr->id); 811 } 812 conf->constraint_errors = 0; 813 } 814 815 int 816 constraint_check(double val) 817 { 818 struct timeval tv; 819 double constraint; 820 time_t now; 821 822 if (conf->constraint_median == 0) 823 return (0); 824 825 /* Calculate the constraint with the current offset */ 826 now = getmonotime(); 827 tv.tv_sec = conf->constraint_median + (now - conf->constraint_last); 828 tv.tv_usec = 0; 829 constraint = gettime_from_timeval(&tv); 830 831 if (((val - constraint) > CONSTRAINT_MARGIN) || 832 ((constraint - val) > CONSTRAINT_MARGIN)) { 833 /* XXX get new constraint if too many errors happened */ 834 if (conf->constraint_errors++ > 835 (CONSTRAINT_ERROR_MARGIN * peer_cnt)) { 836 constraint_reset(); 837 } 838 839 return (-1); 840 } 841 842 return (0); 843 } 844 845 struct httpsdate * 846 httpsdate_init(const char *addr, const char *port, const char *hostname, 847 const char *path, const u_int8_t *ca, size_t ca_len) 848 { 849 struct httpsdate *httpsdate = NULL; 850 851 if ((httpsdate = calloc(1, sizeof(*httpsdate))) == NULL) 852 goto fail; 853 854 if (hostname == NULL) 855 hostname = addr; 856 857 if ((httpsdate->tls_addr = strdup(addr)) == NULL || 858 (httpsdate->tls_port = strdup(port)) == NULL || 859 (httpsdate->tls_hostname = strdup(hostname)) == NULL || 860 (httpsdate->tls_path = strdup(path)) == NULL) 861 goto fail; 862 863 if (asprintf(&httpsdate->tls_request, 864 "HEAD %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", 865 httpsdate->tls_path, httpsdate->tls_hostname) == -1) 866 goto fail; 867 868 if ((httpsdate->tls_config = tls_config_new()) == NULL) 869 goto fail; 870 871 if (tls_config_set_ciphers(httpsdate->tls_config, "all") != 0) 872 goto fail; 873 874 if (ca == NULL || ca_len == 0) 875 tls_config_insecure_noverifycert(httpsdate->tls_config); 876 else 877 tls_config_set_ca_mem(httpsdate->tls_config, ca, ca_len); 878 879 return (httpsdate); 880 881 fail: 882 httpsdate_free(httpsdate); 883 return (NULL); 884 } 885 886 void 887 httpsdate_free(void *arg) 888 { 889 struct httpsdate *httpsdate = arg; 890 if (httpsdate == NULL) 891 return; 892 if (httpsdate->tls_ctx) 893 tls_close(httpsdate->tls_ctx); 894 tls_free(httpsdate->tls_ctx); 895 tls_config_free(httpsdate->tls_config); 896 free(httpsdate->tls_addr); 897 free(httpsdate->tls_port); 898 free(httpsdate->tls_hostname); 899 free(httpsdate->tls_path); 900 free(httpsdate->tls_request); 901 free(httpsdate); 902 } 903 904 int 905 httpsdate_request(struct httpsdate *httpsdate, struct timeval *when) 906 { 907 size_t outlen = 0, maxlength = CONSTRAINT_MAXHEADERLENGTH, len; 908 char *line, *p, *buf; 909 ssize_t ret; 910 911 if ((httpsdate->tls_ctx = tls_client()) == NULL) 912 goto fail; 913 914 if (tls_configure(httpsdate->tls_ctx, httpsdate->tls_config) == -1) 915 goto fail; 916 917 /* 918 * libtls expects an address string, which can also be a DNS name, 919 * but we pass a pre-resolved IP address string in tls_addr so it 920 * does not trigger any DNS operation and is safe to be called 921 * without the dns pledge. 922 */ 923 if (tls_connect_servername(httpsdate->tls_ctx, httpsdate->tls_addr, 924 httpsdate->tls_port, httpsdate->tls_hostname) == -1) { 925 log_debug("tls connect failed: %s (%s): %s", 926 httpsdate->tls_addr, httpsdate->tls_hostname, 927 tls_error(httpsdate->tls_ctx)); 928 goto fail; 929 } 930 931 buf = httpsdate->tls_request; 932 len = strlen(httpsdate->tls_request); 933 while (len > 0) { 934 ret = tls_write(httpsdate->tls_ctx, buf, len); 935 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) 936 continue; 937 if (ret < 0) { 938 log_warnx("tls write failed: %s (%s): %s", 939 httpsdate->tls_addr, httpsdate->tls_hostname, 940 tls_error(httpsdate->tls_ctx)); 941 goto fail; 942 } 943 buf += ret; 944 len -= ret; 945 } 946 947 while ((line = tls_readline(httpsdate->tls_ctx, &outlen, 948 &maxlength, when)) != NULL) { 949 line[strcspn(line, "\r\n")] = '\0'; 950 951 if ((p = strchr(line, ' ')) == NULL || *p == '\0') 952 goto next; 953 *p++ = '\0'; 954 if (strcasecmp("Date:", line) != 0) 955 goto next; 956 957 /* 958 * Expect the date/time format as IMF-fixdate which is 959 * mandated by HTTP/1.1 in the new RFC 7231 and was 960 * preferred by RFC 2616. Other formats would be RFC 850 961 * or ANSI C's asctime() - the latter doesn't include 962 * the timezone which is required here. 963 */ 964 if (strptime(p, "%a, %d %h %Y %T GMT", 965 &httpsdate->tls_tm) == NULL) { 966 log_warnx("unsupported date format"); 967 free(line); 968 return (-1); 969 } 970 971 free(line); 972 break; 973 next: 974 free(line); 975 } 976 977 return (0); 978 979 fail: 980 httpsdate_free(httpsdate); 981 return (-1); 982 } 983 984 void * 985 httpsdate_query(const char *addr, const char *port, const char *hostname, 986 const char *path, const u_int8_t *ca, size_t ca_len, 987 struct timeval *rectv, struct timeval *xmttv) 988 { 989 struct httpsdate *httpsdate; 990 struct timeval when; 991 time_t t; 992 993 if ((httpsdate = httpsdate_init(addr, port, hostname, path, 994 ca, ca_len)) == NULL) 995 return (NULL); 996 997 if (httpsdate_request(httpsdate, &when) == -1) 998 return (NULL); 999 1000 /* Return parsed date as local time */ 1001 t = timegm(&httpsdate->tls_tm); 1002 1003 /* Report parsed Date: as "received time" */ 1004 rectv->tv_sec = t; 1005 rectv->tv_usec = 0; 1006 1007 /* And add delay as "transmit time" */ 1008 xmttv->tv_sec = when.tv_sec; 1009 xmttv->tv_usec = when.tv_usec; 1010 1011 return (httpsdate); 1012 } 1013 1014 /* Based on SSL_readline in ftp/fetch.c */ 1015 char * 1016 tls_readline(struct tls *tls, size_t *lenp, size_t *maxlength, 1017 struct timeval *when) 1018 { 1019 size_t i, len; 1020 char *buf, *q, c; 1021 ssize_t ret; 1022 1023 len = 128; 1024 if ((buf = malloc(len)) == NULL) 1025 fatal("Can't allocate memory for transfer buffer"); 1026 for (i = 0; ; i++) { 1027 if (i >= len - 1) { 1028 if ((q = reallocarray(buf, len, 2)) == NULL) 1029 fatal("Can't expand transfer buffer"); 1030 buf = q; 1031 len *= 2; 1032 } 1033 again: 1034 ret = tls_read(tls, &c, 1); 1035 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) 1036 goto again; 1037 if (ret < 0) { 1038 /* SSL read error, ignore */ 1039 free(buf); 1040 return (NULL); 1041 } 1042 1043 if (maxlength != NULL && (*maxlength)-- == 0) { 1044 log_warnx("maximum length exceeded"); 1045 free(buf); 1046 return (NULL); 1047 } 1048 1049 buf[i] = c; 1050 if (c == '\n') 1051 break; 1052 } 1053 *lenp = i; 1054 if (gettimeofday(when, NULL) == -1) 1055 fatal("gettimeofday"); 1056 return (buf); 1057 } 1058 1059 char * 1060 get_string(u_int8_t *ptr, size_t len) 1061 { 1062 size_t i; 1063 1064 for (i = 0; i < len; i++) 1065 if (!(isprint(ptr[i]) || isspace(ptr[i]))) 1066 break; 1067 1068 return strndup(ptr, i); 1069 } 1070