1 /* 2 * ntp_proto.c - NTP version 4 protocol machinery 3 * 4 * ATTENTION: Get approval from Harlan on all changes to this file! 5 * (Harlan will be discussing these changes with Dave Mills.) 6 * 7 */ 8 #ifdef HAVE_CONFIG_H 9 #include <config.h> 10 #endif 11 12 #include "ntpd.h" 13 #include "ntp_stdlib.h" 14 #include "ntp_unixtime.h" 15 #include "ntp_control.h" 16 #include "ntp_string.h" 17 #include "ntp_leapsec.h" 18 #include "ntp_psl.h" 19 #include "refidsmear.h" 20 #include "lib_strbuf.h" 21 22 #include <stdio.h> 23 #ifdef HAVE_LIBSCF_H 24 #include <libscf.h> 25 #endif 26 #ifdef HAVE_UNISTD_H 27 #include <unistd.h> 28 #endif 29 30 /* [Bug 3031] define automatic broadcastdelay cutoff preset */ 31 #ifndef BDELAY_DEFAULT 32 # define BDELAY_DEFAULT (-0.050) 33 #endif 34 35 #define SRVFUZ_SHIFT 6 /* 64 seconds */ 36 #define SRVRSP_FUZZ(x) \ 37 do { \ 38 x.l_uf &= 0; \ 39 x.l_ui &= ~((1 << SRVFUZ_SHIFT) - 1U); \ 40 } while(0) 41 42 /* 43 * This macro defines the authentication state. If x is 1 authentication 44 * is required; otherwise it is optional. 45 */ 46 #define AUTH(x, y) ((x) ? (y) == AUTH_OK \ 47 : (y) == AUTH_OK || (y) == AUTH_NONE) 48 49 typedef enum 50 auth_state { 51 AUTH_UNKNOWN = -1, /* Unknown */ 52 AUTH_NONE, /* authentication not required */ 53 AUTH_OK, /* authentication OK */ 54 AUTH_ERROR, /* authentication error */ 55 AUTH_CRYPTO /* crypto_NAK */ 56 } auth_code; 57 58 /* 59 * Set up Kiss Code values 60 */ 61 62 typedef enum 63 kiss_codes { 64 NOKISS, /* No Kiss Code */ 65 RATEKISS, /* Rate limit Kiss Code */ 66 DENYKISS, /* Deny Kiss */ 67 RSTRKISS, /* Restricted Kiss */ 68 XKISS /* Experimental Kiss */ 69 } kiss_code; 70 71 typedef enum 72 nak_error_codes { 73 NONAK, /* No NAK seen */ 74 INVALIDNAK, /* NAK cannot be used */ 75 VALIDNAK /* NAK is valid */ 76 } nak_code; 77 78 /* 79 * traffic shaping parameters 80 */ 81 #define NTP_IBURST 6 /* packets in iburst */ 82 #define RESP_DELAY 1 /* refclock burst delay (s) */ 83 84 /* 85 * pool soliciting restriction duration (s) 86 */ 87 #define POOL_SOLICIT_WINDOW 8 88 89 /* 90 * flag bits propagated from pool/manycast to individual peers 91 */ 92 #define POOL_FLAG_PMASK (FLAG_IBURST | FLAG_NOSELECT) 93 94 /* 95 * peer_select groups statistics for a peer used by clock_select() and 96 * clock_cluster(). 97 */ 98 typedef struct peer_select_tag { 99 struct peer * peer; 100 double synch; /* sync distance */ 101 double error; /* jitter */ 102 double seljit; /* selection jitter */ 103 } peer_select; 104 105 /* 106 * System variables are declared here. Unless specified otherwise, all 107 * times are in seconds. 108 */ 109 u_char sys_leap; /* system leap indicator, use set_sys_leap() to change this */ 110 u_char xmt_leap; /* leap indicator sent in client requests, set up by set_sys_leap() */ 111 u_char sys_stratum; /* system stratum */ 112 s_char sys_precision; /* local clock precision (log2 s) */ 113 double sys_rootdelay; /* roundtrip delay to root (primary source) */ 114 double sys_rootdisp; /* dispersion to root (primary source) */ 115 double prev_rootdisp; /* previous root dispersion */ 116 double p2_rootdisp; /* previous previous root dispersion */ 117 u_int32 sys_refid; /* reference id (network byte order) */ 118 l_fp sys_reftime; /* last update time */ 119 l_fp prev_reftime; /* previous sys_reftime */ 120 l_fp p2_reftime; /* previous previous sys_reftime */ 121 u_long prev_time; /* "current_time" when saved prev_time */ 122 u_long p2_time; /* previous prev_time */ 123 struct peer *sys_peer; /* current peer */ 124 125 #ifdef LEAP_SMEAR 126 struct leap_smear_info leap_smear; 127 #endif 128 int leap_sec_in_progress; 129 130 /* 131 * Rate controls. Leaky buckets are used to throttle the packet 132 * transmission rates in order to protect busy servers such as at NIST 133 * and USNO. There is a counter for each association and another for KoD 134 * packets. The association counter decrements each second, but not 135 * below zero. Each time a packet is sent the counter is incremented by 136 * a configurable value representing the average interval between 137 * packets. A packet is delayed as long as the counter is greater than 138 * zero. Note this does not affect the time value computations. 139 */ 140 /* 141 * Nonspecified system state variables 142 */ 143 int sys_bclient; /* broadcast client enable */ 144 int sys_mclient; /* multicast client enable */ 145 double sys_bdelay; /* broadcast client default delay */ 146 int sys_authenticate; /* requre authentication for config */ 147 l_fp sys_authdelay; /* authentication delay */ 148 double sys_offset; /* current local clock offset */ 149 double sys_mindisp = MINDISPERSE; /* minimum distance (s) */ 150 double sys_maxdist = MAXDISTANCE; /* selection threshold */ 151 double sys_jitter; /* system jitter */ 152 u_long sys_epoch; /* last clock update time */ 153 static double sys_clockhop; /* clockhop threshold */ 154 static int leap_vote_ins; /* leap consensus for insert */ 155 static int leap_vote_del; /* leap consensus for delete */ 156 keyid_t sys_private; /* private value for session seed */ 157 int sys_manycastserver; /* respond to manycast client pkts */ 158 int ntp_mode7; /* respond to ntpdc (mode7) */ 159 int peer_ntpdate; /* active peers in ntpdate mode */ 160 int sys_survivors; /* truest of the truechimers */ 161 char *sys_ident = NULL; /* identity scheme */ 162 163 /* 164 * TOS and multicast mapping stuff 165 */ 166 int sys_floor = 0; /* cluster stratum floor */ 167 u_char sys_bcpollbstep = 0; /* Broadcast Poll backstep gate */ 168 int sys_ceiling = STRATUM_UNSPEC - 1; /* cluster stratum ceiling */ 169 int sys_minsane = 1; /* minimum candidates */ 170 int sys_minclock = NTP_MINCLOCK; /* minimum candidates */ 171 int sys_maxclock = NTP_MAXCLOCK; /* maximum candidates */ 172 int sys_cohort = 0; /* cohort switch */ 173 int sys_orphan = STRATUM_UNSPEC + 1; /* orphan stratum */ 174 int sys_orphwait = NTP_ORPHWAIT; /* orphan wait */ 175 int sys_beacon = BEACON; /* manycast beacon interval */ 176 u_int sys_ttlmax; /* max ttl mapping vector index */ 177 u_char sys_ttl[MAX_TTL]; /* ttl mapping vector */ 178 179 /* 180 * Statistics counters - first the good, then the bad 181 */ 182 u_long sys_stattime; /* elapsed time */ 183 u_long sys_received; /* packets received */ 184 u_long sys_processed; /* packets for this host */ 185 u_long sys_newversion; /* current version */ 186 u_long sys_oldversion; /* old version */ 187 u_long sys_restricted; /* access denied */ 188 u_long sys_badlength; /* bad length or format */ 189 u_long sys_badauth; /* bad authentication */ 190 u_long sys_declined; /* declined */ 191 u_long sys_limitrejected; /* rate exceeded */ 192 u_long sys_kodsent; /* KoD sent */ 193 194 /* 195 * Mechanism knobs: how soon do we peer_clear() or unpeer()? 196 * 197 * The default way is "on-receipt". If this was a packet from a 198 * well-behaved source, on-receipt will offer the fastest recovery. 199 * If this was from a DoS attack, the default way makes it easier 200 * for a bad-guy to DoS us. So look and see what bites you harder 201 * and choose according to your environment. 202 */ 203 int peer_clear_digest_early = 1; /* bad digest (TEST5) and Autokey */ 204 int unpeer_crypto_early = 1; /* bad crypto (TEST9) */ 205 int unpeer_crypto_nak_early = 1; /* crypto_NAK (TEST5) */ 206 int unpeer_digest_early = 1; /* bad digest (TEST5) */ 207 208 int dynamic_interleave = DYNAMIC_INTERLEAVE; /* Bug 2978 mitigation */ 209 210 int kiss_code_check(u_char hisleap, u_char hisstratum, u_char hismode, u_int32 refid); 211 nak_code valid_NAK (struct peer *peer, struct recvbuf *rbufp, u_char hismode); 212 static double root_distance (struct peer *); 213 static void clock_combine (peer_select *, int, int); 214 static void peer_xmit (struct peer *); 215 static void fast_xmit (struct recvbuf *, int, keyid_t, int); 216 static void pool_xmit (struct peer *); 217 static void clock_update (struct peer *); 218 static void measure_precision(void); 219 static double measure_tick_fuzz(void); 220 static int local_refid (struct peer *); 221 static int peer_unfit (struct peer *); 222 #ifdef AUTOKEY 223 static int group_test (char *, char *); 224 #endif /* AUTOKEY */ 225 #ifdef WORKER 226 void pool_name_resolved (int, int, void *, const char *, 227 const char *, const struct addrinfo *, 228 const struct addrinfo *); 229 #endif /* WORKER */ 230 231 const char * amtoa (int am); 232 233 234 void 235 set_sys_leap( 236 u_char new_sys_leap 237 ) 238 { 239 sys_leap = new_sys_leap; 240 xmt_leap = sys_leap; 241 242 /* 243 * Under certain conditions we send faked leap bits to clients, so 244 * eventually change xmt_leap below, but never change LEAP_NOTINSYNC. 245 */ 246 if (xmt_leap != LEAP_NOTINSYNC) { 247 if (leap_sec_in_progress) { 248 /* always send "not sync" */ 249 xmt_leap = LEAP_NOTINSYNC; 250 } 251 #ifdef LEAP_SMEAR 252 else { 253 /* 254 * If leap smear is enabled in general we must 255 * never send a leap second warning to clients, 256 * so make sure we only send "in sync". 257 */ 258 if (leap_smear.enabled) 259 xmt_leap = LEAP_NOWARNING; 260 } 261 #endif /* LEAP_SMEAR */ 262 } 263 } 264 265 266 /* 267 * Kiss Code check 268 */ 269 int 270 kiss_code_check( 271 u_char hisleap, 272 u_char hisstratum, 273 u_char hismode, 274 u_int32 refid 275 ) 276 { 277 278 if ( hismode == MODE_SERVER 279 && hisleap == LEAP_NOTINSYNC 280 && hisstratum == STRATUM_UNSPEC) { 281 if(memcmp(&refid,"RATE", 4) == 0) { 282 return (RATEKISS); 283 } else if(memcmp(&refid,"DENY", 4) == 0) { 284 return (DENYKISS); 285 } else if(memcmp(&refid,"RSTR", 4) == 0) { 286 return (RSTRKISS); 287 } else if(memcmp(&refid,"X", 1) == 0) { 288 return (XKISS); 289 } 290 } 291 return (NOKISS); 292 } 293 294 295 /* 296 * Check that NAK is valid 297 */ 298 nak_code 299 valid_NAK( 300 struct peer *peer, 301 struct recvbuf *rbufp, 302 u_char hismode 303 ) 304 { 305 int base_packet_length = MIN_V4_PKT_LEN; 306 int remainder_size; 307 struct pkt * rpkt; 308 int keyid; 309 l_fp p_org; /* origin timestamp */ 310 const l_fp * myorg; /* selected peer origin */ 311 312 /* 313 * Check to see if there is something beyond the basic packet 314 */ 315 if (rbufp->recv_length == base_packet_length) { 316 return NONAK; 317 } 318 319 remainder_size = rbufp->recv_length - base_packet_length; 320 /* 321 * Is this a potential NAK? 322 */ 323 if (remainder_size != 4) { 324 return NONAK; 325 } 326 327 /* 328 * Only server responses can contain NAK's 329 */ 330 331 if (hismode != MODE_SERVER && 332 hismode != MODE_ACTIVE && 333 hismode != MODE_PASSIVE 334 ) { 335 return INVALIDNAK; 336 } 337 338 /* 339 * Make sure that the extra field in the packet is all zeros 340 */ 341 rpkt = &rbufp->recv_pkt; 342 keyid = ntohl(((u_int32 *)rpkt)[base_packet_length / 4]); 343 if (keyid != 0) { 344 return INVALIDNAK; 345 } 346 347 /* 348 * During the first few packets of the autokey dance there will 349 * not (yet) be a keyid, but in this case FLAG_SKEY is set. 350 * So the NAK is invalid if either there's no peer, or 351 * if the keyid is 0 and FLAG_SKEY is not set. 352 */ 353 if (!peer || (!peer->keyid && !(peer->flags & FLAG_SKEY))) { 354 return INVALIDNAK; 355 } 356 357 /* 358 * The ORIGIN must match, or this cannot be a valid NAK, either. 359 */ 360 361 if (FLAG_LOOPNONCE & peer->flags) { 362 myorg = &peer->nonce; 363 } else { 364 if (peer->flip > 0) { 365 myorg = &peer->borg; 366 } else { 367 myorg = &peer->aorg; 368 } 369 } 370 371 NTOHL_FP(&rpkt->org, &p_org); 372 373 if (L_ISZERO(&p_org) || 374 L_ISZERO( myorg) || 375 !L_ISEQU(&p_org, myorg)) { 376 return INVALIDNAK; 377 } 378 379 /* If we ever passed all that checks, we should be safe. Well, 380 * as safe as we can ever be with an unauthenticated crypto-nak. 381 */ 382 return VALIDNAK; 383 } 384 385 386 /* 387 * transmit - transmit procedure called by poll timeout 388 */ 389 void 390 transmit( 391 struct peer *peer /* peer structure pointer */ 392 ) 393 { 394 u_char hpoll; 395 396 /* 397 * The polling state machine. There are two kinds of machines, 398 * those that never expect a reply (broadcast and manycast 399 * server modes) and those that do (all other modes). The dance 400 * is intricate... 401 */ 402 hpoll = peer->hpoll; 403 404 /* 405 * If we haven't received anything (even if unsync) since last 406 * send, reset ppoll. 407 */ 408 if (peer->outdate > peer->timelastrec && !peer->reach) 409 peer->ppoll = peer->maxpoll; 410 411 /* 412 * In broadcast mode the poll interval is never changed from 413 * minpoll. 414 */ 415 if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) { 416 peer->outdate = current_time; 417 poll_update(peer, hpoll, 0); 418 if (sys_leap != LEAP_NOTINSYNC) 419 peer_xmit(peer); 420 return; 421 } 422 423 /* 424 * In manycast mode we start with unity ttl. The ttl is 425 * increased by one for each poll until either sys_maxclock 426 * servers have been found or the maximum ttl is reached. When 427 * sys_maxclock servers are found we stop polling until one or 428 * more servers have timed out or until less than sys_minclock 429 * associations turn up. In this case additional better servers 430 * are dragged in and preempt the existing ones. Once every 431 * sys_beacon seconds we are to transmit unconditionally, but 432 * this code is not quite right -- peer->unreach counts polls 433 * and is being compared with sys_beacon, so the beacons happen 434 * every sys_beacon polls. 435 */ 436 if (peer->cast_flags & MDF_ACAST) { 437 peer->outdate = current_time; 438 poll_update(peer, hpoll, 0); 439 if (peer->unreach > sys_beacon) { 440 peer->unreach = 0; 441 peer->ttl = 0; 442 peer_xmit(peer); 443 } else if ( sys_survivors < sys_minclock 444 || peer_associations < sys_maxclock) { 445 if (peer->ttl < sys_ttlmax) 446 peer->ttl++; 447 peer_xmit(peer); 448 } 449 peer->unreach++; 450 return; 451 } 452 453 /* 454 * Pool associations transmit unicast solicitations when there 455 * are less than a hard limit of 2 * sys_maxclock associations, 456 * and either less than sys_minclock survivors or less than 457 * sys_maxclock associations. The hard limit prevents unbounded 458 * growth in associations if the system clock or network quality 459 * result in survivor count dipping below sys_minclock often. 460 * This was observed testing with pool, where sys_maxclock == 12 461 * resulted in 60 associations without the hard limit. A 462 * similar hard limit on manycastclient ephemeral associations 463 * may be appropriate. 464 */ 465 if (peer->cast_flags & MDF_POOL) { 466 peer->outdate = current_time; 467 poll_update(peer, hpoll, 0); 468 if ( (peer_associations <= 2 * sys_maxclock) 469 && ( peer_associations < sys_maxclock 470 || sys_survivors < sys_minclock)) 471 pool_xmit(peer); 472 return; 473 } 474 475 /* 476 * In unicast modes the dance is much more intricate. It is 477 * designed to back off whenever possible to minimize network 478 * traffic. 479 */ 480 if (peer->burst == 0) { 481 u_char oreach; 482 483 /* 484 * Update the reachability status. If not heard for 485 * three consecutive polls, stuff infinity in the clock 486 * filter. 487 */ 488 oreach = peer->reach; 489 peer->outdate = current_time; 490 peer->unreach++; 491 peer->reach <<= 1; 492 if (!peer->reach) { 493 494 /* 495 * Here the peer is unreachable. If it was 496 * previously reachable raise a trap. Send a 497 * burst if enabled. 498 */ 499 clock_filter(peer, 0., 0., MAXDISPERSE); 500 if (oreach) { 501 peer_unfit(peer); 502 report_event(PEVNT_UNREACH, peer, NULL); 503 } 504 if ( (peer->flags & FLAG_IBURST) 505 && peer->retry == 0) 506 peer->retry = NTP_RETRY; 507 } else { 508 509 /* 510 * Here the peer is reachable. Send a burst if 511 * enabled and the peer is fit. Reset unreach 512 * for persistent and ephemeral associations. 513 * Unreach is also reset for survivors in 514 * clock_select(). 515 */ 516 hpoll = sys_poll; 517 if (!(peer->flags & FLAG_PREEMPT)) 518 peer->unreach = 0; 519 if ( (peer->flags & FLAG_BURST) 520 && peer->retry == 0 521 && !peer_unfit(peer)) 522 peer->retry = NTP_RETRY; 523 } 524 525 /* 526 * Watch for timeout. If ephemeral, toss the rascal; 527 * otherwise, bump the poll interval. Note the 528 * poll_update() routine will clamp it to maxpoll. 529 * If preemptible and we have more peers than maxclock, 530 * and this peer has the minimum score of preemptibles, 531 * demobilize. 532 */ 533 if (peer->unreach >= NTP_UNREACH) { 534 hpoll++; 535 /* ephemeral: no FLAG_CONFIG nor FLAG_PREEMPT */ 536 if (!(peer->flags & (FLAG_CONFIG | FLAG_PREEMPT))) { 537 report_event(PEVNT_RESTART, peer, "timeout"); 538 peer_clear(peer, "TIME"); 539 unpeer(peer); 540 return; 541 } 542 if ( (peer->flags & FLAG_PREEMPT) 543 && (peer_associations > sys_maxclock) 544 && score_all(peer)) { 545 report_event(PEVNT_RESTART, peer, "timeout"); 546 peer_clear(peer, "TIME"); 547 unpeer(peer); 548 return; 549 } 550 } 551 } else { 552 peer->burst--; 553 if (peer->burst == 0) { 554 555 /* 556 * If ntpdate mode and the clock has not been 557 * set and all peers have completed the burst, 558 * we declare a successful failure. 559 */ 560 if (mode_ntpdate) { 561 peer_ntpdate--; 562 if (peer_ntpdate == 0) { 563 msyslog(LOG_NOTICE, 564 "ntpd: no servers found"); 565 if (!msyslog_term) 566 printf( 567 "ntpd: no servers found\n"); 568 exit (0); 569 } 570 } 571 } 572 } 573 if (peer->retry > 0) 574 peer->retry--; 575 576 /* 577 * Do not transmit if in broadcast client mode. 578 */ 579 poll_update(peer, hpoll, (peer->hmode == MODE_CLIENT)); 580 if (peer->hmode != MODE_BCLIENT) 581 peer_xmit(peer); 582 583 return; 584 } 585 586 587 const char * 588 amtoa( 589 int am 590 ) 591 { 592 char *bp; 593 594 switch(am) { 595 case AM_ERR: return "AM_ERR"; 596 case AM_NOMATCH: return "AM_NOMATCH"; 597 case AM_PROCPKT: return "AM_PROCPKT"; 598 case AM_BCST: return "AM_BCST"; 599 case AM_FXMIT: return "AM_FXMIT"; 600 case AM_MANYCAST: return "AM_MANYCAST"; 601 case AM_NEWPASS: return "AM_NEWPASS"; 602 case AM_NEWBCL: return "AM_NEWBCL"; 603 case AM_POSSBCL: return "AM_POSSBCL"; 604 default: 605 LIB_GETBUF(bp); 606 snprintf(bp, LIB_BUFLENGTH, "AM_#%d", am); 607 return bp; 608 } 609 } 610 611 612 /* 613 * receive - receive procedure called for each packet received 614 */ 615 void 616 receive( 617 struct recvbuf *rbufp 618 ) 619 { 620 register struct peer *peer; /* peer structure pointer */ 621 register struct pkt *pkt; /* receive packet pointer */ 622 u_char hisversion; /* packet version */ 623 u_char hisleap; /* packet leap indicator */ 624 u_char hismode; /* packet mode */ 625 u_char hisstratum; /* packet stratum */ 626 r4addr r4a; /* address restrictions */ 627 u_short restrict_mask; /* restrict bits */ 628 const char *hm_str; /* hismode string */ 629 const char *am_str; /* association match string */ 630 int kissCode = NOKISS; /* Kiss Code */ 631 int has_mac; /* length of MAC field */ 632 int authlen; /* offset of MAC field */ 633 auth_code is_authentic = AUTH_UNKNOWN; /* Was AUTH_NONE */ 634 nak_code crypto_nak_test; /* result of crypto-NAK check */ 635 int retcode = AM_NOMATCH; /* match code */ 636 keyid_t skeyid = 0; /* key IDs */ 637 u_int32 opcode = 0; /* extension field opcode */ 638 sockaddr_u *dstadr_sin; /* active runway */ 639 struct peer *peer2; /* aux peer structure pointer */ 640 endpt *match_ep; /* newpeer() local address */ 641 l_fp p_org; /* origin timestamp */ 642 l_fp p_rec; /* receive timestamp */ 643 l_fp p_xmt; /* transmit timestamp */ 644 #ifdef AUTOKEY 645 char hostname[NTP_MAXSTRLEN + 1]; 646 char *groupname = NULL; 647 struct autokey *ap; /* autokey structure pointer */ 648 int rval; /* cookie snatcher */ 649 keyid_t pkeyid = 0, tkeyid = 0; /* key IDs */ 650 #endif /* AUTOKEY */ 651 #ifdef HAVE_NTP_SIGND 652 static unsigned char zero_key[16]; 653 #endif /* HAVE_NTP_SIGND */ 654 655 /* 656 * Note that there are many places we do not call record_raw_stats(). 657 * 658 * We only want to call it *after* we've sent a response, or perhaps 659 * when we've decided to drop a packet. 660 */ 661 662 /* 663 * Monitor the packet and get restrictions. Note that the packet 664 * length for control and private mode packets must be checked 665 * by the service routines. Some restrictions have to be handled 666 * later in order to generate a kiss-o'-death packet. 667 */ 668 /* 669 * Bogus port check is before anything, since it probably 670 * reveals a clogging attack. Likewise the mimimum packet size 671 * of 2 bytes (for mode 6/7) must be checked first. 672 */ 673 sys_received++; 674 if (0 == SRCPORT(&rbufp->recv_srcadr) || rbufp->recv_length < 2) { 675 sys_badlength++; 676 return; /* bogus port / length */ 677 } 678 restrictions(&rbufp->recv_srcadr, &r4a); 679 restrict_mask = r4a.rflags; 680 681 pkt = &rbufp->recv_pkt; 682 hisversion = PKT_VERSION(pkt->li_vn_mode); 683 hismode = (int)PKT_MODE(pkt->li_vn_mode); 684 685 if (restrict_mask & RES_IGNORE) { 686 DPRINTF(2, ("receive: drop: RES_IGNORE\n")); 687 sys_restricted++; 688 return; /* ignore everything */ 689 } 690 if (hismode == MODE_PRIVATE) { 691 if (!ntp_mode7 || (restrict_mask & RES_NOQUERY)) { 692 DPRINTF(2, ("receive: drop: RES_NOQUERY\n")); 693 sys_restricted++; 694 return; /* no query private */ 695 } 696 process_private(rbufp, ((restrict_mask & 697 RES_NOMODIFY) == 0)); 698 return; 699 } 700 if (hismode == MODE_CONTROL) { 701 if (restrict_mask & RES_NOQUERY) { 702 DPRINTF(2, ("receive: drop: RES_NOQUERY\n")); 703 sys_restricted++; 704 return; /* no query control */ 705 } 706 process_control(rbufp, restrict_mask); 707 return; 708 } 709 if (restrict_mask & RES_DONTSERVE) { 710 DPRINTF(2, ("receive: drop: RES_DONTSERVE\n")); 711 sys_restricted++; 712 return; /* no time serve */ 713 } 714 715 716 /* If we arrive here, we should have a standard NTP packet. We 717 * check that the minimum size is available and fetch some more 718 * items from the packet once we can be sure they are indeed 719 * there. 720 */ 721 if (rbufp->recv_length < LEN_PKT_NOMAC) { 722 sys_badlength++; 723 return; /* bogus length */ 724 } 725 726 hisleap = PKT_LEAP(pkt->li_vn_mode); 727 hisstratum = PKT_TO_STRATUM(pkt->stratum); 728 INSIST(0 != hisstratum); /* paranoia check PKT_TO_STRATUM result */ 729 730 DPRINTF(1, ("receive: at %ld %s<-%s ippeerlimit %d mode %d iflags %s " 731 "restrict %s org %#010x.%08x xmt %#010x.%08x\n", 732 current_time, stoa(&rbufp->dstadr->sin), 733 stoa(&rbufp->recv_srcadr), r4a.ippeerlimit, hismode, 734 build_iflags(rbufp->dstadr->flags), 735 build_rflags(restrict_mask), 736 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf), 737 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf))); 738 739 /* 740 * This is for testing. If restricted drop ten percent of 741 * surviving packets. 742 */ 743 if (restrict_mask & RES_FLAKE) { 744 if (ntp_uurandom() < .1) { 745 DPRINTF(2, ("receive: drop: RES_FLAKE\n")); 746 sys_restricted++; 747 return; /* no flakeway */ 748 } 749 } 750 751 /* 752 ** Format Layer Checks 753 ** 754 ** Validate the packet format. The packet size, packet header, 755 ** and any extension field lengths are checked. We identify 756 ** the beginning of the MAC, to identify the upper limit of 757 ** of the hash computation. 758 ** 759 ** In case of a format layer check violation, the packet is 760 ** discarded with no further processing. 761 */ 762 763 /* 764 * Version check must be after the query packets, since they 765 * intentionally use an early version. 766 */ 767 if (hisversion == NTP_VERSION) { 768 sys_newversion++; /* new version */ 769 } else if ( !(restrict_mask & RES_VERSION) 770 && hisversion >= NTP_OLDVERSION) { 771 sys_oldversion++; /* previous version */ 772 } else { 773 DPRINTF(2, ("receive: drop: RES_VERSION\n")); 774 sys_badlength++; 775 return; /* old version */ 776 } 777 778 /* 779 * Figure out his mode and validate the packet. This has some 780 * legacy raunch that probably should be removed. In very early 781 * NTP versions mode 0 was equivalent to what later versions 782 * would interpret as client mode. 783 */ 784 if (hismode == MODE_UNSPEC) { 785 if (hisversion == NTP_OLDVERSION) { 786 hismode = MODE_CLIENT; 787 } else { 788 DPRINTF(2, ("receive: drop: MODE_UNSPEC\n")); 789 sys_badlength++; 790 return; /* invalid mode */ 791 } 792 } 793 794 /* 795 * Validate the poll interval in the packet. 796 * 0 probably indicates a data-minimized packet. 797 * A valid poll interval is required for RATEKISS, where 798 * a value of 0 is not allowed. We check for this below. 799 * 800 * There might be arguments against this check. If you have 801 * any of these arguments, please let us know. 802 * 803 * At this point, the packet cannot be a mode[67] packet. 804 */ 805 if ( pkt->ppoll 806 && ( (NTP_MINPOLL > pkt->ppoll) 807 || (NTP_MAXPOLL < pkt->ppoll) 808 ) 809 ) { 810 DPRINTF(2, ("receive: drop: Invalid ppoll (%d) from %s\n", 811 pkt->ppoll, stoa(&rbufp->recv_srcadr))); 812 sys_badlength++; 813 return; /* invalid packet poll */ 814 } 815 816 /* 817 * Parse the extension field if present. We figure out whether 818 * an extension field is present by measuring the MAC size. If 819 * the number of words following the packet header is 0, no MAC 820 * is present and the packet is not authenticated. If 1, the 821 * packet is a crypto-NAK; if 3, the packet is authenticated 822 * with DES; if 5, the packet is authenticated with MD5; if 6, 823 * the packet is authenticated with SHA. If 2 or * 4, the packet 824 * is a runt and discarded forthwith. If greater than 6, an 825 * extension field is present, so we subtract the length of the 826 * field and go around again. 827 * 828 * Note the above description is lame. We should/could also check 829 * the two bytes that make up the EF type and subtype, and then 830 * check the two bytes that tell us the EF length. A legacy MAC 831 * has a 4 byte keyID, and for conforming symmetric keys its value 832 * must be <= 64k, meaning the top two bytes will always be zero. 833 * Since the EF Type of 0 is reserved/unused, there's no way a 834 * conforming legacy MAC could ever be misinterpreted as an EF. 835 * 836 * There is more, but this isn't the place to document it. 837 */ 838 839 authlen = LEN_PKT_NOMAC; 840 has_mac = rbufp->recv_length - authlen; 841 while (has_mac > 0) { 842 u_int32 len; 843 #ifdef AUTOKEY 844 u_int32 hostlen; 845 struct exten *ep; 846 #endif /*AUTOKEY */ 847 848 if (has_mac % 4 != 0 || has_mac < (int)MIN_MAC_LEN) { 849 DPRINTF(2, ("receive: drop: bad post-packet length\n")); 850 sys_badlength++; 851 return; /* bad length */ 852 } 853 /* 854 * This next test is clearly wrong - it needlessly 855 * prohibits short EFs (which don't yet exist) 856 */ 857 if (has_mac <= (int)MAX_MAC_LEN) { 858 skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]); 859 break; 860 861 } else { 862 opcode = ntohl(((u_int32 *)pkt)[authlen / 4]); 863 len = opcode & 0xffff; 864 if ( len % 4 != 0 865 || len < 4 866 || (int)len + authlen > rbufp->recv_length) { 867 DPRINTF(2, ("receive: drop: bad EF length\n")); 868 sys_badlength++; 869 return; /* bad length */ 870 } 871 #ifdef AUTOKEY 872 /* 873 * Extract calling group name for later. If 874 * sys_groupname is non-NULL, there must be 875 * a group name provided to elicit a response. 876 */ 877 if ( (opcode & 0x3fff0000) == CRYPTO_ASSOC 878 && sys_groupname != NULL) { 879 ep = (struct exten *)&((u_int32 *)pkt)[authlen / 4]; 880 hostlen = ntohl(ep->vallen); 881 if ( hostlen >= sizeof(hostname) 882 || hostlen > len - 883 offsetof(struct exten, pkt)) { 884 DPRINTF(2, ("receive: drop: bad autokey hostname length\n")); 885 sys_badlength++; 886 return; /* bad length */ 887 } 888 memcpy(hostname, &ep->pkt, hostlen); 889 hostname[hostlen] = '\0'; 890 groupname = strchr(hostname, '@'); 891 if (groupname == NULL) { 892 DPRINTF(2, ("receive: drop: empty autokey groupname\n")); 893 sys_declined++; 894 return; 895 } 896 groupname++; 897 } 898 #endif /* AUTOKEY */ 899 authlen += len; 900 has_mac -= len; 901 } 902 } 903 904 /* 905 * If has_mac is < 0 we had a malformed packet. 906 */ 907 if (has_mac < 0) { 908 DPRINTF(2, ("receive: drop: post-packet under-read\n")); 909 sys_badlength++; 910 return; /* bad length */ 911 } 912 913 /* 914 ** Packet Data Verification Layer 915 ** 916 ** This layer verifies the packet data content. If 917 ** authentication is required, a MAC must be present. 918 ** If a MAC is present, it must validate. 919 ** Crypto-NAK? Look - a shiny thing! 920 ** 921 ** If authentication fails, we're done. 922 */ 923 924 /* 925 * If authentication is explicitly required, a MAC must be present. 926 */ 927 if (restrict_mask & RES_DONTTRUST && has_mac == 0) { 928 DPRINTF(2, ("receive: drop: RES_DONTTRUST\n")); 929 sys_restricted++; 930 return; /* access denied */ 931 } 932 933 /* 934 * Update the MRU list and finger the cloggers. It can be a 935 * little expensive, so turn it off for production use. 936 * RES_LIMITED and RES_KOD will be cleared in the returned 937 * restrict_mask unless one or both actions are warranted. 938 */ 939 restrict_mask = ntp_monitor(rbufp, restrict_mask); 940 if (restrict_mask & RES_LIMITED) { 941 sys_limitrejected++; 942 if ( !(restrict_mask & RES_KOD) 943 || MODE_BROADCAST == hismode 944 || MODE_SERVER == hismode) { 945 if (MODE_SERVER == hismode) { 946 DPRINTF(1, ("Possibly self-induced rate limiting of MODE_SERVER from %s\n", 947 stoa(&rbufp->recv_srcadr))); 948 } else { 949 DPRINTF(2, ("receive: drop: RES_KOD\n")); 950 } 951 return; /* rate exceeded */ 952 } 953 if (hismode == MODE_CLIENT) { 954 fast_xmit(rbufp, MODE_SERVER, skeyid, 955 restrict_mask); 956 } else { 957 fast_xmit(rbufp, MODE_ACTIVE, skeyid, 958 restrict_mask); 959 } 960 return; /* rate exceeded */ 961 } 962 restrict_mask &= ~RES_KOD; 963 964 /* 965 * We have tossed out as many buggy packets as possible early in 966 * the game to reduce the exposure to a clogging attack. Now we 967 * have to burn some cycles to find the association and 968 * authenticate the packet if required. Note that we burn only 969 * digest cycles, again to reduce exposure. There may be no 970 * matching association and that's okay. 971 * 972 * More on the autokey mambo. Normally the local interface is 973 * found when the association was mobilized with respect to a 974 * designated remote address. We assume packets arriving from 975 * the remote address arrive via this interface and the local 976 * address used to construct the autokey is the unicast address 977 * of the interface. However, if the sender is a broadcaster, 978 * the interface broadcast address is used instead. 979 * Notwithstanding this technobabble, if the sender is a 980 * multicaster, the broadcast address is null, so we use the 981 * unicast address anyway. Don't ask. 982 */ 983 984 peer = findpeer(rbufp, hismode, &retcode); 985 dstadr_sin = &rbufp->dstadr->sin; 986 NTOHL_FP(&pkt->org, &p_org); 987 NTOHL_FP(&pkt->rec, &p_rec); 988 NTOHL_FP(&pkt->xmt, &p_xmt); 989 hm_str = modetoa(hismode); 990 am_str = amtoa(retcode); 991 992 /* 993 * Authentication is conditioned by three switches: 994 * 995 * NOPEER (RES_NOPEER) do not mobilize an association unless 996 * authenticated 997 * NOTRUST (RES_DONTTRUST) do not allow access unless 998 * authenticated (implies NOPEER) 999 * enable (sys_authenticate) master NOPEER switch, by default 1000 * on 1001 * 1002 * The NOPEER and NOTRUST can be specified on a per-client basis 1003 * using the restrict command. The enable switch if on implies 1004 * NOPEER for all clients. There are four outcomes: 1005 * 1006 * NONE The packet has no MAC. 1007 * OK the packet has a MAC and authentication succeeds 1008 * ERROR the packet has a MAC and authentication fails 1009 * CRYPTO crypto-NAK. The MAC has four octets only. 1010 * 1011 * Note: The AUTH(x, y) macro is used to filter outcomes. If x 1012 * is zero, acceptable outcomes of y are NONE and OK. If x is 1013 * one, the only acceptable outcome of y is OK. 1014 */ 1015 crypto_nak_test = valid_NAK(peer, rbufp, hismode); 1016 1017 /* 1018 * Drop any invalid crypto-NAKs 1019 */ 1020 if (crypto_nak_test == INVALIDNAK) { 1021 report_event(PEVNT_AUTH, peer, "Invalid_NAK"); 1022 if (0 != peer) { 1023 peer->badNAK++; 1024 } 1025 msyslog(LOG_ERR, "Invalid-NAK error at %ld %s<-%s", 1026 current_time, stoa(dstadr_sin), stoa(&rbufp->recv_srcadr)); 1027 return; 1028 } 1029 1030 if (has_mac == 0) { 1031 restrict_mask &= ~RES_MSSNTP; 1032 is_authentic = AUTH_NONE; /* not required */ 1033 DPRINTF(1, ("receive: at %ld %s<-%s mode %d/%s:%s len %d org %#010x.%08x xmt %#010x.%08x NOMAC\n", 1034 current_time, stoa(dstadr_sin), 1035 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str, 1036 authlen, 1037 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf), 1038 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf))); 1039 } else if (crypto_nak_test == VALIDNAK) { 1040 restrict_mask &= ~RES_MSSNTP; 1041 is_authentic = AUTH_CRYPTO; /* crypto-NAK */ 1042 DPRINTF(1, ("receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x CRYPTONAK\n", 1043 current_time, stoa(dstadr_sin), 1044 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str, 1045 skeyid, authlen + has_mac, is_authentic, 1046 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf), 1047 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf))); 1048 1049 #ifdef HAVE_NTP_SIGND 1050 /* 1051 * If the signature is 20 bytes long, the last 16 of 1052 * which are zero, then this is a Microsoft client 1053 * wanting AD-style authentication of the server's 1054 * reply. 1055 * 1056 * This is described in Microsoft's WSPP docs, in MS-SNTP: 1057 * http://msdn.microsoft.com/en-us/library/cc212930.aspx 1058 */ 1059 } else if ( has_mac == MAX_MD5_LEN 1060 && (restrict_mask & RES_MSSNTP) 1061 && (retcode == AM_FXMIT || retcode == AM_NEWPASS) 1062 && (memcmp(zero_key, (char *)pkt + authlen + 4, 1063 MAX_MD5_LEN - 4) == 0)) { 1064 is_authentic = AUTH_NONE; 1065 DPRINTF(1, ("receive: at %ld %s<-%s mode %d/%s:%s len %d org %#010x.%08x xmt %#010x.%08x SIGND\n", 1066 current_time, stoa(dstadr_sin), 1067 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str, 1068 authlen, 1069 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf), 1070 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf))); 1071 #endif /* HAVE_NTP_SIGND */ 1072 1073 } else { 1074 /* 1075 * has_mac is not 0 1076 * Not a VALID_NAK 1077 * Not an MS-SNTP SIGND packet 1078 * 1079 * So there is a MAC here. 1080 */ 1081 1082 restrict_mask &= ~RES_MSSNTP; 1083 #ifdef AUTOKEY 1084 /* 1085 * For autokey modes, generate the session key 1086 * and install in the key cache. Use the socket 1087 * broadcast or unicast address as appropriate. 1088 */ 1089 if (crypto_flags && skeyid > NTP_MAXKEY) { 1090 1091 /* 1092 * More on the autokey dance (AKD). A cookie is 1093 * constructed from public and private values. 1094 * For broadcast packets, the cookie is public 1095 * (zero). For packets that match no 1096 * association, the cookie is hashed from the 1097 * addresses and private value. For server 1098 * packets, the cookie was previously obtained 1099 * from the server. For symmetric modes, the 1100 * cookie was previously constructed using an 1101 * agreement protocol; however, should PKI be 1102 * unavailable, we construct a fake agreement as 1103 * the EXOR of the peer and host cookies. 1104 * 1105 * hismode ephemeral persistent 1106 * ======================================= 1107 * active 0 cookie# 1108 * passive 0% cookie# 1109 * client sys cookie 0% 1110 * server 0% sys cookie 1111 * broadcast 0 0 1112 * 1113 * # if unsync, 0 1114 * % can't happen 1115 */ 1116 if (has_mac < (int)MAX_MD5_LEN) { 1117 DPRINTF(2, ("receive: drop: MD5 digest too short\n")); 1118 sys_badauth++; 1119 return; 1120 } 1121 if (hismode == MODE_BROADCAST) { 1122 1123 /* 1124 * For broadcaster, use the interface 1125 * broadcast address when available; 1126 * otherwise, use the unicast address 1127 * found when the association was 1128 * mobilized. However, if this is from 1129 * the wildcard interface, game over. 1130 */ 1131 if ( crypto_flags 1132 && rbufp->dstadr == 1133 ANY_INTERFACE_CHOOSE(&rbufp->recv_srcadr)) { 1134 DPRINTF(2, ("receive: drop: BCAST from wildcard\n")); 1135 sys_restricted++; 1136 return; /* no wildcard */ 1137 } 1138 pkeyid = 0; 1139 if (!SOCK_UNSPEC(&rbufp->dstadr->bcast)) 1140 dstadr_sin = 1141 &rbufp->dstadr->bcast; 1142 } else if (peer == NULL) { 1143 pkeyid = session_key( 1144 &rbufp->recv_srcadr, dstadr_sin, 0, 1145 sys_private, 0); 1146 } else { 1147 pkeyid = peer->pcookie; 1148 } 1149 1150 /* 1151 * The session key includes both the public 1152 * values and cookie. In case of an extension 1153 * field, the cookie used for authentication 1154 * purposes is zero. Note the hash is saved for 1155 * use later in the autokey mambo. 1156 */ 1157 if (authlen > (int)LEN_PKT_NOMAC && pkeyid != 0) { 1158 session_key(&rbufp->recv_srcadr, 1159 dstadr_sin, skeyid, 0, 2); 1160 tkeyid = session_key( 1161 &rbufp->recv_srcadr, dstadr_sin, 1162 skeyid, pkeyid, 0); 1163 } else { 1164 tkeyid = session_key( 1165 &rbufp->recv_srcadr, dstadr_sin, 1166 skeyid, pkeyid, 2); 1167 } 1168 1169 } 1170 #endif /* AUTOKEY */ 1171 1172 /* 1173 * Compute the cryptosum. Note a clogging attack may 1174 * succeed in bloating the key cache. If an autokey, 1175 * purge it immediately, since we won't be needing it 1176 * again. If the packet is authentic, it can mobilize an 1177 * association. Note that there is no key zero. 1178 */ 1179 if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen, 1180 has_mac)) 1181 is_authentic = AUTH_ERROR; 1182 else 1183 is_authentic = AUTH_OK; 1184 #ifdef AUTOKEY 1185 if (crypto_flags && skeyid > NTP_MAXKEY) 1186 authtrust(skeyid, 0); 1187 #endif /* AUTOKEY */ 1188 DPRINTF(1, ("receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x MAC\n", 1189 current_time, stoa(dstadr_sin), 1190 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str, 1191 skeyid, authlen + has_mac, is_authentic, 1192 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf), 1193 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf))); 1194 } 1195 1196 1197 /* 1198 * Bug 3454: 1199 * 1200 * Now come at this from a different perspective: 1201 * - If we expect a MAC and it's not there, we drop it. 1202 * - If we expect one keyID and get another, we drop it. 1203 * - If we have a MAC ahd it hasn't been validated yet, try. 1204 * - if the provided MAC doesn't validate, we drop it. 1205 * 1206 * There might be more to this. 1207 */ 1208 if (0 != peer && 0 != peer->keyid) { 1209 /* Should we msyslog() any of these? */ 1210 1211 /* 1212 * This should catch: 1213 * - no keyID where one is expected, 1214 * - different keyID than what we expect. 1215 */ 1216 if (peer->keyid != skeyid) { 1217 DPRINTF(2, ("receive: drop: Wanted keyID %d, got %d from %s\n", 1218 peer->keyid, skeyid, 1219 stoa(&rbufp->recv_srcadr))); 1220 sys_restricted++; 1221 return; /* drop: access denied */ 1222 } 1223 1224 /* 1225 * if has_mac != 0 ... 1226 * - If it has not yet been validated, do so. 1227 * (under what circumstances might that happen?) 1228 * - if missing or bad MAC, log and drop. 1229 */ 1230 if (0 != has_mac) { 1231 if (is_authentic == AUTH_UNKNOWN) { 1232 /* How can this happen? */ 1233 DPRINTF(2, ("receive: 3454 check: AUTH_UNKNOWN from %s\n", 1234 stoa(&rbufp->recv_srcadr))); 1235 if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen, 1236 has_mac)) { 1237 /* MAC invalid or not found */ 1238 is_authentic = AUTH_ERROR; 1239 } else { 1240 is_authentic = AUTH_OK; 1241 } 1242 } 1243 if (is_authentic != AUTH_OK) { 1244 DPRINTF(2, ("receive: drop: missing or bad MAC from %s\n", 1245 stoa(&rbufp->recv_srcadr))); 1246 sys_restricted++; 1247 return; /* drop: access denied */ 1248 } 1249 } 1250 } 1251 /**/ 1252 1253 /* 1254 ** On-Wire Protocol Layer 1255 ** 1256 ** Verify protocol operations consistent with the on-wire protocol. 1257 ** The protocol discards bogus and duplicate packets as well as 1258 ** minimizes disruptions doe to protocol restarts and dropped 1259 ** packets. The operations are controlled by two timestamps: 1260 ** the transmit timestamp saved in the client state variables, 1261 ** and the origin timestamp in the server packet header. The 1262 ** comparison of these two timestamps is called the loopback test. 1263 ** The transmit timestamp functions as a nonce to verify that the 1264 ** response corresponds to the original request. The transmit 1265 ** timestamp also serves to discard replays of the most recent 1266 ** packet. Upon failure of either test, the packet is discarded 1267 ** with no further action. 1268 */ 1269 1270 /* 1271 * The association matching rules are implemented by a set of 1272 * routines and an association table. A packet matching an 1273 * association is processed by the peer process for that 1274 * association. If there are no errors, an ephemeral association 1275 * is mobilized: a broadcast packet mobilizes a broadcast client 1276 * aassociation; a manycast server packet mobilizes a manycast 1277 * client association; a symmetric active packet mobilizes a 1278 * symmetric passive association. 1279 */ 1280 DPRINTF(1, ("receive: MATCH_ASSOC dispatch: mode %d/%s:%s \n", 1281 hismode, hm_str, am_str)); 1282 switch (retcode) { 1283 1284 /* 1285 * This is a client mode packet not matching any association. If 1286 * an ordinary client, simply toss a server mode packet back 1287 * over the fence. If a manycast client, we have to work a 1288 * little harder. 1289 * 1290 * There are cases here where we do not call record_raw_stats(). 1291 */ 1292 case AM_FXMIT: 1293 1294 /* 1295 * If authentication OK, send a server reply; otherwise, 1296 * send a crypto-NAK. 1297 */ 1298 if (!(rbufp->dstadr->flags & INT_MCASTOPEN)) { 1299 /* HMS: would be nice to log FAST_XMIT|BADAUTH|RESTRICTED */ 1300 record_raw_stats(&rbufp->recv_srcadr, 1301 &rbufp->dstadr->sin, 1302 &p_org, &p_rec, &p_xmt, &rbufp->recv_time, 1303 PKT_LEAP(pkt->li_vn_mode), 1304 PKT_VERSION(pkt->li_vn_mode), 1305 PKT_MODE(pkt->li_vn_mode), 1306 PKT_TO_STRATUM(pkt->stratum), 1307 pkt->ppoll, 1308 pkt->precision, 1309 FPTOD(NTOHS_FP(pkt->rootdelay)), 1310 FPTOD(NTOHS_FP(pkt->rootdisp)), 1311 pkt->refid, 1312 rbufp->recv_length - MIN_V4_PKT_LEN, (u_char *)&pkt->exten); 1313 1314 if (AUTH(restrict_mask & RES_DONTTRUST, 1315 is_authentic)) { 1316 /* Bug 3596: Do we want to fuzz the reftime? */ 1317 fast_xmit(rbufp, MODE_SERVER, skeyid, 1318 restrict_mask); 1319 } else if (is_authentic == AUTH_ERROR) { 1320 /* Bug 3596: Do we want to fuzz the reftime? */ 1321 fast_xmit(rbufp, MODE_SERVER, 0, 1322 restrict_mask); 1323 sys_badauth++; 1324 } else { 1325 DPRINTF(2, ("receive: AM_FXMIT drop: !mcast restricted\n")); 1326 sys_restricted++; 1327 } 1328 1329 return; /* hooray */ 1330 } 1331 1332 /* 1333 * This must be manycast. Do not respond if not 1334 * configured as a manycast server. 1335 */ 1336 if (!sys_manycastserver) { 1337 DPRINTF(2, ("receive: AM_FXMIT drop: Not manycastserver\n")); 1338 sys_restricted++; 1339 return; /* not enabled */ 1340 } 1341 1342 #ifdef AUTOKEY 1343 /* 1344 * Do not respond if not the same group. 1345 */ 1346 if (group_test(groupname, NULL)) { 1347 DPRINTF(2, ("receive: AM_FXMIT drop: empty groupname\n")); 1348 sys_declined++; 1349 return; 1350 } 1351 #endif /* AUTOKEY */ 1352 1353 /* 1354 * Do not respond if we are not synchronized or our 1355 * stratum is greater than the manycaster or the 1356 * manycaster has already synchronized to us. 1357 */ 1358 if ( sys_leap == LEAP_NOTINSYNC 1359 || sys_stratum >= hisstratum 1360 || (!sys_cohort && sys_stratum == hisstratum + 1) 1361 || rbufp->dstadr->addr_refid == pkt->refid) { 1362 DPRINTF(2, ("receive: sys leap: %0x, sys_stratum %d > hisstratum+1 %d, !sys_cohort %d && sys_stratum == hisstratum+1, loop refid %#x == pkt refid %#x\n", sys_leap, sys_stratum, hisstratum + 1, !sys_cohort, rbufp->dstadr->addr_refid, pkt->refid)); 1363 DPRINTF(2, ("receive: AM_FXMIT drop: LEAP_NOTINSYNC || stratum || loop\n")); 1364 sys_declined++; 1365 return; /* no help */ 1366 } 1367 1368 /* 1369 * Respond only if authentication succeeds. Don't do a 1370 * crypto-NAK, as that would not be useful. 1371 */ 1372 if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic)) { 1373 record_raw_stats(&rbufp->recv_srcadr, 1374 &rbufp->dstadr->sin, 1375 &p_org, &p_rec, &p_xmt, &rbufp->recv_time, 1376 PKT_LEAP(pkt->li_vn_mode), 1377 PKT_VERSION(pkt->li_vn_mode), 1378 PKT_MODE(pkt->li_vn_mode), 1379 PKT_TO_STRATUM(pkt->stratum), 1380 pkt->ppoll, 1381 pkt->precision, 1382 FPTOD(NTOHS_FP(pkt->rootdelay)), 1383 FPTOD(NTOHS_FP(pkt->rootdisp)), 1384 pkt->refid, 1385 rbufp->recv_length - MIN_V4_PKT_LEN, (u_char *)&pkt->exten); 1386 1387 /* Bug 3596: Do we want to fuzz the reftime? */ 1388 fast_xmit(rbufp, MODE_SERVER, skeyid, 1389 restrict_mask); 1390 } 1391 return; /* hooray */ 1392 1393 /* 1394 * This is a server mode packet returned in response to a client 1395 * mode packet sent to a multicast group address (for 1396 * manycastclient) or to a unicast address (for pool). The 1397 * origin timestamp is a good nonce to reliably associate the 1398 * reply with what was sent. If there is no match, that's 1399 * curious and could be an intruder attempting to clog, so we 1400 * just ignore it. 1401 * 1402 * If the packet is authentic and the manycastclient or pool 1403 * association is found, we mobilize a client association and 1404 * copy pertinent variables from the manycastclient or pool 1405 * association to the new client association. If not, just 1406 * ignore the packet. 1407 * 1408 * There is an implosion hazard at the manycast client, since 1409 * the manycast servers send the server packet immediately. If 1410 * the guy is already here, don't fire up a duplicate. 1411 * 1412 * There are cases here where we do not call record_raw_stats(). 1413 */ 1414 case AM_MANYCAST: 1415 1416 #ifdef AUTOKEY 1417 /* 1418 * Do not respond if not the same group. 1419 */ 1420 if (group_test(groupname, NULL)) { 1421 DPRINTF(2, ("receive: AM_MANYCAST drop: empty groupname\n")); 1422 sys_declined++; 1423 return; 1424 } 1425 #endif /* AUTOKEY */ 1426 if ((peer2 = findmanycastpeer(rbufp)) == NULL) { 1427 DPRINTF(2, ("receive: AM_MANYCAST drop: No manycast peer\n")); 1428 sys_restricted++; 1429 return; /* not enabled */ 1430 } 1431 if (!AUTH( (!(peer2->cast_flags & MDF_POOL) 1432 && sys_authenticate) 1433 || (restrict_mask & (RES_NOPEER | 1434 RES_DONTTRUST)), is_authentic) 1435 /* MC: RES_NOEPEER? */ 1436 ) { 1437 DPRINTF(2, ("receive: AM_MANYCAST drop: bad auth || (NOPEER|DONTTRUST)\n")); 1438 sys_restricted++; 1439 return; /* access denied */ 1440 } 1441 1442 /* 1443 * Do not respond if unsynchronized or stratum is below 1444 * the floor or at or above the ceiling. 1445 */ 1446 if ( hisleap == LEAP_NOTINSYNC 1447 || hisstratum < sys_floor 1448 || hisstratum >= sys_ceiling) { 1449 DPRINTF(2, ("receive: AM_MANYCAST drop: unsync/stratum\n")); 1450 sys_declined++; 1451 return; /* no help */ 1452 } 1453 peer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr, 1454 r4a.ippeerlimit, MODE_CLIENT, hisversion, 1455 peer2->minpoll, peer2->maxpoll, 1456 (FLAG_PREEMPT | (POOL_FLAG_PMASK & peer2->flags)), 1457 (MDF_UCAST | MDF_UCLNT), 0, skeyid, sys_ident); 1458 if (NULL == peer) { 1459 DPRINTF(2, ("receive: AM_MANYCAST drop: duplicate\n")); 1460 sys_declined++; 1461 return; /* ignore duplicate */ 1462 } 1463 1464 /* 1465 * After each ephemeral pool association is spun, 1466 * accelerate the next poll for the pool solicitor so 1467 * the pool will fill promptly. 1468 */ 1469 if (peer2->cast_flags & MDF_POOL) 1470 peer2->nextdate = current_time + 1; 1471 1472 /* 1473 * Further processing of the solicitation response would 1474 * simply detect its origin timestamp as bogus for the 1475 * brand-new association (it matches the prototype 1476 * association) and tinker with peer->nextdate delaying 1477 * first sync. 1478 */ 1479 return; /* solicitation response handled */ 1480 1481 /* 1482 * This is the first packet received from a broadcast server. If 1483 * the packet is authentic and we are enabled as broadcast 1484 * client, mobilize a broadcast client association. We don't 1485 * kiss any frogs here. 1486 * 1487 * There are cases here where we do not call record_raw_stats(). 1488 */ 1489 case AM_NEWBCL: 1490 1491 #ifdef AUTOKEY 1492 /* 1493 * Do not respond if not the same group. 1494 */ 1495 if (group_test(groupname, sys_ident)) { 1496 DPRINTF(2, ("receive: AM_NEWBCL drop: groupname mismatch\n")); 1497 sys_declined++; 1498 return; 1499 } 1500 #endif /* AUTOKEY */ 1501 if (!sys_bclient && !sys_mclient) { 1502 DPRINTF(2, ("receive: AM_NEWBCL drop: not a bclient/mclient\n")); 1503 sys_restricted++; 1504 return; /* not enabled */ 1505 } 1506 if (!AUTH(sys_authenticate | (restrict_mask & 1507 (RES_NOPEER | RES_DONTTRUST)), is_authentic) 1508 /* NEWBCL: RES_NOEPEER? */ 1509 ) { 1510 DPRINTF(2, ("receive: AM_NEWBCL drop: AUTH failed\n")); 1511 sys_restricted++; 1512 return; /* access denied */ 1513 } 1514 1515 /* 1516 * Do not respond if unsynchronized or stratum is below 1517 * the floor or at or above the ceiling. 1518 */ 1519 if ( hisleap == LEAP_NOTINSYNC 1520 || hisstratum < sys_floor 1521 || hisstratum >= sys_ceiling) { 1522 DPRINTF(2, ("receive: AM_NEWBCL drop: Unsync or bad stratum\n")); 1523 sys_declined++; 1524 return; /* no help */ 1525 } 1526 1527 #ifdef AUTOKEY 1528 /* 1529 * Do not respond if Autokey and the opcode is not a 1530 * CRYPTO_ASSOC response with association ID. 1531 */ 1532 if ( crypto_flags && skeyid > NTP_MAXKEY 1533 && (opcode & 0xffff0000) != (CRYPTO_ASSOC | CRYPTO_RESP)) { 1534 DPRINTF(2, ("receive: AM_NEWBCL drop: Autokey but not CRYPTO_ASSOC\n")); 1535 sys_declined++; 1536 return; /* protocol error */ 1537 } 1538 #endif /* AUTOKEY */ 1539 1540 /* 1541 * Broadcasts received via a multicast address may 1542 * arrive after a unicast volley has begun 1543 * with the same remote address. newpeer() will not 1544 * find duplicate associations on other local endpoints 1545 * if a non-NULL endpoint is supplied. multicastclient 1546 * ephemeral associations are unique across all local 1547 * endpoints. 1548 */ 1549 if (!(INT_MCASTOPEN & rbufp->dstadr->flags)) 1550 match_ep = rbufp->dstadr; 1551 else 1552 match_ep = NULL; 1553 1554 /* 1555 * Determine whether to execute the initial volley. 1556 */ 1557 if (sys_bdelay > 0.0) { 1558 #ifdef AUTOKEY 1559 /* 1560 * If a two-way exchange is not possible, 1561 * neither is Autokey. 1562 */ 1563 if (crypto_flags && skeyid > NTP_MAXKEY) { 1564 sys_restricted++; 1565 DPRINTF(2, ("receive: AM_NEWBCL drop: Autokey but not 2-way\n")); 1566 return; /* no autokey */ 1567 } 1568 #endif /* AUTOKEY */ 1569 1570 /* 1571 * Do not execute the volley. Start out in 1572 * broadcast client mode. 1573 */ 1574 peer = newpeer(&rbufp->recv_srcadr, NULL, match_ep, 1575 r4a.ippeerlimit, MODE_BCLIENT, hisversion, 1576 pkt->ppoll, pkt->ppoll, 1577 FLAG_PREEMPT, MDF_BCLNT, 0, skeyid, sys_ident); 1578 if (NULL == peer) { 1579 DPRINTF(2, ("receive: AM_NEWBCL drop: duplicate\n")); 1580 sys_restricted++; 1581 return; /* ignore duplicate */ 1582 1583 } else { 1584 peer->delay = sys_bdelay; 1585 peer->bxmt = p_xmt; 1586 } 1587 break; 1588 } 1589 1590 /* 1591 * Execute the initial volley in order to calibrate the 1592 * propagation delay and run the Autokey protocol. 1593 * 1594 * Note that the minpoll is taken from the broadcast 1595 * packet, normally 6 (64 s) and that the poll interval 1596 * is fixed at this value. 1597 */ 1598 peer = newpeer(&rbufp->recv_srcadr, NULL, match_ep, 1599 r4a.ippeerlimit, MODE_CLIENT, hisversion, 1600 pkt->ppoll, pkt->ppoll, 1601 FLAG_BC_VOL | FLAG_IBURST | FLAG_PREEMPT, MDF_BCLNT, 1602 0, skeyid, sys_ident); 1603 if (NULL == peer) { 1604 DPRINTF(2, ("receive: AM_NEWBCL drop: empty newpeer() failed\n")); 1605 sys_restricted++; 1606 return; /* ignore duplicate */ 1607 } 1608 peer->bxmt = p_xmt; 1609 #ifdef AUTOKEY 1610 if (skeyid > NTP_MAXKEY) 1611 crypto_recv(peer, rbufp); 1612 #endif /* AUTOKEY */ 1613 1614 return; /* hooray */ 1615 1616 /* 1617 * This is the first packet received from a potential ephemeral 1618 * symmetric active peer. First, deal with broken Windows clients. 1619 * Then, if NOEPEER is enabled, drop it. If the packet meets our 1620 * authenticty requirements and is the first he sent, mobilize 1621 * a passive association. 1622 * Otherwise, kiss the frog. 1623 * 1624 * There are cases here where we do not call record_raw_stats(). 1625 */ 1626 case AM_NEWPASS: 1627 1628 DEBUG_REQUIRE(MODE_ACTIVE == hismode); 1629 1630 #ifdef AUTOKEY 1631 /* 1632 * Do not respond if not the same group. 1633 */ 1634 if (group_test(groupname, sys_ident)) { 1635 DPRINTF(2, ("receive: AM_NEWPASS drop: Autokey group mismatch\n")); 1636 sys_declined++; 1637 return; 1638 } 1639 #endif /* AUTOKEY */ 1640 if (!AUTH(sys_authenticate | (restrict_mask & 1641 (RES_NOPEER | RES_DONTTRUST)), is_authentic) 1642 ) { 1643 /* 1644 * If authenticated but cannot mobilize an 1645 * association, send a symmetric passive 1646 * response without mobilizing an association. 1647 * This is for drat broken Windows clients. See 1648 * Microsoft KB 875424 for preferred workaround. 1649 */ 1650 if (AUTH(restrict_mask & RES_DONTTRUST, 1651 is_authentic)) { 1652 fast_xmit(rbufp, MODE_PASSIVE, skeyid, 1653 restrict_mask); 1654 return; /* hooray */ 1655 } 1656 /* HMS: Why is this next set of lines a feature? */ 1657 if (is_authentic == AUTH_ERROR) { 1658 fast_xmit(rbufp, MODE_PASSIVE, 0, 1659 restrict_mask); 1660 sys_restricted++; 1661 return; 1662 } 1663 1664 if (restrict_mask & RES_NOEPEER) { 1665 DPRINTF(2, ("receive: AM_NEWPASS drop: NOEPEER\n")); 1666 sys_declined++; 1667 return; 1668 } 1669 1670 /* [Bug 2941] 1671 * If we got here, the packet isn't part of an 1672 * existing association, either isn't correctly 1673 * authenticated or it is but we are refusing 1674 * ephemeral peer requests, and it didn't meet 1675 * either of the previous two special cases so we 1676 * should just drop it on the floor. For example, 1677 * crypto-NAKs (is_authentic == AUTH_CRYPTO) 1678 * will make it this far. This is just 1679 * debug-printed and not logged to avoid log 1680 * flooding. 1681 */ 1682 DPRINTF(2, ("receive: at %ld refusing to mobilize passive association" 1683 " with unknown peer %s mode %d/%s:%s keyid %08x len %d auth %d\n", 1684 current_time, stoa(&rbufp->recv_srcadr), 1685 hismode, hm_str, am_str, skeyid, 1686 (authlen + has_mac), is_authentic)); 1687 sys_declined++; 1688 return; 1689 } 1690 1691 if (restrict_mask & RES_NOEPEER) { 1692 DPRINTF(2, ("receive: AM_NEWPASS drop: NOEPEER\n")); 1693 sys_declined++; 1694 return; 1695 } 1696 1697 /* 1698 * Do not respond if synchronized and if stratum is 1699 * below the floor or at or above the ceiling. Note, 1700 * this allows an unsynchronized peer to synchronize to 1701 * us. It would be very strange if he did and then was 1702 * nipped, but that could only happen if we were 1703 * operating at the top end of the range. It also means 1704 * we will spin an ephemeral association in response to 1705 * MODE_ACTIVE KoDs, which will time out eventually. 1706 */ 1707 if ( hisleap != LEAP_NOTINSYNC 1708 && (hisstratum < sys_floor || hisstratum >= sys_ceiling)) { 1709 DPRINTF(2, ("receive: AM_NEWPASS drop: Remote stratum (%d) out of range\n", 1710 hisstratum)); 1711 sys_declined++; 1712 return; /* no help */ 1713 } 1714 1715 /* 1716 * The message is correctly authenticated and allowed. 1717 * Mobilize a symmetric passive association, if we won't 1718 * exceed the ippeerlimit. 1719 */ 1720 if ((peer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr, 1721 r4a.ippeerlimit, MODE_PASSIVE, hisversion, 1722 pkt->ppoll, NTP_MAXDPOLL, 0, MDF_UCAST, 0, 1723 skeyid, sys_ident)) == NULL) { 1724 DPRINTF(2, ("receive: AM_NEWPASS drop: newpeer() failed\n")); 1725 sys_declined++; 1726 return; /* ignore duplicate */ 1727 } 1728 break; 1729 1730 1731 /* 1732 * Process regular packet. Nothing special. 1733 * 1734 * There are cases here where we do not call record_raw_stats(). 1735 */ 1736 case AM_PROCPKT: 1737 1738 #ifdef AUTOKEY 1739 /* 1740 * Do not respond if not the same group. 1741 */ 1742 if (group_test(groupname, peer->ident)) { 1743 DPRINTF(2, ("receive: AM_PROCPKT drop: Autokey group mismatch\n")); 1744 sys_declined++; 1745 return; 1746 } 1747 #endif /* AUTOKEY */ 1748 1749 if (MODE_BROADCAST == hismode) { 1750 int bail = 0; 1751 l_fp tdiff; 1752 u_long deadband; 1753 1754 DPRINTF(2, ("receive: PROCPKT/BROADCAST: prev pkt %ld seconds ago, ppoll: %d, %d secs\n", 1755 (current_time - peer->timelastrec), 1756 peer->ppoll, (1 << peer->ppoll) 1757 )); 1758 /* Things we can check: 1759 * 1760 * Did the poll interval change? 1761 * Is the poll interval in the packet in-range? 1762 * Did this packet arrive too soon? 1763 * Is the timestamp in this packet monotonic 1764 * with respect to the previous packet? 1765 */ 1766 1767 /* This is noteworthy, not error-worthy */ 1768 if (pkt->ppoll != peer->ppoll) { 1769 msyslog(LOG_INFO, "receive: broadcast poll from %s changed from %u to %u", 1770 stoa(&rbufp->recv_srcadr), 1771 peer->ppoll, pkt->ppoll); 1772 } 1773 1774 /* This is error-worthy */ 1775 if ( pkt->ppoll < peer->minpoll 1776 || pkt->ppoll > peer->maxpoll) { 1777 msyslog(LOG_INFO, "receive: broadcast poll of %u from %s is out-of-range (%d to %d)!", 1778 pkt->ppoll, stoa(&rbufp->recv_srcadr), 1779 peer->minpoll, peer->maxpoll); 1780 ++bail; 1781 } 1782 1783 /* too early? worth an error, too! 1784 * 1785 * [Bug 3113] Ensure that at least one poll 1786 * interval has elapsed since the last **clean** 1787 * packet was received. We limit the check to 1788 * **clean** packets to prevent replayed packets 1789 * and incorrectly authenticated packets, which 1790 * we'll discard, from being used to create a 1791 * denial of service condition. 1792 */ 1793 deadband = (1u << pkt->ppoll); 1794 if (FLAG_BC_VOL & peer->flags) 1795 deadband -= 3; /* allow greater fuzz after volley */ 1796 if ((current_time - peer->timereceived) < deadband) { 1797 msyslog(LOG_INFO, "receive: broadcast packet from %s arrived after %lu, not %lu seconds!", 1798 stoa(&rbufp->recv_srcadr), 1799 (current_time - peer->timereceived), 1800 deadband); 1801 ++bail; 1802 } 1803 1804 /* Alert if time from the server is non-monotonic. 1805 * 1806 * [Bug 3114] is about Broadcast mode replay DoS. 1807 * 1808 * Broadcast mode *assumes* a trusted network. 1809 * Even so, it's nice to be robust in the face 1810 * of attacks. 1811 * 1812 * If we get an authenticated broadcast packet 1813 * with an "earlier" timestamp, it means one of 1814 * two things: 1815 * 1816 * - the broadcast server had a backward step. 1817 * 1818 * - somebody is trying a replay attack. 1819 * 1820 * deadband: By default, we assume the broadcast 1821 * network is trustable, so we take our accepted 1822 * broadcast packets as we receive them. But 1823 * some folks might want to take additional poll 1824 * delays before believing a backward step. 1825 */ 1826 if (sys_bcpollbstep) { 1827 /* pkt->ppoll or peer->ppoll ? */ 1828 deadband = (1u << pkt->ppoll) 1829 * sys_bcpollbstep + 2; 1830 } else { 1831 deadband = 0; 1832 } 1833 1834 if (L_ISZERO(&peer->bxmt)) { 1835 tdiff.l_ui = tdiff.l_uf = 0; 1836 } else { 1837 tdiff = p_xmt; 1838 L_SUB(&tdiff, &peer->bxmt); 1839 } 1840 if ( tdiff.l_i < 0 1841 && (current_time - peer->timereceived) < deadband) 1842 { 1843 msyslog(LOG_INFO, "receive: broadcast packet from %s contains non-monotonic timestamp: %#010x.%08x -> %#010x.%08x", 1844 stoa(&rbufp->recv_srcadr), 1845 peer->bxmt.l_ui, peer->bxmt.l_uf, 1846 p_xmt.l_ui, p_xmt.l_uf 1847 ); 1848 ++bail; 1849 } 1850 1851 if (bail) { 1852 DPRINTF(2, ("receive: AM_PROCPKT drop: bail\n")); 1853 peer->timelastrec = current_time; 1854 sys_declined++; 1855 return; 1856 } 1857 } 1858 1859 break; 1860 1861 /* 1862 * A passive packet matches a passive association. This is 1863 * usually the result of reconfiguring a client on the fly. As 1864 * this association might be legitimate and this packet an 1865 * attempt to deny service, just ignore it. 1866 */ 1867 case AM_ERR: 1868 DPRINTF(2, ("receive: AM_ERR drop.\n")); 1869 sys_declined++; 1870 return; 1871 1872 /* 1873 * For everything else there is the bit bucket. 1874 */ 1875 default: 1876 DPRINTF(2, ("receive: default drop.\n")); 1877 sys_declined++; 1878 return; 1879 } 1880 1881 #ifdef AUTOKEY 1882 /* 1883 * If the association is configured for Autokey, the packet must 1884 * have a public key ID; if not, the packet must have a 1885 * symmetric key ID. 1886 */ 1887 if ( is_authentic != AUTH_CRYPTO 1888 && ( ((peer->flags & FLAG_SKEY) && skeyid <= NTP_MAXKEY) 1889 || (!(peer->flags & FLAG_SKEY) && skeyid > NTP_MAXKEY))) { 1890 DPRINTF(2, ("receive: drop: Autokey but wrong/bad auth\n")); 1891 sys_badauth++; 1892 return; 1893 } 1894 #endif /* AUTOKEY */ 1895 1896 peer->received++; 1897 peer->flash &= ~PKT_TEST_MASK; 1898 if (peer->flags & FLAG_XBOGUS) { 1899 peer->flags &= ~FLAG_XBOGUS; 1900 peer->flash |= TEST3; 1901 } 1902 1903 /* 1904 * Next comes a rigorous schedule of timestamp checking. If the 1905 * transmit timestamp is zero, the server has not initialized in 1906 * interleaved modes or is horribly broken. 1907 * 1908 * A KoD packet we pay attention to cannot have a 0 transmit 1909 * timestamp. 1910 */ 1911 1912 kissCode = kiss_code_check(hisleap, hisstratum, hismode, pkt->refid); 1913 1914 if (L_ISZERO(&p_xmt)) { 1915 peer->flash |= TEST3; /* unsynch */ 1916 if (kissCode != NOKISS) { /* KoD packet */ 1917 peer->bogusorg++; /* for TEST2 or TEST3 */ 1918 msyslog(LOG_INFO, 1919 "receive: Unexpected zero transmit timestamp in KoD from %s", 1920 ntoa(&peer->srcadr)); 1921 return; 1922 } 1923 1924 /* 1925 * If the transmit timestamp duplicates our previous one, the 1926 * packet is a replay. This prevents the bad guys from replaying 1927 * the most recent packet, authenticated or not. 1928 */ 1929 } else if ( ((FLAG_LOOPNONCE & peer->flags) && L_ISEQU(&peer->nonce, &p_xmt)) 1930 || (!(FLAG_LOOPNONCE & peer->flags) && L_ISEQU(&peer->xmt, &p_xmt)) 1931 ) { 1932 DPRINTF(2, ("receive: drop: Duplicate xmit\n")); 1933 peer->flash |= TEST1; /* duplicate */ 1934 peer->oldpkt++; 1935 return; 1936 1937 /* 1938 * If this is a broadcast mode packet, make sure hisstratum 1939 * is appropriate. Don't do anything else here - we wait to 1940 * see if this is an interleave broadcast packet until after 1941 * we've validated the MAC that SHOULD be provided. 1942 * 1943 * hisstratum cannot be 0 - see assertion above. 1944 * If hisstratum is 15, then we'll advertise as UNSPEC but 1945 * at least we'll be able to sync with the broadcast server. 1946 */ 1947 } else if (hismode == MODE_BROADCAST) { 1948 /* 0 is unexpected too, and impossible */ 1949 if (STRATUM_UNSPEC <= hisstratum) { 1950 /* Is this a ++sys_declined or ??? */ 1951 msyslog(LOG_INFO, 1952 "receive: Unexpected stratum (%d) in broadcast from %s", 1953 hisstratum, ntoa(&peer->srcadr)); 1954 return; 1955 } 1956 1957 /* 1958 * Basic KoD validation checking: 1959 * 1960 * KoD packets are a mixed-blessing. Forged KoD packets 1961 * are DoS attacks. There are rare situations where we might 1962 * get a valid KoD response, though. Since KoD packets are 1963 * a special case that complicate the checks we do next, we 1964 * handle the basic KoD checks here. 1965 * 1966 * Note that we expect the incoming KoD packet to have its 1967 * (nonzero) org, rec, and xmt timestamps set to the xmt timestamp 1968 * that we have previously sent out. Watch interleave mode. 1969 */ 1970 } else if (kissCode != NOKISS) { 1971 DEBUG_INSIST(!L_ISZERO(&p_xmt)); 1972 if ( L_ISZERO(&p_org) /* We checked p_xmt above */ 1973 || L_ISZERO(&p_rec)) { 1974 peer->bogusorg++; 1975 msyslog(LOG_INFO, 1976 "receive: KoD packet from %s has a zero org or rec timestamp. Ignoring.", 1977 ntoa(&peer->srcadr)); 1978 return; 1979 } 1980 1981 if ( !L_ISEQU(&p_xmt, &p_org) 1982 || !L_ISEQU(&p_xmt, &p_rec)) { 1983 peer->bogusorg++; 1984 msyslog(LOG_INFO, 1985 "receive: KoD packet from %s has inconsistent xmt/org/rec timestamps. Ignoring.", 1986 ntoa(&peer->srcadr)); 1987 return; 1988 } 1989 1990 /* Be conservative */ 1991 if (peer->flip == 0 && !L_ISEQU(&p_org, &peer->aorg)) { 1992 peer->bogusorg++; 1993 msyslog(LOG_INFO, 1994 "receive: flip 0 KoD origin timestamp %#010x.%08x from %s does not match %#010x.%08x - ignoring.", 1995 p_org.l_ui, p_org.l_uf, 1996 ntoa(&peer->srcadr), 1997 peer->aorg.l_ui, peer->aorg.l_uf); 1998 return; 1999 } else if (peer->flip == 1 && !L_ISEQU(&p_org, &peer->borg)) { 2000 peer->bogusorg++; 2001 msyslog(LOG_INFO, 2002 "receive: flip 1 KoD origin timestamp %#010x.%08x from %s does not match interleave %#010x.%08x - ignoring.", 2003 p_org.l_ui, p_org.l_uf, 2004 ntoa(&peer->srcadr), 2005 peer->borg.l_ui, peer->borg.l_uf); 2006 return; 2007 } 2008 2009 /* 2010 * Basic mode checks: 2011 * 2012 * If there is no origin timestamp, it's either an initial 2013 * packet or we've already received a response to our query. 2014 * Of course, should 'aorg' be all-zero because this really 2015 * was the original transmit timestamp, we'll ignore this 2016 * reply. There is a window of one nanosecond once every 2017 * 136 years' time where this is possible. We currently 2018 * ignore this situation, as a completely zero timestamp 2019 * is (quietly?) disallowed. 2020 * 2021 * Otherwise, check for bogus packet in basic mode. 2022 * If it is bogus, switch to interleaved mode and 2023 * resynchronize, but only after confirming the packet is 2024 * not bogus in symmetric interleaved mode. 2025 * 2026 * This could also mean somebody is forging packets claiming 2027 * to be from us, attempting to cause our server to KoD us. 2028 * 2029 * We have earlier asserted that hisstratum cannot be 0. 2030 * If hisstratum is STRATUM_UNSPEC, it means he's not sync'd. 2031 */ 2032 2033 /* XXX: FLAG_LOOPNONCE */ 2034 DEBUG_INSIST(0 == (FLAG_LOOPNONCE & peer->flags)); 2035 2036 msyslog(LOG_INFO, 2037 "receive: Got KoD %s from %s", 2038 refid_str(pkt->refid, hisstratum), ntoa(&peer->srcadr)); 2039 } else if (peer->flip == 0) { 2040 if (0) { 2041 } else if (L_ISZERO(&p_org)) { 2042 const char *action; 2043 2044 #ifdef BUG3361 2045 msyslog(LOG_INFO, 2046 "receive: BUG 3361: Clearing peer->aorg "); 2047 L_CLR(&peer->aorg); 2048 /* Clear peer->nonce, too? */ 2049 #endif 2050 /**/ 2051 switch (hismode) { 2052 /* We allow 0org for: */ 2053 case UCHAR_MAX: 2054 action = "Allow"; 2055 break; 2056 /* We disallow 0org for: */ 2057 case MODE_UNSPEC: 2058 case MODE_ACTIVE: 2059 case MODE_PASSIVE: 2060 case MODE_CLIENT: 2061 case MODE_SERVER: 2062 case MODE_BROADCAST: 2063 action = "Drop"; 2064 peer->bogusorg++; 2065 peer->flash |= TEST2; /* bogus */ 2066 break; 2067 default: 2068 action = ""; /* for cranky compilers / MSVC */ 2069 INSIST(!"receive(): impossible hismode"); 2070 break; 2071 } 2072 /**/ 2073 msyslog(LOG_INFO, 2074 "receive: %s 0 origin timestamp from %s@%s xmt %#010x.%08x", 2075 action, hm_str, ntoa(&peer->srcadr), 2076 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)); 2077 } else if (!L_ISEQU(&p_org, &peer->aorg)) { 2078 /* are there cases here where we should bail? */ 2079 /* Should we set TEST2 if we decide to try xleave? */ 2080 peer->bogusorg++; 2081 peer->flash |= TEST2; /* bogus */ 2082 msyslog(LOG_INFO, 2083 "receive: Unexpected origin timestamp %#010x.%08x does not match aorg %#010x.%08x from %s@%s xmt %#010x.%08x", 2084 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf), 2085 peer->aorg.l_ui, peer->aorg.l_uf, 2086 hm_str, ntoa(&peer->srcadr), 2087 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)); 2088 if ( !L_ISZERO(&peer->dst) 2089 && L_ISEQU(&p_org, &peer->dst)) { 2090 /* Might be the start of an interleave */ 2091 if (dynamic_interleave) { 2092 peer->flip = 1; 2093 report_event(PEVNT_XLEAVE, peer, NULL); 2094 } else { 2095 msyslog(LOG_INFO, 2096 "receive: Dynamic interleave from %s@%s denied", 2097 hm_str, ntoa(&peer->srcadr)); 2098 } 2099 } 2100 } else { 2101 L_CLR(&peer->aorg); 2102 /* XXX: FLAG_LOOPNONCE */ 2103 } 2104 2105 /* 2106 * Check for valid nonzero timestamp fields. 2107 */ 2108 } else if ( L_ISZERO(&p_org) 2109 || L_ISZERO(&p_rec) 2110 || L_ISZERO(&peer->dst)) { 2111 peer->flash |= TEST3; /* unsynch */ 2112 2113 /* 2114 * Check for bogus packet in interleaved symmetric mode. This 2115 * can happen if a packet is lost, duplicated or crossed. If 2116 * found, flip and resynchronize. 2117 */ 2118 } else if ( !L_ISZERO(&peer->dst) 2119 && !L_ISEQU(&p_org, &peer->dst)) { 2120 DPRINTF(2, ("receive: drop: Bogus packet in interleaved symmetric mode\n")); 2121 peer->bogusorg++; 2122 peer->flags |= FLAG_XBOGUS; 2123 peer->flash |= TEST2; /* bogus */ 2124 #ifdef BUG3453 2125 return; /* Bogus packet, we are done */ 2126 #endif 2127 } 2128 2129 /**/ 2130 2131 /* 2132 * If this is a crypto_NAK, the server cannot authenticate a 2133 * client packet. The server might have just changed keys. Clear 2134 * the association and restart the protocol. 2135 */ 2136 if (crypto_nak_test == VALIDNAK) { 2137 report_event(PEVNT_AUTH, peer, "crypto_NAK"); 2138 peer->flash |= TEST5; /* bad auth */ 2139 peer->badauth++; 2140 if (peer->flags & FLAG_PREEMPT) { 2141 if (unpeer_crypto_nak_early) { 2142 unpeer(peer); 2143 } 2144 DPRINTF(2, ("receive: drop: PREEMPT crypto_NAK\n")); 2145 return; 2146 } 2147 #ifdef AUTOKEY 2148 if (peer->crypto) { 2149 peer_clear(peer, "AUTH"); 2150 } 2151 #endif /* AUTOKEY */ 2152 DPRINTF(2, ("receive: drop: crypto_NAK\n")); 2153 return; 2154 2155 /* 2156 * If the digest fails or it's missing for authenticated 2157 * associations, the client cannot authenticate a server 2158 * reply to a client packet previously sent. The loopback check 2159 * is designed to avoid a bait-and-switch attack, which was 2160 * possible in past versions. If symmetric modes, return a 2161 * crypto-NAK. The peer should restart the protocol. 2162 */ 2163 } else if (!AUTH(peer->keyid || has_mac || 2164 (restrict_mask & RES_DONTTRUST), is_authentic)) { 2165 2166 if (peer->flash & PKT_TEST_MASK) { 2167 msyslog(LOG_INFO, 2168 "receive: Bad auth in packet with bad timestamps from %s denied - spoof?", 2169 ntoa(&peer->srcadr)); 2170 return; 2171 } 2172 2173 report_event(PEVNT_AUTH, peer, "digest"); 2174 peer->flash |= TEST5; /* bad auth */ 2175 peer->badauth++; 2176 if ( has_mac 2177 && ( hismode == MODE_ACTIVE 2178 || hismode == MODE_PASSIVE)) 2179 fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask); 2180 if (peer->flags & FLAG_PREEMPT) { 2181 if (unpeer_digest_early) { 2182 unpeer(peer); 2183 } 2184 } 2185 #ifdef AUTOKEY 2186 else if (peer_clear_digest_early && peer->crypto) { 2187 peer_clear(peer, "AUTH"); 2188 } 2189 #endif /* AUTOKEY */ 2190 DPRINTF(2, ("receive: drop: Bad or missing AUTH\n")); 2191 return; 2192 } 2193 2194 /* 2195 * For broadcast packets: 2196 * 2197 * HMS: This next line never made much sense to me, even 2198 * when it was up higher: 2199 * If an initial volley, bail out now and let the 2200 * client do its stuff. 2201 * 2202 * If the packet has not failed authentication, then 2203 * - if the origin timestamp is nonzero this is an 2204 * interleaved broadcast, so restart the protocol. 2205 * - else, this is not an interleaved broadcast packet. 2206 */ 2207 if (hismode == MODE_BROADCAST) { 2208 if ( is_authentic == AUTH_OK 2209 || is_authentic == AUTH_NONE) { 2210 if (!L_ISZERO(&p_org)) { 2211 if (!(peer->flags & FLAG_XB)) { 2212 msyslog(LOG_INFO, 2213 "receive: Broadcast server at %s is in interleave mode", 2214 ntoa(&peer->srcadr)); 2215 peer->flags |= FLAG_XB; 2216 peer->aorg = p_xmt; 2217 peer->borg = rbufp->recv_time; 2218 report_event(PEVNT_XLEAVE, peer, NULL); 2219 return; 2220 } 2221 } else if (peer->flags & FLAG_XB) { 2222 msyslog(LOG_INFO, 2223 "receive: Broadcast server at %s is no longer in interleave mode", 2224 ntoa(&peer->srcadr)); 2225 peer->flags &= ~FLAG_XB; 2226 } 2227 } else { 2228 msyslog(LOG_INFO, 2229 "receive: Bad broadcast auth (%d) from %s", 2230 is_authentic, ntoa(&peer->srcadr)); 2231 } 2232 2233 /* 2234 * Now that we know the packet is correctly authenticated, 2235 * update peer->bxmt. 2236 */ 2237 peer->bxmt = p_xmt; 2238 } 2239 2240 2241 /* 2242 ** Update the state variables. 2243 */ 2244 if (peer->flip == 0) { 2245 if (hismode != MODE_BROADCAST) 2246 peer->rec = p_xmt; 2247 peer->dst = rbufp->recv_time; 2248 } 2249 peer->xmt = p_xmt; 2250 2251 /* 2252 * Set the peer ppoll to the maximum of the packet ppoll and the 2253 * peer minpoll. If a kiss-o'-death, set the peer minpoll to 2254 * this maximum and advance the headway to give the sender some 2255 * headroom. Very intricate. 2256 */ 2257 2258 /* 2259 * Check for any kiss codes. Note this is only used when a server 2260 * responds to a packet request. 2261 */ 2262 2263 /* 2264 * Check to see if this is a RATE Kiss Code 2265 * Currently this kiss code will accept whatever valid poll 2266 * rate that the server sends 2267 */ 2268 if ( (NTP_MINPOLL > pkt->ppoll) 2269 || (NTP_MAXPOLL < pkt->ppoll) 2270 ) { 2271 DPRINTF(2, ("RATEKISS: Invalid ppoll (%d) from %s\n", 2272 pkt->ppoll, stoa(&rbufp->recv_srcadr))); 2273 sys_badlength++; 2274 return; /* invalid packet poll */ 2275 } 2276 peer->ppoll = max(peer->minpoll, pkt->ppoll); 2277 if (kissCode == RATEKISS) { 2278 peer->selbroken++; /* Increment the KoD count */ 2279 report_event(PEVNT_RATE, peer, NULL); 2280 if (pkt->ppoll > peer->minpoll) 2281 peer->minpoll = peer->ppoll; 2282 peer->burst = peer->retry = 0; 2283 peer->throttle = (NTP_SHIFT + 1) * (1 << peer->minpoll); 2284 poll_update(peer, pkt->ppoll, 0); 2285 return; /* kiss-o'-death */ 2286 } 2287 if (kissCode != NOKISS) { 2288 peer->selbroken++; /* Increment the KoD count */ 2289 return; /* Drop any other kiss code packets */ 2290 } 2291 2292 2293 /* 2294 * XXX 2295 */ 2296 2297 2298 /* 2299 * If: 2300 * - this is a *cast (uni-, broad-, or m-) server packet 2301 * - and it's symmetric-key authenticated 2302 * then see if the sender's IP is trusted for this keyid. 2303 * If it is, great - nothing special to do here. 2304 * Otherwise, we should report and bail. 2305 * 2306 * Autokey-authenticated packets are accepted. 2307 */ 2308 2309 switch (hismode) { 2310 case MODE_SERVER: /* server mode */ 2311 case MODE_BROADCAST: /* broadcast mode */ 2312 case MODE_ACTIVE: /* symmetric active mode */ 2313 case MODE_PASSIVE: /* symmetric passive mode */ 2314 if ( is_authentic == AUTH_OK 2315 && skeyid 2316 && skeyid <= NTP_MAXKEY 2317 && !authistrustedip(skeyid, &peer->srcadr)) { 2318 report_event(PEVNT_AUTH, peer, "authIP"); 2319 peer->badauth++; 2320 return; 2321 } 2322 break; 2323 2324 case MODE_CLIENT: /* client mode */ 2325 #if 0 /* At this point, MODE_CONTROL is overloaded by MODE_BCLIENT */ 2326 case MODE_CONTROL: /* control mode */ 2327 #endif 2328 case MODE_PRIVATE: /* private mode */ 2329 case MODE_BCLIENT: /* broadcast client mode */ 2330 break; 2331 2332 case MODE_UNSPEC: /* unspecified (old version) */ 2333 default: 2334 msyslog(LOG_INFO, 2335 "receive: Unexpected mode (%d) in packet from %s", 2336 hismode, ntoa(&peer->srcadr)); 2337 break; 2338 } 2339 2340 2341 /* 2342 * That was hard and I am sweaty, but the packet is squeaky 2343 * clean. Get on with real work. 2344 */ 2345 peer->timereceived = current_time; 2346 peer->timelastrec = current_time; 2347 if (is_authentic == AUTH_OK) 2348 peer->flags |= FLAG_AUTHENTIC; 2349 else 2350 peer->flags &= ~FLAG_AUTHENTIC; 2351 2352 #ifdef AUTOKEY 2353 /* 2354 * More autokey dance. The rules of the cha-cha are as follows: 2355 * 2356 * 1. If there is no key or the key is not auto, do nothing. 2357 * 2358 * 2. If this packet is in response to the one just previously 2359 * sent or from a broadcast server, do the extension fields. 2360 * Otherwise, assume bogosity and bail out. 2361 * 2362 * 3. If an extension field contains a verified signature, it is 2363 * self-authenticated and we sit the dance. 2364 * 2365 * 4. If this is a server reply, check only to see that the 2366 * transmitted key ID matches the received key ID. 2367 * 2368 * 5. Check to see that one or more hashes of the current key ID 2369 * matches the previous key ID or ultimate original key ID 2370 * obtained from the broadcaster or symmetric peer. If no 2371 * match, sit the dance and call for new autokey values. 2372 * 2373 * In case of crypto error, fire the orchestra, stop dancing and 2374 * restart the protocol. 2375 */ 2376 if (peer->flags & FLAG_SKEY) { 2377 /* 2378 * Decrement remaining autokey hashes. This isn't 2379 * perfect if a packet is lost, but results in no harm. 2380 */ 2381 ap = (struct autokey *)peer->recval.ptr; 2382 if (ap != NULL) { 2383 if (ap->seq > 0) 2384 ap->seq--; 2385 } 2386 peer->flash |= TEST8; 2387 rval = crypto_recv(peer, rbufp); 2388 if (rval == XEVNT_OK) { 2389 peer->unreach = 0; 2390 } else { 2391 if (rval == XEVNT_ERR) { 2392 report_event(PEVNT_RESTART, peer, 2393 "crypto error"); 2394 peer_clear(peer, "CRYP"); 2395 peer->flash |= TEST9; /* bad crypt */ 2396 if (peer->flags & FLAG_PREEMPT) { 2397 if (unpeer_crypto_early) { 2398 unpeer(peer); 2399 } 2400 } 2401 } 2402 return; 2403 } 2404 2405 /* 2406 * If server mode, verify the receive key ID matches 2407 * the transmit key ID. 2408 */ 2409 if (hismode == MODE_SERVER) { 2410 if (skeyid == peer->keyid) 2411 peer->flash &= ~TEST8; 2412 2413 /* 2414 * If an extension field is present, verify only that it 2415 * has been correctly signed. We don't need a sequence 2416 * check here, but the sequence continues. 2417 */ 2418 } else if (!(peer->flash & TEST8)) { 2419 peer->pkeyid = skeyid; 2420 2421 /* 2422 * Now the fun part. Here, skeyid is the current ID in 2423 * the packet, pkeyid is the ID in the last packet and 2424 * tkeyid is the hash of skeyid. If the autokey values 2425 * have not been received, this is an automatic error. 2426 * If so, check that the tkeyid matches pkeyid. If not, 2427 * hash tkeyid and try again. If the number of hashes 2428 * exceeds the number remaining in the sequence, declare 2429 * a successful failure and refresh the autokey values. 2430 */ 2431 } else if (ap != NULL) { 2432 int i; 2433 2434 for (i = 0; ; i++) { 2435 if ( tkeyid == peer->pkeyid 2436 || tkeyid == ap->key) { 2437 peer->flash &= ~TEST8; 2438 peer->pkeyid = skeyid; 2439 ap->seq -= i; 2440 break; 2441 } 2442 if (i > ap->seq) { 2443 peer->crypto &= 2444 ~CRYPTO_FLAG_AUTO; 2445 break; 2446 } 2447 tkeyid = session_key( 2448 &rbufp->recv_srcadr, dstadr_sin, 2449 tkeyid, pkeyid, 0); 2450 } 2451 if (peer->flash & TEST8) 2452 report_event(PEVNT_AUTH, peer, "keylist"); 2453 } 2454 if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */ 2455 peer->flash |= TEST8; /* bad autokey */ 2456 2457 /* 2458 * The maximum lifetime of the protocol is about one 2459 * week before restarting the Autokey protocol to 2460 * refresh certificates and leapseconds values. 2461 */ 2462 if (current_time > peer->refresh) { 2463 report_event(PEVNT_RESTART, peer, 2464 "crypto refresh"); 2465 peer_clear(peer, "TIME"); 2466 return; 2467 } 2468 } 2469 #endif /* AUTOKEY */ 2470 2471 /* 2472 * The dance is complete and the flash bits have been lit. Toss 2473 * the packet over the fence for processing, which may light up 2474 * more flashers. Leave if the packet is not good. 2475 */ 2476 process_packet(peer, pkt, rbufp->recv_length); 2477 if (peer->flash & PKT_TEST_MASK) 2478 return; 2479 2480 /* [bug 3592] Update poll. Ideally this should not happen in a 2481 * receive branch, but too much is going on here... at least we 2482 * do it only if the packet was good! 2483 */ 2484 poll_update(peer, peer->hpoll, (peer->hmode == MODE_CLIENT)); 2485 2486 /* 2487 * In interleaved mode update the state variables. Also adjust the 2488 * transmit phase to avoid crossover. 2489 */ 2490 if (peer->flip != 0) { 2491 peer->rec = p_rec; 2492 peer->dst = rbufp->recv_time; 2493 if (peer->nextdate - current_time < (1U << min(peer->ppoll, 2494 peer->hpoll)) / 2) 2495 peer->nextdate++; 2496 else 2497 peer->nextdate--; 2498 } 2499 } 2500 2501 2502 /* 2503 * process_packet - Packet Procedure, a la Section 3.4.4 of RFC-1305 2504 * Or almost, at least. If we're in here we have a reasonable 2505 * expectation that we will be having a long term 2506 * relationship with this host. 2507 */ 2508 void 2509 process_packet( 2510 register struct peer *peer, 2511 register struct pkt *pkt, 2512 u_int len 2513 ) 2514 { 2515 double t34, t21; 2516 double p_offset, p_del, p_disp; 2517 l_fp p_rec, p_xmt, p_org, p_reftime, ci; 2518 u_char pmode, pleap, pversion, pstratum; 2519 char statstr[NTP_MAXSTRLEN]; 2520 #ifdef ASSYM 2521 int itemp; 2522 double etemp, ftemp, td; 2523 #endif /* ASSYM */ 2524 2525 p_del = FPTOD(NTOHS_FP(pkt->rootdelay)); 2526 p_offset = 0; 2527 p_disp = FPTOD(NTOHS_FP(pkt->rootdisp)); 2528 NTOHL_FP(&pkt->reftime, &p_reftime); 2529 NTOHL_FP(&pkt->org, &p_org); 2530 NTOHL_FP(&pkt->rec, &p_rec); 2531 NTOHL_FP(&pkt->xmt, &p_xmt); 2532 pmode = PKT_MODE(pkt->li_vn_mode); 2533 pleap = PKT_LEAP(pkt->li_vn_mode); 2534 pversion = PKT_VERSION(pkt->li_vn_mode); 2535 pstratum = PKT_TO_STRATUM(pkt->stratum); 2536 2537 /* 2538 * Verify the server is synchronized; that is, the leap bits, 2539 * stratum and root distance are valid. 2540 */ 2541 if ( pleap == LEAP_NOTINSYNC /* test 6 */ 2542 || pstratum < sys_floor || pstratum >= sys_ceiling) 2543 peer->flash |= TEST6; /* bad synch or strat */ 2544 if (p_del / 2 + p_disp >= MAXDISPERSE) /* test 7 */ 2545 peer->flash |= TEST7; /* bad header */ 2546 2547 /* 2548 * If any tests fail at this point, the packet is discarded. 2549 * Note that some flashers may have already been set in the 2550 * receive() routine. 2551 */ 2552 if (peer->flash & PKT_TEST_MASK) { 2553 peer->seldisptoolarge++; 2554 DPRINTF(1, ("packet: flash header %04x\n", 2555 peer->flash)); 2556 /* [Bug 3592] do *not* update poll on bad packets! */ 2557 return; 2558 } 2559 2560 /* 2561 * update stats, now that we really handle this packet: 2562 */ 2563 sys_processed++; 2564 peer->processed++; 2565 2566 /* 2567 * Capture the header values in the client/peer association.. 2568 */ 2569 record_raw_stats(&peer->srcadr, 2570 peer->dstadr ? &peer->dstadr->sin : NULL, 2571 &p_org, &p_rec, &p_xmt, &peer->dst, 2572 pleap, pversion, pmode, pstratum, pkt->ppoll, pkt->precision, 2573 p_del, p_disp, pkt->refid, 2574 len - MIN_V4_PKT_LEN, (u_char *)&pkt->exten); 2575 peer->leap = pleap; 2576 peer->stratum = min(pstratum, STRATUM_UNSPEC); 2577 peer->pmode = pmode; 2578 peer->precision = pkt->precision; 2579 peer->rootdelay = p_del; 2580 peer->rootdisp = p_disp; 2581 peer->refid = pkt->refid; /* network byte order */ 2582 peer->reftime = p_reftime; 2583 2584 /* 2585 * First, if either burst mode is armed, enable the burst. 2586 * Compute the headway for the next packet and delay if 2587 * necessary to avoid exceeding the threshold. 2588 */ 2589 if (peer->retry > 0) { 2590 peer->retry = 0; 2591 if (peer->reach) 2592 peer->burst = min(1 << (peer->hpoll - 2593 peer->minpoll), NTP_SHIFT) - 1; 2594 else 2595 peer->burst = NTP_IBURST - 1; 2596 if (peer->burst > 0) 2597 peer->nextdate = current_time; 2598 } 2599 2600 /* 2601 * If the peer was previously unreachable, raise a trap. In any 2602 * case, mark it reachable. 2603 */ 2604 if (!peer->reach) { 2605 report_event(PEVNT_REACH, peer, NULL); 2606 peer->timereachable = current_time; 2607 } 2608 peer->reach |= 1; 2609 2610 /* 2611 * For a client/server association, calculate the clock offset, 2612 * roundtrip delay and dispersion. The equations are reordered 2613 * from the spec for more efficient use of temporaries. For a 2614 * broadcast association, offset the last measurement by the 2615 * computed delay during the client/server volley. Note the 2616 * computation of dispersion includes the system precision plus 2617 * that due to the frequency error since the origin time. 2618 * 2619 * It is very important to respect the hazards of overflow. The 2620 * only permitted operation on raw timestamps is subtraction, 2621 * where the result is a signed quantity spanning from 68 years 2622 * in the past to 68 years in the future. To avoid loss of 2623 * precision, these calculations are done using 64-bit integer 2624 * arithmetic. However, the offset and delay calculations are 2625 * sums and differences of these first-order differences, which 2626 * if done using 64-bit integer arithmetic, would be valid over 2627 * only half that span. Since the typical first-order 2628 * differences are usually very small, they are converted to 64- 2629 * bit doubles and all remaining calculations done in floating- 2630 * double arithmetic. This preserves the accuracy while 2631 * retaining the 68-year span. 2632 * 2633 * There are three interleaving schemes, basic, interleaved 2634 * symmetric and interleaved broadcast. The timestamps are 2635 * idioscyncratically different. See the onwire briefing/white 2636 * paper at www.eecis.udel.edu/~mills for details. 2637 * 2638 * Interleaved symmetric mode 2639 * t1 = peer->aorg/borg, t2 = peer->rec, t3 = p_xmt, 2640 * t4 = peer->dst 2641 */ 2642 if (peer->flip != 0) { 2643 ci = p_xmt; /* t3 - t4 */ 2644 L_SUB(&ci, &peer->dst); 2645 LFPTOD(&ci, t34); 2646 ci = p_rec; /* t2 - t1 */ 2647 if (peer->flip > 0) 2648 L_SUB(&ci, &peer->borg); 2649 else 2650 L_SUB(&ci, &peer->aorg); 2651 LFPTOD(&ci, t21); 2652 p_del = t21 - t34; 2653 p_offset = (t21 + t34) / 2.; 2654 if (p_del < 0 || p_del > 1.) { 2655 snprintf(statstr, sizeof(statstr), 2656 "t21 %.6f t34 %.6f", t21, t34); 2657 report_event(PEVNT_XERR, peer, statstr); 2658 return; 2659 } 2660 2661 /* 2662 * Broadcast modes 2663 */ 2664 } else if (peer->pmode == MODE_BROADCAST) { 2665 2666 /* 2667 * Interleaved broadcast mode. Use interleaved timestamps. 2668 * t1 = peer->borg, t2 = p_org, t3 = p_org, t4 = aorg 2669 */ 2670 if (peer->flags & FLAG_XB) { 2671 ci = p_org; /* delay */ 2672 L_SUB(&ci, &peer->aorg); 2673 LFPTOD(&ci, t34); 2674 ci = p_org; /* t2 - t1 */ 2675 L_SUB(&ci, &peer->borg); 2676 LFPTOD(&ci, t21); 2677 peer->aorg = p_xmt; 2678 peer->borg = peer->dst; 2679 if (t34 < 0 || t34 > 1.) { 2680 /* drop all if in the initial volley */ 2681 if (FLAG_BC_VOL & peer->flags) 2682 goto bcc_init_volley_fail; 2683 snprintf(statstr, sizeof(statstr), 2684 "offset %.6f delay %.6f", t21, t34); 2685 report_event(PEVNT_XERR, peer, statstr); 2686 return; 2687 } 2688 p_offset = t21; 2689 peer->xleave = t34; 2690 2691 /* 2692 * Basic broadcast - use direct timestamps. 2693 * t3 = p_xmt, t4 = peer->dst 2694 */ 2695 } else { 2696 ci = p_xmt; /* t3 - t4 */ 2697 L_SUB(&ci, &peer->dst); 2698 LFPTOD(&ci, t34); 2699 p_offset = t34; 2700 } 2701 2702 /* 2703 * When calibration is complete and the clock is 2704 * synchronized, the bias is calculated as the difference 2705 * between the unicast timestamp and the broadcast 2706 * timestamp. This works for both basic and interleaved 2707 * modes. 2708 * [Bug 3031] Don't keep this peer when the delay 2709 * calculation gives reason to suspect clock steps. 2710 * This is assumed for delays > 50ms. 2711 */ 2712 if (FLAG_BC_VOL & peer->flags) { 2713 peer->flags &= ~FLAG_BC_VOL; 2714 peer->delay = fabs(peer->offset - p_offset) * 2; 2715 DPRINTF(2, ("broadcast volley: initial delay=%.6f\n", 2716 peer->delay)); 2717 if (peer->delay > fabs(sys_bdelay)) { 2718 bcc_init_volley_fail: 2719 DPRINTF(2, ("%s", "broadcast volley: initial delay exceeds limit\n")); 2720 unpeer(peer); 2721 return; 2722 } 2723 } 2724 peer->nextdate = current_time + (1u << peer->ppoll) - 2u; 2725 p_del = peer->delay; 2726 p_offset += p_del / 2; 2727 2728 2729 /* 2730 * Basic mode, otherwise known as the old fashioned way. 2731 * 2732 * t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->dst 2733 */ 2734 } else { 2735 ci = p_xmt; /* t3 - t4 */ 2736 L_SUB(&ci, &peer->dst); 2737 LFPTOD(&ci, t34); 2738 ci = p_rec; /* t2 - t1 */ 2739 L_SUB(&ci, &p_org); 2740 LFPTOD(&ci, t21); 2741 p_del = fabs(t21 - t34); 2742 p_offset = (t21 + t34) / 2.; 2743 } 2744 p_del = max(p_del, LOGTOD(sys_precision)); 2745 p_disp = LOGTOD(sys_precision) + LOGTOD(peer->precision) + 2746 clock_phi * p_del; 2747 2748 #if ASSYM 2749 /* 2750 * This code calculates the outbound and inbound data rates by 2751 * measuring the differences between timestamps at different 2752 * packet lengths. This is helpful in cases of large asymmetric 2753 * delays commonly experienced on deep space communication 2754 * links. 2755 */ 2756 if (peer->t21_last > 0 && peer->t34_bytes > 0) { 2757 itemp = peer->t21_bytes - peer->t21_last; 2758 if (itemp > 25) { 2759 etemp = t21 - peer->t21; 2760 if (fabs(etemp) > 1e-6) { 2761 ftemp = itemp / etemp; 2762 if (ftemp > 1000.) 2763 peer->r21 = ftemp; 2764 } 2765 } 2766 itemp = len - peer->t34_bytes; 2767 if (itemp > 25) { 2768 etemp = -t34 - peer->t34; 2769 if (fabs(etemp) > 1e-6) { 2770 ftemp = itemp / etemp; 2771 if (ftemp > 1000.) 2772 peer->r34 = ftemp; 2773 } 2774 } 2775 } 2776 2777 /* 2778 * The following section compensates for different data rates on 2779 * the outbound (d21) and inbound (t34) directions. To do this, 2780 * it finds t such that r21 * t - r34 * (d - t) = 0, where d is 2781 * the roundtrip delay. Then it calculates the correction as a 2782 * fraction of d. 2783 */ 2784 peer->t21 = t21; 2785 peer->t21_last = peer->t21_bytes; 2786 peer->t34 = -t34; 2787 peer->t34_bytes = len; 2788 DPRINTF(2, ("packet: t21 %.9lf %d t34 %.9lf %d\n", peer->t21, 2789 peer->t21_bytes, peer->t34, peer->t34_bytes)); 2790 if (peer->r21 > 0 && peer->r34 > 0 && p_del > 0) { 2791 if (peer->pmode != MODE_BROADCAST) 2792 td = (peer->r34 / (peer->r21 + peer->r34) - 2793 .5) * p_del; 2794 else 2795 td = 0; 2796 2797 /* 2798 * Unfortunately, in many cases the errors are 2799 * unacceptable, so for the present the rates are not 2800 * used. In future, we might find conditions where the 2801 * calculations are useful, so this should be considered 2802 * a work in progress. 2803 */ 2804 t21 -= td; 2805 t34 -= td; 2806 DPRINTF(2, ("packet: del %.6lf r21 %.1lf r34 %.1lf %.6lf\n", 2807 p_del, peer->r21 / 1e3, peer->r34 / 1e3, 2808 td)); 2809 } 2810 #endif /* ASSYM */ 2811 2812 /* 2813 * That was awesome. Now hand off to the clock filter. 2814 */ 2815 clock_filter(peer, p_offset + peer->bias, p_del, p_disp); 2816 2817 /* 2818 * If we are in broadcast calibrate mode, return to broadcast 2819 * client mode when the client is fit and the autokey dance is 2820 * complete. 2821 */ 2822 if ( (FLAG_BC_VOL & peer->flags) 2823 && MODE_CLIENT == peer->hmode 2824 && !(TEST11 & peer_unfit(peer))) { /* distance exceeded */ 2825 #ifdef AUTOKEY 2826 if (peer->flags & FLAG_SKEY) { 2827 if (!(~peer->crypto & CRYPTO_FLAG_ALL)) 2828 peer->hmode = MODE_BCLIENT; 2829 } else { 2830 peer->hmode = MODE_BCLIENT; 2831 } 2832 #else /* !AUTOKEY follows */ 2833 peer->hmode = MODE_BCLIENT; 2834 #endif /* !AUTOKEY */ 2835 } 2836 } 2837 2838 2839 /* 2840 * clock_update - Called at system process update intervals. 2841 */ 2842 static void 2843 clock_update( 2844 struct peer *peer /* peer structure pointer */ 2845 ) 2846 { 2847 double dtemp; 2848 l_fp now; 2849 #ifdef HAVE_LIBSCF_H 2850 char *fmri; 2851 #endif /* HAVE_LIBSCF_H */ 2852 2853 /* 2854 * Update the system state variables. We do this very carefully, 2855 * as the poll interval might need to be clamped differently. 2856 */ 2857 sys_peer = peer; 2858 sys_epoch = peer->epoch; 2859 if (sys_poll < peer->minpoll) 2860 sys_poll = peer->minpoll; 2861 if (sys_poll > peer->maxpoll) 2862 sys_poll = peer->maxpoll; 2863 poll_update(peer, sys_poll, 0); 2864 sys_stratum = min(peer->stratum + 1, STRATUM_UNSPEC); 2865 if ( peer->stratum == STRATUM_REFCLOCK 2866 || peer->stratum == STRATUM_UNSPEC) 2867 sys_refid = peer->refid; 2868 else 2869 sys_refid = addr2refid(&peer->srcadr); 2870 /* 2871 * Root Dispersion (E) is defined (in RFC 5905) as: 2872 * 2873 * E = p.epsilon_r + p.epsilon + p.psi + PHI*(s.t - p.t) + |THETA| 2874 * 2875 * where: 2876 * p.epsilon_r is the PollProc's root dispersion 2877 * p.epsilon is the PollProc's dispersion 2878 * p.psi is the PollProc's jitter 2879 * THETA is the combined offset 2880 * 2881 * NB: Think Hard about where these numbers come from and 2882 * what they mean. When did peer->update happen? Has anything 2883 * interesting happened since then? What values are the most 2884 * defensible? Why? 2885 * 2886 * DLM thinks this equation is probably the best of all worse choices. 2887 */ 2888 dtemp = peer->rootdisp 2889 + peer->disp 2890 + sys_jitter 2891 + clock_phi * (current_time - peer->update) 2892 + fabs(sys_offset); 2893 2894 p2_rootdisp = prev_rootdisp; 2895 prev_rootdisp = sys_rootdisp; 2896 if (dtemp > sys_mindisp) 2897 sys_rootdisp = dtemp; 2898 else 2899 sys_rootdisp = sys_mindisp; 2900 2901 sys_rootdelay = peer->delay + peer->rootdelay; 2902 2903 p2_reftime = prev_reftime; 2904 p2_time = prev_time; 2905 2906 prev_reftime = sys_reftime; 2907 prev_time = current_time + 64 + (rand() & 0x3f); /* 64-127 s */ 2908 2909 sys_reftime = peer->dst; 2910 2911 DPRINTF(1, ("clock_update: at %lu sample %lu associd %d\n", 2912 current_time, peer->epoch, peer->associd)); 2913 2914 /* 2915 * Comes now the moment of truth. Crank the clock discipline and 2916 * see what comes out. 2917 */ 2918 switch (local_clock(peer, sys_offset)) { 2919 2920 /* 2921 * Clock exceeds panic threshold. Life as we know it ends. 2922 */ 2923 case -1: 2924 msyslog(LOG_ERR, "Clock offset exceeds panic threshold."); 2925 #ifdef HAVE_LIBSCF_H 2926 /* 2927 * For Solaris enter the maintenance mode. 2928 */ 2929 if ((fmri = getenv("SMF_FMRI")) != NULL) { 2930 if (smf_maintain_instance(fmri, 0) < 0) { 2931 msyslog(LOG_ERR, "smf_maintain_instance: %s", 2932 scf_strerror(scf_error())); 2933 exit(1); 2934 } 2935 /* 2936 * Sleep until SMF kills us. 2937 */ 2938 msyslog(LOG_ERR, "%s placed into maintenance. " 2939 "Set system clock by hand before clearing.", 2940 fmri); 2941 for (;;) 2942 pause(); 2943 } 2944 #endif /* HAVE_LIBSCF_H */ 2945 msyslog(LOG_ERR, "Set system clock by hand."); 2946 exit (-1); 2947 /* not reached */ 2948 2949 /* 2950 * Clock was stepped. Flush all time values of all peers. 2951 */ 2952 case 2: 2953 clear_all(); 2954 set_sys_leap(LEAP_NOTINSYNC); 2955 sys_stratum = STRATUM_UNSPEC; 2956 memcpy(&sys_refid, "STEP", 4); 2957 sys_rootdelay = 0; 2958 p2_rootdisp = 0; 2959 prev_rootdisp = 0; 2960 sys_rootdisp = 0; 2961 L_CLR(&p2_reftime); /* Should we clear p2_reftime? */ 2962 L_CLR(&prev_reftime); /* Should we clear prev_reftime? */ 2963 L_CLR(&sys_reftime); 2964 sys_jitter = LOGTOD(sys_precision); 2965 leapsec_reset_frame(); 2966 break; 2967 2968 /* 2969 * Clock was slewed. Handle the leapsecond stuff. 2970 */ 2971 case 1: 2972 2973 /* 2974 * If this is the first time the clock is set, reset the 2975 * leap bits. If crypto, the timer will goose the setup 2976 * process. 2977 */ 2978 if (sys_leap == LEAP_NOTINSYNC) { 2979 set_sys_leap(LEAP_NOWARNING); 2980 #ifdef AUTOKEY 2981 if (crypto_flags) 2982 crypto_update(); 2983 #endif /* AUTOKEY */ 2984 /* 2985 * If our parent process is waiting for the 2986 * first clock sync, send them home satisfied. 2987 */ 2988 #ifdef HAVE_WORKING_FORK 2989 if (daemon_pipe[1] != -1) { 2990 if (2 != write(daemon_pipe[1], "S\n", 2)) 2991 msyslog(LOG_ERR, "ntpd: daemon failed to notify parent!"); 2992 close(daemon_pipe[1]); 2993 daemon_pipe[1] = -1; 2994 DPRINTF(1, ("notified parent --wait-sync is done\n")); 2995 } 2996 #endif /* HAVE_WORKING_FORK */ 2997 2998 } 2999 3000 /* 3001 * If there is no leap second pending and the number of 3002 * survivor leap bits is greater than half the number of 3003 * survivors, try to schedule a leap for the end of the 3004 * current month. (This only works if no leap second for 3005 * that range is in the table, so doing this more than 3006 * once is mostly harmless.) 3007 */ 3008 if (leapsec == LSPROX_NOWARN) { 3009 if ( leap_vote_ins > leap_vote_del 3010 && leap_vote_ins > sys_survivors / 2) { 3011 get_systime(&now); 3012 leapsec_add_dyn(TRUE, now.l_ui, NULL); 3013 } 3014 if ( leap_vote_del > leap_vote_ins 3015 && leap_vote_del > sys_survivors / 2) { 3016 get_systime(&now); 3017 leapsec_add_dyn(FALSE, now.l_ui, NULL); 3018 } 3019 } 3020 break; 3021 3022 /* 3023 * Popcorn spike or step threshold exceeded. Pretend it never 3024 * happened. 3025 */ 3026 default: 3027 break; 3028 } 3029 } 3030 3031 3032 /* 3033 * poll_update - update peer poll interval 3034 */ 3035 void 3036 poll_update( 3037 struct peer *peer, /* peer structure pointer */ 3038 u_char mpoll, 3039 u_char skewpoll 3040 ) 3041 { 3042 u_long next, utemp, limit; 3043 u_char hpoll; 3044 3045 /* 3046 * This routine figures out when the next poll should be sent. 3047 * That turns out to be wickedly complicated. One problem is 3048 * that sometimes the time for the next poll is in the past when 3049 * the poll interval is reduced. We watch out for races here 3050 * between the receive process and the poll process. 3051 * 3052 * Clamp the poll interval between minpoll and maxpoll. 3053 */ 3054 hpoll = max(min(peer->maxpoll, mpoll), peer->minpoll); 3055 3056 #ifdef AUTOKEY 3057 /* 3058 * If during the crypto protocol the poll interval has changed, 3059 * the lifetimes in the key list are probably bogus. Purge the 3060 * the key list and regenerate it later. 3061 */ 3062 if ((peer->flags & FLAG_SKEY) && hpoll != peer->hpoll) 3063 key_expire(peer); 3064 #endif /* AUTOKEY */ 3065 peer->hpoll = hpoll; 3066 3067 /* 3068 * There are three variables important for poll scheduling, the 3069 * current time (current_time), next scheduled time (nextdate) 3070 * and the earliest time (utemp). The earliest time is 2 s 3071 * seconds, but could be more due to rate management. When 3072 * sending in a burst, use the earliest time. When not in a 3073 * burst but with a reply pending, send at the earliest time 3074 * unless the next scheduled time has not advanced. This can 3075 * only happen if multiple replies are pending in the same 3076 * response interval. Otherwise, send at the later of the next 3077 * scheduled time and the earliest time. 3078 * 3079 * Now we figure out if there is an override. If a burst is in 3080 * progress and we get called from the receive process, just 3081 * slink away. If called from the poll process, delay 1 s for a 3082 * reference clock, otherwise 2 s. 3083 */ 3084 utemp = current_time + max(peer->throttle - (NTP_SHIFT - 1) * 3085 (1 << peer->minpoll), ntp_minpkt); 3086 3087 /*[Bug 3592] avoid unlimited postpone of next poll */ 3088 limit = (2u << hpoll); 3089 if (limit > 64) 3090 limit -= (limit >> 2); 3091 limit += peer->outdate; 3092 if (limit < current_time) 3093 limit = current_time; 3094 3095 if (peer->burst > 0) { 3096 if (peer->nextdate > current_time) 3097 return; 3098 #ifdef REFCLOCK 3099 else if (peer->flags & FLAG_REFCLOCK) 3100 peer->nextdate = current_time + RESP_DELAY; 3101 #endif /* REFCLOCK */ 3102 else 3103 peer->nextdate = utemp; 3104 3105 #ifdef AUTOKEY 3106 /* 3107 * If a burst is not in progress and a crypto response message 3108 * is pending, delay 2 s, but only if this is a new interval. 3109 */ 3110 } else if (peer->cmmd != NULL) { 3111 if (peer->nextdate > current_time) { 3112 if (peer->nextdate + ntp_minpkt != utemp) 3113 peer->nextdate = utemp; 3114 } else { 3115 peer->nextdate = utemp; 3116 } 3117 #endif /* AUTOKEY */ 3118 3119 /* 3120 * The ordinary case. If a retry, use minpoll; if unreachable, 3121 * use host poll; otherwise, use the minimum of host and peer 3122 * polls; In other words, oversampling is okay but 3123 * understampling is evil. Use the maximum of this value and the 3124 * headway. If the average headway is greater than the headway 3125 * threshold, increase the headway by the minimum interval. 3126 */ 3127 } else { 3128 if (peer->retry > 0) 3129 hpoll = peer->minpoll; 3130 else 3131 hpoll = min(peer->ppoll, peer->hpoll); 3132 #ifdef REFCLOCK 3133 if (peer->flags & FLAG_REFCLOCK) 3134 next = 1 << hpoll; 3135 else 3136 #endif /* REFCLOCK */ 3137 next = ((0x1000UL | (ntp_random() & 0x0ff)) << 3138 hpoll) >> 12; 3139 next += peer->outdate; 3140 /* XXX: bug3596: Deal with poll skew list? */ 3141 if (skewpoll) { 3142 psl_item psi; 3143 3144 if (0 == get_pollskew(hpoll, &psi)) { 3145 int sub = psi.sub; 3146 int qty = psi.qty; 3147 int msk = psi.msk; 3148 int val; 3149 3150 if ( 0 != sub 3151 || 0 != qty) { 3152 do { 3153 val = ntp_random() & msk; 3154 } while (val > qty); 3155 3156 next -= sub; 3157 next += val; 3158 } 3159 } else { 3160 /* get_pollskew() already logged this */ 3161 } 3162 } 3163 if (next > utemp) 3164 peer->nextdate = next; 3165 else 3166 peer->nextdate = utemp; 3167 if (peer->throttle > (1 << peer->minpoll)) 3168 peer->nextdate += ntp_minpkt; 3169 } 3170 3171 /*[Bug 3592] avoid unlimited postpone of next poll */ 3172 if (peer->nextdate > limit) { 3173 DPRINTF(1, ("poll_update: clamp reached; limit %lu next %lu\n", 3174 limit, peer->nextdate)); 3175 peer->nextdate = limit; 3176 } 3177 DPRINTF(2, ("poll_update: at %lu %s poll %d burst %d retry %d head %d early %lu next %lu\n", 3178 current_time, ntoa(&peer->srcadr), peer->hpoll, 3179 peer->burst, peer->retry, peer->throttle, 3180 utemp - current_time, peer->nextdate - 3181 current_time)); 3182 } 3183 3184 3185 /* 3186 * peer_clear - clear peer filter registers. See Section 3.4.8 of the 3187 * spec. 3188 */ 3189 void 3190 peer_clear( 3191 struct peer *peer, /* peer structure */ 3192 const char *ident /* tally lights */ 3193 ) 3194 { 3195 u_char u; 3196 l_fp bxmt = peer->bxmt; /* bcast clients retain this! */ 3197 3198 #ifdef AUTOKEY 3199 /* 3200 * If cryptographic credentials have been acquired, toss them to 3201 * Valhalla. Note that autokeys are ephemeral, in that they are 3202 * tossed immediately upon use. Therefore, the keylist can be 3203 * purged anytime without needing to preserve random keys. Note 3204 * that, if the peer is purged, the cryptographic variables are 3205 * purged, too. This makes it much harder to sneak in some 3206 * unauthenticated data in the clock filter. 3207 */ 3208 key_expire(peer); 3209 if (peer->iffval != NULL) 3210 BN_free(peer->iffval); 3211 value_free(&peer->cookval); 3212 value_free(&peer->recval); 3213 value_free(&peer->encrypt); 3214 value_free(&peer->sndval); 3215 if (peer->cmmd != NULL) 3216 free(peer->cmmd); 3217 if (peer->subject != NULL) 3218 free(peer->subject); 3219 if (peer->issuer != NULL) 3220 free(peer->issuer); 3221 #endif /* AUTOKEY */ 3222 3223 /* 3224 * Clear all values, including the optional crypto values above. 3225 */ 3226 memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO(peer)); 3227 peer->ppoll = peer->maxpoll; 3228 peer->hpoll = peer->minpoll; 3229 peer->disp = MAXDISPERSE; 3230 peer->flash = peer_unfit(peer); 3231 peer->jitter = LOGTOD(sys_precision); 3232 3233 /* Don't throw away our broadcast replay protection */ 3234 if (peer->hmode == MODE_BCLIENT) 3235 peer->bxmt = bxmt; 3236 3237 /* 3238 * If interleave mode, initialize the alternate origin switch. 3239 */ 3240 if (peer->flags & FLAG_XLEAVE) 3241 peer->flip = 1; 3242 for (u = 0; u < NTP_SHIFT; u++) { 3243 peer->filter_order[u] = u; 3244 peer->filter_disp[u] = MAXDISPERSE; 3245 } 3246 #ifdef REFCLOCK 3247 if (!(peer->flags & FLAG_REFCLOCK)) { 3248 #endif 3249 peer->leap = LEAP_NOTINSYNC; 3250 peer->stratum = STRATUM_UNSPEC; 3251 memcpy(&peer->refid, ident, 4); 3252 #ifdef REFCLOCK 3253 } else { 3254 /* Clear refclock sample filter */ 3255 peer->procptr->codeproc = 0; 3256 peer->procptr->coderecv = 0; 3257 } 3258 #endif 3259 3260 /* 3261 * During initialization use the association count to spread out 3262 * the polls at one-second intervals. Unconfigured associations' 3263 * first poll is delayed by the "discard minimum" plus 1 to avoid 3264 * rate limiting. Other post-startup new or cleared associations 3265 * randomize the first poll over the minimum poll interval to 3266 * avoid implosion. 3267 */ 3268 peer->nextdate = peer->update = peer->outdate = current_time; 3269 if (initializing) { 3270 peer->nextdate += peer_associations; 3271 } else if (!(FLAG_CONFIG & peer->flags)) { 3272 peer->nextdate += ntp_minpkt + 1; 3273 } else { 3274 peer->nextdate += ntp_random() % (1 << peer->minpoll); 3275 } 3276 #ifdef AUTOKEY 3277 peer->refresh = current_time + (1 << NTP_REFRESH); 3278 #endif /* AUTOKEY */ 3279 DPRINTF(1, ("peer_clear: at %ld next %ld associd %d refid %s\n", 3280 current_time, peer->nextdate, peer->associd, 3281 ident)); 3282 } 3283 3284 3285 /* 3286 * clock_filter - add incoming clock sample to filter register and run 3287 * the filter procedure to find the best sample. 3288 */ 3289 void 3290 clock_filter( 3291 struct peer *peer, /* peer structure pointer */ 3292 double sample_offset, /* clock offset */ 3293 double sample_delay, /* roundtrip delay */ 3294 double sample_disp /* dispersion */ 3295 ) 3296 { 3297 double dst[NTP_SHIFT]; /* distance vector */ 3298 int ord[NTP_SHIFT]; /* index vector */ 3299 int i, j, k, m; 3300 double dtemp, etemp; 3301 char tbuf[80]; 3302 3303 /* 3304 * A sample consists of the offset, delay, dispersion and epoch 3305 * of arrival. The offset and delay are determined by the on- 3306 * wire protocol. The dispersion grows from the last outbound 3307 * packet to the arrival of this one increased by the sum of the 3308 * peer precision and the system precision as required by the 3309 * error budget. First, shift the new arrival into the shift 3310 * register discarding the oldest one. 3311 */ 3312 j = peer->filter_nextpt; 3313 peer->filter_offset[j] = sample_offset; 3314 peer->filter_delay[j] = sample_delay; 3315 peer->filter_disp[j] = sample_disp; 3316 peer->filter_epoch[j] = current_time; 3317 j = (j + 1) % NTP_SHIFT; 3318 peer->filter_nextpt = j; 3319 3320 /* 3321 * Update dispersions since the last update and at the same 3322 * time initialize the distance and index lists. Since samples 3323 * become increasingly uncorrelated beyond the Allan intercept, 3324 * only under exceptional cases will an older sample be used. 3325 * Therefore, the distance list uses a compound metric. If the 3326 * dispersion is greater than the maximum dispersion, clamp the 3327 * distance at that value. If the time since the last update is 3328 * less than the Allan intercept use the delay; otherwise, use 3329 * the sum of the delay and dispersion. 3330 */ 3331 dtemp = clock_phi * (current_time - peer->update); 3332 peer->update = current_time; 3333 for (i = NTP_SHIFT - 1; i >= 0; i--) { 3334 if (i != 0) 3335 peer->filter_disp[j] += dtemp; 3336 if (peer->filter_disp[j] >= MAXDISPERSE) { 3337 peer->filter_disp[j] = MAXDISPERSE; 3338 dst[i] = MAXDISPERSE; 3339 } else if (peer->update - peer->filter_epoch[j] > 3340 (u_long)ULOGTOD(allan_xpt)) { 3341 dst[i] = peer->filter_delay[j] + 3342 peer->filter_disp[j]; 3343 } else { 3344 dst[i] = peer->filter_delay[j]; 3345 } 3346 ord[i] = j; 3347 j = (j + 1) % NTP_SHIFT; 3348 } 3349 3350 /* 3351 * If the clock has stabilized, sort the samples by distance. 3352 */ 3353 if (freq_cnt == 0) { 3354 for (i = 1; i < NTP_SHIFT; i++) { 3355 for (j = 0; j < i; j++) { 3356 if (dst[j] > dst[i]) { 3357 k = ord[j]; 3358 ord[j] = ord[i]; 3359 ord[i] = k; 3360 etemp = dst[j]; 3361 dst[j] = dst[i]; 3362 dst[i] = etemp; 3363 } 3364 } 3365 } 3366 } 3367 3368 /* 3369 * Copy the index list to the association structure so ntpq 3370 * can see it later. Prune the distance list to leave only 3371 * samples less than the maximum dispersion, which disfavors 3372 * uncorrelated samples older than the Allan intercept. To 3373 * further improve the jitter estimate, of the remainder leave 3374 * only samples less than the maximum distance, but keep at 3375 * least two samples for jitter calculation. 3376 */ 3377 m = 0; 3378 for (i = 0; i < NTP_SHIFT; i++) { 3379 peer->filter_order[i] = (u_char) ord[i]; 3380 if ( dst[i] >= MAXDISPERSE 3381 || (m >= 2 && dst[i] >= sys_maxdist)) 3382 continue; 3383 m++; 3384 } 3385 3386 /* 3387 * Compute the dispersion and jitter. The dispersion is weighted 3388 * exponentially by NTP_FWEIGHT (0.5) so it is normalized close 3389 * to 1.0. The jitter is the RMS differences relative to the 3390 * lowest delay sample. 3391 */ 3392 peer->disp = peer->jitter = 0; 3393 k = ord[0]; 3394 for (i = NTP_SHIFT - 1; i >= 0; i--) { 3395 j = ord[i]; 3396 peer->disp = NTP_FWEIGHT * (peer->disp + 3397 peer->filter_disp[j]); 3398 if (i < m) 3399 peer->jitter += DIFF(peer->filter_offset[j], 3400 peer->filter_offset[k]); 3401 } 3402 3403 /* 3404 * If no acceptable samples remain in the shift register, 3405 * quietly tiptoe home leaving only the dispersion. Otherwise, 3406 * save the offset, delay and jitter. Note the jitter must not 3407 * be less than the precision. 3408 */ 3409 if (m == 0) { 3410 clock_select(); 3411 return; 3412 } 3413 etemp = fabs(peer->offset - peer->filter_offset[k]); 3414 peer->offset = peer->filter_offset[k]; 3415 peer->delay = peer->filter_delay[k]; 3416 if (m > 1) 3417 peer->jitter /= m - 1; 3418 peer->jitter = max(SQRT(peer->jitter), LOGTOD(sys_precision)); 3419 3420 /* 3421 * If the the new sample and the current sample are both valid 3422 * and the difference between their offsets exceeds CLOCK_SGATE 3423 * (3) times the jitter and the interval between them is less 3424 * than twice the host poll interval, consider the new sample 3425 * a popcorn spike and ignore it. 3426 */ 3427 if ( peer->disp < sys_maxdist 3428 && peer->filter_disp[k] < sys_maxdist 3429 && etemp > CLOCK_SGATE * peer->jitter 3430 && peer->filter_epoch[k] - peer->epoch 3431 < 2. * ULOGTOD(peer->hpoll)) { 3432 snprintf(tbuf, sizeof(tbuf), "%.6f s", etemp); 3433 report_event(PEVNT_POPCORN, peer, tbuf); 3434 return; 3435 } 3436 3437 /* 3438 * A new minimum sample is useful only if it is later than the 3439 * last one used. In this design the maximum lifetime of any 3440 * sample is not greater than eight times the poll interval, so 3441 * the maximum interval between minimum samples is eight 3442 * packets. 3443 */ 3444 if (peer->filter_epoch[k] <= peer->epoch) { 3445 DPRINTF(2, ("clock_filter: old sample %lu\n", current_time - 3446 peer->filter_epoch[k])); 3447 return; 3448 } 3449 peer->epoch = peer->filter_epoch[k]; 3450 3451 /* 3452 * The mitigated sample statistics are saved for later 3453 * processing. If not synchronized or not in a burst, tickle the 3454 * clock select algorithm. 3455 */ 3456 record_peer_stats(&peer->srcadr, ctlpeerstatus(peer), 3457 peer->offset, peer->delay, peer->disp, peer->jitter); 3458 DPRINTF(1, ("clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f\n", 3459 m, peer->offset, peer->delay, peer->disp, 3460 peer->jitter)); 3461 if (peer->burst == 0 || sys_leap == LEAP_NOTINSYNC) 3462 clock_select(); 3463 } 3464 3465 3466 /* 3467 * clock_select - find the pick-of-the-litter clock 3468 * 3469 * LOCKCLOCK: (1) If the local clock is the prefer peer, it will always 3470 * be enabled, even if declared falseticker, (2) only the prefer peer 3471 * can be selected as the system peer, (3) if the external source is 3472 * down, the system leap bits are set to 11 and the stratum set to 3473 * infinity. 3474 */ 3475 void 3476 clock_select(void) 3477 { 3478 struct peer *peer; 3479 int i, j, k, n; 3480 int nlist, nl2; 3481 int allow; 3482 int speer; 3483 double d, e, f, g; 3484 double high, low; 3485 double speermet; 3486 double lastresort_dist = MAXDISPERSE; 3487 double orphmet = 2.0 * U_INT32_MAX; /* 2x is greater than */ 3488 struct endpoint endp; 3489 struct peer *osys_peer; 3490 struct peer *sys_prefer = NULL; /* prefer peer */ 3491 struct peer *typesystem = NULL; 3492 struct peer *typelastresort = NULL; 3493 struct peer *typeorphan = NULL; 3494 #ifdef REFCLOCK 3495 struct peer *typeacts = NULL; 3496 struct peer *typelocal = NULL; 3497 struct peer *typepps = NULL; 3498 #endif /* REFCLOCK */ 3499 static struct endpoint *endpoint = NULL; 3500 static int *indx = NULL; 3501 static peer_select *peers = NULL; 3502 static u_int endpoint_size = 0; 3503 static u_int peers_size = 0; 3504 static u_int indx_size = 0; 3505 size_t octets; 3506 3507 /* 3508 * Initialize and create endpoint, index and peer lists big 3509 * enough to handle all associations. 3510 */ 3511 osys_peer = sys_peer; 3512 sys_survivors = 0; 3513 #ifdef LOCKCLOCK 3514 set_sys_leap(LEAP_NOTINSYNC); 3515 sys_stratum = STRATUM_UNSPEC; 3516 memcpy(&sys_refid, "DOWN", 4); 3517 #endif /* LOCKCLOCK */ 3518 3519 /* 3520 * Allocate dynamic space depending on the number of 3521 * associations. 3522 */ 3523 nlist = 1; 3524 for (peer = peer_list; peer != NULL; peer = peer->p_link) 3525 nlist++; 3526 endpoint_size = ALIGNED_SIZE(nlist * 2 * sizeof(*endpoint)); 3527 peers_size = ALIGNED_SIZE(nlist * sizeof(*peers)); 3528 indx_size = ALIGNED_SIZE(nlist * 2 * sizeof(*indx)); 3529 octets = endpoint_size + peers_size + indx_size; 3530 endpoint = erealloc(endpoint, octets); 3531 peers = INC_ALIGNED_PTR(endpoint, endpoint_size); 3532 indx = INC_ALIGNED_PTR(peers, peers_size); 3533 3534 /* 3535 * Initially, we populate the island with all the rifraff peers 3536 * that happen to be lying around. Those with seriously 3537 * defective clocks are immediately booted off the island. Then, 3538 * the falsetickers are culled and put to sea. The truechimers 3539 * remaining are subject to repeated rounds where the most 3540 * unpopular at each round is kicked off. When the population 3541 * has dwindled to sys_minclock, the survivors split a million 3542 * bucks and collectively crank the chimes. 3543 */ 3544 nlist = nl2 = 0; /* none yet */ 3545 for (peer = peer_list; peer != NULL; peer = peer->p_link) { 3546 peer->new_status = CTL_PST_SEL_REJECT; 3547 3548 /* 3549 * Leave the island immediately if the peer is 3550 * unfit to synchronize. 3551 */ 3552 if (peer_unfit(peer)) { 3553 continue; 3554 } 3555 3556 /* 3557 * If we have never been synchronised, look for any peer 3558 * which has ever been synchronised and pick the one which 3559 * has the lowest root distance. This can be used as a last 3560 * resort if all else fails. Once we get an initial sync 3561 * with this peer, sys_reftime gets set and so this 3562 * function becomes disabled. 3563 */ 3564 if (L_ISZERO(&sys_reftime)) { 3565 d = root_distance(peer); 3566 if (!L_ISZERO(&peer->reftime) && d < lastresort_dist) { 3567 typelastresort = peer; 3568 lastresort_dist = d; 3569 } 3570 } 3571 3572 /* 3573 * If this peer is an orphan parent, elect the 3574 * one with the lowest metric defined as the 3575 * IPv4 address or the first 64 bits of the 3576 * hashed IPv6 address. To ensure convergence 3577 * on the same selected orphan, consider as 3578 * well that this system may have the lowest 3579 * metric and be the orphan parent. If this 3580 * system wins, sys_peer will be NULL to trigger 3581 * orphan mode in timer(). 3582 */ 3583 if (peer->stratum == sys_orphan) { 3584 u_int32 localmet; 3585 u_int32 peermet; 3586 3587 if (peer->dstadr != NULL) 3588 localmet = ntohl(peer->dstadr->addr_refid); 3589 else 3590 localmet = U_INT32_MAX; 3591 peermet = ntohl(addr2refid(&peer->srcadr)); 3592 if (peermet < localmet && peermet < orphmet) { 3593 typeorphan = peer; 3594 orphmet = peermet; 3595 } 3596 continue; 3597 } 3598 3599 /* 3600 * If this peer could have the orphan parent 3601 * as a synchronization ancestor, exclude it 3602 * from selection to avoid forming a 3603 * synchronization loop within the orphan mesh, 3604 * triggering stratum climb to infinity 3605 * instability. Peers at stratum higher than 3606 * the orphan stratum could have the orphan 3607 * parent in ancestry so are excluded. 3608 * See http://bugs.ntp.org/2050 3609 */ 3610 if (peer->stratum > sys_orphan) { 3611 continue; 3612 } 3613 #ifdef REFCLOCK 3614 /* 3615 * The following are special cases. We deal 3616 * with them later. 3617 */ 3618 if (!(peer->flags & FLAG_PREFER)) { 3619 switch (peer->refclktype) { 3620 case REFCLK_LOCALCLOCK: 3621 if ( current_time > orphwait 3622 && typelocal == NULL) 3623 typelocal = peer; 3624 continue; 3625 3626 case REFCLK_ACTS: 3627 if ( current_time > orphwait 3628 && typeacts == NULL) 3629 typeacts = peer; 3630 continue; 3631 } 3632 } 3633 #endif /* REFCLOCK */ 3634 3635 /* 3636 * If we get this far, the peer can stay on the 3637 * island, but does not yet have the immunity 3638 * idol. 3639 */ 3640 peer->new_status = CTL_PST_SEL_SANE; 3641 f = root_distance(peer); 3642 peers[nlist].peer = peer; 3643 peers[nlist].error = peer->jitter; 3644 peers[nlist].synch = f; 3645 nlist++; 3646 3647 /* 3648 * Insert each interval endpoint on the unsorted 3649 * endpoint[] list. 3650 */ 3651 e = peer->offset; 3652 endpoint[nl2].type = -1; /* lower end */ 3653 endpoint[nl2].val = e - f; 3654 nl2++; 3655 endpoint[nl2].type = 1; /* upper end */ 3656 endpoint[nl2].val = e + f; 3657 nl2++; 3658 } 3659 /* 3660 * Construct sorted indx[] of endpoint[] indexes ordered by 3661 * offset. 3662 */ 3663 for (i = 0; i < nl2; i++) 3664 indx[i] = i; 3665 for (i = 0; i < nl2; i++) { 3666 endp = endpoint[indx[i]]; 3667 e = endp.val; 3668 k = i; 3669 for (j = i + 1; j < nl2; j++) { 3670 endp = endpoint[indx[j]]; 3671 if (endp.val < e) { 3672 e = endp.val; 3673 k = j; 3674 } 3675 } 3676 if (k != i) { 3677 j = indx[k]; 3678 indx[k] = indx[i]; 3679 indx[i] = j; 3680 } 3681 } 3682 for (i = 0; i < nl2; i++) 3683 DPRINTF(3, ("select: endpoint %2d %.6f\n", 3684 endpoint[indx[i]].type, endpoint[indx[i]].val)); 3685 3686 /* 3687 * This is the actual algorithm that cleaves the truechimers 3688 * from the falsetickers. The original algorithm was described 3689 * in Keith Marzullo's dissertation, but has been modified for 3690 * better accuracy. 3691 * 3692 * Briefly put, we first assume there are no falsetickers, then 3693 * scan the candidate list first from the low end upwards and 3694 * then from the high end downwards. The scans stop when the 3695 * number of intersections equals the number of candidates less 3696 * the number of falsetickers. If this doesn't happen for a 3697 * given number of falsetickers, we bump the number of 3698 * falsetickers and try again. If the number of falsetickers 3699 * becomes equal to or greater than half the number of 3700 * candidates, the Albanians have won the Byzantine wars and 3701 * correct synchronization is not possible. 3702 * 3703 * Here, nlist is the number of candidates and allow is the 3704 * number of falsetickers. Upon exit, the truechimers are the 3705 * survivors with offsets not less than low and not greater than 3706 * high. There may be none of them. 3707 */ 3708 low = 1e9; 3709 high = -1e9; 3710 for (allow = 0; 2 * allow < nlist; allow++) { 3711 3712 /* 3713 * Bound the interval (low, high) as the smallest 3714 * interval containing points from the most sources. 3715 */ 3716 n = 0; 3717 for (i = 0; i < nl2; i++) { 3718 low = endpoint[indx[i]].val; 3719 n -= endpoint[indx[i]].type; 3720 if (n >= nlist - allow) 3721 break; 3722 } 3723 n = 0; 3724 for (j = nl2 - 1; j >= 0; j--) { 3725 high = endpoint[indx[j]].val; 3726 n += endpoint[indx[j]].type; 3727 if (n >= nlist - allow) 3728 break; 3729 } 3730 3731 /* 3732 * If an interval containing truechimers is found, stop. 3733 * If not, increase the number of falsetickers and go 3734 * around again. 3735 */ 3736 if (high > low) 3737 break; 3738 } 3739 3740 /* 3741 * Clustering algorithm. Whittle candidate list of falsetickers, 3742 * who leave the island immediately. The TRUE peer is always a 3743 * truechimer. We must leave at least one peer to collect the 3744 * million bucks. 3745 * 3746 * We assert the correct time is contained in the interval, but 3747 * the best offset estimate for the interval might not be 3748 * contained in the interval. For this purpose, a truechimer is 3749 * defined as the midpoint of an interval that overlaps the 3750 * intersection interval. 3751 */ 3752 j = 0; 3753 for (i = 0; i < nlist; i++) { 3754 double h; 3755 3756 peer = peers[i].peer; 3757 h = peers[i].synch; 3758 if (( high <= low 3759 || peer->offset + h < low 3760 || peer->offset - h > high 3761 ) && !(peer->flags & FLAG_TRUE)) 3762 continue; 3763 3764 #ifdef REFCLOCK 3765 /* 3766 * Eligible PPS peers must survive the intersection 3767 * algorithm. Use the first one found, but don't 3768 * include any of them in the cluster population. 3769 */ 3770 if (peer->flags & FLAG_PPS) { 3771 if (typepps == NULL) 3772 typepps = peer; 3773 if (!(peer->flags & FLAG_TSTAMP_PPS)) 3774 continue; 3775 } 3776 #endif /* REFCLOCK */ 3777 3778 if (j != i) 3779 peers[j] = peers[i]; 3780 j++; 3781 } 3782 nlist = j; 3783 3784 /* 3785 * If no survivors remain at this point, check if the modem 3786 * driver, local driver or orphan parent in that order. If so, 3787 * nominate the first one found as the only survivor. 3788 * Otherwise, give up and leave the island to the rats. 3789 */ 3790 if (nlist == 0) { 3791 peers[0].error = 0; 3792 peers[0].synch = sys_mindisp; 3793 #ifdef REFCLOCK 3794 if (typeacts != NULL) { 3795 peers[0].peer = typeacts; 3796 nlist = 1; 3797 } else if (typelocal != NULL) { 3798 peers[0].peer = typelocal; 3799 nlist = 1; 3800 } else 3801 #endif /* REFCLOCK */ 3802 if (typeorphan != NULL) { 3803 peers[0].peer = typeorphan; 3804 nlist = 1; 3805 } else if (typelastresort != NULL) { 3806 peers[0].peer = typelastresort; 3807 nlist = 1; 3808 } 3809 } 3810 3811 /* 3812 * Mark the candidates at this point as truechimers. 3813 */ 3814 for (i = 0; i < nlist; i++) { 3815 peers[i].peer->new_status = CTL_PST_SEL_SELCAND; 3816 DPRINTF(2, ("select: survivor %s %f\n", 3817 stoa(&peers[i].peer->srcadr), peers[i].synch)); 3818 } 3819 3820 /* 3821 * Now, vote outliers off the island by select jitter weighted 3822 * by root distance. Continue voting as long as there are more 3823 * than sys_minclock survivors and the select jitter of the peer 3824 * with the worst metric is greater than the minimum peer 3825 * jitter. Stop if we are about to discard a TRUE or PREFER 3826 * peer, who of course have the immunity idol. 3827 */ 3828 while (1) { 3829 d = 1e9; 3830 e = -1e9; 3831 g = 0; 3832 k = 0; 3833 for (i = 0; i < nlist; i++) { 3834 if (peers[i].error < d) 3835 d = peers[i].error; 3836 peers[i].seljit = 0; 3837 if (nlist > 1) { 3838 f = 0; 3839 for (j = 0; j < nlist; j++) 3840 f += DIFF(peers[j].peer->offset, 3841 peers[i].peer->offset); 3842 peers[i].seljit = SQRT(f / (nlist - 1)); 3843 } 3844 if (peers[i].seljit * peers[i].synch > e) { 3845 g = peers[i].seljit; 3846 e = peers[i].seljit * peers[i].synch; 3847 k = i; 3848 } 3849 } 3850 g = max(g, LOGTOD(sys_precision)); 3851 if ( nlist <= max(1, sys_minclock) 3852 || g <= d 3853 || ((FLAG_TRUE | FLAG_PREFER) & peers[k].peer->flags)) 3854 break; 3855 3856 DPRINTF(3, ("select: drop %s seljit %.6f jit %.6f\n", 3857 ntoa(&peers[k].peer->srcadr), g, d)); 3858 if (nlist > sys_maxclock) 3859 peers[k].peer->new_status = CTL_PST_SEL_EXCESS; 3860 for (j = k + 1; j < nlist; j++) 3861 peers[j - 1] = peers[j]; 3862 nlist--; 3863 } 3864 3865 /* 3866 * What remains is a list usually not greater than sys_minclock 3867 * peers. Note that unsynchronized peers cannot survive this 3868 * far. Count and mark these survivors. 3869 * 3870 * While at it, count the number of leap warning bits found. 3871 * This will be used later to vote the system leap warning bit. 3872 * If a leap warning bit is found on a reference clock, the vote 3873 * is always won. 3874 * 3875 * Choose the system peer using a hybrid metric composed of the 3876 * selection jitter scaled by the root distance augmented by 3877 * stratum scaled by sys_mindisp (.001 by default). The goal of 3878 * the small stratum factor is to avoid clockhop between a 3879 * reference clock and a network peer which has a refclock and 3880 * is using an older ntpd, which does not floor sys_rootdisp at 3881 * sys_mindisp. 3882 * 3883 * In contrast, ntpd 4.2.6 and earlier used stratum primarily 3884 * in selecting the system peer, using a weight of 1 second of 3885 * additional root distance per stratum. This heavy bias is no 3886 * longer appropriate, as the scaled root distance provides a 3887 * more rational metric carrying the cumulative error budget. 3888 */ 3889 e = 1e9; 3890 speer = 0; 3891 leap_vote_ins = 0; 3892 leap_vote_del = 0; 3893 for (i = 0; i < nlist; i++) { 3894 peer = peers[i].peer; 3895 peer->unreach = 0; 3896 peer->new_status = CTL_PST_SEL_SYNCCAND; 3897 sys_survivors++; 3898 if (peer->leap == LEAP_ADDSECOND) { 3899 if (peer->flags & FLAG_REFCLOCK) 3900 leap_vote_ins = nlist; 3901 else if (leap_vote_ins < nlist) 3902 leap_vote_ins++; 3903 } 3904 if (peer->leap == LEAP_DELSECOND) { 3905 if (peer->flags & FLAG_REFCLOCK) 3906 leap_vote_del = nlist; 3907 else if (leap_vote_del < nlist) 3908 leap_vote_del++; 3909 } 3910 if (peer->flags & FLAG_PREFER) 3911 sys_prefer = peer; 3912 speermet = peers[i].seljit * peers[i].synch + 3913 peer->stratum * sys_mindisp; 3914 if (speermet < e) { 3915 e = speermet; 3916 speer = i; 3917 } 3918 } 3919 3920 /* 3921 * Unless there are at least sys_misane survivors, leave the 3922 * building dark. Otherwise, do a clockhop dance. Ordinarily, 3923 * use the selected survivor speer. However, if the current 3924 * system peer is not speer, stay with the current system peer 3925 * as long as it doesn't get too old or too ugly. 3926 */ 3927 if (nlist > 0 && nlist >= sys_minsane) { 3928 double x; 3929 3930 typesystem = peers[speer].peer; 3931 if (osys_peer == NULL || osys_peer == typesystem) { 3932 sys_clockhop = 0; 3933 } else if ((x = fabs(typesystem->offset - 3934 osys_peer->offset)) < sys_mindisp) { 3935 if (sys_clockhop == 0) 3936 sys_clockhop = sys_mindisp; 3937 else 3938 sys_clockhop *= .5; 3939 DPRINTF(1, ("select: clockhop %d %.6f %.6f\n", 3940 j, x, sys_clockhop)); 3941 if (fabs(x) < sys_clockhop) 3942 typesystem = osys_peer; 3943 else 3944 sys_clockhop = 0; 3945 } else { 3946 sys_clockhop = 0; 3947 } 3948 } 3949 3950 /* 3951 * Mitigation rules of the game. We have the pick of the 3952 * litter in typesystem if any survivors are left. If 3953 * there is a prefer peer, use its offset and jitter. 3954 * Otherwise, use the combined offset and jitter of all kitters. 3955 */ 3956 if (typesystem != NULL) { 3957 if (sys_prefer == NULL) { 3958 typesystem->new_status = CTL_PST_SEL_SYSPEER; 3959 clock_combine(peers, sys_survivors, speer); 3960 } else { 3961 typesystem = sys_prefer; 3962 sys_clockhop = 0; 3963 typesystem->new_status = CTL_PST_SEL_SYSPEER; 3964 sys_offset = typesystem->offset; 3965 sys_jitter = typesystem->jitter; 3966 } 3967 DPRINTF(1, ("select: combine offset %.9f jitter %.9f\n", 3968 sys_offset, sys_jitter)); 3969 } 3970 #ifdef REFCLOCK 3971 /* 3972 * If a PPS driver is lit and the combined offset is less than 3973 * 0.4 s, select the driver as the PPS peer and use its offset 3974 * and jitter. However, if this is the atom driver, use it only 3975 * if there is a prefer peer or there are no survivors and none 3976 * are required. 3977 */ 3978 if ( typepps != NULL 3979 && fabs(sys_offset) < 0.4 3980 && ( typepps->refclktype != REFCLK_ATOM_PPS 3981 || ( typepps->refclktype == REFCLK_ATOM_PPS 3982 && ( sys_prefer != NULL 3983 || (typesystem == NULL && sys_minsane == 0))))) { 3984 typesystem = typepps; 3985 sys_clockhop = 0; 3986 typesystem->new_status = CTL_PST_SEL_PPS; 3987 sys_offset = typesystem->offset; 3988 sys_jitter = typesystem->jitter; 3989 DPRINTF(1, ("select: pps offset %.9f jitter %.9f\n", 3990 sys_offset, sys_jitter)); 3991 } 3992 #endif /* REFCLOCK */ 3993 3994 /* 3995 * If there are no survivors at this point, there is no 3996 * system peer. If so and this is an old update, keep the 3997 * current statistics, but do not update the clock. 3998 */ 3999 if (typesystem == NULL) { 4000 if (osys_peer != NULL) { 4001 orphwait = current_time + sys_orphwait; 4002 report_event(EVNT_NOPEER, NULL, NULL); 4003 } 4004 sys_peer = NULL; 4005 for (peer = peer_list; peer != NULL; peer = peer->p_link) 4006 peer->status = peer->new_status; 4007 return; 4008 } 4009 4010 /* 4011 * Do not use old data, as this may mess up the clock discipline 4012 * stability. 4013 */ 4014 if (typesystem->epoch <= sys_epoch) 4015 return; 4016 4017 /* 4018 * We have found the alpha male. Wind the clock. 4019 */ 4020 if (osys_peer != typesystem) 4021 report_event(PEVNT_NEWPEER, typesystem, NULL); 4022 for (peer = peer_list; peer != NULL; peer = peer->p_link) 4023 peer->status = peer->new_status; 4024 clock_update(typesystem); 4025 } 4026 4027 4028 static void 4029 clock_combine( 4030 peer_select * peers, /* survivor list */ 4031 int npeers, /* number of survivors */ 4032 int syspeer /* index of sys.peer */ 4033 ) 4034 { 4035 int i; 4036 double x, y, z, w; 4037 4038 y = z = w = 0; 4039 for (i = 0; i < npeers; i++) { 4040 x = 1. / peers[i].synch; 4041 y += x; 4042 z += x * peers[i].peer->offset; 4043 w += x * DIFF(peers[i].peer->offset, 4044 peers[syspeer].peer->offset); 4045 } 4046 sys_offset = z / y; 4047 sys_jitter = SQRT(w / y + SQUARE(peers[syspeer].seljit)); 4048 } 4049 4050 4051 /* 4052 * root_distance - compute synchronization distance from peer to root 4053 */ 4054 static double 4055 root_distance( 4056 struct peer *peer /* peer structure pointer */ 4057 ) 4058 { 4059 double dtemp; 4060 4061 /* 4062 * Root Distance (LAMBDA) is defined as: 4063 * (delta + DELTA)/2 + epsilon + EPSILON + D 4064 * 4065 * where: 4066 * delta is the round-trip delay 4067 * DELTA is the root delay 4068 * epsilon is the peer dispersion 4069 * + (15 usec each second) 4070 * EPSILON is the root dispersion 4071 * D is sys_jitter 4072 * 4073 * NB: Think hard about why we are using these values, and what 4074 * the alternatives are, and the various pros/cons. 4075 * 4076 * DLM thinks these are probably the best choices from any of the 4077 * other worse choices. 4078 */ 4079 dtemp = (peer->delay + peer->rootdelay) / 2 4080 + peer->disp 4081 + clock_phi * (current_time - peer->update) 4082 + peer->rootdisp 4083 + peer->jitter; 4084 /* 4085 * Careful squeak here. The value returned must be greater than 4086 * the minimum root dispersion in order to avoid clockhop with 4087 * highly precise reference clocks. Note that the root distance 4088 * cannot exceed the sys_maxdist, as this is the cutoff by the 4089 * selection algorithm. 4090 */ 4091 if (dtemp < sys_mindisp) 4092 dtemp = sys_mindisp; 4093 return (dtemp); 4094 } 4095 4096 4097 /* 4098 * peer_xmit - send packet for persistent association. 4099 */ 4100 static void 4101 peer_xmit( 4102 struct peer *peer /* peer structure pointer */ 4103 ) 4104 { 4105 struct pkt xpkt; /* transmit packet */ 4106 size_t sendlen, authlen; 4107 keyid_t xkeyid = 0; /* transmit key ID */ 4108 l_fp xmt_tx, xmt_ty; 4109 4110 if (!peer->dstadr) /* drop peers without interface */ 4111 return; 4112 4113 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version, 4114 peer->hmode); 4115 xpkt.stratum = STRATUM_TO_PKT(sys_stratum); 4116 xpkt.ppoll = peer->hpoll; 4117 xpkt.precision = sys_precision; 4118 xpkt.refid = sys_refid; 4119 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay)); 4120 xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp)); 4121 /* Use sys_reftime for peer exchanges */ 4122 HTONL_FP(&sys_reftime, &xpkt.reftime); 4123 HTONL_FP(&peer->rec, &xpkt.org); 4124 HTONL_FP(&peer->dst, &xpkt.rec); 4125 4126 /* 4127 * If the received packet contains a MAC, the transmitted packet 4128 * is authenticated and contains a MAC. If not, the transmitted 4129 * packet is not authenticated. 4130 * 4131 * It is most important when autokey is in use that the local 4132 * interface IP address be known before the first packet is 4133 * sent. Otherwise, it is not possible to compute a correct MAC 4134 * the recipient will accept. Thus, the I/O semantics have to do 4135 * a little more work. In particular, the wildcard interface 4136 * might not be usable. 4137 */ 4138 sendlen = LEN_PKT_NOMAC; 4139 if ( 4140 #ifdef AUTOKEY 4141 !(peer->flags & FLAG_SKEY) && 4142 #endif /* !AUTOKEY */ 4143 peer->keyid == 0) { 4144 4145 /* 4146 * Transmit a-priori timestamps 4147 */ 4148 get_systime(&xmt_tx); 4149 if (peer->flip == 0) { /* basic mode */ 4150 peer->aorg = xmt_tx; 4151 HTONL_FP(&xmt_tx, &xpkt.xmt); 4152 } else { /* interleaved modes */ 4153 if (peer->hmode == MODE_BROADCAST) { /* bcst */ 4154 HTONL_FP(&xmt_tx, &xpkt.xmt); 4155 if (peer->flip > 0) 4156 HTONL_FP(&peer->borg, 4157 &xpkt.org); 4158 else 4159 HTONL_FP(&peer->aorg, 4160 &xpkt.org); 4161 } else { /* symmetric */ 4162 if (peer->flip > 0) 4163 HTONL_FP(&peer->borg, 4164 &xpkt.xmt); 4165 else 4166 HTONL_FP(&peer->aorg, 4167 &xpkt.xmt); 4168 } 4169 } 4170 peer->t21_bytes = sendlen; 4171 sendpkt(&peer->srcadr, peer->dstadr, 4172 sys_ttl[(peer->ttl >= sys_ttlmax) ? sys_ttlmax : peer->ttl], 4173 &xpkt, sendlen); 4174 peer->sent++; 4175 peer->throttle += (1 << peer->minpoll) - 2; 4176 4177 /* 4178 * Capture a-posteriori timestamps 4179 */ 4180 get_systime(&xmt_ty); 4181 if (peer->flip != 0) { /* interleaved modes */ 4182 if (peer->flip > 0) 4183 peer->aorg = xmt_ty; 4184 else 4185 peer->borg = xmt_ty; 4186 peer->flip = -peer->flip; 4187 } 4188 L_SUB(&xmt_ty, &xmt_tx); 4189 LFPTOD(&xmt_ty, peer->xleave); 4190 DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d len %zu xmt %#010x.%08x\n", 4191 current_time, 4192 peer->dstadr ? stoa(&peer->dstadr->sin) : "-", 4193 stoa(&peer->srcadr), peer->hmode, sendlen, 4194 xmt_tx.l_ui, xmt_tx.l_uf)); 4195 return; 4196 } 4197 4198 /* 4199 * Authentication is enabled, so the transmitted packet must be 4200 * authenticated. If autokey is enabled, fuss with the various 4201 * modes; otherwise, symmetric key cryptography is used. 4202 */ 4203 #ifdef AUTOKEY 4204 if (peer->flags & FLAG_SKEY) { 4205 struct exten *exten; /* extension field */ 4206 4207 /* 4208 * The Public Key Dance (PKD): Cryptographic credentials 4209 * are contained in extension fields, each including a 4210 * 4-octet length/code word followed by a 4-octet 4211 * association ID and optional additional data. Optional 4212 * data includes a 4-octet data length field followed by 4213 * the data itself. Request messages are sent from a 4214 * configured association; response messages can be sent 4215 * from a configured association or can take the fast 4216 * path without ever matching an association. Response 4217 * messages have the same code as the request, but have 4218 * a response bit and possibly an error bit set. In this 4219 * implementation, a message may contain no more than 4220 * one command and one or more responses. 4221 * 4222 * Cryptographic session keys include both a public and 4223 * a private componet. Request and response messages 4224 * using extension fields are always sent with the 4225 * private component set to zero. Packets without 4226 * extension fields indlude the private component when 4227 * the session key is generated. 4228 */ 4229 while (1) { 4230 4231 /* 4232 * Allocate and initialize a keylist if not 4233 * already done. Then, use the list in inverse 4234 * order, discarding keys once used. Keep the 4235 * latest key around until the next one, so 4236 * clients can use client/server packets to 4237 * compute propagation delay. 4238 * 4239 * Note that once a key is used from the list, 4240 * it is retained in the key cache until the 4241 * next key is used. This is to allow a client 4242 * to retrieve the encrypted session key 4243 * identifier to verify authenticity. 4244 * 4245 * If for some reason a key is no longer in the 4246 * key cache, a birthday has happened or the key 4247 * has expired, so the pseudo-random sequence is 4248 * broken. In that case, purge the keylist and 4249 * regenerate it. 4250 */ 4251 if (peer->keynumber == 0) 4252 make_keylist(peer, peer->dstadr); 4253 else 4254 peer->keynumber--; 4255 xkeyid = peer->keylist[peer->keynumber]; 4256 if (authistrusted(xkeyid)) 4257 break; 4258 else 4259 key_expire(peer); 4260 } 4261 peer->keyid = xkeyid; 4262 exten = NULL; 4263 switch (peer->hmode) { 4264 4265 /* 4266 * In broadcast server mode the autokey values are 4267 * required by the broadcast clients. Push them when a 4268 * new keylist is generated; otherwise, push the 4269 * association message so the client can request them at 4270 * other times. 4271 */ 4272 case MODE_BROADCAST: 4273 if (peer->flags & FLAG_ASSOC) 4274 exten = crypto_args(peer, CRYPTO_AUTO | 4275 CRYPTO_RESP, peer->associd, NULL); 4276 else 4277 exten = crypto_args(peer, CRYPTO_ASSOC | 4278 CRYPTO_RESP, peer->associd, NULL); 4279 break; 4280 4281 /* 4282 * In symmetric modes the parameter, certificate, 4283 * identity, cookie and autokey exchanges are 4284 * required. The leapsecond exchange is optional. But, a 4285 * peer will not believe the other peer until the other 4286 * peer has synchronized, so the certificate exchange 4287 * might loop until then. If a peer finds a broken 4288 * autokey sequence, it uses the autokey exchange to 4289 * retrieve the autokey values. In any case, if a new 4290 * keylist is generated, the autokey values are pushed. 4291 */ 4292 case MODE_ACTIVE: 4293 case MODE_PASSIVE: 4294 4295 /* 4296 * Parameter, certificate and identity. 4297 */ 4298 if (!peer->crypto) 4299 exten = crypto_args(peer, CRYPTO_ASSOC, 4300 peer->associd, hostval.ptr); 4301 else if (!(peer->crypto & CRYPTO_FLAG_CERT)) 4302 exten = crypto_args(peer, CRYPTO_CERT, 4303 peer->associd, peer->issuer); 4304 else if (!(peer->crypto & CRYPTO_FLAG_VRFY)) 4305 exten = crypto_args(peer, 4306 crypto_ident(peer), peer->associd, 4307 NULL); 4308 4309 /* 4310 * Cookie and autokey. We request the cookie 4311 * only when the this peer and the other peer 4312 * are synchronized. But, this peer needs the 4313 * autokey values when the cookie is zero. Any 4314 * time we regenerate the key list, we offer the 4315 * autokey values without being asked. If for 4316 * some reason either peer finds a broken 4317 * autokey sequence, the autokey exchange is 4318 * used to retrieve the autokey values. 4319 */ 4320 else if ( sys_leap != LEAP_NOTINSYNC 4321 && peer->leap != LEAP_NOTINSYNC 4322 && !(peer->crypto & CRYPTO_FLAG_COOK)) 4323 exten = crypto_args(peer, CRYPTO_COOK, 4324 peer->associd, NULL); 4325 else if (!(peer->crypto & CRYPTO_FLAG_AUTO)) 4326 exten = crypto_args(peer, CRYPTO_AUTO, 4327 peer->associd, NULL); 4328 else if ( peer->flags & FLAG_ASSOC 4329 && peer->crypto & CRYPTO_FLAG_SIGN) 4330 exten = crypto_args(peer, CRYPTO_AUTO | 4331 CRYPTO_RESP, peer->assoc, NULL); 4332 4333 /* 4334 * Wait for clock sync, then sign the 4335 * certificate and retrieve the leapsecond 4336 * values. 4337 */ 4338 else if (sys_leap == LEAP_NOTINSYNC) 4339 break; 4340 4341 else if (!(peer->crypto & CRYPTO_FLAG_SIGN)) 4342 exten = crypto_args(peer, CRYPTO_SIGN, 4343 peer->associd, hostval.ptr); 4344 else if (!(peer->crypto & CRYPTO_FLAG_LEAP)) 4345 exten = crypto_args(peer, CRYPTO_LEAP, 4346 peer->associd, NULL); 4347 break; 4348 4349 /* 4350 * In client mode the parameter, certificate, identity, 4351 * cookie and sign exchanges are required. The 4352 * leapsecond exchange is optional. If broadcast client 4353 * mode the same exchanges are required, except that the 4354 * autokey exchange is substitutes for the cookie 4355 * exchange, since the cookie is always zero. If the 4356 * broadcast client finds a broken autokey sequence, it 4357 * uses the autokey exchange to retrieve the autokey 4358 * values. 4359 */ 4360 case MODE_CLIENT: 4361 4362 /* 4363 * Parameter, certificate and identity. 4364 */ 4365 if (!peer->crypto) 4366 exten = crypto_args(peer, CRYPTO_ASSOC, 4367 peer->associd, hostval.ptr); 4368 else if (!(peer->crypto & CRYPTO_FLAG_CERT)) 4369 exten = crypto_args(peer, CRYPTO_CERT, 4370 peer->associd, peer->issuer); 4371 else if (!(peer->crypto & CRYPTO_FLAG_VRFY)) 4372 exten = crypto_args(peer, 4373 crypto_ident(peer), peer->associd, 4374 NULL); 4375 4376 /* 4377 * Cookie and autokey. These are requests, but 4378 * we use the peer association ID with autokey 4379 * rather than our own. 4380 */ 4381 else if (!(peer->crypto & CRYPTO_FLAG_COOK)) 4382 exten = crypto_args(peer, CRYPTO_COOK, 4383 peer->associd, NULL); 4384 else if (!(peer->crypto & CRYPTO_FLAG_AUTO)) 4385 exten = crypto_args(peer, CRYPTO_AUTO, 4386 peer->assoc, NULL); 4387 4388 /* 4389 * Wait for clock sync, then sign the 4390 * certificate and retrieve the leapsecond 4391 * values. 4392 */ 4393 else if (sys_leap == LEAP_NOTINSYNC) 4394 break; 4395 4396 else if (!(peer->crypto & CRYPTO_FLAG_SIGN)) 4397 exten = crypto_args(peer, CRYPTO_SIGN, 4398 peer->associd, hostval.ptr); 4399 else if (!(peer->crypto & CRYPTO_FLAG_LEAP)) 4400 exten = crypto_args(peer, CRYPTO_LEAP, 4401 peer->associd, NULL); 4402 break; 4403 } 4404 4405 /* 4406 * Add a queued extension field if present. This is 4407 * always a request message, so the reply ID is already 4408 * in the message. If an error occurs, the error bit is 4409 * lit in the response. 4410 */ 4411 if (peer->cmmd != NULL) { 4412 u_int32 temp32; 4413 4414 temp32 = CRYPTO_RESP; 4415 peer->cmmd->opcode |= htonl(temp32); 4416 sendlen += crypto_xmit(peer, &xpkt, NULL, 4417 sendlen, peer->cmmd, 0); 4418 free(peer->cmmd); 4419 peer->cmmd = NULL; 4420 } 4421 4422 /* 4423 * Add an extension field created above. All but the 4424 * autokey response message are request messages. 4425 */ 4426 if (exten != NULL) { 4427 if (exten->opcode != 0) 4428 sendlen += crypto_xmit(peer, &xpkt, 4429 NULL, sendlen, exten, 0); 4430 free(exten); 4431 } 4432 4433 /* 4434 * Calculate the next session key. Since extension 4435 * fields are present, the cookie value is zero. 4436 */ 4437 if (sendlen > (int)LEN_PKT_NOMAC) { 4438 session_key(&peer->dstadr->sin, &peer->srcadr, 4439 xkeyid, 0, 2); 4440 } 4441 } 4442 #endif /* AUTOKEY */ 4443 4444 /* 4445 * Transmit a-priori timestamps 4446 */ 4447 get_systime(&xmt_tx); 4448 if (peer->flip == 0) { /* basic mode */ 4449 peer->aorg = xmt_tx; 4450 HTONL_FP(&xmt_tx, &xpkt.xmt); 4451 } else { /* interleaved modes */ 4452 if (peer->hmode == MODE_BROADCAST) { /* bcst */ 4453 HTONL_FP(&xmt_tx, &xpkt.xmt); 4454 if (peer->flip > 0) 4455 HTONL_FP(&peer->borg, &xpkt.org); 4456 else 4457 HTONL_FP(&peer->aorg, &xpkt.org); 4458 } else { /* symmetric */ 4459 if (peer->flip > 0) 4460 HTONL_FP(&peer->borg, &xpkt.xmt); 4461 else 4462 HTONL_FP(&peer->aorg, &xpkt.xmt); 4463 } 4464 } 4465 xkeyid = peer->keyid; 4466 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen); 4467 if (authlen == 0) { 4468 report_event(PEVNT_AUTH, peer, "no key"); 4469 peer->flash |= TEST5; /* auth error */ 4470 peer->badauth++; 4471 return; 4472 } 4473 sendlen += authlen; 4474 #ifdef AUTOKEY 4475 if (xkeyid > NTP_MAXKEY) 4476 authtrust(xkeyid, 0); 4477 #endif /* AUTOKEY */ 4478 if (sendlen > sizeof(xpkt)) { 4479 msyslog(LOG_ERR, "peer_xmit: buffer overflow %zu", sendlen); 4480 exit (-1); 4481 } 4482 peer->t21_bytes = sendlen; 4483 sendpkt(&peer->srcadr, peer->dstadr, 4484 sys_ttl[(peer->ttl >= sys_ttlmax) ? sys_ttlmax : peer->ttl], 4485 &xpkt, sendlen); 4486 peer->sent++; 4487 peer->throttle += (1 << peer->minpoll) - 2; 4488 4489 /* 4490 * Capture a-posteriori timestamps 4491 */ 4492 get_systime(&xmt_ty); 4493 if (peer->flip != 0) { /* interleaved modes */ 4494 if (peer->flip > 0) 4495 peer->aorg = xmt_ty; 4496 else 4497 peer->borg = xmt_ty; 4498 peer->flip = -peer->flip; 4499 } 4500 L_SUB(&xmt_ty, &xmt_tx); 4501 LFPTOD(&xmt_ty, peer->xleave); 4502 #ifdef AUTOKEY 4503 DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %zu index %d\n", 4504 current_time, latoa(peer->dstadr), 4505 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen, 4506 peer->keynumber)); 4507 #else /* !AUTOKEY follows */ 4508 DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %zu\n", 4509 current_time, peer->dstadr ? 4510 ntoa(&peer->dstadr->sin) : "-", 4511 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen)); 4512 #endif /* !AUTOKEY */ 4513 4514 return; 4515 } 4516 4517 4518 #ifdef LEAP_SMEAR 4519 4520 static void 4521 leap_smear_add_offs( 4522 l_fp *t, 4523 l_fp *t_recv 4524 ) 4525 { 4526 4527 L_ADD(t, &leap_smear.offset); 4528 4529 /* 4530 ** XXX: Should the smear be added to the root dispersion? 4531 */ 4532 4533 return; 4534 } 4535 4536 #endif /* LEAP_SMEAR */ 4537 4538 4539 /* 4540 * fast_xmit - Send packet for nonpersistent association. Note that 4541 * neither the source or destination can be a broadcast address. 4542 */ 4543 static void 4544 fast_xmit( 4545 struct recvbuf *rbufp, /* receive packet pointer */ 4546 int xmode, /* receive mode */ /* XXX: HMS: really? */ 4547 keyid_t xkeyid, /* transmit key ID */ 4548 int flags /* restrict mask */ 4549 ) 4550 { 4551 struct pkt xpkt; /* transmit packet structure */ 4552 struct pkt *rpkt; /* receive packet structure */ 4553 l_fp xmt_tx, xmt_ty; 4554 size_t sendlen; 4555 #ifdef AUTOKEY 4556 u_int32 temp32; 4557 #endif 4558 4559 /* 4560 * Initialize transmit packet header fields from the receive 4561 * buffer provided. We leave the fields intact as received, but 4562 * set the peer poll at the maximum of the receive peer poll and 4563 * the system minimum poll (ntp_minpoll). This is for KoD rate 4564 * control and not strictly specification compliant, but doesn't 4565 * break anything. 4566 * 4567 * If the gazinta was from a multicast address, the gazoutta 4568 * must go out another way. 4569 */ 4570 rpkt = &rbufp->recv_pkt; 4571 if (rbufp->dstadr->flags & INT_MCASTOPEN) 4572 rbufp->dstadr = findinterface(&rbufp->recv_srcadr); 4573 4574 /* 4575 * If this is a kiss-o'-death (KoD) packet, show leap 4576 * unsynchronized, stratum zero, reference ID the four-character 4577 * kiss code and (???) system root delay. Note we don't reveal 4578 * the local time, so these packets can't be used for 4579 * synchronization. 4580 */ 4581 if (flags & RES_KOD) { 4582 sys_kodsent++; 4583 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC, 4584 PKT_VERSION(rpkt->li_vn_mode), xmode); 4585 xpkt.stratum = STRATUM_PKT_UNSPEC; 4586 xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll); 4587 xpkt.precision = rpkt->precision; 4588 memcpy(&xpkt.refid, "RATE", 4); 4589 xpkt.rootdelay = rpkt->rootdelay; 4590 xpkt.rootdisp = rpkt->rootdisp; 4591 xpkt.reftime = rpkt->reftime; 4592 xpkt.org = rpkt->xmt; 4593 xpkt.rec = rpkt->xmt; 4594 xpkt.xmt = rpkt->xmt; 4595 4596 /* 4597 * This is a normal packet. Use the system variables. 4598 */ 4599 } else { 4600 double this_rootdisp; 4601 l_fp this_ref_time; 4602 4603 #ifdef LEAP_SMEAR 4604 /* 4605 * Make copies of the variables which can be affected by smearing. 4606 */ 4607 l_fp this_recv_time; 4608 #endif 4609 4610 /* 4611 * If we are inside the leap smear interval we add 4612 * the current smear offset to: 4613 * - the packet receive time, 4614 * - the packet transmit time, 4615 * - and eventually to the reftime to make sure the 4616 * reftime isn't later than the transmit/receive times. 4617 */ 4618 xpkt.li_vn_mode = PKT_LI_VN_MODE(xmt_leap, 4619 PKT_VERSION(rpkt->li_vn_mode), xmode); 4620 4621 xpkt.stratum = STRATUM_TO_PKT(sys_stratum); 4622 xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll); 4623 xpkt.precision = sys_precision; 4624 xpkt.refid = sys_refid; 4625 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay)); 4626 4627 /* 4628 ** Server Response Fuzzing 4629 ** 4630 ** Which values do we want to use for reftime and rootdisp? 4631 */ 4632 4633 if ( MODE_SERVER == xmode 4634 && RES_SRVRSPFUZ & flags) { 4635 if (current_time < p2_time) { 4636 this_ref_time = p2_reftime; 4637 this_rootdisp = p2_rootdisp; 4638 } else if (current_time < prev_time) { 4639 this_ref_time = prev_reftime; 4640 this_rootdisp = prev_rootdisp; 4641 } else { 4642 this_ref_time = sys_reftime; 4643 this_rootdisp = sys_rootdisp; 4644 } 4645 4646 SRVRSP_FUZZ(this_ref_time); 4647 } else { 4648 this_ref_time = sys_reftime; 4649 this_rootdisp = sys_rootdisp; 4650 } 4651 4652 /* 4653 ** ROOT DISPERSION 4654 */ 4655 4656 xpkt.rootdisp = HTONS_FP(DTOUFP(this_rootdisp)); 4657 4658 /* 4659 ** REFTIME 4660 */ 4661 4662 #ifdef LEAP_SMEAR 4663 if (leap_smear.in_progress) { 4664 /* adjust the reftime by the same amount as the 4665 * leap smear, as we don't want to risk the 4666 * reftime being later than the transmit time. 4667 */ 4668 leap_smear_add_offs(&this_ref_time, NULL); 4669 } 4670 #endif 4671 4672 HTONL_FP(&this_ref_time, &xpkt.reftime); 4673 4674 /* 4675 ** REFID 4676 */ 4677 4678 #ifdef LEAP_SMEAR 4679 if (leap_smear.in_progress) { 4680 xpkt.refid = convertLFPToRefID(leap_smear.offset); 4681 DPRINTF(2, ("fast_xmit: leap_smear.in_progress: refid %8x, smear %s\n", 4682 ntohl(xpkt.refid), 4683 lfptoa(&leap_smear.offset, 8) 4684 )); 4685 } 4686 #endif 4687 4688 /* 4689 ** ORIGIN 4690 */ 4691 4692 xpkt.org = rpkt->xmt; 4693 4694 /* 4695 ** RECEIVE 4696 */ 4697 #ifdef LEAP_SMEAR 4698 this_recv_time = rbufp->recv_time; 4699 if (leap_smear.in_progress) 4700 leap_smear_add_offs(&this_recv_time, NULL); 4701 HTONL_FP(&this_recv_time, &xpkt.rec); 4702 #else 4703 HTONL_FP(&rbufp->recv_time, &xpkt.rec); 4704 #endif 4705 4706 /* 4707 ** TRANSMIT 4708 */ 4709 4710 get_systime(&xmt_tx); 4711 #ifdef LEAP_SMEAR 4712 if (leap_smear.in_progress) 4713 leap_smear_add_offs(&xmt_tx, &this_recv_time); 4714 #endif 4715 HTONL_FP(&xmt_tx, &xpkt.xmt); 4716 } 4717 4718 #ifdef HAVE_NTP_SIGND 4719 if (flags & RES_MSSNTP) { 4720 send_via_ntp_signd(rbufp, xmode, xkeyid, flags, &xpkt); 4721 return; 4722 } 4723 #endif /* HAVE_NTP_SIGND */ 4724 4725 /* 4726 * If the received packet contains a MAC, the transmitted packet 4727 * is authenticated and contains a MAC. If not, the transmitted 4728 * packet is not authenticated. 4729 */ 4730 sendlen = LEN_PKT_NOMAC; 4731 if (rbufp->recv_length == sendlen) { 4732 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, 4733 sendlen); 4734 DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d len %lu\n", 4735 current_time, stoa(&rbufp->dstadr->sin), 4736 stoa(&rbufp->recv_srcadr), xmode, 4737 (u_long)sendlen)); 4738 return; 4739 } 4740 4741 /* 4742 * The received packet contains a MAC, so the transmitted packet 4743 * must be authenticated. For symmetric key cryptography, use 4744 * the predefined and trusted symmetric keys to generate the 4745 * cryptosum. For autokey cryptography, use the server private 4746 * value to generate the cookie, which is unique for every 4747 * source-destination-key ID combination. 4748 */ 4749 #ifdef AUTOKEY 4750 if (xkeyid > NTP_MAXKEY) { 4751 keyid_t cookie; 4752 4753 /* 4754 * The only way to get here is a reply to a legitimate 4755 * client request message, so the mode must be 4756 * MODE_SERVER. If an extension field is present, there 4757 * can be only one and that must be a command. Do what 4758 * needs, but with private value of zero so the poor 4759 * jerk can decode it. If no extension field is present, 4760 * use the cookie to generate the session key. 4761 */ 4762 cookie = session_key(&rbufp->recv_srcadr, 4763 &rbufp->dstadr->sin, 0, sys_private, 0); 4764 if ((size_t)rbufp->recv_length > sendlen + MAX_MAC_LEN) { 4765 session_key(&rbufp->dstadr->sin, 4766 &rbufp->recv_srcadr, xkeyid, 0, 2); 4767 temp32 = CRYPTO_RESP; 4768 rpkt->exten[0] |= htonl(temp32); 4769 sendlen += crypto_xmit(NULL, &xpkt, rbufp, 4770 sendlen, (struct exten *)rpkt->exten, 4771 cookie); 4772 } else { 4773 session_key(&rbufp->dstadr->sin, 4774 &rbufp->recv_srcadr, xkeyid, cookie, 2); 4775 } 4776 } 4777 #endif /* AUTOKEY */ 4778 get_systime(&xmt_tx); 4779 sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen); 4780 #ifdef AUTOKEY 4781 if (xkeyid > NTP_MAXKEY) 4782 authtrust(xkeyid, 0); 4783 #endif /* AUTOKEY */ 4784 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen); 4785 get_systime(&xmt_ty); 4786 L_SUB(&xmt_ty, &xmt_tx); 4787 sys_authdelay = xmt_ty; 4788 DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d keyid %08x len %lu\n", 4789 current_time, ntoa(&rbufp->dstadr->sin), 4790 ntoa(&rbufp->recv_srcadr), xmode, xkeyid, 4791 (u_long)sendlen)); 4792 } 4793 4794 4795 /* 4796 * pool_xmit - resolve hostname or send unicast solicitation for pool. 4797 */ 4798 static void 4799 pool_xmit( 4800 struct peer *pool /* pool solicitor association */ 4801 ) 4802 { 4803 #ifdef WORKER 4804 struct pkt xpkt; /* transmit packet structure */ 4805 struct addrinfo hints; 4806 int rc; 4807 struct interface * lcladr; 4808 sockaddr_u * rmtadr; 4809 r4addr r4a; 4810 u_short restrict_mask; 4811 struct peer * p; 4812 l_fp xmt_tx; 4813 4814 DEBUG_REQUIRE(pool); 4815 if (NULL == pool->ai) { 4816 if (pool->addrs != NULL) { 4817 /* free() is used with copy_addrinfo_list() */ 4818 free(pool->addrs); 4819 pool->addrs = NULL; 4820 } 4821 ZERO(hints); 4822 hints.ai_family = AF(&pool->srcadr); 4823 hints.ai_socktype = SOCK_DGRAM; 4824 hints.ai_protocol = IPPROTO_UDP; 4825 /* ignore getaddrinfo_sometime() errors, we will retry */ 4826 rc = getaddrinfo_sometime( 4827 pool->hostname, 4828 "ntp", 4829 &hints, 4830 0, /* no retry */ 4831 &pool_name_resolved, 4832 (void *)(intptr_t)pool->associd); 4833 if (!rc) 4834 DPRINTF(1, ("pool DNS lookup %s started\n", 4835 pool->hostname)); 4836 else 4837 msyslog(LOG_ERR, 4838 "unable to start pool DNS %s: %m", 4839 pool->hostname); 4840 return; 4841 } 4842 4843 do { 4844 /* copy_addrinfo_list ai_addr points to a sockaddr_u */ 4845 rmtadr = (sockaddr_u *)(void *)pool->ai->ai_addr; 4846 pool->ai = pool->ai->ai_next; 4847 p = findexistingpeer(rmtadr, NULL, NULL, MODE_CLIENT, 0, NULL); 4848 } while (p != NULL && pool->ai != NULL); 4849 if (p != NULL) 4850 return; /* out of addresses, re-query DNS next poll */ 4851 restrictions(rmtadr, &r4a); 4852 restrict_mask = r4a.rflags; 4853 if (RES_FLAGS & restrict_mask) 4854 restrict_source(rmtadr, 0, 4855 current_time + POOL_SOLICIT_WINDOW + 1); 4856 lcladr = findinterface(rmtadr); 4857 memset(&xpkt, 0, sizeof(xpkt)); 4858 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, pool->version, 4859 MODE_CLIENT); 4860 xpkt.stratum = STRATUM_TO_PKT(sys_stratum); 4861 xpkt.ppoll = pool->hpoll; 4862 xpkt.precision = sys_precision; 4863 xpkt.refid = sys_refid; 4864 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay)); 4865 xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp)); 4866 /* Bug 3596: What are the pros/cons of using sys_reftime here? */ 4867 HTONL_FP(&sys_reftime, &xpkt.reftime); 4868 4869 /* HMS: the following is better done after the ntp_random() calls */ 4870 get_systime(&xmt_tx); 4871 pool->aorg = xmt_tx; 4872 4873 if (FLAG_LOOPNONCE & pool->flags) { 4874 l_fp nonce; 4875 4876 do { 4877 nonce.l_ui = ntp_random(); 4878 } while (0 == nonce.l_ui); 4879 do { 4880 nonce.l_uf = ntp_random(); 4881 } while (0 == nonce.l_uf); 4882 pool->nonce = nonce; 4883 HTONL_FP(&nonce, &xpkt.xmt); 4884 } else { 4885 L_CLR(&pool->nonce); 4886 HTONL_FP(&xmt_tx, &xpkt.xmt); 4887 } 4888 sendpkt(rmtadr, lcladr, 4889 sys_ttl[(pool->ttl >= sys_ttlmax) ? sys_ttlmax : pool->ttl], 4890 &xpkt, LEN_PKT_NOMAC); 4891 pool->sent++; 4892 pool->throttle += (1 << pool->minpoll) - 2; 4893 DPRINTF(1, ("pool_xmit: at %ld %s->%s pool\n", 4894 current_time, latoa(lcladr), stoa(rmtadr))); 4895 msyslog(LOG_INFO, "Soliciting pool server %s", stoa(rmtadr)); 4896 #endif /* WORKER */ 4897 } 4898 4899 4900 #ifdef AUTOKEY 4901 /* 4902 * group_test - test if this is the same group 4903 * 4904 * host assoc return action 4905 * none none 0 mobilize * 4906 * none group 0 mobilize * 4907 * group none 0 mobilize * 4908 * group group 1 mobilize 4909 * group different 1 ignore 4910 * * ignore if notrust 4911 */ 4912 int 4913 group_test( 4914 char *grp, 4915 char *ident 4916 ) 4917 { 4918 if (grp == NULL) 4919 return (0); 4920 4921 if (strcmp(grp, sys_groupname) == 0) 4922 return (0); 4923 4924 if (ident == NULL) 4925 return (1); 4926 4927 if (strcmp(grp, ident) == 0) 4928 return (0); 4929 4930 return (1); 4931 } 4932 #endif /* AUTOKEY */ 4933 4934 4935 #ifdef WORKER 4936 void 4937 pool_name_resolved( 4938 int rescode, 4939 int gai_errno, 4940 void * context, 4941 const char * name, 4942 const char * service, 4943 const struct addrinfo * hints, 4944 const struct addrinfo * res 4945 ) 4946 { 4947 struct peer * pool; /* pool solicitor association */ 4948 associd_t assoc; 4949 4950 if (rescode) { 4951 msyslog(LOG_ERR, 4952 "error resolving pool %s: %s (%d)", 4953 name, gai_strerror(rescode), rescode); 4954 return; 4955 } 4956 4957 assoc = (associd_t)(intptr_t)context; 4958 pool = findpeerbyassoc(assoc); 4959 if (NULL == pool) { 4960 msyslog(LOG_ERR, 4961 "Could not find assoc %u for pool DNS %s", 4962 assoc, name); 4963 return; 4964 } 4965 DPRINTF(1, ("pool DNS %s completed\n", name)); 4966 pool->addrs = copy_addrinfo_list(res); 4967 pool->ai = pool->addrs; 4968 pool_xmit(pool); 4969 4970 } 4971 #endif /* WORKER */ 4972 4973 4974 #ifdef AUTOKEY 4975 /* 4976 * key_expire - purge the key list 4977 */ 4978 void 4979 key_expire( 4980 struct peer *peer /* peer structure pointer */ 4981 ) 4982 { 4983 int i; 4984 4985 if (peer->keylist != NULL) { 4986 for (i = 0; i <= peer->keynumber; i++) 4987 authtrust(peer->keylist[i], 0); 4988 free(peer->keylist); 4989 peer->keylist = NULL; 4990 } 4991 value_free(&peer->sndval); 4992 peer->keynumber = 0; 4993 peer->flags &= ~FLAG_ASSOC; 4994 DPRINTF(1, ("key_expire: at %lu associd %d\n", current_time, 4995 peer->associd)); 4996 } 4997 #endif /* AUTOKEY */ 4998 4999 5000 /* 5001 * local_refid(peer) - check peer refid to avoid selecting peers 5002 * currently synced to this ntpd. 5003 */ 5004 static int 5005 local_refid( 5006 struct peer * p 5007 ) 5008 { 5009 endpt * unicast_ep; 5010 5011 if (p->dstadr != NULL && !(INT_MCASTIF & p->dstadr->flags)) 5012 unicast_ep = p->dstadr; 5013 else 5014 unicast_ep = findinterface(&p->srcadr); 5015 5016 if (unicast_ep != NULL && p->refid == unicast_ep->addr_refid) 5017 return TRUE; 5018 else 5019 return FALSE; 5020 } 5021 5022 5023 /* 5024 * Determine if the peer is unfit for synchronization 5025 * 5026 * A peer is unfit for synchronization if 5027 * > TEST10 bad leap or stratum below floor or at or above ceiling 5028 * > TEST11 root distance exceeded for remote peer 5029 * > TEST12 a direct or indirect synchronization loop would form 5030 * > TEST13 unreachable or noselect 5031 */ 5032 int /* FALSE if fit, TRUE if unfit */ 5033 peer_unfit( 5034 struct peer *peer /* peer structure pointer */ 5035 ) 5036 { 5037 int rval = 0; 5038 5039 /* 5040 * A stratum error occurs if (1) the server has never been 5041 * synchronized, (2) the server stratum is below the floor or 5042 * greater than or equal to the ceiling. 5043 */ 5044 if ( peer->leap == LEAP_NOTINSYNC 5045 || peer->stratum < sys_floor 5046 || peer->stratum >= sys_ceiling) { 5047 rval |= TEST10; /* bad synch or stratum */ 5048 } 5049 5050 /* 5051 * A distance error for a remote peer occurs if the root 5052 * distance is greater than or equal to the distance threshold 5053 * plus the increment due to one host poll interval. 5054 */ 5055 if ( !(peer->flags & FLAG_REFCLOCK) 5056 && root_distance(peer) >= sys_maxdist 5057 + clock_phi * ULOGTOD(peer->hpoll)) { 5058 rval |= TEST11; /* distance exceeded */ 5059 } 5060 5061 /* 5062 * A loop error occurs if the remote peer is synchronized to the 5063 * local peer or if the remote peer is synchronized to the same 5064 * server as the local peer but only if the remote peer is 5065 * neither a reference clock nor an orphan. 5066 */ 5067 if (peer->stratum > 1 && local_refid(peer)) { 5068 rval |= TEST12; /* synchronization loop */ 5069 } 5070 5071 /* 5072 * An unreachable error occurs if the server is unreachable or 5073 * the noselect bit is set. 5074 */ 5075 if (!peer->reach || (peer->flags & FLAG_NOSELECT)) { 5076 rval |= TEST13; /* unreachable */ 5077 } 5078 5079 peer->flash &= ~PEER_TEST_MASK; 5080 peer->flash |= rval; 5081 return (rval); 5082 } 5083 5084 5085 /* 5086 * Find the precision of this particular machine 5087 */ 5088 #define MINSTEP 20e-9 /* minimum clock increment (s) */ 5089 #define MAXSTEP 1 /* maximum clock increment (s) */ 5090 #define MINCHANGES 12 /* minimum number of step samples */ 5091 #define MAXLOOPS ((int)(1. / MINSTEP)) /* avoid infinite loop */ 5092 5093 /* 5094 * This routine measures the system precision defined as the minimum of 5095 * a sequence of differences between successive readings of the system 5096 * clock. However, if a difference is less than MINSTEP, the clock has 5097 * been read more than once during a clock tick and the difference is 5098 * ignored. We set MINSTEP greater than zero in case something happens 5099 * like a cache miss, and to tolerate underlying system clocks which 5100 * ensure each reading is strictly greater than prior readings while 5101 * using an underlying stepping (not interpolated) clock. 5102 * 5103 * sys_tick and sys_precision represent the time to read the clock for 5104 * systems with high-precision clocks, and the tick interval or step 5105 * size for lower-precision stepping clocks. 5106 * 5107 * This routine also measures the time to read the clock on stepping 5108 * system clocks by counting the number of readings between changes of 5109 * the underlying clock. With either type of clock, the minimum time 5110 * to read the clock is saved as sys_fuzz, and used to ensure the 5111 * get_systime() readings always increase and are fuzzed below sys_fuzz. 5112 */ 5113 void 5114 measure_precision(void) 5115 { 5116 /* 5117 * With sys_fuzz set to zero, get_systime() fuzzing of low bits 5118 * is effectively disabled. trunc_os_clock is FALSE to disable 5119 * get_ostime() simulation of a low-precision system clock. 5120 */ 5121 set_sys_fuzz(0.); 5122 trunc_os_clock = FALSE; 5123 measured_tick = measure_tick_fuzz(); 5124 set_sys_tick_precision(measured_tick); 5125 msyslog(LOG_INFO, "proto: precision = %.3f usec (%d)", 5126 sys_tick * 1e6, sys_precision); 5127 if (sys_fuzz < sys_tick) { 5128 msyslog(LOG_NOTICE, "proto: fuzz beneath %.3f usec", 5129 sys_fuzz * 1e6); 5130 } 5131 } 5132 5133 5134 /* 5135 * measure_tick_fuzz() 5136 * 5137 * measures the minimum time to read the clock (stored in sys_fuzz) 5138 * and returns the tick, the larger of the minimum increment observed 5139 * between successive clock readings and the time to read the clock. 5140 */ 5141 double 5142 measure_tick_fuzz(void) 5143 { 5144 l_fp minstep; /* MINSTEP as l_fp */ 5145 l_fp val; /* current seconds fraction */ 5146 l_fp last; /* last seconds fraction */ 5147 l_fp ldiff; /* val - last */ 5148 double tick; /* computed tick value */ 5149 double diff; 5150 long repeats; 5151 long max_repeats; 5152 int changes; 5153 int i; /* log2 precision */ 5154 5155 tick = MAXSTEP; 5156 max_repeats = 0; 5157 repeats = 0; 5158 changes = 0; 5159 DTOLFP(MINSTEP, &minstep); 5160 get_systime(&last); 5161 for (i = 0; i < MAXLOOPS && changes < MINCHANGES; i++) { 5162 get_systime(&val); 5163 ldiff = val; 5164 L_SUB(&ldiff, &last); 5165 last = val; 5166 if (L_ISGT(&ldiff, &minstep)) { 5167 max_repeats = max(repeats, max_repeats); 5168 repeats = 0; 5169 changes++; 5170 LFPTOD(&ldiff, diff); 5171 tick = min(diff, tick); 5172 } else { 5173 repeats++; 5174 } 5175 } 5176 if (changes < MINCHANGES) { 5177 msyslog(LOG_ERR, "Fatal error: precision could not be measured (MINSTEP too large?)"); 5178 exit(1); 5179 } 5180 5181 if (0 == max_repeats) { 5182 set_sys_fuzz(tick); 5183 } else { 5184 set_sys_fuzz(tick / max_repeats); 5185 } 5186 5187 return tick; 5188 } 5189 5190 5191 void 5192 set_sys_tick_precision( 5193 double tick 5194 ) 5195 { 5196 int i; 5197 5198 if (tick > 1.) { 5199 msyslog(LOG_ERR, 5200 "unsupported tick %.3f > 1s ignored", tick); 5201 return; 5202 } 5203 if (tick < measured_tick) { 5204 msyslog(LOG_ERR, 5205 "proto: tick %.3f less than measured tick %.3f, ignored", 5206 tick, measured_tick); 5207 return; 5208 } else if (tick > measured_tick) { 5209 trunc_os_clock = TRUE; 5210 msyslog(LOG_NOTICE, 5211 "proto: truncating system clock to multiples of %.9f", 5212 tick); 5213 } 5214 sys_tick = tick; 5215 5216 /* 5217 * Find the nearest power of two. 5218 */ 5219 for (i = 0; tick <= 1; i--) 5220 tick *= 2; 5221 if (tick - 1 > 1 - tick / 2) 5222 i++; 5223 5224 sys_precision = (s_char)i; 5225 } 5226 5227 5228 /* 5229 * init_proto - initialize the protocol module's data 5230 */ 5231 void 5232 init_proto(void) 5233 { 5234 l_fp dummy; 5235 int i; 5236 5237 /* 5238 * Fill in the sys_* stuff. Default is don't listen to 5239 * broadcasting, require authentication. 5240 */ 5241 set_sys_leap(LEAP_NOTINSYNC); 5242 sys_stratum = STRATUM_UNSPEC; 5243 memcpy(&sys_refid, "INIT", 4); 5244 sys_peer = NULL; 5245 sys_rootdelay = 0; 5246 sys_rootdisp = 0; 5247 L_CLR(&sys_reftime); 5248 sys_jitter = 0; 5249 measure_precision(); 5250 get_systime(&dummy); 5251 sys_survivors = 0; 5252 sys_manycastserver = 0; 5253 sys_bclient = 0; 5254 sys_mclient = 0; 5255 sys_bdelay = BDELAY_DEFAULT; /*[Bug 3031] delay cutoff */ 5256 sys_authenticate = 1; 5257 sys_stattime = current_time; 5258 orphwait = current_time + sys_orphwait; 5259 proto_clr_stats(); 5260 for (i = 0; i < MAX_TTL; ++i) 5261 sys_ttl[i] = (u_char)((i * 256) / MAX_TTL); 5262 sys_ttlmax = (MAX_TTL - 1); 5263 hardpps_enable = 0; 5264 stats_control = 1; 5265 } 5266 5267 5268 /* 5269 * proto_config - configure the protocol module 5270 */ 5271 void 5272 proto_config( 5273 int item, 5274 u_long value, 5275 double dvalue, 5276 sockaddr_u *svalue 5277 ) 5278 { 5279 /* 5280 * Figure out what he wants to change, then do it 5281 */ 5282 DPRINTF(2, ("proto_config: code %d value %lu dvalue %lf\n", 5283 item, value, dvalue)); 5284 5285 switch (item) { 5286 5287 /* 5288 * enable and disable commands - arguments are Boolean. 5289 */ 5290 case PROTO_AUTHENTICATE: /* authentication (auth) */ 5291 sys_authenticate = value; 5292 break; 5293 5294 case PROTO_BROADCLIENT: /* broadcast client (bclient) */ 5295 sys_bclient = (int)value; 5296 if (!sys_bclient) 5297 io_unsetbclient(); 5298 else 5299 io_setbclient(); 5300 break; 5301 5302 #ifdef REFCLOCK 5303 case PROTO_CAL: /* refclock calibrate (calibrate) */ 5304 cal_enable = value; 5305 break; 5306 #endif /* REFCLOCK */ 5307 5308 case PROTO_KERNEL: /* kernel discipline (kernel) */ 5309 select_loop(value); 5310 break; 5311 5312 case PROTO_MONITOR: /* monitoring (monitor) */ 5313 if (value) 5314 mon_start(MON_ON); 5315 else { 5316 mon_stop(MON_ON); 5317 if (mon_enabled) 5318 msyslog(LOG_WARNING, 5319 "restrict: 'monitor' cannot be disabled while 'limited' is enabled"); 5320 } 5321 break; 5322 5323 case PROTO_NTP: /* NTP discipline (ntp) */ 5324 ntp_enable = value; 5325 break; 5326 5327 case PROTO_MODE7: /* mode7 management (ntpdc) */ 5328 ntp_mode7 = value; 5329 break; 5330 5331 case PROTO_PPS: /* PPS discipline (pps) */ 5332 hardpps_enable = value; 5333 break; 5334 5335 case PROTO_FILEGEN: /* statistics (stats) */ 5336 stats_control = value; 5337 break; 5338 5339 /* 5340 * tos command - arguments are double, sometimes cast to int 5341 */ 5342 5343 case PROTO_BCPOLLBSTEP: /* Broadcast Poll Backstep gate (bcpollbstep) */ 5344 sys_bcpollbstep = (u_char)dvalue; 5345 break; 5346 5347 case PROTO_BEACON: /* manycast beacon (beacon) */ 5348 sys_beacon = (int)dvalue; 5349 break; 5350 5351 case PROTO_BROADDELAY: /* default broadcast delay (bdelay) */ 5352 sys_bdelay = (dvalue ? dvalue : BDELAY_DEFAULT); 5353 break; 5354 5355 case PROTO_CEILING: /* stratum ceiling (ceiling) */ 5356 sys_ceiling = (int)dvalue; 5357 break; 5358 5359 case PROTO_COHORT: /* cohort switch (cohort) */ 5360 sys_cohort = (int)dvalue; 5361 break; 5362 5363 case PROTO_FLOOR: /* stratum floor (floor) */ 5364 sys_floor = (int)dvalue; 5365 break; 5366 5367 case PROTO_MAXCLOCK: /* maximum candidates (maxclock) */ 5368 sys_maxclock = (int)dvalue; 5369 break; 5370 5371 case PROTO_MAXDIST: /* select threshold (maxdist) */ 5372 sys_maxdist = dvalue; 5373 break; 5374 5375 case PROTO_CALLDELAY: /* modem call delay (mdelay) */ 5376 break; /* NOT USED */ 5377 5378 case PROTO_MINCLOCK: /* minimum candidates (minclock) */ 5379 sys_minclock = (int)dvalue; 5380 break; 5381 5382 case PROTO_MINDISP: /* minimum distance (mindist) */ 5383 sys_mindisp = dvalue; 5384 break; 5385 5386 case PROTO_MINSANE: /* minimum survivors (minsane) */ 5387 sys_minsane = (int)dvalue; 5388 break; 5389 5390 case PROTO_ORPHAN: /* orphan stratum (orphan) */ 5391 sys_orphan = (int)dvalue; 5392 break; 5393 5394 case PROTO_ORPHWAIT: /* orphan wait (orphwait) */ 5395 orphwait -= sys_orphwait; 5396 sys_orphwait = (dvalue >= 1) ? (int)dvalue : NTP_ORPHWAIT; 5397 orphwait += sys_orphwait; 5398 break; 5399 5400 /* 5401 * Miscellaneous commands 5402 */ 5403 case PROTO_MULTICAST_ADD: /* add group address */ 5404 if (svalue != NULL) 5405 io_multicast_add(svalue); 5406 sys_mclient = 1; 5407 break; 5408 5409 case PROTO_MULTICAST_DEL: /* delete group address */ 5410 if (svalue != NULL) 5411 io_multicast_del(svalue); 5412 break; 5413 5414 /* 5415 * Peer_clear Early policy choices 5416 */ 5417 5418 case PROTO_PCEDIGEST: /* Digest */ 5419 peer_clear_digest_early = value; 5420 break; 5421 5422 /* 5423 * Unpeer Early policy choices 5424 */ 5425 5426 case PROTO_UECRYPTO: /* Crypto */ 5427 unpeer_crypto_early = value; 5428 break; 5429 5430 case PROTO_UECRYPTONAK: /* Crypto_NAK */ 5431 unpeer_crypto_nak_early = value; 5432 break; 5433 5434 case PROTO_UEDIGEST: /* Digest */ 5435 unpeer_digest_early = value; 5436 break; 5437 5438 default: 5439 msyslog(LOG_NOTICE, 5440 "proto: unsupported option %d", item); 5441 } 5442 } 5443 5444 5445 /* 5446 * proto_clr_stats - clear protocol stat counters 5447 */ 5448 void 5449 proto_clr_stats(void) 5450 { 5451 sys_stattime = current_time; 5452 sys_received = 0; 5453 sys_processed = 0; 5454 sys_newversion = 0; 5455 sys_oldversion = 0; 5456 sys_declined = 0; 5457 sys_restricted = 0; 5458 sys_badlength = 0; 5459 sys_badauth = 0; 5460 sys_limitrejected = 0; 5461 sys_kodsent = 0; 5462 sys_lamport = 0; 5463 sys_tsrounding = 0; 5464 } 5465