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