2 * ntp_proto.c - NTP version 4 protocol machinery
4 * ATTENTION: Get approval from Harlan on all changes to this file!
5 * (Harlan will be discussing these changes with Dave Mills.)
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"
19 #include "refidsmear.h"
20 #include "lib_strbuf.h"
30 /* [Bug 3031] define automatic broadcastdelay cutoff preset */
31 #ifndef BDELAY_DEFAULT
32 # define BDELAY_DEFAULT (-0.050)
35 #define SRVFUZ_SHIFT 6 /* 64 seconds */
36 #define SRVRSP_FUZZ(x) \
39 x.l_ui &= ~((1 << SRVFUZ_SHIFT) - 1U); \
43 * This macro defines the authentication state. If x is 1 authentication
44 * is required; otherwise it is optional.
46 #define AUTH(x, y) ((x) ? (y) == AUTH_OK \
47 : (y) == AUTH_OK || (y) == AUTH_NONE)
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 */
59 * Set up Kiss Code values
64 NOKISS, /* No Kiss Code */
65 RATEKISS, /* Rate limit Kiss Code */
66 DENYKISS, /* Deny Kiss */
67 RSTRKISS, /* Restricted Kiss */
68 XKISS /* Experimental Kiss */
73 NONAK, /* No NAK seen */
74 INVALIDNAK, /* NAK cannot be used */
75 VALIDNAK /* NAK is valid */
79 * traffic shaping parameters
81 #define NTP_IBURST 6 /* packets in iburst */
82 #define RESP_DELAY 1 /* refclock burst delay (s) */
85 * pool soliciting restriction duration (s)
87 #define POOL_SOLICIT_WINDOW 8
90 * flag bits propagated from pool to individual peers
92 #define POOL_FLAG_PMASK (FLAG_IBURST | FLAG_NOSELECT)
95 * peer_select groups statistics for a peer used by clock_select() and
98 typedef struct peer_select_tag {
100 double synch; /* sync distance */
101 double error; /* jitter */
102 double seljit; /* selection jitter */
106 * System variables are declared here. Unless specified otherwise, all
107 * times are in seconds.
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 */
126 struct leap_smear_info leap_smear;
128 int leap_sec_in_progress;
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.
141 * Nonspecified system state variables
143 int sys_bclient; /* broadcast client enable */
144 double sys_bdelay; /* broadcast client default delay */
145 int sys_authenticate; /* requre authentication for config */
146 l_fp sys_authdelay; /* authentication delay */
147 double sys_offset; /* current local clock offset */
148 double sys_mindisp = MINDISPERSE; /* minimum distance (s) */
149 double sys_maxdist = MAXDISTANCE; /* selection threshold */
150 double sys_jitter; /* system jitter */
151 u_long sys_epoch; /* last clock update time */
152 static double sys_clockhop; /* clockhop threshold */
153 static int leap_vote_ins; /* leap consensus for insert */
154 static int leap_vote_del; /* leap consensus for delete */
155 keyid_t sys_private; /* private value for session seed */
156 int sys_manycastserver; /* respond to manycast client pkts */
157 int ntp_mode7; /* respond to ntpdc (mode7) */
158 int peer_ntpdate; /* active peers in ntpdate mode */
159 int sys_survivors; /* truest of the truechimers */
160 char *sys_ident = NULL; /* identity scheme */
163 * TOS and multicast mapping stuff
165 int sys_floor = 0; /* cluster stratum floor */
166 u_char sys_bcpollbstep = 0; /* Broadcast Poll backstep gate */
167 int sys_ceiling = STRATUM_UNSPEC - 1; /* cluster stratum ceiling */
168 int sys_minsane = 1; /* minimum candidates */
169 int sys_minclock = NTP_MINCLOCK; /* minimum candidates */
170 int sys_maxclock = NTP_MAXCLOCK; /* maximum candidates */
171 int sys_cohort = 0; /* cohort switch */
172 int sys_orphan = STRATUM_UNSPEC + 1; /* orphan stratum */
173 int sys_orphwait = NTP_ORPHWAIT; /* orphan wait */
174 int sys_beacon = BEACON; /* manycast beacon interval */
175 u_int sys_ttlmax; /* max ttl mapping vector index */
176 u_char sys_ttl[MAX_TTL]; /* ttl mapping vector */
179 * Statistics counters - first the good, then the bad
181 u_long sys_stattime; /* elapsed time */
182 u_long sys_received; /* packets received */
183 u_long sys_processed; /* packets for this host */
184 u_long sys_newversion; /* current version */
185 u_long sys_oldversion; /* old version */
186 u_long sys_restricted; /* access denied */
187 u_long sys_badlength; /* bad length or format */
188 u_long sys_badauth; /* bad authentication */
189 u_long sys_declined; /* declined */
190 u_long sys_limitrejected; /* rate exceeded */
191 u_long sys_kodsent; /* KoD sent */
194 * Mechanism knobs: how soon do we peer_clear() or unpeer()?
196 * The default way is "on-receipt". If this was a packet from a
197 * well-behaved source, on-receipt will offer the fastest recovery.
198 * If this was from a DoS attack, the default way makes it easier
199 * for a bad-guy to DoS us. So look and see what bites you harder
200 * and choose according to your environment.
202 int peer_clear_digest_early = 1; /* bad digest (TEST5) and Autokey */
203 int unpeer_crypto_early = 1; /* bad crypto (TEST9) */
204 int unpeer_crypto_nak_early = 1; /* crypto_NAK (TEST5) */
205 int unpeer_digest_early = 1; /* bad digest (TEST5) */
207 int dynamic_interleave = DYNAMIC_INTERLEAVE; /* Bug 2978 mitigation */
209 int kiss_code_check(u_char hisleap, u_char hisstratum, u_char hismode, u_int32 refid);
210 nak_code valid_NAK (struct peer *peer, struct recvbuf *rbufp, u_char hismode);
211 static double root_distance (struct peer *);
212 static void clock_combine (peer_select *, int, int);
213 static void peer_xmit (struct peer *);
214 static void fast_xmit (struct recvbuf *, int, keyid_t, int);
215 static void pool_xmit (struct peer *);
216 static void clock_update (struct peer *);
217 static void measure_precision(void);
218 static double measure_tick_fuzz(void);
219 static int local_refid (struct peer *);
220 static int peer_unfit (struct peer *);
222 static int group_test (char *, char *);
225 void pool_name_resolved (int, int, void *, const char *,
226 const char *, const struct addrinfo *,
227 const struct addrinfo *);
230 const char * amtoa (int am);
238 sys_leap = new_sys_leap;
242 * Under certain conditions we send faked leap bits to clients, so
243 * eventually change xmt_leap below, but never change LEAP_NOTINSYNC.
245 if (xmt_leap != LEAP_NOTINSYNC) {
246 if (leap_sec_in_progress) {
247 /* always send "not sync" */
248 xmt_leap = LEAP_NOTINSYNC;
253 * If leap smear is enabled in general we must
254 * never send a leap second warning to clients,
255 * so make sure we only send "in sync".
257 if (leap_smear.enabled)
258 xmt_leap = LEAP_NOWARNING;
260 #endif /* LEAP_SMEAR */
277 if ( hismode == MODE_SERVER
278 && hisleap == LEAP_NOTINSYNC
279 && hisstratum == STRATUM_UNSPEC) {
280 if(memcmp(&refid,"RATE", 4) == 0) {
282 } else if(memcmp(&refid,"DENY", 4) == 0) {
284 } else if(memcmp(&refid,"RSTR", 4) == 0) {
286 } else if(memcmp(&refid,"X", 1) == 0) {
295 * Check that NAK is valid
300 struct recvbuf *rbufp,
304 int base_packet_length = MIN_V4_PKT_LEN;
308 l_fp p_org; /* origin timestamp */
309 const l_fp * myorg; /* selected peer origin */
312 * Check to see if there is something beyond the basic packet
314 if (rbufp->recv_length == base_packet_length) {
318 remainder_size = rbufp->recv_length - base_packet_length;
320 * Is this a potential NAK?
322 if (remainder_size != 4) {
327 * Only server responses can contain NAK's
330 if (hismode != MODE_SERVER &&
331 hismode != MODE_ACTIVE &&
332 hismode != MODE_PASSIVE
338 * Make sure that the extra field in the packet is all zeros
340 rpkt = &rbufp->recv_pkt;
341 keyid = ntohl(((u_int32 *)rpkt)[base_packet_length / 4]);
347 * During the first few packets of the autokey dance there will
348 * not (yet) be a keyid, but in this case FLAG_SKEY is set.
349 * So the NAK is invalid if either there's no peer, or
350 * if the keyid is 0 and FLAG_SKEY is not set.
352 if (!peer || (!peer->keyid && !(peer->flags & FLAG_SKEY))) {
357 * The ORIGIN must match, or this cannot be a valid NAK, either.
360 if (FLAG_LOOPNONCE & peer->flags) {
361 myorg = &peer->nonce;
363 if (peer->flip > 0) {
370 NTOHL_FP(&rpkt->org, &p_org);
372 if (L_ISZERO(&p_org) ||
374 !L_ISEQU(&p_org, myorg)) {
378 /* If we ever passed all that checks, we should be safe. Well,
379 * as safe as we can ever be with an unauthenticated crypto-nak.
386 * transmit - transmit procedure called by poll timeout
390 struct peer *peer /* peer structure pointer */
396 * The polling state machine. There are two kinds of machines,
397 * those that never expect a reply (broadcast and manycast
398 * server modes) and those that do (all other modes). The dance
404 * If we haven't received anything (even if unsync) since last
407 if (peer->outdate > peer->timelastrec && !peer->reach)
408 peer->ppoll = peer->maxpoll;
411 * In broadcast mode the poll interval is never changed from
414 if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
415 peer->outdate = current_time;
416 poll_update(peer, hpoll, 0);
417 if (sys_leap != LEAP_NOTINSYNC)
423 * In manycast mode we start with unity ttl. The ttl is
424 * increased by one for each poll until either sys_maxclock
425 * servers have been found or the maximum ttl is reached. When
426 * sys_maxclock servers are found we stop polling until one or
427 * more servers have timed out or until less than sys_minclock
428 * associations turn up. In this case additional better servers
429 * are dragged in and preempt the existing ones. Once every
430 * sys_beacon seconds we are to transmit unconditionally, but
431 * this code is not quite right -- peer->unreach counts polls
432 * and is being compared with sys_beacon, so the beacons happen
433 * every sys_beacon polls.
435 if (peer->cast_flags & MDF_ACAST) {
436 peer->outdate = current_time;
437 poll_update(peer, hpoll, 0);
438 if (peer->unreach > sys_beacon) {
442 } else if ( sys_survivors < sys_minclock
443 || peer_associations < sys_maxclock) {
444 if (peer->ttl < sys_ttlmax)
453 * Pool associations transmit unicast solicitations when there
454 * are less than a hard limit of 2 * sys_maxclock associations,
455 * and either less than sys_minclock survivors or less than
456 * sys_maxclock associations. The hard limit prevents unbounded
457 * growth in associations if the system clock or network quality
458 * result in survivor count dipping below sys_minclock often.
459 * This was observed testing with pool, where sys_maxclock == 12
460 * resulted in 60 associations without the hard limit. A
461 * similar hard limit on manycastclient ephemeral associations
462 * may be appropriate.
464 if (peer->cast_flags & MDF_POOL) {
465 peer->outdate = current_time;
466 poll_update(peer, hpoll, 0);
467 if ( (peer_associations <= 2 * sys_maxclock)
468 && ( peer_associations < sys_maxclock
469 || sys_survivors < sys_minclock))
475 * In unicast modes the dance is much more intricate. It is
476 * designed to back off whenever possible to minimize network
479 if (peer->burst == 0) {
483 * Update the reachability status. If not heard for
484 * three consecutive polls, stuff infinity in the clock
487 oreach = peer->reach;
488 peer->outdate = current_time;
494 * Here the peer is unreachable. If it was
495 * previously reachable raise a trap. Send a
498 clock_filter(peer, 0., 0., MAXDISPERSE);
501 report_event(PEVNT_UNREACH, peer, NULL);
503 if ( (peer->flags & FLAG_IBURST)
505 peer->retry = NTP_RETRY;
509 * Here the peer is reachable. Send a burst if
510 * enabled and the peer is fit. Reset unreach
511 * for persistent and ephemeral associations.
512 * Unreach is also reset for survivors in
516 if (!(peer->flags & FLAG_PREEMPT))
518 if ( (peer->flags & FLAG_BURST)
520 && !peer_unfit(peer))
521 peer->retry = NTP_RETRY;
525 * Watch for timeout. If ephemeral, toss the rascal;
526 * otherwise, bump the poll interval. Note the
527 * poll_update() routine will clamp it to maxpoll.
528 * If preemptible and we have more peers than maxclock,
529 * and this peer has the minimum score of preemptibles,
532 if (peer->unreach >= NTP_UNREACH) {
534 /* ephemeral: no FLAG_CONFIG nor FLAG_PREEMPT */
535 if (!(peer->flags & (FLAG_CONFIG | FLAG_PREEMPT))) {
536 report_event(PEVNT_RESTART, peer, "timeout");
537 peer_clear(peer, "TIME");
541 if ( (peer->flags & FLAG_PREEMPT)
542 && (peer_associations > sys_maxclock)
543 && score_all(peer)) {
544 report_event(PEVNT_RESTART, peer, "timeout");
545 peer_clear(peer, "TIME");
552 if (peer->burst == 0) {
555 * If ntpdate mode and the clock has not been
556 * set and all peers have completed the burst,
557 * we declare a successful failure.
561 if (peer_ntpdate == 0) {
563 "ntpd: no servers found");
566 "ntpd: no servers found\n");
576 * Do not transmit if in broadcast client mode.
578 poll_update(peer, hpoll, (peer->hmode == MODE_CLIENT));
579 if (peer->hmode != MODE_BCLIENT)
594 case AM_ERR: return "AM_ERR";
595 case AM_NOMATCH: return "AM_NOMATCH";
596 case AM_PROCPKT: return "AM_PROCPKT";
597 case AM_BCST: return "AM_BCST";
598 case AM_FXMIT: return "AM_FXMIT";
599 case AM_MANYCAST: return "AM_MANYCAST";
600 case AM_NEWPASS: return "AM_NEWPASS";
601 case AM_NEWBCL: return "AM_NEWBCL";
602 case AM_POSSBCL: return "AM_POSSBCL";
605 snprintf(bp, LIB_BUFLENGTH, "AM_#%d", am);
612 * receive - receive procedure called for each packet received
616 struct recvbuf *rbufp
619 register struct peer *peer; /* peer structure pointer */
620 register struct pkt *pkt; /* receive packet pointer */
621 u_char hisversion; /* packet version */
622 u_char hisleap; /* packet leap indicator */
623 u_char hismode; /* packet mode */
624 u_char hisstratum; /* packet stratum */
625 r4addr r4a; /* address restrictions */
626 u_short restrict_mask; /* restrict bits */
627 const char *hm_str; /* hismode string */
628 const char *am_str; /* association match string */
629 int kissCode = NOKISS; /* Kiss Code */
630 int has_mac; /* length of MAC field */
631 int authlen; /* offset of MAC field */
632 auth_code is_authentic = AUTH_UNKNOWN; /* Was AUTH_NONE */
633 nak_code crypto_nak_test; /* result of crypto-NAK check */
634 int retcode = AM_NOMATCH; /* match code */
635 keyid_t skeyid = 0; /* key IDs */
636 u_int32 opcode = 0; /* extension field opcode */
637 sockaddr_u *dstadr_sin; /* active runway */
638 struct peer *peer2; /* aux peer structure pointer */
639 endpt *match_ep; /* newpeer() local address */
640 l_fp p_org; /* origin timestamp */
641 l_fp p_rec; /* receive timestamp */
642 l_fp p_xmt; /* transmit timestamp */
644 char hostname[NTP_MAXSTRLEN + 1];
645 char *groupname = NULL;
646 struct autokey *ap; /* autokey structure pointer */
647 int rval; /* cookie snatcher */
648 keyid_t pkeyid = 0, tkeyid = 0; /* key IDs */
650 #ifdef HAVE_NTP_SIGND
651 static unsigned char zero_key[16];
652 #endif /* HAVE_NTP_SIGND */
655 * Note that there are many places we do not call record_raw_stats().
657 * We only want to call it *after* we've sent a response, or perhaps
658 * when we've decided to drop a packet.
662 * Monitor the packet and get restrictions. Note that the packet
663 * length for control and private mode packets must be checked
664 * by the service routines. Some restrictions have to be handled
665 * later in order to generate a kiss-o'-death packet.
668 * Bogus port check is before anything, since it probably
669 * reveals a clogging attack. Likewise the mimimum packet size
670 * of 2 bytes (for mode 6/7) must be checked first.
673 if (0 == SRCPORT(&rbufp->recv_srcadr) || rbufp->recv_length < 2) {
675 return; /* bogus port / length */
677 restrictions(&rbufp->recv_srcadr, &r4a);
678 restrict_mask = r4a.rflags;
680 pkt = &rbufp->recv_pkt;
681 hisversion = PKT_VERSION(pkt->li_vn_mode);
682 hismode = (int)PKT_MODE(pkt->li_vn_mode);
684 if (restrict_mask & RES_IGNORE) {
685 DPRINTF(2, ("receive: drop: RES_IGNORE\n"));
687 return; /* ignore everything */
689 if (hismode == MODE_PRIVATE) {
690 if (!ntp_mode7 || (restrict_mask & RES_NOQUERY)) {
691 DPRINTF(2, ("receive: drop: RES_NOQUERY\n"));
693 return; /* no query private */
695 process_private(rbufp, ((restrict_mask &
696 RES_NOMODIFY) == 0));
699 if (hismode == MODE_CONTROL) {
700 if (restrict_mask & RES_NOQUERY) {
701 DPRINTF(2, ("receive: drop: RES_NOQUERY\n"));
703 return; /* no query control */
705 process_control(rbufp, restrict_mask);
708 if (restrict_mask & RES_DONTSERVE) {
709 DPRINTF(2, ("receive: drop: RES_DONTSERVE\n"));
711 return; /* no time serve */
715 /* If we arrive here, we should have a standard NTP packet. We
716 * check that the minimum size is available and fetch some more
717 * items from the packet once we can be sure they are indeed
720 if (rbufp->recv_length < LEN_PKT_NOMAC) {
722 return; /* bogus length */
725 hisleap = PKT_LEAP(pkt->li_vn_mode);
726 hisstratum = PKT_TO_STRATUM(pkt->stratum);
727 INSIST(0 != hisstratum); /* paranoia check PKT_TO_STRATUM result */
729 DPRINTF(1, ("receive: at %ld %s<-%s ippeerlimit %d mode %d iflags %s "
730 "restrict %s org %#010x.%08x xmt %#010x.%08x\n",
731 current_time, stoa(&rbufp->dstadr->sin),
732 stoa(&rbufp->recv_srcadr), r4a.ippeerlimit, hismode,
733 build_iflags(rbufp->dstadr->flags),
734 build_rflags(restrict_mask),
735 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
736 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
739 * This is for testing. If restricted drop ten percent of
742 if (restrict_mask & RES_FLAKE) {
743 if ((double)ntp_random() / 0x7fffffff < .1) {
744 DPRINTF(2, ("receive: drop: RES_FLAKE\n"));
746 return; /* no flakeway */
751 ** Format Layer Checks
753 ** Validate the packet format. The packet size, packet header,
754 ** and any extension field lengths are checked. We identify
755 ** the beginning of the MAC, to identify the upper limit of
756 ** of the hash computation.
758 ** In case of a format layer check violation, the packet is
759 ** discarded with no further processing.
763 * Version check must be after the query packets, since they
764 * intentionally use an early version.
766 if (hisversion == NTP_VERSION) {
767 sys_newversion++; /* new version */
768 } else if ( !(restrict_mask & RES_VERSION)
769 && hisversion >= NTP_OLDVERSION) {
770 sys_oldversion++; /* previous version */
772 DPRINTF(2, ("receive: drop: RES_VERSION\n"));
774 return; /* old version */
778 * Figure out his mode and validate the packet. This has some
779 * legacy raunch that probably should be removed. In very early
780 * NTP versions mode 0 was equivalent to what later versions
781 * would interpret as client mode.
783 if (hismode == MODE_UNSPEC) {
784 if (hisversion == NTP_OLDVERSION) {
785 hismode = MODE_CLIENT;
787 DPRINTF(2, ("receive: drop: MODE_UNSPEC\n"));
789 return; /* invalid mode */
794 * Parse the extension field if present. We figure out whether
795 * an extension field is present by measuring the MAC size. If
796 * the number of words following the packet header is 0, no MAC
797 * is present and the packet is not authenticated. If 1, the
798 * packet is a crypto-NAK; if 3, the packet is authenticated
799 * with DES; if 5, the packet is authenticated with MD5; if 6,
800 * the packet is authenticated with SHA. If 2 or * 4, the packet
801 * is a runt and discarded forthwith. If greater than 6, an
802 * extension field is present, so we subtract the length of the
803 * field and go around again.
805 * Note the above description is lame. We should/could also check
806 * the two bytes that make up the EF type and subtype, and then
807 * check the two bytes that tell us the EF length. A legacy MAC
808 * has a 4 byte keyID, and for conforming symmetric keys its value
809 * must be <= 64k, meaning the top two bytes will always be zero.
810 * Since the EF Type of 0 is reserved/unused, there's no way a
811 * conforming legacy MAC could ever be misinterpreted as an EF.
813 * There is more, but this isn't the place to document it.
816 authlen = LEN_PKT_NOMAC;
817 has_mac = rbufp->recv_length - authlen;
818 while (has_mac > 0) {
825 if (has_mac % 4 != 0 || has_mac < (int)MIN_MAC_LEN) {
826 DPRINTF(2, ("receive: drop: bad post-packet length\n"));
828 return; /* bad length */
831 * This next test is clearly wrong - it needlessly
832 * prohibits short EFs (which don't yet exist)
834 if (has_mac <= (int)MAX_MAC_LEN) {
835 skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
839 opcode = ntohl(((u_int32 *)pkt)[authlen / 4]);
840 len = opcode & 0xffff;
843 || (int)len + authlen > rbufp->recv_length) {
844 DPRINTF(2, ("receive: drop: bad EF length\n"));
846 return; /* bad length */
850 * Extract calling group name for later. If
851 * sys_groupname is non-NULL, there must be
852 * a group name provided to elicit a response.
854 if ( (opcode & 0x3fff0000) == CRYPTO_ASSOC
855 && sys_groupname != NULL) {
856 ep = (struct exten *)&((u_int32 *)pkt)[authlen / 4];
857 hostlen = ntohl(ep->vallen);
858 if ( hostlen >= sizeof(hostname)
860 offsetof(struct exten, pkt)) {
861 DPRINTF(2, ("receive: drop: bad autokey hostname length\n"));
863 return; /* bad length */
865 memcpy(hostname, &ep->pkt, hostlen);
866 hostname[hostlen] = '\0';
867 groupname = strchr(hostname, '@');
868 if (groupname == NULL) {
869 DPRINTF(2, ("receive: drop: empty autokey groupname\n"));
882 * If has_mac is < 0 we had a malformed packet.
885 DPRINTF(2, ("receive: drop: post-packet under-read\n"));
887 return; /* bad length */
891 ** Packet Data Verification Layer
893 ** This layer verifies the packet data content. If
894 ** authentication is required, a MAC must be present.
895 ** If a MAC is present, it must validate.
896 ** Crypto-NAK? Look - a shiny thing!
898 ** If authentication fails, we're done.
902 * If authentication is explicitly required, a MAC must be present.
904 if (restrict_mask & RES_DONTTRUST && has_mac == 0) {
905 DPRINTF(2, ("receive: drop: RES_DONTTRUST\n"));
907 return; /* access denied */
911 * Update the MRU list and finger the cloggers. It can be a
912 * little expensive, so turn it off for production use.
913 * RES_LIMITED and RES_KOD will be cleared in the returned
914 * restrict_mask unless one or both actions are warranted.
916 restrict_mask = ntp_monitor(rbufp, restrict_mask);
917 if (restrict_mask & RES_LIMITED) {
919 if ( !(restrict_mask & RES_KOD)
920 || MODE_BROADCAST == hismode
921 || MODE_SERVER == hismode) {
922 if (MODE_SERVER == hismode) {
923 DPRINTF(1, ("Possibly self-induced rate limiting of MODE_SERVER from %s\n",
924 stoa(&rbufp->recv_srcadr)));
926 DPRINTF(2, ("receive: drop: RES_KOD\n"));
928 return; /* rate exceeded */
930 if (hismode == MODE_CLIENT) {
931 fast_xmit(rbufp, MODE_SERVER, skeyid,
934 fast_xmit(rbufp, MODE_ACTIVE, skeyid,
937 return; /* rate exceeded */
939 restrict_mask &= ~RES_KOD;
942 * We have tossed out as many buggy packets as possible early in
943 * the game to reduce the exposure to a clogging attack. Now we
944 * have to burn some cycles to find the association and
945 * authenticate the packet if required. Note that we burn only
946 * digest cycles, again to reduce exposure. There may be no
947 * matching association and that's okay.
949 * More on the autokey mambo. Normally the local interface is
950 * found when the association was mobilized with respect to a
951 * designated remote address. We assume packets arriving from
952 * the remote address arrive via this interface and the local
953 * address used to construct the autokey is the unicast address
954 * of the interface. However, if the sender is a broadcaster,
955 * the interface broadcast address is used instead.
956 * Notwithstanding this technobabble, if the sender is a
957 * multicaster, the broadcast address is null, so we use the
958 * unicast address anyway. Don't ask.
961 peer = findpeer(rbufp, hismode, &retcode);
962 dstadr_sin = &rbufp->dstadr->sin;
963 NTOHL_FP(&pkt->org, &p_org);
964 NTOHL_FP(&pkt->rec, &p_rec);
965 NTOHL_FP(&pkt->xmt, &p_xmt);
966 hm_str = modetoa(hismode);
967 am_str = amtoa(retcode);
970 * Authentication is conditioned by three switches:
972 * NOPEER (RES_NOPEER) do not mobilize an association unless
974 * NOTRUST (RES_DONTTRUST) do not allow access unless
975 * authenticated (implies NOPEER)
976 * enable (sys_authenticate) master NOPEER switch, by default
979 * The NOPEER and NOTRUST can be specified on a per-client basis
980 * using the restrict command. The enable switch if on implies
981 * NOPEER for all clients. There are four outcomes:
983 * NONE The packet has no MAC.
984 * OK the packet has a MAC and authentication succeeds
985 * ERROR the packet has a MAC and authentication fails
986 * CRYPTO crypto-NAK. The MAC has four octets only.
988 * Note: The AUTH(x, y) macro is used to filter outcomes. If x
989 * is zero, acceptable outcomes of y are NONE and OK. If x is
990 * one, the only acceptable outcome of y is OK.
992 crypto_nak_test = valid_NAK(peer, rbufp, hismode);
995 * Drop any invalid crypto-NAKs
997 if (crypto_nak_test == INVALIDNAK) {
998 report_event(PEVNT_AUTH, peer, "Invalid_NAK");
1002 msyslog(LOG_ERR, "Invalid-NAK error at %ld %s<-%s",
1003 current_time, stoa(dstadr_sin), stoa(&rbufp->recv_srcadr));
1008 restrict_mask &= ~RES_MSSNTP;
1009 is_authentic = AUTH_NONE; /* not required */
1010 DPRINTF(1, ("receive: at %ld %s<-%s mode %d/%s:%s len %d org %#010x.%08x xmt %#010x.%08x NOMAC\n",
1011 current_time, stoa(dstadr_sin),
1012 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
1014 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1015 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
1016 } else if (crypto_nak_test == VALIDNAK) {
1017 restrict_mask &= ~RES_MSSNTP;
1018 is_authentic = AUTH_CRYPTO; /* crypto-NAK */
1019 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",
1020 current_time, stoa(dstadr_sin),
1021 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
1022 skeyid, authlen + has_mac, is_authentic,
1023 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1024 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
1026 #ifdef HAVE_NTP_SIGND
1028 * If the signature is 20 bytes long, the last 16 of
1029 * which are zero, then this is a Microsoft client
1030 * wanting AD-style authentication of the server's
1033 * This is described in Microsoft's WSPP docs, in MS-SNTP:
1034 * http://msdn.microsoft.com/en-us/library/cc212930.aspx
1036 } else if ( has_mac == MAX_MD5_LEN
1037 && (restrict_mask & RES_MSSNTP)
1038 && (retcode == AM_FXMIT || retcode == AM_NEWPASS)
1039 && (memcmp(zero_key, (char *)pkt + authlen + 4,
1040 MAX_MD5_LEN - 4) == 0)) {
1041 is_authentic = AUTH_NONE;
1042 DPRINTF(1, ("receive: at %ld %s<-%s mode %d/%s:%s len %d org %#010x.%08x xmt %#010x.%08x SIGND\n",
1043 current_time, stoa(dstadr_sin),
1044 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
1046 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1047 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
1048 #endif /* HAVE_NTP_SIGND */
1054 * Not an MS-SNTP SIGND packet
1056 * So there is a MAC here.
1059 restrict_mask &= ~RES_MSSNTP;
1062 * For autokey modes, generate the session key
1063 * and install in the key cache. Use the socket
1064 * broadcast or unicast address as appropriate.
1066 if (crypto_flags && skeyid > NTP_MAXKEY) {
1069 * More on the autokey dance (AKD). A cookie is
1070 * constructed from public and private values.
1071 * For broadcast packets, the cookie is public
1072 * (zero). For packets that match no
1073 * association, the cookie is hashed from the
1074 * addresses and private value. For server
1075 * packets, the cookie was previously obtained
1076 * from the server. For symmetric modes, the
1077 * cookie was previously constructed using an
1078 * agreement protocol; however, should PKI be
1079 * unavailable, we construct a fake agreement as
1080 * the EXOR of the peer and host cookies.
1082 * hismode ephemeral persistent
1083 * =======================================
1085 * passive 0% cookie#
1086 * client sys cookie 0%
1087 * server 0% sys cookie
1093 if (has_mac < (int)MAX_MD5_LEN) {
1094 DPRINTF(2, ("receive: drop: MD5 digest too short\n"));
1098 if (hismode == MODE_BROADCAST) {
1101 * For broadcaster, use the interface
1102 * broadcast address when available;
1103 * otherwise, use the unicast address
1104 * found when the association was
1105 * mobilized. However, if this is from
1106 * the wildcard interface, game over.
1110 ANY_INTERFACE_CHOOSE(&rbufp->recv_srcadr)) {
1111 DPRINTF(2, ("receive: drop: BCAST from wildcard\n"));
1113 return; /* no wildcard */
1116 if (!SOCK_UNSPEC(&rbufp->dstadr->bcast))
1118 &rbufp->dstadr->bcast;
1119 } else if (peer == NULL) {
1120 pkeyid = session_key(
1121 &rbufp->recv_srcadr, dstadr_sin, 0,
1124 pkeyid = peer->pcookie;
1128 * The session key includes both the public
1129 * values and cookie. In case of an extension
1130 * field, the cookie used for authentication
1131 * purposes is zero. Note the hash is saved for
1132 * use later in the autokey mambo.
1134 if (authlen > (int)LEN_PKT_NOMAC && pkeyid != 0) {
1135 session_key(&rbufp->recv_srcadr,
1136 dstadr_sin, skeyid, 0, 2);
1137 tkeyid = session_key(
1138 &rbufp->recv_srcadr, dstadr_sin,
1141 tkeyid = session_key(
1142 &rbufp->recv_srcadr, dstadr_sin,
1147 #endif /* AUTOKEY */
1150 * Compute the cryptosum. Note a clogging attack may
1151 * succeed in bloating the key cache. If an autokey,
1152 * purge it immediately, since we won't be needing it
1153 * again. If the packet is authentic, it can mobilize an
1154 * association. Note that there is no key zero.
1156 if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,
1158 is_authentic = AUTH_ERROR;
1160 is_authentic = AUTH_OK;
1162 if (crypto_flags && skeyid > NTP_MAXKEY)
1163 authtrust(skeyid, 0);
1164 #endif /* AUTOKEY */
1165 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",
1166 current_time, stoa(dstadr_sin),
1167 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
1168 skeyid, authlen + has_mac, is_authentic,
1169 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1170 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
1177 * Now come at this from a different perspective:
1178 * - If we expect a MAC and it's not there, we drop it.
1179 * - If we expect one keyID and get another, we drop it.
1180 * - If we have a MAC ahd it hasn't been validated yet, try.
1181 * - if the provided MAC doesn't validate, we drop it.
1183 * There might be more to this.
1185 if (0 != peer && 0 != peer->keyid) {
1186 /* Should we msyslog() any of these? */
1189 * This should catch:
1190 * - no keyID where one is expected,
1191 * - different keyID than what we expect.
1193 if (peer->keyid != skeyid) {
1194 DPRINTF(2, ("receive: drop: Wanted keyID %d, got %d from %s\n",
1195 peer->keyid, skeyid,
1196 stoa(&rbufp->recv_srcadr)));
1198 return; /* drop: access denied */
1202 * if has_mac != 0 ...
1203 * - If it has not yet been validated, do so.
1204 * (under what circumstances might that happen?)
1205 * - if missing or bad MAC, log and drop.
1208 if (is_authentic == AUTH_UNKNOWN) {
1209 /* How can this happen? */
1210 DPRINTF(2, ("receive: 3454 check: AUTH_UNKNOWN from %s\n",
1211 stoa(&rbufp->recv_srcadr)));
1212 if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,
1214 /* MAC invalid or not found */
1215 is_authentic = AUTH_ERROR;
1217 is_authentic = AUTH_OK;
1220 if (is_authentic != AUTH_OK) {
1221 DPRINTF(2, ("receive: drop: missing or bad MAC from %s\n",
1222 stoa(&rbufp->recv_srcadr)));
1224 return; /* drop: access denied */
1231 ** On-Wire Protocol Layer
1233 ** Verify protocol operations consistent with the on-wire protocol.
1234 ** The protocol discards bogus and duplicate packets as well as
1235 ** minimizes disruptions doe to protocol restarts and dropped
1236 ** packets. The operations are controlled by two timestamps:
1237 ** the transmit timestamp saved in the client state variables,
1238 ** and the origin timestamp in the server packet header. The
1239 ** comparison of these two timestamps is called the loopback test.
1240 ** The transmit timestamp functions as a nonce to verify that the
1241 ** response corresponds to the original request. The transmit
1242 ** timestamp also serves to discard replays of the most recent
1243 ** packet. Upon failure of either test, the packet is discarded
1244 ** with no further action.
1248 * The association matching rules are implemented by a set of
1249 * routines and an association table. A packet matching an
1250 * association is processed by the peer process for that
1251 * association. If there are no errors, an ephemeral association
1252 * is mobilized: a broadcast packet mobilizes a broadcast client
1253 * aassociation; a manycast server packet mobilizes a manycast
1254 * client association; a symmetric active packet mobilizes a
1255 * symmetric passive association.
1257 DPRINTF(1, ("receive: MATCH_ASSOC dispatch: mode %d/%s:%s \n",
1258 hismode, hm_str, am_str));
1262 * This is a client mode packet not matching any association. If
1263 * an ordinary client, simply toss a server mode packet back
1264 * over the fence. If a manycast client, we have to work a
1267 * There are cases here where we do not call record_raw_stats().
1272 * If authentication OK, send a server reply; otherwise,
1273 * send a crypto-NAK.
1275 if (!(rbufp->dstadr->flags & INT_MCASTOPEN)) {
1276 /* HMS: would be nice to log FAST_XMIT|BADAUTH|RESTRICTED */
1277 record_raw_stats(&rbufp->recv_srcadr,
1278 &rbufp->dstadr->sin,
1279 &p_org, &p_rec, &p_xmt, &rbufp->recv_time,
1280 PKT_LEAP(pkt->li_vn_mode),
1281 PKT_VERSION(pkt->li_vn_mode),
1282 PKT_MODE(pkt->li_vn_mode),
1283 PKT_TO_STRATUM(pkt->stratum),
1286 FPTOD(NTOHS_FP(pkt->rootdelay)),
1287 FPTOD(NTOHS_FP(pkt->rootdisp)),
1289 rbufp->recv_length - MIN_V4_PKT_LEN, (u_char *)&pkt->exten);
1291 if (AUTH(restrict_mask & RES_DONTTRUST,
1293 /* Bug 3596: Do we want to fuzz the reftime? */
1294 fast_xmit(rbufp, MODE_SERVER, skeyid,
1296 } else if (is_authentic == AUTH_ERROR) {
1297 /* Bug 3596: Do we want to fuzz the reftime? */
1298 fast_xmit(rbufp, MODE_SERVER, 0,
1302 DPRINTF(2, ("receive: AM_FXMIT drop: !mcast restricted\n"));
1306 return; /* hooray */
1310 * This must be manycast. Do not respond if not
1311 * configured as a manycast server.
1313 if (!sys_manycastserver) {
1314 DPRINTF(2, ("receive: AM_FXMIT drop: Not manycastserver\n"));
1316 return; /* not enabled */
1321 * Do not respond if not the same group.
1323 if (group_test(groupname, NULL)) {
1324 DPRINTF(2, ("receive: AM_FXMIT drop: empty groupname\n"));
1328 #endif /* AUTOKEY */
1331 * Do not respond if we are not synchronized or our
1332 * stratum is greater than the manycaster or the
1333 * manycaster has already synchronized to us.
1335 if ( sys_leap == LEAP_NOTINSYNC
1336 || sys_stratum > hisstratum + 1
1337 || (!sys_cohort && sys_stratum == hisstratum + 1)
1338 || rbufp->dstadr->addr_refid == pkt->refid) {
1339 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));
1340 DPRINTF(2, ("receive: AM_FXMIT drop: LEAP_NOTINSYNC || stratum || loop\n"));
1342 return; /* no help */
1346 * Respond only if authentication succeeds. Don't do a
1347 * crypto-NAK, as that would not be useful.
1349 if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic)) {
1350 record_raw_stats(&rbufp->recv_srcadr,
1351 &rbufp->dstadr->sin,
1352 &p_org, &p_rec, &p_xmt, &rbufp->recv_time,
1353 PKT_LEAP(pkt->li_vn_mode),
1354 PKT_VERSION(pkt->li_vn_mode),
1355 PKT_MODE(pkt->li_vn_mode),
1356 PKT_TO_STRATUM(pkt->stratum),
1359 FPTOD(NTOHS_FP(pkt->rootdelay)),
1360 FPTOD(NTOHS_FP(pkt->rootdisp)),
1362 rbufp->recv_length - MIN_V4_PKT_LEN, (u_char *)&pkt->exten);
1364 /* Bug 3596: Do we want to fuzz the reftime? */
1365 fast_xmit(rbufp, MODE_SERVER, skeyid,
1368 return; /* hooray */
1371 * This is a server mode packet returned in response to a client
1372 * mode packet sent to a multicast group address (for
1373 * manycastclient) or to a unicast address (for pool). The
1374 * origin timestamp is a good nonce to reliably associate the
1375 * reply with what was sent. If there is no match, that's
1376 * curious and could be an intruder attempting to clog, so we
1379 * If the packet is authentic and the manycastclient or pool
1380 * association is found, we mobilize a client association and
1381 * copy pertinent variables from the manycastclient or pool
1382 * association to the new client association. If not, just
1383 * ignore the packet.
1385 * There is an implosion hazard at the manycast client, since
1386 * the manycast servers send the server packet immediately. If
1387 * the guy is already here, don't fire up a duplicate.
1389 * There are cases here where we do not call record_raw_stats().
1395 * Do not respond if not the same group.
1397 if (group_test(groupname, NULL)) {
1398 DPRINTF(2, ("receive: AM_MANYCAST drop: empty groupname\n"));
1402 #endif /* AUTOKEY */
1403 if ((peer2 = findmanycastpeer(rbufp)) == NULL) {
1404 DPRINTF(2, ("receive: AM_MANYCAST drop: No manycast peer\n"));
1406 return; /* not enabled */
1408 if (!AUTH( (!(peer2->cast_flags & MDF_POOL)
1409 && sys_authenticate)
1410 || (restrict_mask & (RES_NOPEER |
1411 RES_DONTTRUST)), is_authentic)
1412 /* MC: RES_NOEPEER? */
1414 DPRINTF(2, ("receive: AM_MANYCAST drop: bad auth || (NOPEER|DONTTRUST)\n"));
1416 return; /* access denied */
1420 * Do not respond if unsynchronized or stratum is below
1421 * the floor or at or above the ceiling.
1423 if ( hisleap == LEAP_NOTINSYNC
1424 || hisstratum < sys_floor
1425 || hisstratum >= sys_ceiling) {
1426 DPRINTF(2, ("receive: AM_MANYCAST drop: unsync/stratum\n"));
1428 return; /* no help */
1430 peer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr,
1431 r4a.ippeerlimit, MODE_CLIENT, hisversion,
1432 peer2->minpoll, peer2->maxpoll,
1433 (FLAG_PREEMPT | (POOL_FLAG_PMASK & peer2->flags)),
1434 (MDF_UCAST | MDF_UCLNT), 0, skeyid, sys_ident);
1436 DPRINTF(2, ("receive: AM_MANYCAST drop: duplicate\n"));
1438 return; /* ignore duplicate */
1442 * After each ephemeral pool association is spun,
1443 * accelerate the next poll for the pool solicitor so
1444 * the pool will fill promptly.
1446 if (peer2->cast_flags & MDF_POOL)
1447 peer2->nextdate = current_time + 1;
1450 * Further processing of the solicitation response would
1451 * simply detect its origin timestamp as bogus for the
1452 * brand-new association (it matches the prototype
1453 * association) and tinker with peer->nextdate delaying
1456 return; /* solicitation response handled */
1459 * This is the first packet received from a broadcast server. If
1460 * the packet is authentic and we are enabled as broadcast
1461 * client, mobilize a broadcast client association. We don't
1462 * kiss any frogs here.
1464 * There are cases here where we do not call record_raw_stats().
1470 * Do not respond if not the same group.
1472 if (group_test(groupname, sys_ident)) {
1473 DPRINTF(2, ("receive: AM_NEWBCL drop: groupname mismatch\n"));
1477 #endif /* AUTOKEY */
1478 if (sys_bclient == 0) {
1479 DPRINTF(2, ("receive: AM_NEWBCL drop: not a bclient\n"));
1481 return; /* not enabled */
1483 if (!AUTH(sys_authenticate | (restrict_mask &
1484 (RES_NOPEER | RES_DONTTRUST)), is_authentic)
1485 /* NEWBCL: RES_NOEPEER? */
1487 DPRINTF(2, ("receive: AM_NEWBCL drop: AUTH failed\n"));
1489 return; /* access denied */
1493 * Do not respond if unsynchronized or stratum is below
1494 * the floor or at or above the ceiling.
1496 if ( hisleap == LEAP_NOTINSYNC
1497 || hisstratum < sys_floor
1498 || hisstratum >= sys_ceiling) {
1499 DPRINTF(2, ("receive: AM_NEWBCL drop: Unsync or bad stratum\n"));
1501 return; /* no help */
1506 * Do not respond if Autokey and the opcode is not a
1507 * CRYPTO_ASSOC response with association ID.
1509 if ( crypto_flags && skeyid > NTP_MAXKEY
1510 && (opcode & 0xffff0000) != (CRYPTO_ASSOC | CRYPTO_RESP)) {
1511 DPRINTF(2, ("receive: AM_NEWBCL drop: Autokey but not CRYPTO_ASSOC\n"));
1513 return; /* protocol error */
1515 #endif /* AUTOKEY */
1518 * Broadcasts received via a multicast address may
1519 * arrive after a unicast volley has begun
1520 * with the same remote address. newpeer() will not
1521 * find duplicate associations on other local endpoints
1522 * if a non-NULL endpoint is supplied. multicastclient
1523 * ephemeral associations are unique across all local
1526 if (!(INT_MCASTOPEN & rbufp->dstadr->flags))
1527 match_ep = rbufp->dstadr;
1532 * Determine whether to execute the initial volley.
1534 if (sys_bdelay > 0.0) {
1537 * If a two-way exchange is not possible,
1538 * neither is Autokey.
1540 if (crypto_flags && skeyid > NTP_MAXKEY) {
1542 DPRINTF(2, ("receive: AM_NEWBCL drop: Autokey but not 2-way\n"));
1543 return; /* no autokey */
1545 #endif /* AUTOKEY */
1548 * Do not execute the volley. Start out in
1549 * broadcast client mode.
1551 peer = newpeer(&rbufp->recv_srcadr, NULL, match_ep,
1552 r4a.ippeerlimit, MODE_BCLIENT, hisversion,
1553 pkt->ppoll, pkt->ppoll,
1554 FLAG_PREEMPT, MDF_BCLNT, 0, skeyid, sys_ident);
1556 DPRINTF(2, ("receive: AM_NEWBCL drop: duplicate\n"));
1558 return; /* ignore duplicate */
1561 peer->delay = sys_bdelay;
1568 * Execute the initial volley in order to calibrate the
1569 * propagation delay and run the Autokey protocol.
1571 * Note that the minpoll is taken from the broadcast
1572 * packet, normally 6 (64 s) and that the poll interval
1573 * is fixed at this value.
1575 peer = newpeer(&rbufp->recv_srcadr, NULL, match_ep,
1576 r4a.ippeerlimit, MODE_CLIENT, hisversion,
1577 pkt->ppoll, pkt->ppoll,
1578 FLAG_BC_VOL | FLAG_IBURST | FLAG_PREEMPT, MDF_BCLNT,
1579 0, skeyid, sys_ident);
1581 DPRINTF(2, ("receive: AM_NEWBCL drop: empty newpeer() failed\n"));
1583 return; /* ignore duplicate */
1587 if (skeyid > NTP_MAXKEY)
1588 crypto_recv(peer, rbufp);
1589 #endif /* AUTOKEY */
1591 return; /* hooray */
1594 * This is the first packet received from a potential ephemeral
1595 * symmetric active peer. First, deal with broken Windows clients.
1596 * Then, if NOEPEER is enabled, drop it. If the packet meets our
1597 * authenticty requirements and is the first he sent, mobilize
1598 * a passive association.
1599 * Otherwise, kiss the frog.
1601 * There are cases here where we do not call record_raw_stats().
1605 DEBUG_REQUIRE(MODE_ACTIVE == hismode);
1609 * Do not respond if not the same group.
1611 if (group_test(groupname, sys_ident)) {
1612 DPRINTF(2, ("receive: AM_NEWPASS drop: Autokey group mismatch\n"));
1616 #endif /* AUTOKEY */
1617 if (!AUTH(sys_authenticate | (restrict_mask &
1618 (RES_NOPEER | RES_DONTTRUST)), is_authentic)
1621 * If authenticated but cannot mobilize an
1622 * association, send a symmetric passive
1623 * response without mobilizing an association.
1624 * This is for drat broken Windows clients. See
1625 * Microsoft KB 875424 for preferred workaround.
1627 if (AUTH(restrict_mask & RES_DONTTRUST,
1629 fast_xmit(rbufp, MODE_PASSIVE, skeyid,
1631 return; /* hooray */
1633 /* HMS: Why is this next set of lines a feature? */
1634 if (is_authentic == AUTH_ERROR) {
1635 fast_xmit(rbufp, MODE_PASSIVE, 0,
1641 if (restrict_mask & RES_NOEPEER) {
1642 DPRINTF(2, ("receive: AM_NEWPASS drop: NOEPEER\n"));
1648 * If we got here, the packet isn't part of an
1649 * existing association, either isn't correctly
1650 * authenticated or it is but we are refusing
1651 * ephemeral peer requests, and it didn't meet
1652 * either of the previous two special cases so we
1653 * should just drop it on the floor. For example,
1654 * crypto-NAKs (is_authentic == AUTH_CRYPTO)
1655 * will make it this far. This is just
1656 * debug-printed and not logged to avoid log
1659 DPRINTF(2, ("receive: at %ld refusing to mobilize passive association"
1660 " with unknown peer %s mode %d/%s:%s keyid %08x len %d auth %d\n",
1661 current_time, stoa(&rbufp->recv_srcadr),
1662 hismode, hm_str, am_str, skeyid,
1663 (authlen + has_mac), is_authentic));
1668 if (restrict_mask & RES_NOEPEER) {
1669 DPRINTF(2, ("receive: AM_NEWPASS drop: NOEPEER\n"));
1675 * Do not respond if synchronized and if stratum is
1676 * below the floor or at or above the ceiling. Note,
1677 * this allows an unsynchronized peer to synchronize to
1678 * us. It would be very strange if he did and then was
1679 * nipped, but that could only happen if we were
1680 * operating at the top end of the range. It also means
1681 * we will spin an ephemeral association in response to
1682 * MODE_ACTIVE KoDs, which will time out eventually.
1684 if ( hisleap != LEAP_NOTINSYNC
1685 && (hisstratum < sys_floor || hisstratum >= sys_ceiling)) {
1686 DPRINTF(2, ("receive: AM_NEWPASS drop: Remote stratum (%d) out of range\n",
1689 return; /* no help */
1693 * The message is correctly authenticated and allowed.
1694 * Mobilize a symmetric passive association, if we won't
1695 * exceed the ippeerlimit.
1697 if ((peer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr,
1698 r4a.ippeerlimit, MODE_PASSIVE, hisversion,
1699 pkt->ppoll, NTP_MAXDPOLL, 0, MDF_UCAST, 0,
1700 skeyid, sys_ident)) == NULL) {
1701 DPRINTF(2, ("receive: AM_NEWPASS drop: newpeer() failed\n"));
1703 return; /* ignore duplicate */
1709 * Process regular packet. Nothing special.
1711 * There are cases here where we do not call record_raw_stats().
1717 * Do not respond if not the same group.
1719 if (group_test(groupname, peer->ident)) {
1720 DPRINTF(2, ("receive: AM_PROCPKT drop: Autokey group mismatch\n"));
1724 #endif /* AUTOKEY */
1726 if (MODE_BROADCAST == hismode) {
1731 DPRINTF(2, ("receive: PROCPKT/BROADCAST: prev pkt %ld seconds ago, ppoll: %d, %d secs\n",
1732 (current_time - peer->timelastrec),
1733 peer->ppoll, (1 << peer->ppoll)
1735 /* Things we can check:
1737 * Did the poll interval change?
1738 * Is the poll interval in the packet in-range?
1739 * Did this packet arrive too soon?
1740 * Is the timestamp in this packet monotonic
1741 * with respect to the previous packet?
1744 /* This is noteworthy, not error-worthy */
1745 if (pkt->ppoll != peer->ppoll) {
1746 msyslog(LOG_INFO, "receive: broadcast poll from %s changed from %u to %u",
1747 stoa(&rbufp->recv_srcadr),
1748 peer->ppoll, pkt->ppoll);
1751 /* This is error-worthy */
1752 if ( pkt->ppoll < peer->minpoll
1753 || pkt->ppoll > peer->maxpoll) {
1754 msyslog(LOG_INFO, "receive: broadcast poll of %u from %s is out-of-range (%d to %d)!",
1755 pkt->ppoll, stoa(&rbufp->recv_srcadr),
1756 peer->minpoll, peer->maxpoll);
1760 /* too early? worth an error, too!
1762 * [Bug 3113] Ensure that at least one poll
1763 * interval has elapsed since the last **clean**
1764 * packet was received. We limit the check to
1765 * **clean** packets to prevent replayed packets
1766 * and incorrectly authenticated packets, which
1767 * we'll discard, from being used to create a
1768 * denial of service condition.
1770 deadband = (1u << pkt->ppoll);
1771 if (FLAG_BC_VOL & peer->flags)
1772 deadband -= 3; /* allow greater fuzz after volley */
1773 if ((current_time - peer->timereceived) < deadband) {
1774 msyslog(LOG_INFO, "receive: broadcast packet from %s arrived after %lu, not %lu seconds!",
1775 stoa(&rbufp->recv_srcadr),
1776 (current_time - peer->timereceived),
1781 /* Alert if time from the server is non-monotonic.
1783 * [Bug 3114] is about Broadcast mode replay DoS.
1785 * Broadcast mode *assumes* a trusted network.
1786 * Even so, it's nice to be robust in the face
1789 * If we get an authenticated broadcast packet
1790 * with an "earlier" timestamp, it means one of
1793 * - the broadcast server had a backward step.
1795 * - somebody is trying a replay attack.
1797 * deadband: By default, we assume the broadcast
1798 * network is trustable, so we take our accepted
1799 * broadcast packets as we receive them. But
1800 * some folks might want to take additional poll
1801 * delays before believing a backward step.
1803 if (sys_bcpollbstep) {
1804 /* pkt->ppoll or peer->ppoll ? */
1805 deadband = (1u << pkt->ppoll)
1806 * sys_bcpollbstep + 2;
1811 if (L_ISZERO(&peer->bxmt)) {
1812 tdiff.l_ui = tdiff.l_uf = 0;
1815 L_SUB(&tdiff, &peer->bxmt);
1818 && (current_time - peer->timereceived) < deadband)
1820 msyslog(LOG_INFO, "receive: broadcast packet from %s contains non-monotonic timestamp: %#010x.%08x -> %#010x.%08x",
1821 stoa(&rbufp->recv_srcadr),
1822 peer->bxmt.l_ui, peer->bxmt.l_uf,
1823 p_xmt.l_ui, p_xmt.l_uf
1829 DPRINTF(2, ("receive: AM_PROCPKT drop: bail\n"));
1830 peer->timelastrec = current_time;
1839 * A passive packet matches a passive association. This is
1840 * usually the result of reconfiguring a client on the fly. As
1841 * this association might be legitimate and this packet an
1842 * attempt to deny service, just ignore it.
1845 DPRINTF(2, ("receive: AM_ERR drop.\n"));
1850 * For everything else there is the bit bucket.
1853 DPRINTF(2, ("receive: default drop.\n"));
1860 * If the association is configured for Autokey, the packet must
1861 * have a public key ID; if not, the packet must have a
1864 if ( is_authentic != AUTH_CRYPTO
1865 && ( ((peer->flags & FLAG_SKEY) && skeyid <= NTP_MAXKEY)
1866 || (!(peer->flags & FLAG_SKEY) && skeyid > NTP_MAXKEY))) {
1867 DPRINTF(2, ("receive: drop: Autokey but wrong/bad auth\n"));
1871 #endif /* AUTOKEY */
1874 peer->flash &= ~PKT_TEST_MASK;
1875 if (peer->flags & FLAG_XBOGUS) {
1876 peer->flags &= ~FLAG_XBOGUS;
1877 peer->flash |= TEST3;
1881 * Next comes a rigorous schedule of timestamp checking. If the
1882 * transmit timestamp is zero, the server has not initialized in
1883 * interleaved modes or is horribly broken.
1885 * A KoD packet we pay attention to cannot have a 0 transmit
1889 kissCode = kiss_code_check(hisleap, hisstratum, hismode, pkt->refid);
1891 if (L_ISZERO(&p_xmt)) {
1892 peer->flash |= TEST3; /* unsynch */
1893 if (kissCode != NOKISS) { /* KoD packet */
1894 peer->bogusorg++; /* for TEST2 or TEST3 */
1896 "receive: Unexpected zero transmit timestamp in KoD from %s",
1897 ntoa(&peer->srcadr));
1902 * If the transmit timestamp duplicates our previous one, the
1903 * packet is a replay. This prevents the bad guys from replaying
1904 * the most recent packet, authenticated or not.
1906 } else if ( ((FLAG_LOOPNONCE & peer->flags) && L_ISEQU(&peer->nonce, &p_xmt))
1907 || (!(FLAG_LOOPNONCE & peer->flags) && L_ISEQU(&peer->xmt, &p_xmt))
1909 DPRINTF(2, ("receive: drop: Duplicate xmit\n"));
1910 peer->flash |= TEST1; /* duplicate */
1915 * If this is a broadcast mode packet, make sure hisstratum
1916 * is appropriate. Don't do anything else here - we wait to
1917 * see if this is an interleave broadcast packet until after
1918 * we've validated the MAC that SHOULD be provided.
1920 * hisstratum cannot be 0 - see assertion above.
1921 * If hisstratum is 15, then we'll advertise as UNSPEC but
1922 * at least we'll be able to sync with the broadcast server.
1924 } else if (hismode == MODE_BROADCAST) {
1925 /* 0 is unexpected too, and impossible */
1926 if (STRATUM_UNSPEC <= hisstratum) {
1927 /* Is this a ++sys_declined or ??? */
1929 "receive: Unexpected stratum (%d) in broadcast from %s",
1930 hisstratum, ntoa(&peer->srcadr));
1935 * Basic KoD validation checking:
1937 * KoD packets are a mixed-blessing. Forged KoD packets
1938 * are DoS attacks. There are rare situations where we might
1939 * get a valid KoD response, though. Since KoD packets are
1940 * a special case that complicate the checks we do next, we
1941 * handle the basic KoD checks here.
1943 * Note that we expect the incoming KoD packet to have its
1944 * (nonzero) org, rec, and xmt timestamps set to the xmt timestamp
1945 * that we have previously sent out. Watch interleave mode.
1947 } else if (kissCode != NOKISS) {
1948 DEBUG_INSIST(!L_ISZERO(&p_xmt));
1949 if ( L_ISZERO(&p_org) /* We checked p_xmt above */
1950 || L_ISZERO(&p_rec)) {
1953 "receive: KoD packet from %s has a zero org or rec timestamp. Ignoring.",
1954 ntoa(&peer->srcadr));
1958 if ( !L_ISEQU(&p_xmt, &p_org)
1959 || !L_ISEQU(&p_xmt, &p_rec)) {
1962 "receive: KoD packet from %s has inconsistent xmt/org/rec timestamps. Ignoring.",
1963 ntoa(&peer->srcadr));
1967 /* Be conservative */
1968 if (peer->flip == 0 && !L_ISEQU(&p_org, &peer->aorg)) {
1971 "receive: flip 0 KoD origin timestamp %#010x.%08x from %s does not match %#010x.%08x - ignoring.",
1972 p_org.l_ui, p_org.l_uf,
1973 ntoa(&peer->srcadr),
1974 peer->aorg.l_ui, peer->aorg.l_uf);
1976 } else if (peer->flip == 1 && !L_ISEQU(&p_org, &peer->borg)) {
1979 "receive: flip 1 KoD origin timestamp %#010x.%08x from %s does not match interleave %#010x.%08x - ignoring.",
1980 p_org.l_ui, p_org.l_uf,
1981 ntoa(&peer->srcadr),
1982 peer->borg.l_ui, peer->borg.l_uf);
1987 * Basic mode checks:
1989 * If there is no origin timestamp, it's either an initial packet
1990 * or we've already received a response to our query. Of course,
1991 * should 'aorg' be all-zero because this really was the original
1992 * transmit timestamp, we'll ignore this reply. There is a window
1993 * of one nanosecond once every 136 years' time where this is
1994 * possible. We currently ignore this situation, as a completely
1995 * zero timestamp is (quietly?) disallowed.
1997 * Otherwise, check for bogus packet in basic mode.
1998 * If it is bogus, switch to interleaved mode and resynchronize,
1999 * but only after confirming the packet is not bogus in
2000 * symmetric interleaved mode.
2002 * This could also mean somebody is forging packets claiming to
2003 * be from us, attempting to cause our server to KoD us.
2005 * We have earlier asserted that hisstratum cannot be 0.
2006 * If hisstratum is STRATUM_UNSPEC, it means he's not sync'd.
2009 /* XXX: FLAG_LOOPNONCE */
2010 DEBUG_INSIST(0 == (FLAG_LOOPNONCE & peer->flags));
2012 } else if (peer->flip == 0) {
2014 } else if (L_ISZERO(&p_org)) {
2019 "receive: BUG 3361: Clearing peer->aorg ");
2021 /* Clear peer->nonce, too? */
2025 /* We allow 0org for: */
2029 /* We disallow 0org for: */
2035 case MODE_BROADCAST:
2038 peer->flash |= TEST2; /* bogus */
2041 action = ""; /* for cranky compilers / MSVC */
2042 INSIST(!"receive(): impossible hismode");
2047 "receive: %s 0 origin timestamp from %s@%s xmt %#010x.%08x",
2048 action, hm_str, ntoa(&peer->srcadr),
2049 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));
2050 } else if (!L_ISEQU(&p_org, &peer->aorg)) {
2051 /* are there cases here where we should bail? */
2052 /* Should we set TEST2 if we decide to try xleave? */
2054 peer->flash |= TEST2; /* bogus */
2056 "receive: Unexpected origin timestamp %#010x.%08x does not match aorg %#010x.%08x from %s@%s xmt %#010x.%08x",
2057 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
2058 peer->aorg.l_ui, peer->aorg.l_uf,
2059 hm_str, ntoa(&peer->srcadr),
2060 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));
2061 if ( !L_ISZERO(&peer->dst)
2062 && L_ISEQU(&p_org, &peer->dst)) {
2063 /* Might be the start of an interleave */
2064 if (dynamic_interleave) {
2066 report_event(PEVNT_XLEAVE, peer, NULL);
2069 "receive: Dynamic interleave from %s@%s denied",
2070 hm_str, ntoa(&peer->srcadr));
2075 /* XXX: FLAG_LOOPNONCE */
2079 * Check for valid nonzero timestamp fields.
2081 } else if ( L_ISZERO(&p_org)
2083 || L_ISZERO(&peer->dst)) {
2084 peer->flash |= TEST3; /* unsynch */
2087 * Check for bogus packet in interleaved symmetric mode. This
2088 * can happen if a packet is lost, duplicated or crossed. If
2089 * found, flip and resynchronize.
2091 } else if ( !L_ISZERO(&peer->dst)
2092 && !L_ISEQU(&p_org, &peer->dst)) {
2093 DPRINTF(2, ("receive: drop: Bogus packet in interleaved symmetric mode\n"));
2095 peer->flags |= FLAG_XBOGUS;
2096 peer->flash |= TEST2; /* bogus */
2098 return; /* Bogus packet, we are done */
2105 * If this is a crypto_NAK, the server cannot authenticate a
2106 * client packet. The server might have just changed keys. Clear
2107 * the association and restart the protocol.
2109 if (crypto_nak_test == VALIDNAK) {
2110 report_event(PEVNT_AUTH, peer, "crypto_NAK");
2111 peer->flash |= TEST5; /* bad auth */
2113 if (peer->flags & FLAG_PREEMPT) {
2114 if (unpeer_crypto_nak_early) {
2117 DPRINTF(2, ("receive: drop: PREEMPT crypto_NAK\n"));
2122 peer_clear(peer, "AUTH");
2124 #endif /* AUTOKEY */
2125 DPRINTF(2, ("receive: drop: crypto_NAK\n"));
2129 * If the digest fails or it's missing for authenticated
2130 * associations, the client cannot authenticate a server
2131 * reply to a client packet previously sent. The loopback check
2132 * is designed to avoid a bait-and-switch attack, which was
2133 * possible in past versions. If symmetric modes, return a
2134 * crypto-NAK. The peer should restart the protocol.
2136 } else if (!AUTH(peer->keyid || has_mac ||
2137 (restrict_mask & RES_DONTTRUST), is_authentic)) {
2139 if (peer->flash & PKT_TEST_MASK) {
2141 "receive: Bad auth in packet with bad timestamps from %s denied - spoof?",
2142 ntoa(&peer->srcadr));
2146 report_event(PEVNT_AUTH, peer, "digest");
2147 peer->flash |= TEST5; /* bad auth */
2150 && ( hismode == MODE_ACTIVE
2151 || hismode == MODE_PASSIVE))
2152 fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
2153 if (peer->flags & FLAG_PREEMPT) {
2154 if (unpeer_digest_early) {
2159 else if (peer_clear_digest_early && peer->crypto) {
2160 peer_clear(peer, "AUTH");
2162 #endif /* AUTOKEY */
2163 DPRINTF(2, ("receive: drop: Bad or missing AUTH\n"));
2168 * For broadcast packets:
2170 * HMS: This next line never made much sense to me, even
2171 * when it was up higher:
2172 * If an initial volley, bail out now and let the
2173 * client do its stuff.
2175 * If the packet has not failed authentication, then
2176 * - if the origin timestamp is nonzero this is an
2177 * interleaved broadcast, so restart the protocol.
2178 * - else, this is not an interleaved broadcast packet.
2180 if (hismode == MODE_BROADCAST) {
2181 if ( is_authentic == AUTH_OK
2182 || is_authentic == AUTH_NONE) {
2183 if (!L_ISZERO(&p_org)) {
2184 if (!(peer->flags & FLAG_XB)) {
2186 "receive: Broadcast server at %s is in interleave mode",
2187 ntoa(&peer->srcadr));
2188 peer->flags |= FLAG_XB;
2190 peer->borg = rbufp->recv_time;
2191 report_event(PEVNT_XLEAVE, peer, NULL);
2194 } else if (peer->flags & FLAG_XB) {
2196 "receive: Broadcast server at %s is no longer in interleave mode",
2197 ntoa(&peer->srcadr));
2198 peer->flags &= ~FLAG_XB;
2202 "receive: Bad broadcast auth (%d) from %s",
2203 is_authentic, ntoa(&peer->srcadr));
2207 * Now that we know the packet is correctly authenticated,
2208 * update peer->bxmt.
2215 ** Update the state variables.
2217 if (peer->flip == 0) {
2218 if (hismode != MODE_BROADCAST)
2220 peer->dst = rbufp->recv_time;
2225 * Set the peer ppoll to the maximum of the packet ppoll and the
2226 * peer minpoll. If a kiss-o'-death, set the peer minpoll to
2227 * this maximum and advance the headway to give the sender some
2228 * headroom. Very intricate.
2232 * Check for any kiss codes. Note this is only used when a server
2233 * responds to a packet request.
2237 * Check to see if this is a RATE Kiss Code
2238 * Currently this kiss code will accept whatever poll
2239 * rate that the server sends
2241 peer->ppoll = max(peer->minpoll, pkt->ppoll);
2242 if (kissCode == RATEKISS) {
2243 peer->selbroken++; /* Increment the KoD count */
2244 report_event(PEVNT_RATE, peer, NULL);
2245 if (pkt->ppoll > peer->minpoll)
2246 peer->minpoll = peer->ppoll;
2247 peer->burst = peer->retry = 0;
2248 peer->throttle = (NTP_SHIFT + 1) * (1 << peer->minpoll);
2249 poll_update(peer, pkt->ppoll, 0);
2250 return; /* kiss-o'-death */
2252 if (kissCode != NOKISS) {
2253 peer->selbroken++; /* Increment the KoD count */
2254 return; /* Drop any other kiss code packets */
2265 * - this is a *cast (uni-, broad-, or m-) server packet
2266 * - and it's symmetric-key authenticated
2267 * then see if the sender's IP is trusted for this keyid.
2268 * If it is, great - nothing special to do here.
2269 * Otherwise, we should report and bail.
2271 * Autokey-authenticated packets are accepted.
2275 case MODE_SERVER: /* server mode */
2276 case MODE_BROADCAST: /* broadcast mode */
2277 case MODE_ACTIVE: /* symmetric active mode */
2278 case MODE_PASSIVE: /* symmetric passive mode */
2279 if ( is_authentic == AUTH_OK
2281 && skeyid <= NTP_MAXKEY
2282 && !authistrustedip(skeyid, &peer->srcadr)) {
2283 report_event(PEVNT_AUTH, peer, "authIP");
2289 case MODE_CLIENT: /* client mode */
2290 #if 0 /* At this point, MODE_CONTROL is overloaded by MODE_BCLIENT */
2291 case MODE_CONTROL: /* control mode */
2293 case MODE_PRIVATE: /* private mode */
2294 case MODE_BCLIENT: /* broadcast client mode */
2297 case MODE_UNSPEC: /* unspecified (old version) */
2300 "receive: Unexpected mode (%d) in packet from %s",
2301 hismode, ntoa(&peer->srcadr));
2307 * That was hard and I am sweaty, but the packet is squeaky
2308 * clean. Get on with real work.
2310 peer->timereceived = current_time;
2311 peer->timelastrec = current_time;
2312 if (is_authentic == AUTH_OK)
2313 peer->flags |= FLAG_AUTHENTIC;
2315 peer->flags &= ~FLAG_AUTHENTIC;
2319 * More autokey dance. The rules of the cha-cha are as follows:
2321 * 1. If there is no key or the key is not auto, do nothing.
2323 * 2. If this packet is in response to the one just previously
2324 * sent or from a broadcast server, do the extension fields.
2325 * Otherwise, assume bogosity and bail out.
2327 * 3. If an extension field contains a verified signature, it is
2328 * self-authenticated and we sit the dance.
2330 * 4. If this is a server reply, check only to see that the
2331 * transmitted key ID matches the received key ID.
2333 * 5. Check to see that one or more hashes of the current key ID
2334 * matches the previous key ID or ultimate original key ID
2335 * obtained from the broadcaster or symmetric peer. If no
2336 * match, sit the dance and call for new autokey values.
2338 * In case of crypto error, fire the orchestra, stop dancing and
2339 * restart the protocol.
2341 if (peer->flags & FLAG_SKEY) {
2343 * Decrement remaining autokey hashes. This isn't
2344 * perfect if a packet is lost, but results in no harm.
2346 ap = (struct autokey *)peer->recval.ptr;
2351 peer->flash |= TEST8;
2352 rval = crypto_recv(peer, rbufp);
2353 if (rval == XEVNT_OK) {
2356 if (rval == XEVNT_ERR) {
2357 report_event(PEVNT_RESTART, peer,
2359 peer_clear(peer, "CRYP");
2360 peer->flash |= TEST9; /* bad crypt */
2361 if (peer->flags & FLAG_PREEMPT) {
2362 if (unpeer_crypto_early) {
2371 * If server mode, verify the receive key ID matches
2372 * the transmit key ID.
2374 if (hismode == MODE_SERVER) {
2375 if (skeyid == peer->keyid)
2376 peer->flash &= ~TEST8;
2379 * If an extension field is present, verify only that it
2380 * has been correctly signed. We don't need a sequence
2381 * check here, but the sequence continues.
2383 } else if (!(peer->flash & TEST8)) {
2384 peer->pkeyid = skeyid;
2387 * Now the fun part. Here, skeyid is the current ID in
2388 * the packet, pkeyid is the ID in the last packet and
2389 * tkeyid is the hash of skeyid. If the autokey values
2390 * have not been received, this is an automatic error.
2391 * If so, check that the tkeyid matches pkeyid. If not,
2392 * hash tkeyid and try again. If the number of hashes
2393 * exceeds the number remaining in the sequence, declare
2394 * a successful failure and refresh the autokey values.
2396 } else if (ap != NULL) {
2399 for (i = 0; ; i++) {
2400 if ( tkeyid == peer->pkeyid
2401 || tkeyid == ap->key) {
2402 peer->flash &= ~TEST8;
2403 peer->pkeyid = skeyid;
2412 tkeyid = session_key(
2413 &rbufp->recv_srcadr, dstadr_sin,
2416 if (peer->flash & TEST8)
2417 report_event(PEVNT_AUTH, peer, "keylist");
2419 if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */
2420 peer->flash |= TEST8; /* bad autokey */
2423 * The maximum lifetime of the protocol is about one
2424 * week before restarting the Autokey protocol to
2425 * refresh certificates and leapseconds values.
2427 if (current_time > peer->refresh) {
2428 report_event(PEVNT_RESTART, peer,
2430 peer_clear(peer, "TIME");
2434 #endif /* AUTOKEY */
2437 * The dance is complete and the flash bits have been lit. Toss
2438 * the packet over the fence for processing, which may light up
2439 * more flashers. Leave if the packet is not good.
2441 process_packet(peer, pkt, rbufp->recv_length);
2442 if (peer->flash & PKT_TEST_MASK)
2445 /* [bug 3592] Update poll. Ideally this should not happen in a
2446 * receive branch, but too much is going on here... at least we
2447 * do it only if the packet was good!
2449 poll_update(peer, peer->hpoll, (peer->hmode == MODE_CLIENT));
2452 * In interleaved mode update the state variables. Also adjust the
2453 * transmit phase to avoid crossover.
2455 if (peer->flip != 0) {
2457 peer->dst = rbufp->recv_time;
2458 if (peer->nextdate - current_time < (1U << min(peer->ppoll,
2468 * process_packet - Packet Procedure, a la Section 3.4.4 of RFC-1305
2469 * Or almost, at least. If we're in here we have a reasonable
2470 * expectation that we will be having a long term
2471 * relationship with this host.
2475 register struct peer *peer,
2476 register struct pkt *pkt,
2481 double p_offset, p_del, p_disp;
2482 l_fp p_rec, p_xmt, p_org, p_reftime, ci;
2483 u_char pmode, pleap, pversion, pstratum;
2484 char statstr[NTP_MAXSTRLEN];
2487 double etemp, ftemp, td;
2490 p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
2492 p_disp = FPTOD(NTOHS_FP(pkt->rootdisp));
2493 NTOHL_FP(&pkt->reftime, &p_reftime);
2494 NTOHL_FP(&pkt->org, &p_org);
2495 NTOHL_FP(&pkt->rec, &p_rec);
2496 NTOHL_FP(&pkt->xmt, &p_xmt);
2497 pmode = PKT_MODE(pkt->li_vn_mode);
2498 pleap = PKT_LEAP(pkt->li_vn_mode);
2499 pversion = PKT_VERSION(pkt->li_vn_mode);
2500 pstratum = PKT_TO_STRATUM(pkt->stratum);
2503 * Verify the server is synchronized; that is, the leap bits,
2504 * stratum and root distance are valid.
2506 if ( pleap == LEAP_NOTINSYNC /* test 6 */
2507 || pstratum < sys_floor || pstratum >= sys_ceiling)
2508 peer->flash |= TEST6; /* bad synch or strat */
2509 if (p_del / 2 + p_disp >= MAXDISPERSE) /* test 7 */
2510 peer->flash |= TEST7; /* bad header */
2513 * If any tests fail at this point, the packet is discarded.
2514 * Note that some flashers may have already been set in the
2515 * receive() routine.
2517 if (peer->flash & PKT_TEST_MASK) {
2518 peer->seldisptoolarge++;
2519 DPRINTF(1, ("packet: flash header %04x\n",
2521 /* [Bug 3592] do *not* update poll on bad packets! */
2526 * update stats, now that we really handle this packet:
2532 * Capture the header values in the client/peer association..
2534 record_raw_stats(&peer->srcadr,
2535 peer->dstadr ? &peer->dstadr->sin : NULL,
2536 &p_org, &p_rec, &p_xmt, &peer->dst,
2537 pleap, pversion, pmode, pstratum, pkt->ppoll, pkt->precision,
2538 p_del, p_disp, pkt->refid,
2539 len - MIN_V4_PKT_LEN, (u_char *)&pkt->exten);
2541 peer->stratum = min(pstratum, STRATUM_UNSPEC);
2542 peer->pmode = pmode;
2543 peer->precision = pkt->precision;
2544 peer->rootdelay = p_del;
2545 peer->rootdisp = p_disp;
2546 peer->refid = pkt->refid; /* network byte order */
2547 peer->reftime = p_reftime;
2550 * First, if either burst mode is armed, enable the burst.
2551 * Compute the headway for the next packet and delay if
2552 * necessary to avoid exceeding the threshold.
2554 if (peer->retry > 0) {
2557 peer->burst = min(1 << (peer->hpoll -
2558 peer->minpoll), NTP_SHIFT) - 1;
2560 peer->burst = NTP_IBURST - 1;
2561 if (peer->burst > 0)
2562 peer->nextdate = current_time;
2566 * If the peer was previously unreachable, raise a trap. In any
2567 * case, mark it reachable.
2570 report_event(PEVNT_REACH, peer, NULL);
2571 peer->timereachable = current_time;
2576 * For a client/server association, calculate the clock offset,
2577 * roundtrip delay and dispersion. The equations are reordered
2578 * from the spec for more efficient use of temporaries. For a
2579 * broadcast association, offset the last measurement by the
2580 * computed delay during the client/server volley. Note the
2581 * computation of dispersion includes the system precision plus
2582 * that due to the frequency error since the origin time.
2584 * It is very important to respect the hazards of overflow. The
2585 * only permitted operation on raw timestamps is subtraction,
2586 * where the result is a signed quantity spanning from 68 years
2587 * in the past to 68 years in the future. To avoid loss of
2588 * precision, these calculations are done using 64-bit integer
2589 * arithmetic. However, the offset and delay calculations are
2590 * sums and differences of these first-order differences, which
2591 * if done using 64-bit integer arithmetic, would be valid over
2592 * only half that span. Since the typical first-order
2593 * differences are usually very small, they are converted to 64-
2594 * bit doubles and all remaining calculations done in floating-
2595 * double arithmetic. This preserves the accuracy while
2596 * retaining the 68-year span.
2598 * There are three interleaving schemes, basic, interleaved
2599 * symmetric and interleaved broadcast. The timestamps are
2600 * idioscyncratically different. See the onwire briefing/white
2601 * paper at www.eecis.udel.edu/~mills for details.
2603 * Interleaved symmetric mode
2604 * t1 = peer->aorg/borg, t2 = peer->rec, t3 = p_xmt,
2607 if (peer->flip != 0) {
2608 ci = p_xmt; /* t3 - t4 */
2609 L_SUB(&ci, &peer->dst);
2611 ci = p_rec; /* t2 - t1 */
2613 L_SUB(&ci, &peer->borg);
2615 L_SUB(&ci, &peer->aorg);
2618 p_offset = (t21 + t34) / 2.;
2619 if (p_del < 0 || p_del > 1.) {
2620 snprintf(statstr, sizeof(statstr),
2621 "t21 %.6f t34 %.6f", t21, t34);
2622 report_event(PEVNT_XERR, peer, statstr);
2629 } else if (peer->pmode == MODE_BROADCAST) {
2632 * Interleaved broadcast mode. Use interleaved timestamps.
2633 * t1 = peer->borg, t2 = p_org, t3 = p_org, t4 = aorg
2635 if (peer->flags & FLAG_XB) {
2636 ci = p_org; /* delay */
2637 L_SUB(&ci, &peer->aorg);
2639 ci = p_org; /* t2 - t1 */
2640 L_SUB(&ci, &peer->borg);
2643 peer->borg = peer->dst;
2644 if (t34 < 0 || t34 > 1.) {
2645 /* drop all if in the initial volley */
2646 if (FLAG_BC_VOL & peer->flags)
2647 goto bcc_init_volley_fail;
2648 snprintf(statstr, sizeof(statstr),
2649 "offset %.6f delay %.6f", t21, t34);
2650 report_event(PEVNT_XERR, peer, statstr);
2657 * Basic broadcast - use direct timestamps.
2658 * t3 = p_xmt, t4 = peer->dst
2661 ci = p_xmt; /* t3 - t4 */
2662 L_SUB(&ci, &peer->dst);
2668 * When calibration is complete and the clock is
2669 * synchronized, the bias is calculated as the difference
2670 * between the unicast timestamp and the broadcast
2671 * timestamp. This works for both basic and interleaved
2673 * [Bug 3031] Don't keep this peer when the delay
2674 * calculation gives reason to suspect clock steps.
2675 * This is assumed for delays > 50ms.
2677 if (FLAG_BC_VOL & peer->flags) {
2678 peer->flags &= ~FLAG_BC_VOL;
2679 peer->delay = fabs(peer->offset - p_offset) * 2;
2680 DPRINTF(2, ("broadcast volley: initial delay=%.6f\n",
2682 if (peer->delay > fabs(sys_bdelay)) {
2683 bcc_init_volley_fail:
2684 DPRINTF(2, ("%s", "broadcast volley: initial delay exceeds limit\n"));
2689 peer->nextdate = current_time + (1u << peer->ppoll) - 2u;
2690 p_del = peer->delay;
2691 p_offset += p_del / 2;
2695 * Basic mode, otherwise known as the old fashioned way.
2697 * t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->dst
2700 ci = p_xmt; /* t3 - t4 */
2701 L_SUB(&ci, &peer->dst);
2703 ci = p_rec; /* t2 - t1 */
2706 p_del = fabs(t21 - t34);
2707 p_offset = (t21 + t34) / 2.;
2709 p_del = max(p_del, LOGTOD(sys_precision));
2710 p_disp = LOGTOD(sys_precision) + LOGTOD(peer->precision) +
2715 * This code calculates the outbound and inbound data rates by
2716 * measuring the differences between timestamps at different
2717 * packet lengths. This is helpful in cases of large asymmetric
2718 * delays commonly experienced on deep space communication
2721 if (peer->t21_last > 0 && peer->t34_bytes > 0) {
2722 itemp = peer->t21_bytes - peer->t21_last;
2724 etemp = t21 - peer->t21;
2725 if (fabs(etemp) > 1e-6) {
2726 ftemp = itemp / etemp;
2731 itemp = len - peer->t34_bytes;
2733 etemp = -t34 - peer->t34;
2734 if (fabs(etemp) > 1e-6) {
2735 ftemp = itemp / etemp;
2743 * The following section compensates for different data rates on
2744 * the outbound (d21) and inbound (t34) directions. To do this,
2745 * it finds t such that r21 * t - r34 * (d - t) = 0, where d is
2746 * the roundtrip delay. Then it calculates the correction as a
2750 peer->t21_last = peer->t21_bytes;
2752 peer->t34_bytes = len;
2753 DPRINTF(2, ("packet: t21 %.9lf %d t34 %.9lf %d\n", peer->t21,
2754 peer->t21_bytes, peer->t34, peer->t34_bytes));
2755 if (peer->r21 > 0 && peer->r34 > 0 && p_del > 0) {
2756 if (peer->pmode != MODE_BROADCAST)
2757 td = (peer->r34 / (peer->r21 + peer->r34) -
2763 * Unfortunately, in many cases the errors are
2764 * unacceptable, so for the present the rates are not
2765 * used. In future, we might find conditions where the
2766 * calculations are useful, so this should be considered
2767 * a work in progress.
2771 DPRINTF(2, ("packet: del %.6lf r21 %.1lf r34 %.1lf %.6lf\n",
2772 p_del, peer->r21 / 1e3, peer->r34 / 1e3,
2778 * That was awesome. Now hand off to the clock filter.
2780 clock_filter(peer, p_offset + peer->bias, p_del, p_disp);
2783 * If we are in broadcast calibrate mode, return to broadcast
2784 * client mode when the client is fit and the autokey dance is
2787 if ( (FLAG_BC_VOL & peer->flags)
2788 && MODE_CLIENT == peer->hmode
2789 && !(TEST11 & peer_unfit(peer))) { /* distance exceeded */
2791 if (peer->flags & FLAG_SKEY) {
2792 if (!(~peer->crypto & CRYPTO_FLAG_ALL))
2793 peer->hmode = MODE_BCLIENT;
2795 peer->hmode = MODE_BCLIENT;
2797 #else /* !AUTOKEY follows */
2798 peer->hmode = MODE_BCLIENT;
2799 #endif /* !AUTOKEY */
2805 * clock_update - Called at system process update intervals.
2809 struct peer *peer /* peer structure pointer */
2814 #ifdef HAVE_LIBSCF_H
2816 #endif /* HAVE_LIBSCF_H */
2819 * Update the system state variables. We do this very carefully,
2820 * as the poll interval might need to be clamped differently.
2823 sys_epoch = peer->epoch;
2824 if (sys_poll < peer->minpoll)
2825 sys_poll = peer->minpoll;
2826 if (sys_poll > peer->maxpoll)
2827 sys_poll = peer->maxpoll;
2828 poll_update(peer, sys_poll, 0);
2829 sys_stratum = min(peer->stratum + 1, STRATUM_UNSPEC);
2830 if ( peer->stratum == STRATUM_REFCLOCK
2831 || peer->stratum == STRATUM_UNSPEC)
2832 sys_refid = peer->refid;
2834 sys_refid = addr2refid(&peer->srcadr);
2836 * Root Dispersion (E) is defined (in RFC 5905) as:
2838 * E = p.epsilon_r + p.epsilon + p.psi + PHI*(s.t - p.t) + |THETA|
2841 * p.epsilon_r is the PollProc's root dispersion
2842 * p.epsilon is the PollProc's dispersion
2843 * p.psi is the PollProc's jitter
2844 * THETA is the combined offset
2846 * NB: Think Hard about where these numbers come from and
2847 * what they mean. When did peer->update happen? Has anything
2848 * interesting happened since then? What values are the most
2851 * DLM thinks this equation is probably the best of all worse choices.
2853 dtemp = peer->rootdisp
2856 + clock_phi * (current_time - peer->update)
2859 p2_rootdisp = prev_rootdisp;
2860 prev_rootdisp = sys_rootdisp;
2861 if (dtemp > sys_mindisp)
2862 sys_rootdisp = dtemp;
2864 sys_rootdisp = sys_mindisp;
2866 sys_rootdelay = peer->delay + peer->rootdelay;
2868 p2_reftime = prev_reftime;
2869 p2_time = prev_time;
2871 prev_reftime = sys_reftime;
2872 prev_time = current_time + 64 + (rand() & 0x3f); /* 64-127 s */
2874 sys_reftime = peer->dst;
2876 DPRINTF(1, ("clock_update: at %lu sample %lu associd %d\n",
2877 current_time, peer->epoch, peer->associd));
2880 * Comes now the moment of truth. Crank the clock discipline and
2881 * see what comes out.
2883 switch (local_clock(peer, sys_offset)) {
2886 * Clock exceeds panic threshold. Life as we know it ends.
2889 #ifdef HAVE_LIBSCF_H
2891 * For Solaris enter the maintenance mode.
2893 if ((fmri = getenv("SMF_FMRI")) != NULL) {
2894 if (smf_maintain_instance(fmri, 0) < 0) {
2895 printf("smf_maintain_instance: %s\n",
2896 scf_strerror(scf_error()));
2900 * Sleep until SMF kills us.
2905 #endif /* HAVE_LIBSCF_H */
2910 * Clock was stepped. Flush all time values of all peers.
2914 set_sys_leap(LEAP_NOTINSYNC);
2915 sys_stratum = STRATUM_UNSPEC;
2916 memcpy(&sys_refid, "STEP", 4);
2921 L_CLR(&p2_reftime); /* Should we clear p2_reftime? */
2922 L_CLR(&prev_reftime); /* Should we clear prev_reftime? */
2923 L_CLR(&sys_reftime);
2924 sys_jitter = LOGTOD(sys_precision);
2925 leapsec_reset_frame();
2929 * Clock was slewed. Handle the leapsecond stuff.
2934 * If this is the first time the clock is set, reset the
2935 * leap bits. If crypto, the timer will goose the setup
2938 if (sys_leap == LEAP_NOTINSYNC) {
2939 set_sys_leap(LEAP_NOWARNING);
2943 #endif /* AUTOKEY */
2945 * If our parent process is waiting for the
2946 * first clock sync, send them home satisfied.
2948 #ifdef HAVE_WORKING_FORK
2949 if (daemon_pipe[1] != -1) {
2950 write(daemon_pipe[1], "S\n", 2);
2951 close(daemon_pipe[1]);
2952 daemon_pipe[1] = -1;
2953 DPRINTF(1, ("notified parent --wait-sync is done\n"));
2955 #endif /* HAVE_WORKING_FORK */
2960 * If there is no leap second pending and the number of
2961 * survivor leap bits is greater than half the number of
2962 * survivors, try to schedule a leap for the end of the
2963 * current month. (This only works if no leap second for
2964 * that range is in the table, so doing this more than
2965 * once is mostly harmless.)
2967 if (leapsec == LSPROX_NOWARN) {
2968 if ( leap_vote_ins > leap_vote_del
2969 && leap_vote_ins > sys_survivors / 2) {
2971 leapsec_add_dyn(TRUE, now.l_ui, NULL);
2973 if ( leap_vote_del > leap_vote_ins
2974 && leap_vote_del > sys_survivors / 2) {
2976 leapsec_add_dyn(FALSE, now.l_ui, NULL);
2982 * Popcorn spike or step threshold exceeded. Pretend it never
2992 * poll_update - update peer poll interval
2996 struct peer *peer, /* peer structure pointer */
3001 u_long next, utemp, limit;
3005 * This routine figures out when the next poll should be sent.
3006 * That turns out to be wickedly complicated. One problem is
3007 * that sometimes the time for the next poll is in the past when
3008 * the poll interval is reduced. We watch out for races here
3009 * between the receive process and the poll process.
3011 * Clamp the poll interval between minpoll and maxpoll.
3013 hpoll = max(min(peer->maxpoll, mpoll), peer->minpoll);
3017 * If during the crypto protocol the poll interval has changed,
3018 * the lifetimes in the key list are probably bogus. Purge the
3019 * the key list and regenerate it later.
3021 if ((peer->flags & FLAG_SKEY) && hpoll != peer->hpoll)
3023 #endif /* AUTOKEY */
3024 peer->hpoll = hpoll;
3027 * There are three variables important for poll scheduling, the
3028 * current time (current_time), next scheduled time (nextdate)
3029 * and the earliest time (utemp). The earliest time is 2 s
3030 * seconds, but could be more due to rate management. When
3031 * sending in a burst, use the earliest time. When not in a
3032 * burst but with a reply pending, send at the earliest time
3033 * unless the next scheduled time has not advanced. This can
3034 * only happen if multiple replies are pending in the same
3035 * response interval. Otherwise, send at the later of the next
3036 * scheduled time and the earliest time.
3038 * Now we figure out if there is an override. If a burst is in
3039 * progress and we get called from the receive process, just
3040 * slink away. If called from the poll process, delay 1 s for a
3041 * reference clock, otherwise 2 s.
3043 utemp = current_time + max(peer->throttle - (NTP_SHIFT - 1) *
3044 (1 << peer->minpoll), ntp_minpkt);
3046 /*[Bug 3592] avoid unlimited postpone of next poll */
3047 limit = (2u << hpoll);
3049 limit -= (limit >> 2);
3050 limit += peer->outdate;
3051 if (limit < current_time)
3052 limit = current_time;
3054 if (peer->burst > 0) {
3055 if (peer->nextdate > current_time)
3058 else if (peer->flags & FLAG_REFCLOCK)
3059 peer->nextdate = current_time + RESP_DELAY;
3060 #endif /* REFCLOCK */
3062 peer->nextdate = utemp;
3066 * If a burst is not in progress and a crypto response message
3067 * is pending, delay 2 s, but only if this is a new interval.
3069 } else if (peer->cmmd != NULL) {
3070 if (peer->nextdate > current_time) {
3071 if (peer->nextdate + ntp_minpkt != utemp)
3072 peer->nextdate = utemp;
3074 peer->nextdate = utemp;
3076 #endif /* AUTOKEY */
3079 * The ordinary case. If a retry, use minpoll; if unreachable,
3080 * use host poll; otherwise, use the minimum of host and peer
3081 * polls; In other words, oversampling is okay but
3082 * understampling is evil. Use the maximum of this value and the
3083 * headway. If the average headway is greater than the headway
3084 * threshold, increase the headway by the minimum interval.
3087 if (peer->retry > 0)
3088 hpoll = peer->minpoll;
3090 hpoll = min(peer->ppoll, peer->hpoll);
3092 if (peer->flags & FLAG_REFCLOCK)
3095 #endif /* REFCLOCK */
3096 next = ((0x1000UL | (ntp_random() & 0x0ff)) <<
3098 next += peer->outdate;
3099 /* XXX: bug3596: Deal with poll skew list? */
3103 if (0 == get_pollskew(hpoll, &psi)) {
3112 val = ntp_random() & msk;
3113 } while (val > qty);
3119 /* get_pollskew() already logged this */
3123 peer->nextdate = next;
3125 peer->nextdate = utemp;
3126 if (peer->throttle > (1 << peer->minpoll))
3127 peer->nextdate += ntp_minpkt;
3130 /*[Bug 3592] avoid unlimited postpone of next poll */
3131 if (peer->nextdate > limit) {
3132 DPRINTF(1, ("poll_update: clamp reached; limit %lu next %lu\n",
3133 limit, peer->nextdate));
3134 peer->nextdate = limit;
3136 DPRINTF(2, ("poll_update: at %lu %s poll %d burst %d retry %d head %d early %lu next %lu\n",
3137 current_time, ntoa(&peer->srcadr), peer->hpoll,
3138 peer->burst, peer->retry, peer->throttle,
3139 utemp - current_time, peer->nextdate -
3145 * peer_clear - clear peer filter registers. See Section 3.4.8 of the
3150 struct peer *peer, /* peer structure */
3151 const char *ident /* tally lights */
3155 l_fp bxmt = peer->bxmt; /* bcast clients retain this! */
3159 * If cryptographic credentials have been acquired, toss them to
3160 * Valhalla. Note that autokeys are ephemeral, in that they are
3161 * tossed immediately upon use. Therefore, the keylist can be
3162 * purged anytime without needing to preserve random keys. Note
3163 * that, if the peer is purged, the cryptographic variables are
3164 * purged, too. This makes it much harder to sneak in some
3165 * unauthenticated data in the clock filter.
3168 if (peer->iffval != NULL)
3169 BN_free(peer->iffval);
3170 value_free(&peer->cookval);
3171 value_free(&peer->recval);
3172 value_free(&peer->encrypt);
3173 value_free(&peer->sndval);
3174 if (peer->cmmd != NULL)
3176 if (peer->subject != NULL)
3177 free(peer->subject);
3178 if (peer->issuer != NULL)
3180 #endif /* AUTOKEY */
3183 * Clear all values, including the optional crypto values above.
3185 memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO(peer));
3186 peer->ppoll = peer->maxpoll;
3187 peer->hpoll = peer->minpoll;
3188 peer->disp = MAXDISPERSE;
3189 peer->flash = peer_unfit(peer);
3190 peer->jitter = LOGTOD(sys_precision);
3192 /* Don't throw away our broadcast replay protection */
3193 if (peer->hmode == MODE_BCLIENT)
3197 * If interleave mode, initialize the alternate origin switch.
3199 if (peer->flags & FLAG_XLEAVE)
3201 for (u = 0; u < NTP_SHIFT; u++) {
3202 peer->filter_order[u] = u;
3203 peer->filter_disp[u] = MAXDISPERSE;
3206 if (!(peer->flags & FLAG_REFCLOCK)) {
3208 peer->leap = LEAP_NOTINSYNC;
3209 peer->stratum = STRATUM_UNSPEC;
3210 memcpy(&peer->refid, ident, 4);
3213 /* Clear refclock sample filter */
3214 peer->procptr->codeproc = 0;
3215 peer->procptr->coderecv = 0;
3220 * During initialization use the association count to spread out
3221 * the polls at one-second intervals. Passive associations'
3222 * first poll is delayed by the "discard minimum" to avoid rate
3223 * limiting. Other post-startup new or cleared associations
3224 * randomize the first poll over the minimum poll interval to
3227 peer->nextdate = peer->update = peer->outdate = current_time;
3229 peer->nextdate += peer_associations;
3230 } else if (MODE_PASSIVE == peer->hmode) {
3231 peer->nextdate += ntp_minpkt;
3233 peer->nextdate += ntp_random() % peer->minpoll;
3236 peer->refresh = current_time + (1 << NTP_REFRESH);
3237 #endif /* AUTOKEY */
3238 DPRINTF(1, ("peer_clear: at %ld next %ld associd %d refid %s\n",
3239 current_time, peer->nextdate, peer->associd,
3245 * clock_filter - add incoming clock sample to filter register and run
3246 * the filter procedure to find the best sample.
3250 struct peer *peer, /* peer structure pointer */
3251 double sample_offset, /* clock offset */
3252 double sample_delay, /* roundtrip delay */
3253 double sample_disp /* dispersion */
3256 double dst[NTP_SHIFT]; /* distance vector */
3257 int ord[NTP_SHIFT]; /* index vector */
3259 double dtemp, etemp;
3263 * A sample consists of the offset, delay, dispersion and epoch
3264 * of arrival. The offset and delay are determined by the on-
3265 * wire protocol. The dispersion grows from the last outbound
3266 * packet to the arrival of this one increased by the sum of the
3267 * peer precision and the system precision as required by the
3268 * error budget. First, shift the new arrival into the shift
3269 * register discarding the oldest one.
3271 j = peer->filter_nextpt;
3272 peer->filter_offset[j] = sample_offset;
3273 peer->filter_delay[j] = sample_delay;
3274 peer->filter_disp[j] = sample_disp;
3275 peer->filter_epoch[j] = current_time;
3276 j = (j + 1) % NTP_SHIFT;
3277 peer->filter_nextpt = j;
3280 * Update dispersions since the last update and at the same
3281 * time initialize the distance and index lists. Since samples
3282 * become increasingly uncorrelated beyond the Allan intercept,
3283 * only under exceptional cases will an older sample be used.
3284 * Therefore, the distance list uses a compound metric. If the
3285 * dispersion is greater than the maximum dispersion, clamp the
3286 * distance at that value. If the time since the last update is
3287 * less than the Allan intercept use the delay; otherwise, use
3288 * the sum of the delay and dispersion.
3290 dtemp = clock_phi * (current_time - peer->update);
3291 peer->update = current_time;
3292 for (i = NTP_SHIFT - 1; i >= 0; i--) {
3294 peer->filter_disp[j] += dtemp;
3295 if (peer->filter_disp[j] >= MAXDISPERSE) {
3296 peer->filter_disp[j] = MAXDISPERSE;
3297 dst[i] = MAXDISPERSE;
3298 } else if (peer->update - peer->filter_epoch[j] >
3299 (u_long)ULOGTOD(allan_xpt)) {
3300 dst[i] = peer->filter_delay[j] +
3301 peer->filter_disp[j];
3303 dst[i] = peer->filter_delay[j];
3306 j = (j + 1) % NTP_SHIFT;
3310 * If the clock has stabilized, sort the samples by distance.
3312 if (freq_cnt == 0) {
3313 for (i = 1; i < NTP_SHIFT; i++) {
3314 for (j = 0; j < i; j++) {
3315 if (dst[j] > dst[i]) {
3328 * Copy the index list to the association structure so ntpq
3329 * can see it later. Prune the distance list to leave only
3330 * samples less than the maximum dispersion, which disfavors
3331 * uncorrelated samples older than the Allan intercept. To
3332 * further improve the jitter estimate, of the remainder leave
3333 * only samples less than the maximum distance, but keep at
3334 * least two samples for jitter calculation.
3337 for (i = 0; i < NTP_SHIFT; i++) {
3338 peer->filter_order[i] = (u_char) ord[i];
3339 if ( dst[i] >= MAXDISPERSE
3340 || (m >= 2 && dst[i] >= sys_maxdist))
3346 * Compute the dispersion and jitter. The dispersion is weighted
3347 * exponentially by NTP_FWEIGHT (0.5) so it is normalized close
3348 * to 1.0. The jitter is the RMS differences relative to the
3349 * lowest delay sample.
3351 peer->disp = peer->jitter = 0;
3353 for (i = NTP_SHIFT - 1; i >= 0; i--) {
3355 peer->disp = NTP_FWEIGHT * (peer->disp +
3356 peer->filter_disp[j]);
3358 peer->jitter += DIFF(peer->filter_offset[j],
3359 peer->filter_offset[k]);
3363 * If no acceptable samples remain in the shift register,
3364 * quietly tiptoe home leaving only the dispersion. Otherwise,
3365 * save the offset, delay and jitter. Note the jitter must not
3366 * be less than the precision.
3372 etemp = fabs(peer->offset - peer->filter_offset[k]);
3373 peer->offset = peer->filter_offset[k];
3374 peer->delay = peer->filter_delay[k];
3376 peer->jitter /= m - 1;
3377 peer->jitter = max(SQRT(peer->jitter), LOGTOD(sys_precision));
3380 * If the the new sample and the current sample are both valid
3381 * and the difference between their offsets exceeds CLOCK_SGATE
3382 * (3) times the jitter and the interval between them is less
3383 * than twice the host poll interval, consider the new sample
3384 * a popcorn spike and ignore it.
3386 if ( peer->disp < sys_maxdist
3387 && peer->filter_disp[k] < sys_maxdist
3388 && etemp > CLOCK_SGATE * peer->jitter
3389 && peer->filter_epoch[k] - peer->epoch
3390 < 2. * ULOGTOD(peer->hpoll)) {
3391 snprintf(tbuf, sizeof(tbuf), "%.6f s", etemp);
3392 report_event(PEVNT_POPCORN, peer, tbuf);
3397 * A new minimum sample is useful only if it is later than the
3398 * last one used. In this design the maximum lifetime of any
3399 * sample is not greater than eight times the poll interval, so
3400 * the maximum interval between minimum samples is eight
3403 if (peer->filter_epoch[k] <= peer->epoch) {
3404 DPRINTF(2, ("clock_filter: old sample %lu\n", current_time -
3405 peer->filter_epoch[k]));
3408 peer->epoch = peer->filter_epoch[k];
3411 * The mitigated sample statistics are saved for later
3412 * processing. If not synchronized or not in a burst, tickle the
3413 * clock select algorithm.
3415 record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
3416 peer->offset, peer->delay, peer->disp, peer->jitter);
3417 DPRINTF(1, ("clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f\n",
3418 m, peer->offset, peer->delay, peer->disp,
3420 if (peer->burst == 0 || sys_leap == LEAP_NOTINSYNC)
3426 * clock_select - find the pick-of-the-litter clock
3428 * LOCKCLOCK: (1) If the local clock is the prefer peer, it will always
3429 * be enabled, even if declared falseticker, (2) only the prefer peer
3430 * can be selected as the system peer, (3) if the external source is
3431 * down, the system leap bits are set to 11 and the stratum set to
3445 double lastresort_dist = MAXDISPERSE;
3446 double orphmet = 2.0 * U_INT32_MAX; /* 2x is greater than */
3447 struct endpoint endp;
3448 struct peer *osys_peer;
3449 struct peer *sys_prefer = NULL; /* prefer peer */
3450 struct peer *typesystem = NULL;
3451 struct peer *typelastresort = NULL;
3452 struct peer *typeorphan = NULL;
3454 struct peer *typeacts = NULL;
3455 struct peer *typelocal = NULL;
3456 struct peer *typepps = NULL;
3457 #endif /* REFCLOCK */
3458 static struct endpoint *endpoint = NULL;
3459 static int *indx = NULL;
3460 static peer_select *peers = NULL;
3461 static u_int endpoint_size = 0;
3462 static u_int peers_size = 0;
3463 static u_int indx_size = 0;
3467 * Initialize and create endpoint, index and peer lists big
3468 * enough to handle all associations.
3470 osys_peer = sys_peer;
3473 set_sys_leap(LEAP_NOTINSYNC);
3474 sys_stratum = STRATUM_UNSPEC;
3475 memcpy(&sys_refid, "DOWN", 4);
3476 #endif /* LOCKCLOCK */
3479 * Allocate dynamic space depending on the number of
3483 for (peer = peer_list; peer != NULL; peer = peer->p_link)
3485 endpoint_size = ALIGNED_SIZE(nlist * 2 * sizeof(*endpoint));
3486 peers_size = ALIGNED_SIZE(nlist * sizeof(*peers));
3487 indx_size = ALIGNED_SIZE(nlist * 2 * sizeof(*indx));
3488 octets = endpoint_size + peers_size + indx_size;
3489 endpoint = erealloc(endpoint, octets);
3490 peers = INC_ALIGNED_PTR(endpoint, endpoint_size);
3491 indx = INC_ALIGNED_PTR(peers, peers_size);
3494 * Initially, we populate the island with all the rifraff peers
3495 * that happen to be lying around. Those with seriously
3496 * defective clocks are immediately booted off the island. Then,
3497 * the falsetickers are culled and put to sea. The truechimers
3498 * remaining are subject to repeated rounds where the most
3499 * unpopular at each round is kicked off. When the population
3500 * has dwindled to sys_minclock, the survivors split a million
3501 * bucks and collectively crank the chimes.
3503 nlist = nl2 = 0; /* none yet */
3504 for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3505 peer->new_status = CTL_PST_SEL_REJECT;
3508 * Leave the island immediately if the peer is
3509 * unfit to synchronize.
3511 if (peer_unfit(peer)) {
3516 * If we have never been synchronised, look for any peer
3517 * which has ever been synchronised and pick the one which
3518 * has the lowest root distance. This can be used as a last
3519 * resort if all else fails. Once we get an initial sync
3520 * with this peer, sys_reftime gets set and so this
3521 * function becomes disabled.
3523 if (L_ISZERO(&sys_reftime)) {
3524 d = root_distance(peer);
3525 if (!L_ISZERO(&peer->reftime) && d < lastresort_dist) {
3526 typelastresort = peer;
3527 lastresort_dist = d;
3532 * If this peer is an orphan parent, elect the
3533 * one with the lowest metric defined as the
3534 * IPv4 address or the first 64 bits of the
3535 * hashed IPv6 address. To ensure convergence
3536 * on the same selected orphan, consider as
3537 * well that this system may have the lowest
3538 * metric and be the orphan parent. If this
3539 * system wins, sys_peer will be NULL to trigger
3540 * orphan mode in timer().
3542 if (peer->stratum == sys_orphan) {
3546 if (peer->dstadr != NULL)
3547 localmet = ntohl(peer->dstadr->addr_refid);
3549 localmet = U_INT32_MAX;
3550 peermet = ntohl(addr2refid(&peer->srcadr));
3551 if (peermet < localmet && peermet < orphmet) {
3559 * If this peer could have the orphan parent
3560 * as a synchronization ancestor, exclude it
3561 * from selection to avoid forming a
3562 * synchronization loop within the orphan mesh,
3563 * triggering stratum climb to infinity
3564 * instability. Peers at stratum higher than
3565 * the orphan stratum could have the orphan
3566 * parent in ancestry so are excluded.
3567 * See http://bugs.ntp.org/2050
3569 if (peer->stratum > sys_orphan) {
3574 * The following are special cases. We deal
3577 if (!(peer->flags & FLAG_PREFER)) {
3578 switch (peer->refclktype) {
3579 case REFCLK_LOCALCLOCK:
3580 if ( current_time > orphwait
3581 && typelocal == NULL)
3586 if ( current_time > orphwait
3587 && typeacts == NULL)
3592 #endif /* REFCLOCK */
3595 * If we get this far, the peer can stay on the
3596 * island, but does not yet have the immunity
3599 peer->new_status = CTL_PST_SEL_SANE;
3600 f = root_distance(peer);
3601 peers[nlist].peer = peer;
3602 peers[nlist].error = peer->jitter;
3603 peers[nlist].synch = f;
3607 * Insert each interval endpoint on the unsorted
3611 endpoint[nl2].type = -1; /* lower end */
3612 endpoint[nl2].val = e - f;
3614 endpoint[nl2].type = 1; /* upper end */
3615 endpoint[nl2].val = e + f;
3619 * Construct sorted indx[] of endpoint[] indexes ordered by
3622 for (i = 0; i < nl2; i++)
3624 for (i = 0; i < nl2; i++) {
3625 endp = endpoint[indx[i]];
3628 for (j = i + 1; j < nl2; j++) {
3629 endp = endpoint[indx[j]];
3641 for (i = 0; i < nl2; i++)
3642 DPRINTF(3, ("select: endpoint %2d %.6f\n",
3643 endpoint[indx[i]].type, endpoint[indx[i]].val));
3646 * This is the actual algorithm that cleaves the truechimers
3647 * from the falsetickers. The original algorithm was described
3648 * in Keith Marzullo's dissertation, but has been modified for
3651 * Briefly put, we first assume there are no falsetickers, then
3652 * scan the candidate list first from the low end upwards and
3653 * then from the high end downwards. The scans stop when the
3654 * number of intersections equals the number of candidates less
3655 * the number of falsetickers. If this doesn't happen for a
3656 * given number of falsetickers, we bump the number of
3657 * falsetickers and try again. If the number of falsetickers
3658 * becomes equal to or greater than half the number of
3659 * candidates, the Albanians have won the Byzantine wars and
3660 * correct synchronization is not possible.
3662 * Here, nlist is the number of candidates and allow is the
3663 * number of falsetickers. Upon exit, the truechimers are the
3664 * survivors with offsets not less than low and not greater than
3665 * high. There may be none of them.
3669 for (allow = 0; 2 * allow < nlist; allow++) {
3672 * Bound the interval (low, high) as the smallest
3673 * interval containing points from the most sources.
3676 for (i = 0; i < nl2; i++) {
3677 low = endpoint[indx[i]].val;
3678 n -= endpoint[indx[i]].type;
3679 if (n >= nlist - allow)
3683 for (j = nl2 - 1; j >= 0; j--) {
3684 high = endpoint[indx[j]].val;
3685 n += endpoint[indx[j]].type;
3686 if (n >= nlist - allow)
3691 * If an interval containing truechimers is found, stop.
3692 * If not, increase the number of falsetickers and go
3700 * Clustering algorithm. Whittle candidate list of falsetickers,
3701 * who leave the island immediately. The TRUE peer is always a
3702 * truechimer. We must leave at least one peer to collect the
3705 * We assert the correct time is contained in the interval, but
3706 * the best offset estimate for the interval might not be
3707 * contained in the interval. For this purpose, a truechimer is
3708 * defined as the midpoint of an interval that overlaps the
3709 * intersection interval.
3712 for (i = 0; i < nlist; i++) {
3715 peer = peers[i].peer;
3718 || peer->offset + h < low
3719 || peer->offset - h > high
3720 ) && !(peer->flags & FLAG_TRUE))
3725 * Eligible PPS peers must survive the intersection
3726 * algorithm. Use the first one found, but don't
3727 * include any of them in the cluster population.
3729 if (peer->flags & FLAG_PPS) {
3730 if (typepps == NULL)
3732 if (!(peer->flags & FLAG_TSTAMP_PPS))
3735 #endif /* REFCLOCK */
3738 peers[j] = peers[i];
3744 * If no survivors remain at this point, check if the modem
3745 * driver, local driver or orphan parent in that order. If so,
3746 * nominate the first one found as the only survivor.
3747 * Otherwise, give up and leave the island to the rats.
3751 peers[0].synch = sys_mindisp;
3753 if (typeacts != NULL) {
3754 peers[0].peer = typeacts;
3756 } else if (typelocal != NULL) {
3757 peers[0].peer = typelocal;
3760 #endif /* REFCLOCK */
3761 if (typeorphan != NULL) {
3762 peers[0].peer = typeorphan;
3764 } else if (typelastresort != NULL) {
3765 peers[0].peer = typelastresort;
3771 * Mark the candidates at this point as truechimers.
3773 for (i = 0; i < nlist; i++) {
3774 peers[i].peer->new_status = CTL_PST_SEL_SELCAND;
3775 DPRINTF(2, ("select: survivor %s %f\n",
3776 stoa(&peers[i].peer->srcadr), peers[i].synch));
3780 * Now, vote outliers off the island by select jitter weighted
3781 * by root distance. Continue voting as long as there are more
3782 * than sys_minclock survivors and the select jitter of the peer
3783 * with the worst metric is greater than the minimum peer
3784 * jitter. Stop if we are about to discard a TRUE or PREFER
3785 * peer, who of course have the immunity idol.
3792 for (i = 0; i < nlist; i++) {
3793 if (peers[i].error < d)
3795 peers[i].seljit = 0;
3798 for (j = 0; j < nlist; j++)
3799 f += DIFF(peers[j].peer->offset,
3800 peers[i].peer->offset);
3801 peers[i].seljit = SQRT(f / (nlist - 1));
3803 if (peers[i].seljit * peers[i].synch > e) {
3804 g = peers[i].seljit;
3805 e = peers[i].seljit * peers[i].synch;
3809 g = max(g, LOGTOD(sys_precision));
3810 if ( nlist <= max(1, sys_minclock)
3812 || ((FLAG_TRUE | FLAG_PREFER) & peers[k].peer->flags))
3815 DPRINTF(3, ("select: drop %s seljit %.6f jit %.6f\n",
3816 ntoa(&peers[k].peer->srcadr), g, d));
3817 if (nlist > sys_maxclock)
3818 peers[k].peer->new_status = CTL_PST_SEL_EXCESS;
3819 for (j = k + 1; j < nlist; j++)
3820 peers[j - 1] = peers[j];
3825 * What remains is a list usually not greater than sys_minclock
3826 * peers. Note that unsynchronized peers cannot survive this
3827 * far. Count and mark these survivors.
3829 * While at it, count the number of leap warning bits found.
3830 * This will be used later to vote the system leap warning bit.
3831 * If a leap warning bit is found on a reference clock, the vote
3834 * Choose the system peer using a hybrid metric composed of the
3835 * selection jitter scaled by the root distance augmented by
3836 * stratum scaled by sys_mindisp (.001 by default). The goal of
3837 * the small stratum factor is to avoid clockhop between a
3838 * reference clock and a network peer which has a refclock and
3839 * is using an older ntpd, which does not floor sys_rootdisp at
3842 * In contrast, ntpd 4.2.6 and earlier used stratum primarily
3843 * in selecting the system peer, using a weight of 1 second of
3844 * additional root distance per stratum. This heavy bias is no
3845 * longer appropriate, as the scaled root distance provides a
3846 * more rational metric carrying the cumulative error budget.
3852 for (i = 0; i < nlist; i++) {
3853 peer = peers[i].peer;
3855 peer->new_status = CTL_PST_SEL_SYNCCAND;
3857 if (peer->leap == LEAP_ADDSECOND) {
3858 if (peer->flags & FLAG_REFCLOCK)
3859 leap_vote_ins = nlist;
3860 else if (leap_vote_ins < nlist)
3863 if (peer->leap == LEAP_DELSECOND) {
3864 if (peer->flags & FLAG_REFCLOCK)
3865 leap_vote_del = nlist;
3866 else if (leap_vote_del < nlist)
3869 if (peer->flags & FLAG_PREFER)
3871 speermet = peers[i].seljit * peers[i].synch +
3872 peer->stratum * sys_mindisp;
3880 * Unless there are at least sys_misane survivors, leave the
3881 * building dark. Otherwise, do a clockhop dance. Ordinarily,
3882 * use the selected survivor speer. However, if the current
3883 * system peer is not speer, stay with the current system peer
3884 * as long as it doesn't get too old or too ugly.
3886 if (nlist > 0 && nlist >= sys_minsane) {
3889 typesystem = peers[speer].peer;
3890 if (osys_peer == NULL || osys_peer == typesystem) {
3892 } else if ((x = fabs(typesystem->offset -
3893 osys_peer->offset)) < sys_mindisp) {
3894 if (sys_clockhop == 0)
3895 sys_clockhop = sys_mindisp;
3898 DPRINTF(1, ("select: clockhop %d %.6f %.6f\n",
3899 j, x, sys_clockhop));
3900 if (fabs(x) < sys_clockhop)
3901 typesystem = osys_peer;
3910 * Mitigation rules of the game. We have the pick of the
3911 * litter in typesystem if any survivors are left. If
3912 * there is a prefer peer, use its offset and jitter.
3913 * Otherwise, use the combined offset and jitter of all kitters.
3915 if (typesystem != NULL) {
3916 if (sys_prefer == NULL) {
3917 typesystem->new_status = CTL_PST_SEL_SYSPEER;
3918 clock_combine(peers, sys_survivors, speer);
3920 typesystem = sys_prefer;
3922 typesystem->new_status = CTL_PST_SEL_SYSPEER;
3923 sys_offset = typesystem->offset;
3924 sys_jitter = typesystem->jitter;
3926 DPRINTF(1, ("select: combine offset %.9f jitter %.9f\n",
3927 sys_offset, sys_jitter));
3931 * If a PPS driver is lit and the combined offset is less than
3932 * 0.4 s, select the driver as the PPS peer and use its offset
3933 * and jitter. However, if this is the atom driver, use it only
3934 * if there is a prefer peer or there are no survivors and none
3937 if ( typepps != NULL
3938 && fabs(sys_offset) < 0.4
3939 && ( typepps->refclktype != REFCLK_ATOM_PPS
3940 || ( typepps->refclktype == REFCLK_ATOM_PPS
3941 && ( sys_prefer != NULL
3942 || (typesystem == NULL && sys_minsane == 0))))) {
3943 typesystem = typepps;
3945 typesystem->new_status = CTL_PST_SEL_PPS;
3946 sys_offset = typesystem->offset;
3947 sys_jitter = typesystem->jitter;
3948 DPRINTF(1, ("select: pps offset %.9f jitter %.9f\n",
3949 sys_offset, sys_jitter));
3951 #endif /* REFCLOCK */
3954 * If there are no survivors at this point, there is no
3955 * system peer. If so and this is an old update, keep the
3956 * current statistics, but do not update the clock.
3958 if (typesystem == NULL) {
3959 if (osys_peer != NULL) {
3960 orphwait = current_time + sys_orphwait;
3961 report_event(EVNT_NOPEER, NULL, NULL);
3964 for (peer = peer_list; peer != NULL; peer = peer->p_link)
3965 peer->status = peer->new_status;
3970 * Do not use old data, as this may mess up the clock discipline
3973 if (typesystem->epoch <= sys_epoch)
3977 * We have found the alpha male. Wind the clock.
3979 if (osys_peer != typesystem)
3980 report_event(PEVNT_NEWPEER, typesystem, NULL);
3981 for (peer = peer_list; peer != NULL; peer = peer->p_link)
3982 peer->status = peer->new_status;
3983 clock_update(typesystem);
3989 peer_select * peers, /* survivor list */
3990 int npeers, /* number of survivors */
3991 int syspeer /* index of sys.peer */
3998 for (i = 0; i < npeers; i++) {
3999 x = 1. / peers[i].synch;
4001 z += x * peers[i].peer->offset;
4002 w += x * DIFF(peers[i].peer->offset,
4003 peers[syspeer].peer->offset);
4006 sys_jitter = SQRT(w / y + SQUARE(peers[syspeer].seljit));
4011 * root_distance - compute synchronization distance from peer to root
4015 struct peer *peer /* peer structure pointer */
4021 * Root Distance (LAMBDA) is defined as:
4022 * (delta + DELTA)/2 + epsilon + EPSILON + D
4025 * delta is the round-trip delay
4026 * DELTA is the root delay
4027 * epsilon is the peer dispersion
4028 * + (15 usec each second)
4029 * EPSILON is the root dispersion
4032 * NB: Think hard about why we are using these values, and what
4033 * the alternatives are, and the various pros/cons.
4035 * DLM thinks these are probably the best choices from any of the
4036 * other worse choices.
4038 dtemp = (peer->delay + peer->rootdelay) / 2
4040 + clock_phi * (current_time - peer->update)
4044 * Careful squeak here. The value returned must be greater than
4045 * the minimum root dispersion in order to avoid clockhop with
4046 * highly precise reference clocks. Note that the root distance
4047 * cannot exceed the sys_maxdist, as this is the cutoff by the
4048 * selection algorithm.
4050 if (dtemp < sys_mindisp)
4051 dtemp = sys_mindisp;
4057 * peer_xmit - send packet for persistent association.
4061 struct peer *peer /* peer structure pointer */
4064 struct pkt xpkt; /* transmit packet */
4065 size_t sendlen, authlen;
4066 keyid_t xkeyid = 0; /* transmit key ID */
4067 l_fp xmt_tx, xmt_ty;
4069 if (!peer->dstadr) /* drop peers without interface */
4072 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
4074 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4075 xpkt.ppoll = peer->hpoll;
4076 xpkt.precision = sys_precision;
4077 xpkt.refid = sys_refid;
4078 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4079 xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
4080 /* Use sys_reftime for peer exchanges */
4081 HTONL_FP(&sys_reftime, &xpkt.reftime);
4082 HTONL_FP(&peer->rec, &xpkt.org);
4083 HTONL_FP(&peer->dst, &xpkt.rec);
4086 * If the received packet contains a MAC, the transmitted packet
4087 * is authenticated and contains a MAC. If not, the transmitted
4088 * packet is not authenticated.
4090 * It is most important when autokey is in use that the local
4091 * interface IP address be known before the first packet is
4092 * sent. Otherwise, it is not possible to compute a correct MAC
4093 * the recipient will accept. Thus, the I/O semantics have to do
4094 * a little more work. In particular, the wildcard interface
4095 * might not be usable.
4097 sendlen = LEN_PKT_NOMAC;
4100 !(peer->flags & FLAG_SKEY) &&
4101 #endif /* !AUTOKEY */
4105 * Transmit a-priori timestamps
4107 get_systime(&xmt_tx);
4108 if (peer->flip == 0) { /* basic mode */
4109 peer->aorg = xmt_tx;
4110 HTONL_FP(&xmt_tx, &xpkt.xmt);
4111 } else { /* interleaved modes */
4112 if (peer->hmode == MODE_BROADCAST) { /* bcst */
4113 HTONL_FP(&xmt_tx, &xpkt.xmt);
4115 HTONL_FP(&peer->borg,
4118 HTONL_FP(&peer->aorg,
4120 } else { /* symmetric */
4122 HTONL_FP(&peer->borg,
4125 HTONL_FP(&peer->aorg,
4129 peer->t21_bytes = sendlen;
4130 sendpkt(&peer->srcadr, peer->dstadr,
4131 sys_ttl[(peer->ttl >= sys_ttlmax) ? sys_ttlmax : peer->ttl],
4134 peer->throttle += (1 << peer->minpoll) - 2;
4137 * Capture a-posteriori timestamps
4139 get_systime(&xmt_ty);
4140 if (peer->flip != 0) { /* interleaved modes */
4142 peer->aorg = xmt_ty;
4144 peer->borg = xmt_ty;
4145 peer->flip = -peer->flip;
4147 L_SUB(&xmt_ty, &xmt_tx);
4148 LFPTOD(&xmt_ty, peer->xleave);
4149 DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d len %zu xmt %#010x.%08x\n",
4151 peer->dstadr ? stoa(&peer->dstadr->sin) : "-",
4152 stoa(&peer->srcadr), peer->hmode, sendlen,
4153 xmt_tx.l_ui, xmt_tx.l_uf));
4158 * Authentication is enabled, so the transmitted packet must be
4159 * authenticated. If autokey is enabled, fuss with the various
4160 * modes; otherwise, symmetric key cryptography is used.
4163 if (peer->flags & FLAG_SKEY) {
4164 struct exten *exten; /* extension field */
4167 * The Public Key Dance (PKD): Cryptographic credentials
4168 * are contained in extension fields, each including a
4169 * 4-octet length/code word followed by a 4-octet
4170 * association ID and optional additional data. Optional
4171 * data includes a 4-octet data length field followed by
4172 * the data itself. Request messages are sent from a
4173 * configured association; response messages can be sent
4174 * from a configured association or can take the fast
4175 * path without ever matching an association. Response
4176 * messages have the same code as the request, but have
4177 * a response bit and possibly an error bit set. In this
4178 * implementation, a message may contain no more than
4179 * one command and one or more responses.
4181 * Cryptographic session keys include both a public and
4182 * a private componet. Request and response messages
4183 * using extension fields are always sent with the
4184 * private component set to zero. Packets without
4185 * extension fields indlude the private component when
4186 * the session key is generated.
4191 * Allocate and initialize a keylist if not
4192 * already done. Then, use the list in inverse
4193 * order, discarding keys once used. Keep the
4194 * latest key around until the next one, so
4195 * clients can use client/server packets to
4196 * compute propagation delay.
4198 * Note that once a key is used from the list,
4199 * it is retained in the key cache until the
4200 * next key is used. This is to allow a client
4201 * to retrieve the encrypted session key
4202 * identifier to verify authenticity.
4204 * If for some reason a key is no longer in the
4205 * key cache, a birthday has happened or the key
4206 * has expired, so the pseudo-random sequence is
4207 * broken. In that case, purge the keylist and
4210 if (peer->keynumber == 0)
4211 make_keylist(peer, peer->dstadr);
4214 xkeyid = peer->keylist[peer->keynumber];
4215 if (authistrusted(xkeyid))
4220 peer->keyid = xkeyid;
4222 switch (peer->hmode) {
4225 * In broadcast server mode the autokey values are
4226 * required by the broadcast clients. Push them when a
4227 * new keylist is generated; otherwise, push the
4228 * association message so the client can request them at
4231 case MODE_BROADCAST:
4232 if (peer->flags & FLAG_ASSOC)
4233 exten = crypto_args(peer, CRYPTO_AUTO |
4234 CRYPTO_RESP, peer->associd, NULL);
4236 exten = crypto_args(peer, CRYPTO_ASSOC |
4237 CRYPTO_RESP, peer->associd, NULL);
4241 * In symmetric modes the parameter, certificate,
4242 * identity, cookie and autokey exchanges are
4243 * required. The leapsecond exchange is optional. But, a
4244 * peer will not believe the other peer until the other
4245 * peer has synchronized, so the certificate exchange
4246 * might loop until then. If a peer finds a broken
4247 * autokey sequence, it uses the autokey exchange to
4248 * retrieve the autokey values. In any case, if a new
4249 * keylist is generated, the autokey values are pushed.
4255 * Parameter, certificate and identity.
4258 exten = crypto_args(peer, CRYPTO_ASSOC,
4259 peer->associd, hostval.ptr);
4260 else if (!(peer->crypto & CRYPTO_FLAG_CERT))
4261 exten = crypto_args(peer, CRYPTO_CERT,
4262 peer->associd, peer->issuer);
4263 else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
4264 exten = crypto_args(peer,
4265 crypto_ident(peer), peer->associd,
4269 * Cookie and autokey. We request the cookie
4270 * only when the this peer and the other peer
4271 * are synchronized. But, this peer needs the
4272 * autokey values when the cookie is zero. Any
4273 * time we regenerate the key list, we offer the
4274 * autokey values without being asked. If for
4275 * some reason either peer finds a broken
4276 * autokey sequence, the autokey exchange is
4277 * used to retrieve the autokey values.
4279 else if ( sys_leap != LEAP_NOTINSYNC
4280 && peer->leap != LEAP_NOTINSYNC
4281 && !(peer->crypto & CRYPTO_FLAG_COOK))
4282 exten = crypto_args(peer, CRYPTO_COOK,
4283 peer->associd, NULL);
4284 else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
4285 exten = crypto_args(peer, CRYPTO_AUTO,
4286 peer->associd, NULL);
4287 else if ( peer->flags & FLAG_ASSOC
4288 && peer->crypto & CRYPTO_FLAG_SIGN)
4289 exten = crypto_args(peer, CRYPTO_AUTO |
4290 CRYPTO_RESP, peer->assoc, NULL);
4293 * Wait for clock sync, then sign the
4294 * certificate and retrieve the leapsecond
4297 else if (sys_leap == LEAP_NOTINSYNC)
4300 else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
4301 exten = crypto_args(peer, CRYPTO_SIGN,
4302 peer->associd, hostval.ptr);
4303 else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
4304 exten = crypto_args(peer, CRYPTO_LEAP,
4305 peer->associd, NULL);
4309 * In client mode the parameter, certificate, identity,
4310 * cookie and sign exchanges are required. The
4311 * leapsecond exchange is optional. If broadcast client
4312 * mode the same exchanges are required, except that the
4313 * autokey exchange is substitutes for the cookie
4314 * exchange, since the cookie is always zero. If the
4315 * broadcast client finds a broken autokey sequence, it
4316 * uses the autokey exchange to retrieve the autokey
4322 * Parameter, certificate and identity.
4325 exten = crypto_args(peer, CRYPTO_ASSOC,
4326 peer->associd, hostval.ptr);
4327 else if (!(peer->crypto & CRYPTO_FLAG_CERT))
4328 exten = crypto_args(peer, CRYPTO_CERT,
4329 peer->associd, peer->issuer);
4330 else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
4331 exten = crypto_args(peer,
4332 crypto_ident(peer), peer->associd,
4336 * Cookie and autokey. These are requests, but
4337 * we use the peer association ID with autokey
4338 * rather than our own.
4340 else if (!(peer->crypto & CRYPTO_FLAG_COOK))
4341 exten = crypto_args(peer, CRYPTO_COOK,
4342 peer->associd, NULL);
4343 else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
4344 exten = crypto_args(peer, CRYPTO_AUTO,
4348 * Wait for clock sync, then sign the
4349 * certificate and retrieve the leapsecond
4352 else if (sys_leap == LEAP_NOTINSYNC)
4355 else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
4356 exten = crypto_args(peer, CRYPTO_SIGN,
4357 peer->associd, hostval.ptr);
4358 else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
4359 exten = crypto_args(peer, CRYPTO_LEAP,
4360 peer->associd, NULL);
4365 * Add a queued extension field if present. This is
4366 * always a request message, so the reply ID is already
4367 * in the message. If an error occurs, the error bit is
4368 * lit in the response.
4370 if (peer->cmmd != NULL) {
4373 temp32 = CRYPTO_RESP;
4374 peer->cmmd->opcode |= htonl(temp32);
4375 sendlen += crypto_xmit(peer, &xpkt, NULL,
4376 sendlen, peer->cmmd, 0);
4382 * Add an extension field created above. All but the
4383 * autokey response message are request messages.
4385 if (exten != NULL) {
4386 if (exten->opcode != 0)
4387 sendlen += crypto_xmit(peer, &xpkt,
4388 NULL, sendlen, exten, 0);
4393 * Calculate the next session key. Since extension
4394 * fields are present, the cookie value is zero.
4396 if (sendlen > (int)LEN_PKT_NOMAC) {
4397 session_key(&peer->dstadr->sin, &peer->srcadr,
4401 #endif /* AUTOKEY */
4404 * Transmit a-priori timestamps
4406 get_systime(&xmt_tx);
4407 if (peer->flip == 0) { /* basic mode */
4408 peer->aorg = xmt_tx;
4409 HTONL_FP(&xmt_tx, &xpkt.xmt);
4410 } else { /* interleaved modes */
4411 if (peer->hmode == MODE_BROADCAST) { /* bcst */
4412 HTONL_FP(&xmt_tx, &xpkt.xmt);
4414 HTONL_FP(&peer->borg, &xpkt.org);
4416 HTONL_FP(&peer->aorg, &xpkt.org);
4417 } else { /* symmetric */
4419 HTONL_FP(&peer->borg, &xpkt.xmt);
4421 HTONL_FP(&peer->aorg, &xpkt.xmt);
4424 xkeyid = peer->keyid;
4425 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
4427 report_event(PEVNT_AUTH, peer, "no key");
4428 peer->flash |= TEST5; /* auth error */
4434 if (xkeyid > NTP_MAXKEY)
4435 authtrust(xkeyid, 0);
4436 #endif /* AUTOKEY */
4437 if (sendlen > sizeof(xpkt)) {
4438 msyslog(LOG_ERR, "peer_xmit: buffer overflow %zu", sendlen);
4441 peer->t21_bytes = sendlen;
4442 sendpkt(&peer->srcadr, peer->dstadr,
4443 sys_ttl[(peer->ttl >= sys_ttlmax) ? sys_ttlmax : peer->ttl],
4446 peer->throttle += (1 << peer->minpoll) - 2;
4449 * Capture a-posteriori timestamps
4451 get_systime(&xmt_ty);
4452 if (peer->flip != 0) { /* interleaved modes */
4454 peer->aorg = xmt_ty;
4456 peer->borg = xmt_ty;
4457 peer->flip = -peer->flip;
4459 L_SUB(&xmt_ty, &xmt_tx);
4460 LFPTOD(&xmt_ty, peer->xleave);
4462 DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %zu index %d\n",
4463 current_time, latoa(peer->dstadr),
4464 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
4466 #else /* !AUTOKEY follows */
4467 DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %zu\n",
4468 current_time, peer->dstadr ?
4469 ntoa(&peer->dstadr->sin) : "-",
4470 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen));
4471 #endif /* !AUTOKEY */
4480 leap_smear_add_offs(
4486 L_ADD(t, &leap_smear.offset);
4489 ** XXX: Should the smear be added to the root dispersion?
4495 #endif /* LEAP_SMEAR */
4499 * fast_xmit - Send packet for nonpersistent association. Note that
4500 * neither the source or destination can be a broadcast address.
4504 struct recvbuf *rbufp, /* receive packet pointer */
4505 int xmode, /* receive mode */ /* XXX: HMS: really? */
4506 keyid_t xkeyid, /* transmit key ID */
4507 int flags /* restrict mask */
4510 struct pkt xpkt; /* transmit packet structure */
4511 struct pkt *rpkt; /* receive packet structure */
4512 l_fp xmt_tx, xmt_ty;
4519 * Initialize transmit packet header fields from the receive
4520 * buffer provided. We leave the fields intact as received, but
4521 * set the peer poll at the maximum of the receive peer poll and
4522 * the system minimum poll (ntp_minpoll). This is for KoD rate
4523 * control and not strictly specification compliant, but doesn't
4526 * If the gazinta was from a multicast address, the gazoutta
4527 * must go out another way.
4529 rpkt = &rbufp->recv_pkt;
4530 if (rbufp->dstadr->flags & INT_MCASTOPEN)
4531 rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
4534 * If this is a kiss-o'-death (KoD) packet, show leap
4535 * unsynchronized, stratum zero, reference ID the four-character
4536 * kiss code and (???) system root delay. Note we don't reveal
4537 * the local time, so these packets can't be used for
4540 if (flags & RES_KOD) {
4542 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
4543 PKT_VERSION(rpkt->li_vn_mode), xmode);
4544 xpkt.stratum = STRATUM_PKT_UNSPEC;
4545 xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
4546 xpkt.precision = rpkt->precision;
4547 memcpy(&xpkt.refid, "RATE", 4);
4548 xpkt.rootdelay = rpkt->rootdelay;
4549 xpkt.rootdisp = rpkt->rootdisp;
4550 xpkt.reftime = rpkt->reftime;
4551 xpkt.org = rpkt->xmt;
4552 xpkt.rec = rpkt->xmt;
4553 xpkt.xmt = rpkt->xmt;
4556 * This is a normal packet. Use the system variables.
4559 double this_rootdisp;
4564 * Make copies of the variables which can be affected by smearing.
4566 l_fp this_recv_time;
4570 * If we are inside the leap smear interval we add
4571 * the current smear offset to:
4572 * - the packet receive time,
4573 * - the packet transmit time,
4574 * - and eventually to the reftime to make sure the
4575 * reftime isn't later than the transmit/receive times.
4577 xpkt.li_vn_mode = PKT_LI_VN_MODE(xmt_leap,
4578 PKT_VERSION(rpkt->li_vn_mode), xmode);
4580 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4581 xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
4582 xpkt.precision = sys_precision;
4583 xpkt.refid = sys_refid;
4584 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4587 ** Server Response Fuzzing
4589 ** Which values do we want to use for reftime and rootdisp?
4592 if ( MODE_SERVER == xmode
4593 && RES_SRVRSPFUZ & flags) {
4594 if (current_time < p2_time) {
4595 this_ref_time = p2_reftime;
4596 this_rootdisp = p2_rootdisp;
4597 } else if (current_time < prev_time) {
4598 this_ref_time = prev_reftime;
4599 this_rootdisp = prev_rootdisp;
4601 this_ref_time = sys_reftime;
4602 this_rootdisp = sys_rootdisp;
4605 SRVRSP_FUZZ(this_ref_time);
4607 this_ref_time = sys_reftime;
4608 this_rootdisp = sys_rootdisp;
4615 xpkt.rootdisp = HTONS_FP(DTOUFP(this_rootdisp));
4622 if (leap_smear.in_progress) {
4623 /* adjust the reftime by the same amount as the
4624 * leap smear, as we don't want to risk the
4625 * reftime being later than the transmit time.
4627 leap_smear_add_offs(&this_ref_time, NULL);
4631 HTONL_FP(&this_ref_time, &xpkt.reftime);
4638 if (leap_smear.in_progress) {
4639 xpkt.refid = convertLFPToRefID(leap_smear.offset);
4640 DPRINTF(2, ("fast_xmit: leap_smear.in_progress: refid %8x, smear %s\n",
4642 lfptoa(&leap_smear.offset, 8)
4651 xpkt.org = rpkt->xmt;
4657 this_recv_time = rbufp->recv_time;
4658 if (leap_smear.in_progress)
4659 leap_smear_add_offs(&this_recv_time, NULL);
4660 HTONL_FP(&this_recv_time, &xpkt.rec);
4662 HTONL_FP(&rbufp->recv_time, &xpkt.rec);
4669 get_systime(&xmt_tx);
4671 if (leap_smear.in_progress)
4672 leap_smear_add_offs(&xmt_tx, &this_recv_time);
4674 HTONL_FP(&xmt_tx, &xpkt.xmt);
4677 #ifdef HAVE_NTP_SIGND
4678 if (flags & RES_MSSNTP) {
4679 send_via_ntp_signd(rbufp, xmode, xkeyid, flags, &xpkt);
4682 #endif /* HAVE_NTP_SIGND */
4685 * If the received packet contains a MAC, the transmitted packet
4686 * is authenticated and contains a MAC. If not, the transmitted
4687 * packet is not authenticated.
4689 sendlen = LEN_PKT_NOMAC;
4690 if (rbufp->recv_length == sendlen) {
4691 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
4693 DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d len %lu\n",
4694 current_time, stoa(&rbufp->dstadr->sin),
4695 stoa(&rbufp->recv_srcadr), xmode,
4701 * The received packet contains a MAC, so the transmitted packet
4702 * must be authenticated. For symmetric key cryptography, use
4703 * the predefined and trusted symmetric keys to generate the
4704 * cryptosum. For autokey cryptography, use the server private
4705 * value to generate the cookie, which is unique for every
4706 * source-destination-key ID combination.
4709 if (xkeyid > NTP_MAXKEY) {
4713 * The only way to get here is a reply to a legitimate
4714 * client request message, so the mode must be
4715 * MODE_SERVER. If an extension field is present, there
4716 * can be only one and that must be a command. Do what
4717 * needs, but with private value of zero so the poor
4718 * jerk can decode it. If no extension field is present,
4719 * use the cookie to generate the session key.
4721 cookie = session_key(&rbufp->recv_srcadr,
4722 &rbufp->dstadr->sin, 0, sys_private, 0);
4723 if ((size_t)rbufp->recv_length > sendlen + MAX_MAC_LEN) {
4724 session_key(&rbufp->dstadr->sin,
4725 &rbufp->recv_srcadr, xkeyid, 0, 2);
4726 temp32 = CRYPTO_RESP;
4727 rpkt->exten[0] |= htonl(temp32);
4728 sendlen += crypto_xmit(NULL, &xpkt, rbufp,
4729 sendlen, (struct exten *)rpkt->exten,
4732 session_key(&rbufp->dstadr->sin,
4733 &rbufp->recv_srcadr, xkeyid, cookie, 2);
4736 #endif /* AUTOKEY */
4737 get_systime(&xmt_tx);
4738 sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
4740 if (xkeyid > NTP_MAXKEY)
4741 authtrust(xkeyid, 0);
4742 #endif /* AUTOKEY */
4743 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
4744 get_systime(&xmt_ty);
4745 L_SUB(&xmt_ty, &xmt_tx);
4746 sys_authdelay = xmt_ty;
4747 DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d keyid %08x len %lu\n",
4748 current_time, ntoa(&rbufp->dstadr->sin),
4749 ntoa(&rbufp->recv_srcadr), xmode, xkeyid,
4755 * pool_xmit - resolve hostname or send unicast solicitation for pool.
4759 struct peer *pool /* pool solicitor association */
4763 struct pkt xpkt; /* transmit packet structure */
4764 struct addrinfo hints;
4766 struct interface * lcladr;
4767 sockaddr_u * rmtadr;
4769 u_short restrict_mask;
4773 DEBUG_REQUIRE(pool);
4774 if (NULL == pool->ai) {
4775 if (pool->addrs != NULL) {
4776 /* free() is used with copy_addrinfo_list() */
4781 hints.ai_family = AF(&pool->srcadr);
4782 hints.ai_socktype = SOCK_DGRAM;
4783 hints.ai_protocol = IPPROTO_UDP;
4784 /* ignore getaddrinfo_sometime() errors, we will retry */
4785 rc = getaddrinfo_sometime(
4790 &pool_name_resolved,
4791 (void *)(intptr_t)pool->associd);
4793 DPRINTF(1, ("pool DNS lookup %s started\n",
4797 "unable to start pool DNS %s: %m",
4803 /* copy_addrinfo_list ai_addr points to a sockaddr_u */
4804 rmtadr = (sockaddr_u *)(void *)pool->ai->ai_addr;
4805 pool->ai = pool->ai->ai_next;
4806 p = findexistingpeer(rmtadr, NULL, NULL, MODE_CLIENT, 0, NULL);
4807 } while (p != NULL && pool->ai != NULL);
4809 return; /* out of addresses, re-query DNS next poll */
4810 restrictions(rmtadr, &r4a);
4811 restrict_mask = r4a.rflags;
4812 if (RES_FLAGS & restrict_mask)
4813 restrict_source(rmtadr, 0,
4814 current_time + POOL_SOLICIT_WINDOW + 1);
4815 lcladr = findinterface(rmtadr);
4816 memset(&xpkt, 0, sizeof(xpkt));
4817 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, pool->version,
4819 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4820 xpkt.ppoll = pool->hpoll;
4821 xpkt.precision = sys_precision;
4822 xpkt.refid = sys_refid;
4823 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4824 xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
4825 /* Bug 3596: What are the pros/cons of using sys_reftime here? */
4826 HTONL_FP(&sys_reftime, &xpkt.reftime);
4828 /* HMS: the following is better done after the ntp_random() calls */
4829 get_systime(&xmt_tx);
4830 pool->aorg = xmt_tx;
4832 if (FLAG_LOOPNONCE & pool->flags) {
4836 nonce.l_ui = ntp_random();
4837 } while (0 == nonce.l_ui);
4839 nonce.l_uf = ntp_random();
4840 } while (0 == nonce.l_uf);
4841 pool->nonce = nonce;
4842 HTONL_FP(&nonce, &xpkt.xmt);
4844 L_CLR(&pool->nonce);
4845 HTONL_FP(&xmt_tx, &xpkt.xmt);
4847 sendpkt(rmtadr, lcladr,
4848 sys_ttl[(pool->ttl >= sys_ttlmax) ? sys_ttlmax : pool->ttl],
4849 &xpkt, LEN_PKT_NOMAC);
4851 pool->throttle += (1 << pool->minpoll) - 2;
4852 DPRINTF(1, ("pool_xmit: at %ld %s->%s pool\n",
4853 current_time, latoa(lcladr), stoa(rmtadr)));
4854 msyslog(LOG_INFO, "Soliciting pool server %s", stoa(rmtadr));
4861 * group_test - test if this is the same group
4863 * host assoc return action
4864 * none none 0 mobilize *
4865 * none group 0 mobilize *
4866 * group none 0 mobilize *
4867 * group group 1 mobilize
4868 * group different 1 ignore
4869 * * ignore if notrust
4880 if (strcmp(grp, sys_groupname) == 0)
4886 if (strcmp(grp, ident) == 0)
4891 #endif /* AUTOKEY */
4901 const char * service,
4902 const struct addrinfo * hints,
4903 const struct addrinfo * res
4906 struct peer * pool; /* pool solicitor association */
4911 "error resolving pool %s: %s (%d)",
4912 name, gai_strerror(rescode), rescode);
4916 assoc = (associd_t)(intptr_t)context;
4917 pool = findpeerbyassoc(assoc);
4920 "Could not find assoc %u for pool DNS %s",
4924 DPRINTF(1, ("pool DNS %s completed\n", name));
4925 pool->addrs = copy_addrinfo_list(res);
4926 pool->ai = pool->addrs;
4935 * key_expire - purge the key list
4939 struct peer *peer /* peer structure pointer */
4944 if (peer->keylist != NULL) {
4945 for (i = 0; i <= peer->keynumber; i++)
4946 authtrust(peer->keylist[i], 0);
4947 free(peer->keylist);
4948 peer->keylist = NULL;
4950 value_free(&peer->sndval);
4951 peer->keynumber = 0;
4952 peer->flags &= ~FLAG_ASSOC;
4953 DPRINTF(1, ("key_expire: at %lu associd %d\n", current_time,
4956 #endif /* AUTOKEY */
4960 * local_refid(peer) - check peer refid to avoid selecting peers
4961 * currently synced to this ntpd.
4970 if (p->dstadr != NULL && !(INT_MCASTIF & p->dstadr->flags))
4971 unicast_ep = p->dstadr;
4973 unicast_ep = findinterface(&p->srcadr);
4975 if (unicast_ep != NULL && p->refid == unicast_ep->addr_refid)
4983 * Determine if the peer is unfit for synchronization
4985 * A peer is unfit for synchronization if
4986 * > TEST10 bad leap or stratum below floor or at or above ceiling
4987 * > TEST11 root distance exceeded for remote peer
4988 * > TEST12 a direct or indirect synchronization loop would form
4989 * > TEST13 unreachable or noselect
4991 int /* FALSE if fit, TRUE if unfit */
4993 struct peer *peer /* peer structure pointer */
4999 * A stratum error occurs if (1) the server has never been
5000 * synchronized, (2) the server stratum is below the floor or
5001 * greater than or equal to the ceiling.
5003 if ( peer->leap == LEAP_NOTINSYNC
5004 || peer->stratum < sys_floor
5005 || peer->stratum >= sys_ceiling) {
5006 rval |= TEST10; /* bad synch or stratum */
5010 * A distance error for a remote peer occurs if the root
5011 * distance is greater than or equal to the distance threshold
5012 * plus the increment due to one host poll interval.
5014 if ( !(peer->flags & FLAG_REFCLOCK)
5015 && root_distance(peer) >= sys_maxdist
5016 + clock_phi * ULOGTOD(peer->hpoll)) {
5017 rval |= TEST11; /* distance exceeded */
5021 * A loop error occurs if the remote peer is synchronized to the
5022 * local peer or if the remote peer is synchronized to the same
5023 * server as the local peer but only if the remote peer is
5024 * neither a reference clock nor an orphan.
5026 if (peer->stratum > 1 && local_refid(peer)) {
5027 rval |= TEST12; /* synchronization loop */
5031 * An unreachable error occurs if the server is unreachable or
5032 * the noselect bit is set.
5034 if (!peer->reach || (peer->flags & FLAG_NOSELECT)) {
5035 rval |= TEST13; /* unreachable */
5038 peer->flash &= ~PEER_TEST_MASK;
5039 peer->flash |= rval;
5045 * Find the precision of this particular machine
5047 #define MINSTEP 20e-9 /* minimum clock increment (s) */
5048 #define MAXSTEP 1 /* maximum clock increment (s) */
5049 #define MINCHANGES 12 /* minimum number of step samples */
5050 #define MAXLOOPS ((int)(1. / MINSTEP)) /* avoid infinite loop */
5053 * This routine measures the system precision defined as the minimum of
5054 * a sequence of differences between successive readings of the system
5055 * clock. However, if a difference is less than MINSTEP, the clock has
5056 * been read more than once during a clock tick and the difference is
5057 * ignored. We set MINSTEP greater than zero in case something happens
5058 * like a cache miss, and to tolerate underlying system clocks which
5059 * ensure each reading is strictly greater than prior readings while
5060 * using an underlying stepping (not interpolated) clock.
5062 * sys_tick and sys_precision represent the time to read the clock for
5063 * systems with high-precision clocks, and the tick interval or step
5064 * size for lower-precision stepping clocks.
5066 * This routine also measures the time to read the clock on stepping
5067 * system clocks by counting the number of readings between changes of
5068 * the underlying clock. With either type of clock, the minimum time
5069 * to read the clock is saved as sys_fuzz, and used to ensure the
5070 * get_systime() readings always increase and are fuzzed below sys_fuzz.
5073 measure_precision(void)
5076 * With sys_fuzz set to zero, get_systime() fuzzing of low bits
5077 * is effectively disabled. trunc_os_clock is FALSE to disable
5078 * get_ostime() simulation of a low-precision system clock.
5081 trunc_os_clock = FALSE;
5082 measured_tick = measure_tick_fuzz();
5083 set_sys_tick_precision(measured_tick);
5084 msyslog(LOG_INFO, "proto: precision = %.3f usec (%d)",
5085 sys_tick * 1e6, sys_precision);
5086 if (sys_fuzz < sys_tick) {
5087 msyslog(LOG_NOTICE, "proto: fuzz beneath %.3f usec",
5094 * measure_tick_fuzz()
5096 * measures the minimum time to read the clock (stored in sys_fuzz)
5097 * and returns the tick, the larger of the minimum increment observed
5098 * between successive clock readings and the time to read the clock.
5101 measure_tick_fuzz(void)
5103 l_fp minstep; /* MINSTEP as l_fp */
5104 l_fp val; /* current seconds fraction */
5105 l_fp last; /* last seconds fraction */
5106 l_fp ldiff; /* val - last */
5107 double tick; /* computed tick value */
5112 int i; /* log2 precision */
5118 DTOLFP(MINSTEP, &minstep);
5120 for (i = 0; i < MAXLOOPS && changes < MINCHANGES; i++) {
5123 L_SUB(&ldiff, &last);
5125 if (L_ISGT(&ldiff, &minstep)) {
5126 max_repeats = max(repeats, max_repeats);
5129 LFPTOD(&ldiff, diff);
5130 tick = min(diff, tick);
5135 if (changes < MINCHANGES) {
5136 msyslog(LOG_ERR, "Fatal error: precision could not be measured (MINSTEP too large?)");
5140 if (0 == max_repeats) {
5143 set_sys_fuzz(tick / max_repeats);
5151 set_sys_tick_precision(
5159 "unsupported tick %.3f > 1s ignored", tick);
5162 if (tick < measured_tick) {
5164 "proto: tick %.3f less than measured tick %.3f, ignored",
5165 tick, measured_tick);
5167 } else if (tick > measured_tick) {
5168 trunc_os_clock = TRUE;
5170 "proto: truncating system clock to multiples of %.9f",
5176 * Find the nearest power of two.
5178 for (i = 0; tick <= 1; i--)
5180 if (tick - 1 > 1 - tick / 2)
5183 sys_precision = (s_char)i;
5188 * init_proto - initialize the protocol module's data
5197 * Fill in the sys_* stuff. Default is don't listen to
5198 * broadcasting, require authentication.
5200 set_sys_leap(LEAP_NOTINSYNC);
5201 sys_stratum = STRATUM_UNSPEC;
5202 memcpy(&sys_refid, "INIT", 4);
5206 L_CLR(&sys_reftime);
5208 measure_precision();
5209 get_systime(&dummy);
5211 sys_manycastserver = 0;
5213 sys_bdelay = BDELAY_DEFAULT; /*[Bug 3031] delay cutoff */
5214 sys_authenticate = 1;
5215 sys_stattime = current_time;
5216 orphwait = current_time + sys_orphwait;
5218 for (i = 0; i < MAX_TTL; ++i)
5219 sys_ttl[i] = (u_char)((i * 256) / MAX_TTL);
5220 sys_ttlmax = (MAX_TTL - 1);
5227 * proto_config - configure the protocol module
5238 * Figure out what he wants to change, then do it
5240 DPRINTF(2, ("proto_config: code %d value %lu dvalue %lf\n",
5241 item, value, dvalue));
5246 * enable and disable commands - arguments are Boolean.
5248 case PROTO_AUTHENTICATE: /* authentication (auth) */
5249 sys_authenticate = value;
5252 case PROTO_BROADCLIENT: /* broadcast client (bclient) */
5253 sys_bclient = (int)value;
5254 if (sys_bclient == 0)
5261 case PROTO_CAL: /* refclock calibrate (calibrate) */
5264 #endif /* REFCLOCK */
5266 case PROTO_KERNEL: /* kernel discipline (kernel) */
5270 case PROTO_MONITOR: /* monitoring (monitor) */
5276 msyslog(LOG_WARNING,
5277 "restrict: 'monitor' cannot be disabled while 'limited' is enabled");
5281 case PROTO_NTP: /* NTP discipline (ntp) */
5285 case PROTO_MODE7: /* mode7 management (ntpdc) */
5289 case PROTO_PPS: /* PPS discipline (pps) */
5290 hardpps_enable = value;
5293 case PROTO_FILEGEN: /* statistics (stats) */
5294 stats_control = value;
5298 * tos command - arguments are double, sometimes cast to int
5301 case PROTO_BCPOLLBSTEP: /* Broadcast Poll Backstep gate (bcpollbstep) */
5302 sys_bcpollbstep = (u_char)dvalue;
5305 case PROTO_BEACON: /* manycast beacon (beacon) */
5306 sys_beacon = (int)dvalue;
5309 case PROTO_BROADDELAY: /* default broadcast delay (bdelay) */
5310 sys_bdelay = (dvalue ? dvalue : BDELAY_DEFAULT);
5313 case PROTO_CEILING: /* stratum ceiling (ceiling) */
5314 sys_ceiling = (int)dvalue;
5317 case PROTO_COHORT: /* cohort switch (cohort) */
5318 sys_cohort = (int)dvalue;
5321 case PROTO_FLOOR: /* stratum floor (floor) */
5322 sys_floor = (int)dvalue;
5325 case PROTO_MAXCLOCK: /* maximum candidates (maxclock) */
5326 sys_maxclock = (int)dvalue;
5329 case PROTO_MAXDIST: /* select threshold (maxdist) */
5330 sys_maxdist = dvalue;
5333 case PROTO_CALLDELAY: /* modem call delay (mdelay) */
5334 break; /* NOT USED */
5336 case PROTO_MINCLOCK: /* minimum candidates (minclock) */
5337 sys_minclock = (int)dvalue;
5340 case PROTO_MINDISP: /* minimum distance (mindist) */
5341 sys_mindisp = dvalue;
5344 case PROTO_MINSANE: /* minimum survivors (minsane) */
5345 sys_minsane = (int)dvalue;
5348 case PROTO_ORPHAN: /* orphan stratum (orphan) */
5349 sys_orphan = (int)dvalue;
5352 case PROTO_ORPHWAIT: /* orphan wait (orphwait) */
5353 orphwait -= sys_orphwait;
5354 sys_orphwait = (dvalue >= 1) ? (int)dvalue : NTP_ORPHWAIT;
5355 orphwait += sys_orphwait;
5359 * Miscellaneous commands
5361 case PROTO_MULTICAST_ADD: /* add group address */
5363 io_multicast_add(svalue);
5367 case PROTO_MULTICAST_DEL: /* delete group address */
5369 io_multicast_del(svalue);
5373 * Peer_clear Early policy choices
5376 case PROTO_PCEDIGEST: /* Digest */
5377 peer_clear_digest_early = value;
5381 * Unpeer Early policy choices
5384 case PROTO_UECRYPTO: /* Crypto */
5385 unpeer_crypto_early = value;
5388 case PROTO_UECRYPTONAK: /* Crypto_NAK */
5389 unpeer_crypto_nak_early = value;
5392 case PROTO_UEDIGEST: /* Digest */
5393 unpeer_digest_early = value;
5398 "proto: unsupported option %d", item);
5404 * proto_clr_stats - clear protocol stat counters
5407 proto_clr_stats(void)
5409 sys_stattime = current_time;
5418 sys_limitrejected = 0;