1 /* $OpenBSD: client.c,v 1.113 2020/01/30 15:55: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 int 268 client_dispatch(struct ntp_peer *p, u_int8_t settime, u_int8_t automatic) 269 { 270 struct ntp_msg msg; 271 struct msghdr somsg; 272 struct iovec iov[1]; 273 struct timeval tv; 274 char buf[NTP_MSGSIZE]; 275 union { 276 struct cmsghdr hdr; 277 char buf[CMSG_SPACE(sizeof(tv))]; 278 } cmsgbuf; 279 struct cmsghdr *cmsg; 280 ssize_t size; 281 double T1, T2, T3, T4; 282 time_t interval; 283 284 memset(&somsg, 0, sizeof(somsg)); 285 iov[0].iov_base = buf; 286 iov[0].iov_len = sizeof(buf); 287 somsg.msg_iov = iov; 288 somsg.msg_iovlen = 1; 289 somsg.msg_control = cmsgbuf.buf; 290 somsg.msg_controllen = sizeof(cmsgbuf.buf); 291 292 T4 = getoffset(); 293 if ((size = recvmsg(p->query->fd, &somsg, 0)) == -1) { 294 if (errno == EHOSTUNREACH || errno == EHOSTDOWN || 295 errno == ENETUNREACH || errno == ENETDOWN || 296 errno == ECONNREFUSED || errno == EADDRNOTAVAIL || 297 errno == ENOPROTOOPT || errno == ENOENT) { 298 client_log_error(p, "recvmsg", errno); 299 set_next(p, error_interval()); 300 return (0); 301 } else 302 fatal("recvfrom"); 303 } 304 305 if (somsg.msg_flags & MSG_TRUNC) { 306 client_log_error(p, "recvmsg packet", EMSGSIZE); 307 set_next(p, error_interval()); 308 return (0); 309 } 310 311 if (somsg.msg_flags & MSG_CTRUNC) { 312 client_log_error(p, "recvmsg control data", E2BIG); 313 set_next(p, error_interval()); 314 return (0); 315 } 316 317 for (cmsg = CMSG_FIRSTHDR(&somsg); cmsg != NULL; 318 cmsg = CMSG_NXTHDR(&somsg, cmsg)) { 319 if (cmsg->cmsg_level == SOL_SOCKET && 320 cmsg->cmsg_type == SCM_TIMESTAMP) { 321 memcpy(&tv, CMSG_DATA(cmsg), sizeof(tv)); 322 T4 += gettime_from_timeval(&tv); 323 break; 324 } 325 } 326 327 ntp_getmsg((struct sockaddr *)&p->addr->ss, buf, size, &msg); 328 329 if (msg.orgtime.int_partl != p->query->msg.xmttime.int_partl || 330 msg.orgtime.fractionl != p->query->msg.xmttime.fractionl) 331 return (0); 332 333 if ((msg.status & LI_ALARM) == LI_ALARM || msg.stratum == 0 || 334 msg.stratum > NTP_MAXSTRATUM) { 335 char s[16]; 336 337 if ((msg.status & LI_ALARM) == LI_ALARM) { 338 strlcpy(s, "alarm", sizeof(s)); 339 } else if (msg.stratum == 0) { 340 /* Kiss-o'-Death (KoD) packet */ 341 strlcpy(s, "KoD", sizeof(s)); 342 } else if (msg.stratum > NTP_MAXSTRATUM) { 343 snprintf(s, sizeof(s), "stratum %d", msg.stratum); 344 } 345 interval = error_interval(); 346 set_next(p, interval); 347 log_info("reply from %s: not synced (%s), next query %llds", 348 log_sockaddr((struct sockaddr *)&p->addr->ss), s, 349 (long long)interval); 350 return (0); 351 } 352 353 /* 354 * From RFC 2030 (with a correction to the delay math): 355 * 356 * Timestamp Name ID When Generated 357 * ------------------------------------------------------------ 358 * Originate Timestamp T1 time request sent by client 359 * Receive Timestamp T2 time request received by server 360 * Transmit Timestamp T3 time reply sent by server 361 * Destination Timestamp T4 time reply received by client 362 * 363 * The roundtrip delay d and local clock offset t are defined as 364 * 365 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2. 366 */ 367 368 T1 = p->query->xmttime; 369 T2 = lfp_to_d(msg.rectime); 370 T3 = lfp_to_d(msg.xmttime); 371 372 /* Detect liars */ 373 if (!p->trusted && conf->constraint_median != 0 && 374 (constraint_check(T2) != 0 || constraint_check(T3) != 0)) { 375 log_info("reply from %s: constraint check failed", 376 log_sockaddr((struct sockaddr *)&p->addr->ss)); 377 set_next(p, error_interval()); 378 return (0); 379 } 380 381 p->reply[p->shift].offset = ((T2 - T1) + (T3 - T4)) / 2; 382 p->reply[p->shift].delay = (T4 - T1) - (T3 - T2); 383 p->reply[p->shift].status.stratum = msg.stratum; 384 if (p->reply[p->shift].delay < 0) { 385 interval = error_interval(); 386 set_next(p, interval); 387 log_info("reply from %s: negative delay %fs, " 388 "next query %llds", 389 log_sockaddr((struct sockaddr *)&p->addr->ss), 390 p->reply[p->shift].delay, (long long)interval); 391 return (0); 392 } 393 p->reply[p->shift].error = (T2 - T1) - (T3 - T4); 394 p->reply[p->shift].rcvd = getmonotime(); 395 p->reply[p->shift].good = 1; 396 397 p->reply[p->shift].status.leap = (msg.status & LIMASK); 398 p->reply[p->shift].status.precision = msg.precision; 399 p->reply[p->shift].status.rootdelay = sfp_to_d(msg.rootdelay); 400 p->reply[p->shift].status.rootdispersion = sfp_to_d(msg.dispersion); 401 p->reply[p->shift].status.refid = msg.refid; 402 p->reply[p->shift].status.reftime = lfp_to_d(msg.reftime); 403 p->reply[p->shift].status.poll = msg.ppoll; 404 405 if (p->addr->ss.ss_family == AF_INET) { 406 p->reply[p->shift].status.send_refid = 407 ((struct sockaddr_in *)&p->addr->ss)->sin_addr.s_addr; 408 } else if (p->addr->ss.ss_family == AF_INET6) { 409 MD5_CTX context; 410 u_int8_t digest[MD5_DIGEST_LENGTH]; 411 412 MD5Init(&context); 413 MD5Update(&context, ((struct sockaddr_in6 *)&p->addr->ss)-> 414 sin6_addr.s6_addr, sizeof(struct in6_addr)); 415 MD5Final(digest, &context); 416 memcpy((char *)&p->reply[p->shift].status.send_refid, digest, 417 sizeof(u_int32_t)); 418 } else 419 p->reply[p->shift].status.send_refid = msg.xmttime.fractionl; 420 421 if (p->trustlevel < TRUSTLEVEL_PATHETIC) 422 interval = scale_interval(INTERVAL_QUERY_PATHETIC); 423 else if (p->trustlevel < TRUSTLEVEL_AGGRESSIVE) 424 interval = (conf->settime && conf->automatic) ? 425 INTERVAL_QUERY_ULTRA_VIOLENCE : 426 scale_interval(INTERVAL_QUERY_AGGRESSIVE); 427 else 428 interval = scale_interval(INTERVAL_QUERY_NORMAL); 429 430 set_next(p, interval); 431 p->state = STATE_REPLY_RECEIVED; 432 433 /* every received reply which we do not discard increases trust */ 434 if (p->trustlevel < TRUSTLEVEL_MAX) { 435 if (p->trustlevel < TRUSTLEVEL_BADPEER && 436 p->trustlevel + 1 >= TRUSTLEVEL_BADPEER) 437 log_info("peer %s now valid", 438 log_sockaddr((struct sockaddr *)&p->addr->ss)); 439 p->trustlevel++; 440 } 441 442 log_debug("reply from %s: offset %f delay %f, " 443 "next query %llds", 444 log_sockaddr((struct sockaddr *)&p->addr->ss), 445 p->reply[p->shift].offset, p->reply[p->shift].delay, 446 (long long)interval); 447 448 client_update(p); 449 if (settime) { 450 if (automatic) 451 handle_auto(p->trusted, p->reply[p->shift].offset); 452 else 453 priv_settime(p->reply[p->shift].offset, ""); 454 } 455 456 if (++p->shift >= OFFSET_ARRAY_SIZE) 457 p->shift = 0; 458 459 return (0); 460 } 461 462 int 463 client_update(struct ntp_peer *p) 464 { 465 int i, best = 0, good = 0; 466 467 /* 468 * clock filter 469 * find the offset which arrived with the lowest delay 470 * use that as the peer update 471 * invalidate it and all older ones 472 */ 473 474 for (i = 0; good == 0 && i < OFFSET_ARRAY_SIZE; i++) 475 if (p->reply[i].good) { 476 good++; 477 best = i; 478 } 479 480 for (; i < OFFSET_ARRAY_SIZE; i++) 481 if (p->reply[i].good) { 482 good++; 483 if (p->reply[i].delay < p->reply[best].delay) 484 best = i; 485 } 486 487 if (good < 8) 488 return (-1); 489 490 memcpy(&p->update, &p->reply[best], sizeof(p->update)); 491 if (priv_adjtime() == 0) { 492 for (i = 0; i < OFFSET_ARRAY_SIZE; i++) 493 if (p->reply[i].rcvd <= p->reply[best].rcvd) 494 p->reply[i].good = 0; 495 } 496 return (0); 497 } 498 499 void 500 client_log_error(struct ntp_peer *peer, const char *operation, int error) 501 { 502 const char *address; 503 504 address = log_sockaddr((struct sockaddr *)&peer->addr->ss); 505 if (peer->lasterror == error) { 506 log_debug("%s %s: %s", operation, address, strerror(error)); 507 return; 508 } 509 peer->lasterror = error; 510 log_warn("%s %s", operation, address); 511 } 512