1 /* $OpenBSD: client.c,v 1.114 2020/09/11 07:09:41 otto Exp $ */ 2 3 /* 4 * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org> 5 * Copyright (c) 2004 Alexander Guy <alexander.guy@andern.org> 6 * 7 * Permission to use, copy, modify, and distribute this software for any 8 * purpose with or without fee is hereby granted, provided that the above 9 * copyright notice and this permission notice appear in all copies. 10 * 11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 18 */ 19 20 #include <sys/types.h> 21 #include <errno.h> 22 #include <md5.h> 23 #include <stdio.h> 24 #include <stdlib.h> 25 #include <string.h> 26 #include <time.h> 27 #include <unistd.h> 28 29 #include "ntpd.h" 30 31 int client_update(struct ntp_peer *); 32 int auto_cmp(const void *, const void *); 33 void handle_auto(u_int8_t, double); 34 void set_deadline(struct ntp_peer *, time_t); 35 36 void 37 set_next(struct ntp_peer *p, time_t t) 38 { 39 p->next = getmonotime() + t; 40 p->deadline = 0; 41 p->poll = t; 42 } 43 44 void 45 set_deadline(struct ntp_peer *p, time_t t) 46 { 47 p->deadline = getmonotime() + t; 48 p->next = 0; 49 } 50 51 int 52 client_peer_init(struct ntp_peer *p) 53 { 54 if ((p->query = calloc(1, sizeof(struct ntp_query))) == NULL) 55 fatal("client_peer_init calloc"); 56 p->query->fd = -1; 57 p->query->msg.status = MODE_CLIENT | (NTP_VERSION << 3); 58 p->state = STATE_NONE; 59 p->shift = 0; 60 p->trustlevel = TRUSTLEVEL_PATHETIC; 61 p->lasterror = 0; 62 p->senderrors = 0; 63 64 return (client_addr_init(p)); 65 } 66 67 int 68 client_addr_init(struct ntp_peer *p) 69 { 70 struct sockaddr_in *sa_in; 71 struct sockaddr_in6 *sa_in6; 72 struct ntp_addr *h; 73 74 for (h = p->addr; h != NULL; h = h->next) { 75 switch (h->ss.ss_family) { 76 case AF_INET: 77 sa_in = (struct sockaddr_in *)&h->ss; 78 if (ntohs(sa_in->sin_port) == 0) 79 sa_in->sin_port = htons(123); 80 p->state = STATE_DNS_DONE; 81 break; 82 case AF_INET6: 83 sa_in6 = (struct sockaddr_in6 *)&h->ss; 84 if (ntohs(sa_in6->sin6_port) == 0) 85 sa_in6->sin6_port = htons(123); 86 p->state = STATE_DNS_DONE; 87 break; 88 default: 89 fatalx("king bula sez: wrong AF in client_addr_init"); 90 /* NOTREACHED */ 91 } 92 } 93 94 p->query->fd = -1; 95 set_next(p, 0); 96 97 return (0); 98 } 99 100 int 101 client_nextaddr(struct ntp_peer *p) 102 { 103 if (p->query->fd != -1) { 104 close(p->query->fd); 105 p->query->fd = -1; 106 } 107 108 if (p->state == STATE_DNS_INPROGRESS) 109 return (-1); 110 111 if (p->addr_head.a == NULL) { 112 priv_dns(IMSG_HOST_DNS, p->addr_head.name, p->id); 113 p->state = STATE_DNS_INPROGRESS; 114 return (-1); 115 } 116 117 p->shift = 0; 118 p->trustlevel = TRUSTLEVEL_PATHETIC; 119 120 if (p->addr == NULL) 121 p->addr = p->addr_head.a; 122 else if ((p->addr = p->addr->next) == NULL) 123 return (1); 124 125 return (0); 126 } 127 128 int 129 client_query(struct ntp_peer *p) 130 { 131 int val; 132 133 if (p->addr == NULL && client_nextaddr(p) == -1) { 134 if (conf->settime) 135 set_next(p, INTERVAL_AUIO_DNSFAIL); 136 else 137 set_next(p, MAXIMUM(SETTIME_TIMEOUT, 138 scale_interval(INTERVAL_QUERY_AGGRESSIVE))); 139 return (0); 140 } 141 142 if (conf->status.synced && p->addr->notauth) { 143 peer_addr_head_clear(p); 144 client_nextaddr(p); 145 return (0); 146 } 147 148 if (p->state < STATE_DNS_DONE || p->addr == NULL) 149 return (-1); 150 151 if (p->query->fd == -1) { 152 struct sockaddr *sa = (struct sockaddr *)&p->addr->ss; 153 struct sockaddr *qa4 = (struct sockaddr *)&p->query_addr4; 154 struct sockaddr *qa6 = (struct sockaddr *)&p->query_addr6; 155 156 if ((p->query->fd = socket(p->addr->ss.ss_family, SOCK_DGRAM, 157 0)) == -1) 158 fatal("client_query socket"); 159 160 if (p->addr->ss.ss_family == qa4->sa_family) { 161 if (bind(p->query->fd, qa4, SA_LEN(qa4)) == -1) 162 fatal("couldn't bind to IPv4 query address: %s", 163 log_sockaddr(qa4)); 164 } else if (p->addr->ss.ss_family == qa6->sa_family) { 165 if (bind(p->query->fd, qa6, SA_LEN(qa6)) == -1) 166 fatal("couldn't bind to IPv6 query address: %s", 167 log_sockaddr(qa6)); 168 } 169 170 if (connect(p->query->fd, sa, SA_LEN(sa)) == -1) { 171 if (errno == ECONNREFUSED || errno == ENETUNREACH || 172 errno == EHOSTUNREACH || errno == EADDRNOTAVAIL) { 173 /* cycle through addresses, but do increase 174 senderrors */ 175 client_nextaddr(p); 176 if (p->addr == NULL) 177 p->addr = p->addr_head.a; 178 set_next(p, MAXIMUM(SETTIME_TIMEOUT, 179 scale_interval(INTERVAL_QUERY_AGGRESSIVE))); 180 p->senderrors++; 181 return (-1); 182 } else 183 fatal("client_query connect"); 184 } 185 val = IPTOS_LOWDELAY; 186 if (p->addr->ss.ss_family == AF_INET && setsockopt(p->query->fd, 187 IPPROTO_IP, IP_TOS, &val, sizeof(val)) == -1) 188 log_warn("setsockopt IPTOS_LOWDELAY"); 189 val = 1; 190 if (setsockopt(p->query->fd, SOL_SOCKET, SO_TIMESTAMP, 191 &val, sizeof(val)) == -1) 192 fatal("setsockopt SO_TIMESTAMP"); 193 } 194 195 /* 196 * Send out a random 64-bit number as our transmit time. The NTP 197 * server will copy said number into the originate field on the 198 * response that it sends us. This is totally legal per the SNTP spec. 199 * 200 * The impact of this is two fold: we no longer send out the current 201 * system time for the world to see (which may aid an attacker), and 202 * it gives us a (not very secure) way of knowing that we're not 203 * getting spoofed by an attacker that can't capture our traffic 204 * but can spoof packets from the NTP server we're communicating with. 205 * 206 * Save the real transmit timestamp locally. 207 */ 208 209 p->query->msg.xmttime.int_partl = arc4random(); 210 p->query->msg.xmttime.fractionl = arc4random(); 211 p->query->xmttime = gettime_corrected(); 212 213 if (ntp_sendmsg(p->query->fd, NULL, &p->query->msg) == -1) { 214 p->senderrors++; 215 set_next(p, INTERVAL_QUERY_PATHETIC); 216 p->trustlevel = TRUSTLEVEL_PATHETIC; 217 return (-1); 218 } 219 220 p->senderrors = 0; 221 p->state = STATE_QUERY_SENT; 222 set_deadline(p, QUERYTIME_MAX); 223 224 return (0); 225 } 226 227 int 228 auto_cmp(const void *a, const void *b) 229 { 230 double at = *(const double *)a; 231 double bt = *(const double *)b; 232 return at < bt ? -1 : (at > bt ? 1 : 0); 233 } 234 235 void 236 handle_auto(uint8_t trusted, double offset) 237 { 238 static int count; 239 static double v[AUTO_REPLIES]; 240 241 /* 242 * It happens the (constraint) resolves initially fail, don't give up 243 * but see if we get validated replies later. 244 */ 245 if (!trusted && conf->constraint_median == 0) 246 return; 247 248 if (offset < AUTO_THRESHOLD) { 249 /* don't bother */ 250 priv_settime(0, "offset is negative or close enough"); 251 return; 252 } 253 /* collect some more */ 254 v[count++] = offset; 255 if (count < AUTO_REPLIES) 256 return; 257 258 /* we have enough */ 259 qsort(v, count, sizeof(double), auto_cmp); 260 if (AUTO_REPLIES % 2 == 0) 261 offset = (v[AUTO_REPLIES / 2 - 1] + v[AUTO_REPLIES / 2]) / 2; 262 else 263 offset = v[AUTO_REPLIES / 2]; 264 priv_settime(offset, ""); 265 } 266 267 268 /* 269 * -1: Not processed, not an NTP message (e.g. icmp induced ECONNREFUSED) 270 * 0: Not prrocessed due to validation issues 271 * 1: NTP message validated and processed 272 */ 273 int 274 client_dispatch(struct ntp_peer *p, u_int8_t settime, u_int8_t automatic) 275 { 276 struct ntp_msg msg; 277 struct msghdr somsg; 278 struct iovec iov[1]; 279 struct timeval tv; 280 char buf[NTP_MSGSIZE]; 281 union { 282 struct cmsghdr hdr; 283 char buf[CMSG_SPACE(sizeof(tv))]; 284 } cmsgbuf; 285 struct cmsghdr *cmsg; 286 ssize_t size; 287 double T1, T2, T3, T4, offset, delay; 288 time_t interval; 289 290 memset(&somsg, 0, sizeof(somsg)); 291 iov[0].iov_base = buf; 292 iov[0].iov_len = sizeof(buf); 293 somsg.msg_iov = iov; 294 somsg.msg_iovlen = 1; 295 somsg.msg_control = cmsgbuf.buf; 296 somsg.msg_controllen = sizeof(cmsgbuf.buf); 297 298 T4 = getoffset(); 299 if ((size = recvmsg(p->query->fd, &somsg, 0)) == -1) { 300 if (errno == EHOSTUNREACH || errno == EHOSTDOWN || 301 errno == ENETUNREACH || errno == ENETDOWN || 302 errno == ECONNREFUSED || errno == EADDRNOTAVAIL || 303 errno == ENOPROTOOPT || errno == ENOENT) { 304 client_log_error(p, "recvmsg", errno); 305 set_next(p, error_interval()); 306 return (-1); 307 } else 308 fatal("recvfrom"); 309 } 310 311 if (somsg.msg_flags & MSG_TRUNC) { 312 client_log_error(p, "recvmsg packet", EMSGSIZE); 313 set_next(p, error_interval()); 314 return (0); 315 } 316 317 if (somsg.msg_flags & MSG_CTRUNC) { 318 client_log_error(p, "recvmsg control data", E2BIG); 319 set_next(p, error_interval()); 320 return (0); 321 } 322 323 for (cmsg = CMSG_FIRSTHDR(&somsg); cmsg != NULL; 324 cmsg = CMSG_NXTHDR(&somsg, cmsg)) { 325 if (cmsg->cmsg_level == SOL_SOCKET && 326 cmsg->cmsg_type == SCM_TIMESTAMP) { 327 memcpy(&tv, CMSG_DATA(cmsg), sizeof(tv)); 328 T4 += gettime_from_timeval(&tv); 329 break; 330 } 331 } 332 333 ntp_getmsg((struct sockaddr *)&p->addr->ss, buf, size, &msg); 334 335 if (msg.orgtime.int_partl != p->query->msg.xmttime.int_partl || 336 msg.orgtime.fractionl != p->query->msg.xmttime.fractionl) 337 return (0); 338 339 if ((msg.status & LI_ALARM) == LI_ALARM || msg.stratum == 0 || 340 msg.stratum > NTP_MAXSTRATUM) { 341 char s[16]; 342 343 if ((msg.status & LI_ALARM) == LI_ALARM) { 344 strlcpy(s, "alarm", sizeof(s)); 345 } else if (msg.stratum == 0) { 346 /* Kiss-o'-Death (KoD) packet */ 347 strlcpy(s, "KoD", sizeof(s)); 348 } else if (msg.stratum > NTP_MAXSTRATUM) { 349 snprintf(s, sizeof(s), "stratum %d", msg.stratum); 350 } 351 interval = error_interval(); 352 set_next(p, interval); 353 log_info("reply from %s: not synced (%s), next query %llds", 354 log_sockaddr((struct sockaddr *)&p->addr->ss), s, 355 (long long)interval); 356 return (0); 357 } 358 359 /* 360 * From RFC 2030 (with a correction to the delay math): 361 * 362 * Timestamp Name ID When Generated 363 * ------------------------------------------------------------ 364 * Originate Timestamp T1 time request sent by client 365 * Receive Timestamp T2 time request received by server 366 * Transmit Timestamp T3 time reply sent by server 367 * Destination Timestamp T4 time reply received by client 368 * 369 * The roundtrip delay d and local clock offset t are defined as 370 * 371 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2. 372 */ 373 374 T1 = p->query->xmttime; 375 T2 = lfp_to_d(msg.rectime); 376 T3 = lfp_to_d(msg.xmttime); 377 378 /* Detect liars */ 379 if (!p->trusted && conf->constraint_median != 0 && 380 (constraint_check(T2) != 0 || constraint_check(T3) != 0)) { 381 log_info("reply from %s: constraint check failed", 382 log_sockaddr((struct sockaddr *)&p->addr->ss)); 383 set_next(p, error_interval()); 384 return (0); 385 } 386 387 p->reply[p->shift].offset = ((T2 - T1) + (T3 - T4)) / 2; 388 p->reply[p->shift].delay = (T4 - T1) - (T3 - T2); 389 p->reply[p->shift].status.stratum = msg.stratum; 390 if (p->reply[p->shift].delay < 0) { 391 interval = error_interval(); 392 set_next(p, interval); 393 log_info("reply from %s: negative delay %fs, " 394 "next query %llds", 395 log_sockaddr((struct sockaddr *)&p->addr->ss), 396 p->reply[p->shift].delay, (long long)interval); 397 return (0); 398 } 399 p->reply[p->shift].error = (T2 - T1) - (T3 - T4); 400 p->reply[p->shift].rcvd = getmonotime(); 401 p->reply[p->shift].good = 1; 402 403 p->reply[p->shift].status.leap = (msg.status & LIMASK); 404 p->reply[p->shift].status.precision = msg.precision; 405 p->reply[p->shift].status.rootdelay = sfp_to_d(msg.rootdelay); 406 p->reply[p->shift].status.rootdispersion = sfp_to_d(msg.dispersion); 407 p->reply[p->shift].status.refid = msg.refid; 408 p->reply[p->shift].status.reftime = lfp_to_d(msg.reftime); 409 p->reply[p->shift].status.poll = msg.ppoll; 410 411 if (p->addr->ss.ss_family == AF_INET) { 412 p->reply[p->shift].status.send_refid = 413 ((struct sockaddr_in *)&p->addr->ss)->sin_addr.s_addr; 414 } else if (p->addr->ss.ss_family == AF_INET6) { 415 MD5_CTX context; 416 u_int8_t digest[MD5_DIGEST_LENGTH]; 417 418 MD5Init(&context); 419 MD5Update(&context, ((struct sockaddr_in6 *)&p->addr->ss)-> 420 sin6_addr.s6_addr, sizeof(struct in6_addr)); 421 MD5Final(digest, &context); 422 memcpy((char *)&p->reply[p->shift].status.send_refid, digest, 423 sizeof(u_int32_t)); 424 } else 425 p->reply[p->shift].status.send_refid = msg.xmttime.fractionl; 426 427 p->state = STATE_REPLY_RECEIVED; 428 429 /* every received reply which we do not discard increases trust */ 430 if (p->trustlevel < TRUSTLEVEL_MAX) { 431 if (p->trustlevel < TRUSTLEVEL_BADPEER && 432 p->trustlevel + 1 >= TRUSTLEVEL_BADPEER) 433 log_info("peer %s now valid", 434 log_sockaddr((struct sockaddr *)&p->addr->ss)); 435 p->trustlevel++; 436 } 437 438 offset = p->reply[p->shift].offset; 439 delay = p->reply[p->shift].delay; 440 441 client_update(p); 442 if (settime) { 443 if (automatic) 444 handle_auto(p->trusted, p->reply[p->shift].offset); 445 else 446 priv_settime(p->reply[p->shift].offset, ""); 447 } 448 449 if (p->trustlevel < TRUSTLEVEL_PATHETIC) 450 interval = scale_interval(INTERVAL_QUERY_PATHETIC); 451 else if (p->trustlevel < TRUSTLEVEL_AGGRESSIVE) 452 interval = (conf->settime && conf->automatic) ? 453 INTERVAL_QUERY_ULTRA_VIOLENCE : 454 scale_interval(INTERVAL_QUERY_AGGRESSIVE); 455 else 456 interval = scale_interval(INTERVAL_QUERY_NORMAL); 457 458 log_debug("reply from %s: offset %f delay %f, " 459 "next query %llds", 460 log_sockaddr((struct sockaddr *)&p->addr->ss), 461 offset, delay, 462 (long long)interval); 463 464 set_next(p, interval); 465 466 if (++p->shift >= OFFSET_ARRAY_SIZE) 467 p->shift = 0; 468 469 return (1); 470 } 471 472 int 473 client_update(struct ntp_peer *p) 474 { 475 int i, best = 0, good = 0; 476 477 /* 478 * clock filter 479 * find the offset which arrived with the lowest delay 480 * use that as the peer update 481 * invalidate it and all older ones 482 */ 483 484 for (i = 0; good == 0 && i < OFFSET_ARRAY_SIZE; i++) 485 if (p->reply[i].good) { 486 good++; 487 best = i; 488 } 489 490 for (; i < OFFSET_ARRAY_SIZE; i++) 491 if (p->reply[i].good) { 492 good++; 493 if (p->reply[i].delay < p->reply[best].delay) 494 best = i; 495 } 496 497 if (good < 8) 498 return (-1); 499 500 memcpy(&p->update, &p->reply[best], sizeof(p->update)); 501 if (priv_adjtime() == 0) { 502 for (i = 0; i < OFFSET_ARRAY_SIZE; i++) 503 if (p->reply[i].rcvd <= p->reply[best].rcvd) 504 p->reply[i].good = 0; 505 } 506 return (0); 507 } 508 509 void 510 client_log_error(struct ntp_peer *peer, const char *operation, int error) 511 { 512 const char *address; 513 514 address = log_sockaddr((struct sockaddr *)&peer->addr->ss); 515 if (peer->lasterror == error) { 516 log_debug("%s %s: %s", operation, address, strerror(error)); 517 return; 518 } 519 peer->lasterror = error; 520 log_warn("%s %s", operation, address); 521 } 522