2 * ntp_proto.c - NTP version 4 protocol machinery
4 * ATTENTION: Get approval from Dave Mills on all changes to this file!
12 #include "ntp_stdlib.h"
13 #include "ntp_unixtime.h"
14 #include "ntp_control.h"
15 #include "ntp_string.h"
16 #include "ntp_leapsec.h"
17 #include "refidsmear.h"
18 #include "lib_strbuf.h"
28 /* [Bug 3031] define automatic broadcastdelay cutoff preset */
29 #ifndef BDELAY_DEFAULT
30 # define BDELAY_DEFAULT (-0.050)
34 * This macro defines the authentication state. If x is 1 authentication
35 * is required; othewise it is optional.
37 #define AUTH(x, y) ((x) ? (y) == AUTH_OK \
38 : (y) == AUTH_OK || (y) == AUTH_NONE)
40 #define AUTH_NONE 0 /* authentication not required */
41 #define AUTH_OK 1 /* authentication OK */
42 #define AUTH_ERROR 2 /* authentication error */
43 #define AUTH_CRYPTO 3 /* crypto_NAK */
46 * Set up Kiss Code values
50 NOKISS, /* No Kiss Code */
51 RATEKISS, /* Rate limit Kiss Code */
52 DENYKISS, /* Deny Kiss */
53 RSTRKISS, /* Restricted Kiss */
54 XKISS, /* Experimental Kiss */
55 UNKNOWNKISS /* Unknown Kiss Code */
58 enum nak_error_codes {
59 NONAK, /* No NAK seen */
60 INVALIDNAK, /* NAK cannot be used */
61 VALIDNAK /* NAK is valid */
65 * traffic shaping parameters
67 #define NTP_IBURST 6 /* packets in iburst */
68 #define RESP_DELAY 1 /* refclock burst delay (s) */
71 * pool soliciting restriction duration (s)
73 #define POOL_SOLICIT_WINDOW 8
76 * peer_select groups statistics for a peer used by clock_select() and
79 typedef struct peer_select_tag {
81 double synch; /* sync distance */
82 double error; /* jitter */
83 double seljit; /* selection jitter */
87 * System variables are declared here. Unless specified otherwise, all
88 * times are in seconds.
90 u_char sys_leap; /* system leap indicator, use set_sys_leap() to change this */
91 u_char xmt_leap; /* leap indicator sent in client requests, set up by set_sys_leap() */
92 u_char sys_stratum; /* system stratum */
93 s_char sys_precision; /* local clock precision (log2 s) */
94 double sys_rootdelay; /* roundtrip delay to primary source */
95 double sys_rootdisp; /* dispersion to primary source */
96 u_int32 sys_refid; /* reference id (network byte order) */
97 l_fp sys_reftime; /* last update time */
98 struct peer *sys_peer; /* current peer */
101 struct leap_smear_info leap_smear;
103 int leap_sec_in_progress;
106 * Rate controls. Leaky buckets are used to throttle the packet
107 * transmission rates in order to protect busy servers such as at NIST
108 * and USNO. There is a counter for each association and another for KoD
109 * packets. The association counter decrements each second, but not
110 * below zero. Each time a packet is sent the counter is incremented by
111 * a configurable value representing the average interval between
112 * packets. A packet is delayed as long as the counter is greater than
113 * zero. Note this does not affect the time value computations.
116 * Nonspecified system state variables
118 int sys_bclient; /* broadcast client enable */
119 double sys_bdelay; /* broadcast client default delay */
120 int sys_authenticate; /* requre authentication for config */
121 l_fp sys_authdelay; /* authentication delay */
122 double sys_offset; /* current local clock offset */
123 double sys_mindisp = MINDISPERSE; /* minimum distance (s) */
124 double sys_maxdist = MAXDISTANCE; /* selection threshold */
125 double sys_jitter; /* system jitter */
126 u_long sys_epoch; /* last clock update time */
127 static double sys_clockhop; /* clockhop threshold */
128 static int leap_vote_ins; /* leap consensus for insert */
129 static int leap_vote_del; /* leap consensus for delete */
130 keyid_t sys_private; /* private value for session seed */
131 int sys_manycastserver; /* respond to manycast client pkts */
132 int ntp_mode7; /* respond to ntpdc (mode7) */
133 int peer_ntpdate; /* active peers in ntpdate mode */
134 int sys_survivors; /* truest of the truechimers */
135 char *sys_ident = NULL; /* identity scheme */
138 * TOS and multicast mapping stuff
140 int sys_floor = 0; /* cluster stratum floor */
141 u_char sys_bcpollbstep = 0; /* Broadcast Poll backstep gate */
142 int sys_ceiling = STRATUM_UNSPEC - 1; /* cluster stratum ceiling */
143 int sys_minsane = 1; /* minimum candidates */
144 int sys_minclock = NTP_MINCLOCK; /* minimum candidates */
145 int sys_maxclock = NTP_MAXCLOCK; /* maximum candidates */
146 int sys_cohort = 0; /* cohort switch */
147 int sys_orphan = STRATUM_UNSPEC + 1; /* orphan stratum */
148 int sys_orphwait = NTP_ORPHWAIT; /* orphan wait */
149 int sys_beacon = BEACON; /* manycast beacon interval */
150 int sys_ttlmax; /* max ttl mapping vector index */
151 u_char sys_ttl[MAX_TTL]; /* ttl mapping vector */
154 * Statistics counters - first the good, then the bad
156 u_long sys_stattime; /* elapsed time */
157 u_long sys_received; /* packets received */
158 u_long sys_processed; /* packets for this host */
159 u_long sys_newversion; /* current version */
160 u_long sys_oldversion; /* old version */
161 u_long sys_restricted; /* access denied */
162 u_long sys_badlength; /* bad length or format */
163 u_long sys_badauth; /* bad authentication */
164 u_long sys_declined; /* declined */
165 u_long sys_limitrejected; /* rate exceeded */
166 u_long sys_kodsent; /* KoD sent */
169 * Mechanism knobs: how soon do we peer_clear() or unpeer()?
171 * The default way is "on-receipt". If this was a packet from a
172 * well-behaved source, on-receipt will offer the fastest recovery.
173 * If this was from a DoS attack, the default way makes it easier
174 * for a bad-guy to DoS us. So look and see what bites you harder
175 * and choose according to your environment.
177 int peer_clear_digest_early = 1; /* bad digest (TEST5) and Autokey */
178 int unpeer_crypto_early = 1; /* bad crypto (TEST9) */
179 int unpeer_crypto_nak_early = 1; /* crypto_NAK (TEST5) */
180 int unpeer_digest_early = 1; /* bad digest (TEST5) */
182 int dynamic_interleave = DYNAMIC_INTERLEAVE; /* Bug 2978 mitigation */
184 int kiss_code_check(u_char hisleap, u_char hisstratum, u_char hismode, u_int32 refid);
185 enum nak_error_codes valid_NAK(struct peer *peer, struct recvbuf *rbufp, u_char hismode);
186 static double root_distance (struct peer *);
187 static void clock_combine (peer_select *, int, int);
188 static void peer_xmit (struct peer *);
189 static void fast_xmit (struct recvbuf *, int, keyid_t, int);
190 static void pool_xmit (struct peer *);
191 static void clock_update (struct peer *);
192 static void measure_precision(void);
193 static double measure_tick_fuzz(void);
194 static int local_refid (struct peer *);
195 static int peer_unfit (struct peer *);
197 static int group_test (char *, char *);
200 void pool_name_resolved (int, int, void *, const char *,
201 const char *, const struct addrinfo *,
202 const struct addrinfo *);
205 const char * amtoa (int am);
213 sys_leap = new_sys_leap;
217 * Under certain conditions we send faked leap bits to clients, so
218 * eventually change xmt_leap below, but never change LEAP_NOTINSYNC.
220 if (xmt_leap != LEAP_NOTINSYNC) {
221 if (leap_sec_in_progress) {
222 /* always send "not sync" */
223 xmt_leap = LEAP_NOTINSYNC;
228 * If leap smear is enabled in general we must
229 * never send a leap second warning to clients,
230 * so make sure we only send "in sync".
232 if (leap_smear.enabled)
233 xmt_leap = LEAP_NOWARNING;
235 #endif /* LEAP_SMEAR */
252 if ( hismode == MODE_SERVER
253 && hisleap == LEAP_NOTINSYNC
254 && hisstratum == STRATUM_UNSPEC) {
255 if(memcmp(&refid,"RATE", 4) == 0) {
257 } else if(memcmp(&refid,"DENY", 4) == 0) {
259 } else if(memcmp(&refid,"RSTR", 4) == 0) {
261 } else if(memcmp(&refid,"X", 1) == 0) {
264 return (UNKNOWNKISS);
273 * Check that NAK is valid
278 struct recvbuf *rbufp,
282 int base_packet_length = MIN_V4_PKT_LEN;
286 l_fp p_org; /* origin timestamp */
287 const l_fp * myorg; /* selected peer origin */
290 * Check to see if there is something beyond the basic packet
292 if (rbufp->recv_length == base_packet_length) {
296 remainder_size = rbufp->recv_length - base_packet_length;
298 * Is this a potential NAK?
300 if (remainder_size != 4) {
305 * Only server responses can contain NAK's
308 if (hismode != MODE_SERVER &&
309 hismode != MODE_ACTIVE &&
310 hismode != MODE_PASSIVE
316 * Make sure that the extra field in the packet is all zeros
318 rpkt = &rbufp->recv_pkt;
319 keyid = ntohl(((u_int32 *)rpkt)[base_packet_length / 4]);
325 * Only valid if peer uses a key
327 if (!peer || !peer->keyid || !(peer->flags & FLAG_SKEY)) {
332 * The ORIGIN must match, or this cannot be a valid NAK, either.
334 NTOHL_FP(&rpkt->org, &p_org);
340 if (L_ISZERO(&p_org) ||
342 !L_ISEQU(&p_org, myorg)) {
346 /* If we ever passed all that checks, we should be safe. Well,
347 * as safe as we can ever be with an unauthenticated crypto-nak.
354 * transmit - transmit procedure called by poll timeout
358 struct peer *peer /* peer structure pointer */
364 * The polling state machine. There are two kinds of machines,
365 * those that never expect a reply (broadcast and manycast
366 * server modes) and those that do (all other modes). The dance
372 * In broadcast mode the poll interval is never changed from
375 if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
376 peer->outdate = current_time;
377 if (sys_leap != LEAP_NOTINSYNC)
379 poll_update(peer, hpoll);
384 * In manycast mode we start with unity ttl. The ttl is
385 * increased by one for each poll until either sys_maxclock
386 * servers have been found or the maximum ttl is reached. When
387 * sys_maxclock servers are found we stop polling until one or
388 * more servers have timed out or until less than sys_minclock
389 * associations turn up. In this case additional better servers
390 * are dragged in and preempt the existing ones. Once every
391 * sys_beacon seconds we are to transmit unconditionally, but
392 * this code is not quite right -- peer->unreach counts polls
393 * and is being compared with sys_beacon, so the beacons happen
394 * every sys_beacon polls.
396 if (peer->cast_flags & MDF_ACAST) {
397 peer->outdate = current_time;
398 if (peer->unreach > sys_beacon) {
402 } else if ( sys_survivors < sys_minclock
403 || peer_associations < sys_maxclock) {
404 if (peer->ttl < (u_int32)sys_ttlmax)
409 poll_update(peer, hpoll);
414 * Pool associations transmit unicast solicitations when there
415 * are less than a hard limit of 2 * sys_maxclock associations,
416 * and either less than sys_minclock survivors or less than
417 * sys_maxclock associations. The hard limit prevents unbounded
418 * growth in associations if the system clock or network quality
419 * result in survivor count dipping below sys_minclock often.
420 * This was observed testing with pool, where sys_maxclock == 12
421 * resulted in 60 associations without the hard limit. A
422 * similar hard limit on manycastclient ephemeral associations
423 * may be appropriate.
425 if (peer->cast_flags & MDF_POOL) {
426 peer->outdate = current_time;
427 if ( (peer_associations <= 2 * sys_maxclock)
428 && ( peer_associations < sys_maxclock
429 || sys_survivors < sys_minclock))
431 poll_update(peer, hpoll);
436 * In unicast modes the dance is much more intricate. It is
437 * designed to back off whenever possible to minimize network
440 if (peer->burst == 0) {
444 * Update the reachability status. If not heard for
445 * three consecutive polls, stuff infinity in the clock
448 oreach = peer->reach;
449 peer->outdate = current_time;
455 * Here the peer is unreachable. If it was
456 * previously reachable raise a trap. Send a
459 clock_filter(peer, 0., 0., MAXDISPERSE);
462 report_event(PEVNT_UNREACH, peer, NULL);
464 if ( (peer->flags & FLAG_IBURST)
466 peer->retry = NTP_RETRY;
470 * Here the peer is reachable. Send a burst if
471 * enabled and the peer is fit. Reset unreach
472 * for persistent and ephemeral associations.
473 * Unreach is also reset for survivors in
477 if (!(peer->flags & FLAG_PREEMPT))
479 if ( (peer->flags & FLAG_BURST)
481 && !peer_unfit(peer))
482 peer->retry = NTP_RETRY;
486 * Watch for timeout. If ephemeral, toss the rascal;
487 * otherwise, bump the poll interval. Note the
488 * poll_update() routine will clamp it to maxpoll.
489 * If preemptible and we have more peers than maxclock,
490 * and this peer has the minimum score of preemptibles,
493 if (peer->unreach >= NTP_UNREACH) {
495 /* ephemeral: no FLAG_CONFIG nor FLAG_PREEMPT */
496 if (!(peer->flags & (FLAG_CONFIG | FLAG_PREEMPT))) {
497 report_event(PEVNT_RESTART, peer, "timeout");
498 peer_clear(peer, "TIME");
502 if ( (peer->flags & FLAG_PREEMPT)
503 && (peer_associations > sys_maxclock)
504 && score_all(peer)) {
505 report_event(PEVNT_RESTART, peer, "timeout");
506 peer_clear(peer, "TIME");
513 if (peer->burst == 0) {
516 * If ntpdate mode and the clock has not been
517 * set and all peers have completed the burst,
518 * we declare a successful failure.
522 if (peer_ntpdate == 0) {
524 "ntpd: no servers found");
527 "ntpd: no servers found\n");
537 * Do not transmit if in broadcast client mode.
539 if (peer->hmode != MODE_BCLIENT)
541 poll_update(peer, hpoll);
555 case AM_ERR: return "AM_ERR";
556 case AM_NOMATCH: return "AM_NOMATCH";
557 case AM_PROCPKT: return "AM_PROCPKT";
558 case AM_BCST: return "AM_BCST";
559 case AM_FXMIT: return "AM_FXMIT";
560 case AM_MANYCAST: return "AM_MANYCAST";
561 case AM_NEWPASS: return "AM_NEWPASS";
562 case AM_NEWBCL: return "AM_NEWBCL";
563 case AM_POSSBCL: return "AM_POSSBCL";
566 snprintf(bp, LIB_BUFLENGTH, "AM_#%d", am);
573 * receive - receive procedure called for each packet received
577 struct recvbuf *rbufp
580 register struct peer *peer; /* peer structure pointer */
581 register struct pkt *pkt; /* receive packet pointer */
582 u_char hisversion; /* packet version */
583 u_char hisleap; /* packet leap indicator */
584 u_char hismode; /* packet mode */
585 u_char hisstratum; /* packet stratum */
586 u_short restrict_mask; /* restrict bits */
587 const char *hm_str; /* hismode string */
588 const char *am_str; /* association match string */
589 int kissCode = NOKISS; /* Kiss Code */
590 int has_mac; /* length of MAC field */
591 int authlen; /* offset of MAC field */
592 int is_authentic = AUTH_NONE; /* cryptosum ok */
593 int crypto_nak_test; /* result of crypto-NAK check */
594 int retcode = AM_NOMATCH; /* match code */
595 keyid_t skeyid = 0; /* key IDs */
596 u_int32 opcode = 0; /* extension field opcode */
597 sockaddr_u *dstadr_sin; /* active runway */
598 struct peer *peer2; /* aux peer structure pointer */
599 endpt *match_ep; /* newpeer() local address */
600 l_fp p_org; /* origin timestamp */
601 l_fp p_rec; /* receive timestamp */
602 l_fp p_xmt; /* transmit timestamp */
604 char hostname[NTP_MAXSTRLEN + 1];
605 char *groupname = NULL;
606 struct autokey *ap; /* autokey structure pointer */
607 int rval; /* cookie snatcher */
608 keyid_t pkeyid = 0, tkeyid = 0; /* key IDs */
610 #ifdef HAVE_NTP_SIGND
611 static unsigned char zero_key[16];
612 #endif /* HAVE_NTP_SIGND */
615 * Monitor the packet and get restrictions. Note that the packet
616 * length for control and private mode packets must be checked
617 * by the service routines. Some restrictions have to be handled
618 * later in order to generate a kiss-o'-death packet.
621 * Bogus port check is before anything, since it probably
622 * reveals a clogging attack.
625 if (0 == SRCPORT(&rbufp->recv_srcadr)) {
627 return; /* bogus port */
629 restrict_mask = restrictions(&rbufp->recv_srcadr);
630 pkt = &rbufp->recv_pkt;
631 DPRINTF(2, ("receive: at %ld %s<-%s flags %x restrict %03x org %#010x.%08x xmt %#010x.%08x\n",
632 current_time, stoa(&rbufp->dstadr->sin),
633 stoa(&rbufp->recv_srcadr), rbufp->dstadr->flags,
634 restrict_mask, ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
635 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
636 hisversion = PKT_VERSION(pkt->li_vn_mode);
637 hisleap = PKT_LEAP(pkt->li_vn_mode);
638 hismode = (int)PKT_MODE(pkt->li_vn_mode);
639 hisstratum = PKT_TO_STRATUM(pkt->stratum);
640 INSIST(0 != hisstratum);
642 if (restrict_mask & RES_IGNORE) {
644 return; /* ignore everything */
646 if (hismode == MODE_PRIVATE) {
647 if (!ntp_mode7 || (restrict_mask & RES_NOQUERY)) {
649 return; /* no query private */
651 process_private(rbufp, ((restrict_mask &
652 RES_NOMODIFY) == 0));
655 if (hismode == MODE_CONTROL) {
656 if (restrict_mask & RES_NOQUERY) {
658 return; /* no query control */
660 process_control(rbufp, restrict_mask);
663 if (restrict_mask & RES_DONTSERVE) {
665 return; /* no time serve */
669 * This is for testing. If restricted drop ten percent of
672 if (restrict_mask & RES_FLAKE) {
673 if ((double)ntp_random() / 0x7fffffff < .1) {
675 return; /* no flakeway */
680 * Version check must be after the query packets, since they
681 * intentionally use an early version.
683 if (hisversion == NTP_VERSION) {
684 sys_newversion++; /* new version */
685 } else if ( !(restrict_mask & RES_VERSION)
686 && hisversion >= NTP_OLDVERSION) {
687 sys_oldversion++; /* previous version */
690 return; /* old version */
694 * Figure out his mode and validate the packet. This has some
695 * legacy raunch that probably should be removed. In very early
696 * NTP versions mode 0 was equivalent to what later versions
697 * would interpret as client mode.
699 if (hismode == MODE_UNSPEC) {
700 if (hisversion == NTP_OLDVERSION) {
701 hismode = MODE_CLIENT;
704 return; /* invalid mode */
709 * Parse the extension field if present. We figure out whether
710 * an extension field is present by measuring the MAC size. If
711 * the number of words following the packet header is 0, no MAC
712 * is present and the packet is not authenticated. If 1, the
713 * packet is a crypto-NAK; if 3, the packet is authenticated
714 * with DES; if 5, the packet is authenticated with MD5; if 6,
715 * the packet is authenticated with SHA. If 2 or * 4, the packet
716 * is a runt and discarded forthwith. If greater than 6, an
717 * extension field is present, so we subtract the length of the
718 * field and go around again.
721 authlen = LEN_PKT_NOMAC;
722 has_mac = rbufp->recv_length - authlen;
723 while (has_mac > 0) {
730 if (has_mac % 4 != 0 || has_mac < (int)MIN_MAC_LEN) {
732 return; /* bad length */
734 if (has_mac <= (int)MAX_MAC_LEN) {
735 skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
739 opcode = ntohl(((u_int32 *)pkt)[authlen / 4]);
740 len = opcode & 0xffff;
743 || (int)len + authlen > rbufp->recv_length) {
745 return; /* bad length */
749 * Extract calling group name for later. If
750 * sys_groupname is non-NULL, there must be
751 * a group name provided to elicit a response.
753 if ( (opcode & 0x3fff0000) == CRYPTO_ASSOC
754 && sys_groupname != NULL) {
755 ep = (struct exten *)&((u_int32 *)pkt)[authlen / 4];
756 hostlen = ntohl(ep->vallen);
757 if ( hostlen >= sizeof(hostname)
759 offsetof(struct exten, pkt)) {
761 return; /* bad length */
763 memcpy(hostname, &ep->pkt, hostlen);
764 hostname[hostlen] = '\0';
765 groupname = strchr(hostname, '@');
766 if (groupname == NULL) {
779 * If has_mac is < 0 we had a malformed packet.
783 return; /* bad length */
787 * If authentication required, a MAC must be present.
789 if (restrict_mask & RES_DONTTRUST && has_mac == 0) {
791 return; /* access denied */
795 * Update the MRU list and finger the cloggers. It can be a
796 * little expensive, so turn it off for production use.
797 * RES_LIMITED and RES_KOD will be cleared in the returned
798 * restrict_mask unless one or both actions are warranted.
800 restrict_mask = ntp_monitor(rbufp, restrict_mask);
801 if (restrict_mask & RES_LIMITED) {
803 if ( !(restrict_mask & RES_KOD)
804 || MODE_BROADCAST == hismode
805 || MODE_SERVER == hismode) {
806 if (MODE_SERVER == hismode)
807 DPRINTF(1, ("Possibly self-induced rate limiting of MODE_SERVER from %s\n",
808 stoa(&rbufp->recv_srcadr)));
809 return; /* rate exceeded */
811 if (hismode == MODE_CLIENT)
812 fast_xmit(rbufp, MODE_SERVER, skeyid,
815 fast_xmit(rbufp, MODE_ACTIVE, skeyid,
817 return; /* rate exceeded */
819 restrict_mask &= ~RES_KOD;
822 * We have tossed out as many buggy packets as possible early in
823 * the game to reduce the exposure to a clogging attack. Now we
824 * have to burn some cycles to find the association and
825 * authenticate the packet if required. Note that we burn only
826 * digest cycles, again to reduce exposure. There may be no
827 * matching association and that's okay.
829 * More on the autokey mambo. Normally the local interface is
830 * found when the association was mobilized with respect to a
831 * designated remote address. We assume packets arriving from
832 * the remote address arrive via this interface and the local
833 * address used to construct the autokey is the unicast address
834 * of the interface. However, if the sender is a broadcaster,
835 * the interface broadcast address is used instead.
836 * Notwithstanding this technobabble, if the sender is a
837 * multicaster, the broadcast address is null, so we use the
838 * unicast address anyway. Don't ask.
840 peer = findpeer(rbufp, hismode, &retcode);
841 dstadr_sin = &rbufp->dstadr->sin;
842 NTOHL_FP(&pkt->org, &p_org);
843 NTOHL_FP(&pkt->rec, &p_rec);
844 NTOHL_FP(&pkt->xmt, &p_xmt);
845 hm_str = modetoa(hismode);
846 am_str = amtoa(retcode);
849 * Authentication is conditioned by three switches:
851 * NOPEER (RES_NOPEER) do not mobilize an association unless
853 * NOTRUST (RES_DONTTRUST) do not allow access unless
854 * authenticated (implies NOPEER)
855 * enable (sys_authenticate) master NOPEER switch, by default
858 * The NOPEER and NOTRUST can be specified on a per-client basis
859 * using the restrict command. The enable switch if on implies
860 * NOPEER for all clients. There are four outcomes:
862 * NONE The packet has no MAC.
863 * OK the packet has a MAC and authentication succeeds
864 * ERROR the packet has a MAC and authentication fails
865 * CRYPTO crypto-NAK. The MAC has four octets only.
867 * Note: The AUTH(x, y) macro is used to filter outcomes. If x
868 * is zero, acceptable outcomes of y are NONE and OK. If x is
869 * one, the only acceptable outcome of y is OK.
871 crypto_nak_test = valid_NAK(peer, rbufp, hismode);
874 * Drop any invalid crypto-NAKs
876 if (crypto_nak_test == INVALIDNAK) {
877 report_event(PEVNT_AUTH, peer, "Invalid_NAK");
881 msyslog(LOG_ERR, "Invalid-NAK error at %ld %s<-%s",
882 current_time, stoa(dstadr_sin), stoa(&rbufp->recv_srcadr));
887 restrict_mask &= ~RES_MSSNTP;
888 is_authentic = AUTH_NONE; /* not required */
889 DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s len %d org %#010x.%08x xmt %#010x.%08x NOMAC\n",
890 current_time, stoa(dstadr_sin),
891 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
893 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
894 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
895 } else if (crypto_nak_test == VALIDNAK) {
896 restrict_mask &= ~RES_MSSNTP;
897 is_authentic = AUTH_CRYPTO; /* crypto-NAK */
898 DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x MAC4\n",
899 current_time, stoa(dstadr_sin),
900 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
901 skeyid, authlen + has_mac, is_authentic,
902 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
903 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
905 #ifdef HAVE_NTP_SIGND
907 * If the signature is 20 bytes long, the last 16 of
908 * which are zero, then this is a Microsoft client
909 * wanting AD-style authentication of the server's
912 * This is described in Microsoft's WSPP docs, in MS-SNTP:
913 * http://msdn.microsoft.com/en-us/library/cc212930.aspx
915 } else if ( has_mac == MAX_MD5_LEN
916 && (restrict_mask & RES_MSSNTP)
917 && (retcode == AM_FXMIT || retcode == AM_NEWPASS)
918 && (memcmp(zero_key, (char *)pkt + authlen + 4,
919 MAX_MD5_LEN - 4) == 0)) {
920 is_authentic = AUTH_NONE;
921 #endif /* HAVE_NTP_SIGND */
924 restrict_mask &= ~RES_MSSNTP;
927 * For autokey modes, generate the session key
928 * and install in the key cache. Use the socket
929 * broadcast or unicast address as appropriate.
931 if (crypto_flags && skeyid > NTP_MAXKEY) {
934 * More on the autokey dance (AKD). A cookie is
935 * constructed from public and private values.
936 * For broadcast packets, the cookie is public
937 * (zero). For packets that match no
938 * association, the cookie is hashed from the
939 * addresses and private value. For server
940 * packets, the cookie was previously obtained
941 * from the server. For symmetric modes, the
942 * cookie was previously constructed using an
943 * agreement protocol; however, should PKI be
944 * unavailable, we construct a fake agreement as
945 * the EXOR of the peer and host cookies.
947 * hismode ephemeral persistent
948 * =======================================
951 * client sys cookie 0%
952 * server 0% sys cookie
958 if (has_mac < (int)MAX_MD5_LEN) {
962 if (hismode == MODE_BROADCAST) {
965 * For broadcaster, use the interface
966 * broadcast address when available;
967 * otherwise, use the unicast address
968 * found when the association was
969 * mobilized. However, if this is from
970 * the wildcard interface, game over.
974 ANY_INTERFACE_CHOOSE(&rbufp->recv_srcadr)) {
976 return; /* no wildcard */
979 if (!SOCK_UNSPEC(&rbufp->dstadr->bcast))
981 &rbufp->dstadr->bcast;
982 } else if (peer == NULL) {
983 pkeyid = session_key(
984 &rbufp->recv_srcadr, dstadr_sin, 0,
987 pkeyid = peer->pcookie;
991 * The session key includes both the public
992 * values and cookie. In case of an extension
993 * field, the cookie used for authentication
994 * purposes is zero. Note the hash is saved for
995 * use later in the autokey mambo.
997 if (authlen > (int)LEN_PKT_NOMAC && pkeyid != 0) {
998 session_key(&rbufp->recv_srcadr,
999 dstadr_sin, skeyid, 0, 2);
1000 tkeyid = session_key(
1001 &rbufp->recv_srcadr, dstadr_sin,
1004 tkeyid = session_key(
1005 &rbufp->recv_srcadr, dstadr_sin,
1010 #endif /* AUTOKEY */
1013 * Compute the cryptosum. Note a clogging attack may
1014 * succeed in bloating the key cache. If an autokey,
1015 * purge it immediately, since we won't be needing it
1016 * again. If the packet is authentic, it can mobilize an
1017 * association. Note that there is no key zero.
1019 if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,
1021 is_authentic = AUTH_ERROR;
1023 is_authentic = AUTH_OK;
1025 if (crypto_flags && skeyid > NTP_MAXKEY)
1026 authtrust(skeyid, 0);
1027 #endif /* AUTOKEY */
1028 DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x\n",
1029 current_time, stoa(dstadr_sin),
1030 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
1031 skeyid, authlen + has_mac, is_authentic,
1032 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1033 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
1037 * The association matching rules are implemented by a set of
1038 * routines and an association table. A packet matching an
1039 * association is processed by the peer process for that
1040 * association. If there are no errors, an ephemeral association
1041 * is mobilized: a broadcast packet mobilizes a broadcast client
1042 * aassociation; a manycast server packet mobilizes a manycast
1043 * client association; a symmetric active packet mobilizes a
1044 * symmetric passive association.
1049 * This is a client mode packet not matching any association. If
1050 * an ordinary client, simply toss a server mode packet back
1051 * over the fence. If a manycast client, we have to work a
1057 * If authentication OK, send a server reply; otherwise,
1058 * send a crypto-NAK.
1060 if (!(rbufp->dstadr->flags & INT_MCASTOPEN)) {
1061 if (AUTH(restrict_mask & RES_DONTTRUST,
1063 fast_xmit(rbufp, MODE_SERVER, skeyid,
1065 } else if (is_authentic == AUTH_ERROR) {
1066 fast_xmit(rbufp, MODE_SERVER, 0,
1072 return; /* hooray */
1076 * This must be manycast. Do not respond if not
1077 * configured as a manycast server.
1079 if (!sys_manycastserver) {
1081 return; /* not enabled */
1086 * Do not respond if not the same group.
1088 if (group_test(groupname, NULL)) {
1092 #endif /* AUTOKEY */
1095 * Do not respond if we are not synchronized or our
1096 * stratum is greater than the manycaster or the
1097 * manycaster has already synchronized to us.
1099 if ( sys_leap == LEAP_NOTINSYNC
1100 || sys_stratum >= hisstratum
1101 || (!sys_cohort && sys_stratum == hisstratum + 1)
1102 || rbufp->dstadr->addr_refid == pkt->refid) {
1104 return; /* no help */
1108 * Respond only if authentication succeeds. Don't do a
1109 * crypto-NAK, as that would not be useful.
1111 if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic))
1112 fast_xmit(rbufp, MODE_SERVER, skeyid,
1114 return; /* hooray */
1117 * This is a server mode packet returned in response to a client
1118 * mode packet sent to a multicast group address (for
1119 * manycastclient) or to a unicast address (for pool). The
1120 * origin timestamp is a good nonce to reliably associate the
1121 * reply with what was sent. If there is no match, that's
1122 * curious and could be an intruder attempting to clog, so we
1125 * If the packet is authentic and the manycastclient or pool
1126 * association is found, we mobilize a client association and
1127 * copy pertinent variables from the manycastclient or pool
1128 * association to the new client association. If not, just
1129 * ignore the packet.
1131 * There is an implosion hazard at the manycast client, since
1132 * the manycast servers send the server packet immediately. If
1133 * the guy is already here, don't fire up a duplicate.
1139 * Do not respond if not the same group.
1141 if (group_test(groupname, NULL)) {
1145 #endif /* AUTOKEY */
1146 if ((peer2 = findmanycastpeer(rbufp)) == NULL) {
1148 return; /* not enabled */
1150 if (!AUTH( (!(peer2->cast_flags & MDF_POOL)
1151 && sys_authenticate)
1152 || (restrict_mask & (RES_NOPEER |
1153 RES_DONTTRUST)), is_authentic)) {
1155 return; /* access denied */
1159 * Do not respond if unsynchronized or stratum is below
1160 * the floor or at or above the ceiling.
1162 if ( hisleap == LEAP_NOTINSYNC
1163 || hisstratum < sys_floor
1164 || hisstratum >= sys_ceiling) {
1166 return; /* no help */
1168 peer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr,
1169 MODE_CLIENT, hisversion, peer2->minpoll,
1170 peer2->maxpoll, FLAG_PREEMPT |
1171 (FLAG_IBURST & peer2->flags), MDF_UCAST |
1172 MDF_UCLNT, 0, skeyid, sys_ident);
1175 return; /* ignore duplicate */
1179 * After each ephemeral pool association is spun,
1180 * accelerate the next poll for the pool solicitor so
1181 * the pool will fill promptly.
1183 if (peer2->cast_flags & MDF_POOL)
1184 peer2->nextdate = current_time + 1;
1187 * Further processing of the solicitation response would
1188 * simply detect its origin timestamp as bogus for the
1189 * brand-new association (it matches the prototype
1190 * association) and tinker with peer->nextdate delaying
1193 return; /* solicitation response handled */
1196 * This is the first packet received from a broadcast server. If
1197 * the packet is authentic and we are enabled as broadcast
1198 * client, mobilize a broadcast client association. We don't
1199 * kiss any frogs here.
1205 * Do not respond if not the same group.
1207 if (group_test(groupname, sys_ident)) {
1211 #endif /* AUTOKEY */
1212 if (sys_bclient == 0) {
1214 return; /* not enabled */
1216 if (!AUTH(sys_authenticate | (restrict_mask &
1217 (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
1219 return; /* access denied */
1223 * Do not respond if unsynchronized or stratum is below
1224 * the floor or at or above the ceiling.
1226 if ( hisleap == LEAP_NOTINSYNC
1227 || hisstratum < sys_floor
1228 || hisstratum >= sys_ceiling) {
1230 return; /* no help */
1235 * Do not respond if Autokey and the opcode is not a
1236 * CRYPTO_ASSOC response with association ID.
1238 if ( crypto_flags && skeyid > NTP_MAXKEY
1239 && (opcode & 0xffff0000) != (CRYPTO_ASSOC | CRYPTO_RESP)) {
1241 return; /* protocol error */
1243 #endif /* AUTOKEY */
1246 * Broadcasts received via a multicast address may
1247 * arrive after a unicast volley has begun
1248 * with the same remote address. newpeer() will not
1249 * find duplicate associations on other local endpoints
1250 * if a non-NULL endpoint is supplied. multicastclient
1251 * ephemeral associations are unique across all local
1254 if (!(INT_MCASTOPEN & rbufp->dstadr->flags))
1255 match_ep = rbufp->dstadr;
1260 * Determine whether to execute the initial volley.
1262 if (sys_bdelay > 0.0) {
1265 * If a two-way exchange is not possible,
1266 * neither is Autokey.
1268 if (crypto_flags && skeyid > NTP_MAXKEY) {
1270 return; /* no autokey */
1272 #endif /* AUTOKEY */
1275 * Do not execute the volley. Start out in
1276 * broadcast client mode.
1278 peer = newpeer(&rbufp->recv_srcadr, NULL,
1279 match_ep, MODE_BCLIENT, hisversion,
1280 pkt->ppoll, pkt->ppoll, FLAG_PREEMPT,
1281 MDF_BCLNT, 0, skeyid, sys_ident);
1284 return; /* ignore duplicate */
1287 peer->delay = sys_bdelay;
1294 * Execute the initial volley in order to calibrate the
1295 * propagation delay and run the Autokey protocol.
1297 * Note that the minpoll is taken from the broadcast
1298 * packet, normally 6 (64 s) and that the poll interval
1299 * is fixed at this value.
1301 peer = newpeer(&rbufp->recv_srcadr, NULL, match_ep,
1302 MODE_CLIENT, hisversion, pkt->ppoll, pkt->ppoll,
1303 FLAG_BC_VOL | FLAG_IBURST | FLAG_PREEMPT, MDF_BCLNT,
1304 0, skeyid, sys_ident);
1307 return; /* ignore duplicate */
1311 if (skeyid > NTP_MAXKEY)
1312 crypto_recv(peer, rbufp);
1313 #endif /* AUTOKEY */
1315 return; /* hooray */
1318 * This is the first packet received from a symmetric active
1319 * peer. If the packet is authentic and the first he sent,
1320 * mobilize a passive association. If not, kiss the frog.
1326 * Do not respond if not the same group.
1328 if (group_test(groupname, sys_ident)) {
1332 #endif /* AUTOKEY */
1333 if (!AUTH(sys_authenticate | (restrict_mask &
1334 (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
1337 * If authenticated but cannot mobilize an
1338 * association, send a symmetric passive
1339 * response without mobilizing an association.
1340 * This is for drat broken Windows clients. See
1341 * Microsoft KB 875424 for preferred workaround.
1343 if (AUTH(restrict_mask & RES_DONTTRUST,
1345 fast_xmit(rbufp, MODE_PASSIVE, skeyid,
1347 return; /* hooray */
1349 if (is_authentic == AUTH_ERROR) {
1350 fast_xmit(rbufp, MODE_ACTIVE, 0,
1356 * If we got here, the packet isn't part of an
1357 * existing association, it isn't correctly
1358 * authenticated, and it didn't meet either of
1359 * the previous two special cases so we should
1360 * just drop it on the floor. For example,
1361 * crypto-NAKs (is_authentic == AUTH_CRYPTO)
1362 * will make it this far. This is just
1363 * debug-printed and not logged to avoid log
1366 DPRINTF(2, ("receive: at %ld refusing to mobilize passive association"
1367 " with unknown peer %s mode %d/%s:%s keyid %08x len %d auth %d\n",
1368 current_time, stoa(&rbufp->recv_srcadr),
1369 hismode, hm_str, am_str, skeyid,
1370 (authlen + has_mac), is_authentic));
1376 * Do not respond if synchronized and if stratum is
1377 * below the floor or at or above the ceiling. Note,
1378 * this allows an unsynchronized peer to synchronize to
1379 * us. It would be very strange if he did and then was
1380 * nipped, but that could only happen if we were
1381 * operating at the top end of the range. It also means
1382 * we will spin an ephemeral association in response to
1383 * MODE_ACTIVE KoDs, which will time out eventually.
1385 if ( hisleap != LEAP_NOTINSYNC
1386 && (hisstratum < sys_floor || hisstratum >= sys_ceiling)) {
1388 return; /* no help */
1392 * The message is correctly authenticated and allowed.
1393 * Mobilize a symmetric passive association.
1395 if ((peer = newpeer(&rbufp->recv_srcadr, NULL,
1396 rbufp->dstadr, MODE_PASSIVE, hisversion, pkt->ppoll,
1397 NTP_MAXDPOLL, 0, MDF_UCAST, 0, skeyid,
1398 sys_ident)) == NULL) {
1400 return; /* ignore duplicate */
1406 * Process regular packet. Nothing special.
1412 * Do not respond if not the same group.
1414 if (group_test(groupname, peer->ident)) {
1418 #endif /* AUTOKEY */
1420 if (MODE_BROADCAST == hismode) {
1425 DPRINTF(2, ("receive: PROCPKT/BROADCAST: prev pkt %ld seconds ago, ppoll: %d, %d secs\n",
1426 (current_time - peer->timelastrec),
1427 peer->ppoll, (1 << peer->ppoll)
1429 /* Things we can check:
1431 * Did the poll interval change?
1432 * Is the poll interval in the packet in-range?
1433 * Did this packet arrive too soon?
1434 * Is the timestamp in this packet monotonic
1435 * with respect to the previous packet?
1438 /* This is noteworthy, not error-worthy */
1439 if (pkt->ppoll != peer->ppoll) {
1440 msyslog(LOG_INFO, "receive: broadcast poll from %s changed from %ud to %ud",
1441 stoa(&rbufp->recv_srcadr),
1442 peer->ppoll, pkt->ppoll);
1445 /* This is error-worthy */
1446 if (pkt->ppoll < peer->minpoll ||
1447 pkt->ppoll > peer->maxpoll ) {
1448 msyslog(LOG_INFO, "receive: broadcast poll of %ud from %s is out-of-range (%d to %d)!",
1449 pkt->ppoll, stoa(&rbufp->recv_srcadr),
1450 peer->minpoll, peer->maxpoll);
1454 /* too early? worth an error, too!
1456 * [Bug 3113] Ensure that at least one poll
1457 * interval has elapsed since the last **clean**
1458 * packet was received. We limit the check to
1459 * **clean** packets to prevent replayed packets
1460 * and incorrectly authenticated packets, which
1461 * we'll discard, from being used to create a
1462 * denial of service condition.
1464 deadband = (1u << pkt->ppoll);
1465 if (FLAG_BC_VOL & peer->flags)
1466 deadband -= 3; /* allow greater fuzz after volley */
1467 if ((current_time - peer->timereceived) < deadband) {
1468 msyslog(LOG_INFO, "receive: broadcast packet from %s arrived after %lu, not %lu seconds!",
1469 stoa(&rbufp->recv_srcadr),
1470 (current_time - peer->timereceived),
1475 /* Alert if time from the server is non-monotonic.
1477 * [Bug 3114] is about Broadcast mode replay DoS.
1479 * Broadcast mode *assumes* a trusted network.
1480 * Even so, it's nice to be robust in the face
1483 * If we get an authenticated broadcast packet
1484 * with an "earlier" timestamp, it means one of
1487 * - the broadcast server had a backward step.
1489 * - somebody is trying a replay attack.
1491 * deadband: By default, we assume the broadcast
1492 * network is trustable, so we take our accepted
1493 * broadcast packets as we receive them. But
1494 * some folks might want to take additional poll
1495 * delays before believing a backward step.
1497 if (sys_bcpollbstep) {
1498 /* pkt->ppoll or peer->ppoll ? */
1499 deadband = (1u << pkt->ppoll)
1500 * sys_bcpollbstep + 2;
1505 if (L_ISZERO(&peer->bxmt)) {
1506 tdiff.l_ui = tdiff.l_uf = 0;
1509 L_SUB(&tdiff, &peer->bxmt);
1511 if (tdiff.l_i < 0 &&
1512 (current_time - peer->timereceived) < deadband)
1514 msyslog(LOG_INFO, "receive: broadcast packet from %s contains non-monotonic timestamp: %#010x.%08x -> %#010x.%08x",
1515 stoa(&rbufp->recv_srcadr),
1516 peer->bxmt.l_ui, peer->bxmt.l_uf,
1517 p_xmt.l_ui, p_xmt.l_uf
1523 peer->timelastrec = current_time;
1532 * A passive packet matches a passive association. This is
1533 * usually the result of reconfiguring a client on the fly. As
1534 * this association might be legitimate and this packet an
1535 * attempt to deny service, just ignore it.
1542 * For everything else there is the bit bucket.
1551 * If the association is configured for Autokey, the packet must
1552 * have a public key ID; if not, the packet must have a
1555 if ( is_authentic != AUTH_CRYPTO
1556 && ( ((peer->flags & FLAG_SKEY) && skeyid <= NTP_MAXKEY)
1557 || (!(peer->flags & FLAG_SKEY) && skeyid > NTP_MAXKEY))) {
1561 #endif /* AUTOKEY */
1564 peer->flash &= ~PKT_TEST_MASK;
1565 if (peer->flags & FLAG_XBOGUS) {
1566 peer->flags &= ~FLAG_XBOGUS;
1567 peer->flash |= TEST3;
1571 * Next comes a rigorous schedule of timestamp checking. If the
1572 * transmit timestamp is zero, the server has not initialized in
1573 * interleaved modes or is horribly broken.
1575 * A KoD packet we pay attention to cannot have a 0 transmit
1578 if (L_ISZERO(&p_xmt)) {
1579 peer->flash |= TEST3; /* unsynch */
1580 if (STRATUM_UNSPEC == hisstratum) { /* KoD packet */
1581 peer->bogusorg++; /* for TEST2 or TEST3 */
1583 "receive: Unexpected zero transmit timestamp in KoD from %s",
1584 ntoa(&peer->srcadr));
1589 * If the transmit timestamp duplicates our previous one, the
1590 * packet is a replay. This prevents the bad guys from replaying
1591 * the most recent packet, authenticated or not.
1593 } else if (L_ISEQU(&peer->xmt, &p_xmt)) {
1594 peer->flash |= TEST1; /* duplicate */
1599 * If this is a broadcast mode packet, make sure hisstratum
1600 * is appropriate. Don't do anything else here - we wait to
1601 * see if this is an interleave broadcast packet until after
1602 * we've validated the MAC that SHOULD be provided.
1604 * hisstratum should never be 0.
1605 * If hisstratum is 15, then we'll advertise as UNSPEC but
1606 * at least we'll be able to sync with the broadcast server.
1608 } else if (hismode == MODE_BROADCAST) {
1609 if ( 0 == hisstratum
1610 || STRATUM_UNSPEC <= hisstratum) {
1611 /* Is this a ++sys_declined or ??? */
1613 "receive: Unexpected stratum (%d) in broadcast from %s",
1614 hisstratum, ntoa(&peer->srcadr));
1619 * Basic KoD validation checking:
1621 * KoD packets are a mixed-blessing. Forged KoD packets
1622 * are DoS attacks. There are rare situations where we might
1623 * get a valid KoD response, though. Since KoD packets are
1624 * a special case that complicate the checks we do next, we
1625 * handle the basic KoD checks here.
1627 * Note that we expect the incoming KoD packet to have its
1628 * (nonzero) org, rec, and xmt timestamps set to the xmt timestamp
1629 * that we have previously sent out. Watch interleave mode.
1631 } else if (STRATUM_UNSPEC == hisstratum) {
1632 DEBUG_INSIST(!L_ISZERO(&p_xmt));
1633 if ( L_ISZERO(&p_org) /* We checked p_xmt above */
1634 || L_ISZERO(&p_rec)) {
1637 "receive: KoD packet from %s has a zero org or rec timestamp. Ignoring.",
1638 ntoa(&peer->srcadr));
1642 if ( !L_ISEQU(&p_xmt, &p_org)
1643 || !L_ISEQU(&p_xmt, &p_rec)) {
1646 "receive: KoD packet from %s has inconsistent xmt/org/rec timestamps. Ignoring.",
1647 ntoa(&peer->srcadr));
1651 /* Be conservative */
1652 if (peer->flip == 0 && !L_ISEQU(&p_org, &peer->aorg)) {
1655 "receive: flip 0 KoD origin timestamp %#010x.%08x from %s does not match %#010x.%08x - ignoring.",
1656 p_org.l_ui, p_org.l_uf,
1657 ntoa(&peer->srcadr),
1658 peer->aorg.l_ui, peer->aorg.l_uf);
1660 } else if (peer->flip == 1 && !L_ISEQU(&p_org, &peer->borg)) {
1663 "receive: flip 1 KoD origin timestamp %#010x.%08x from %s does not match interleave %#010x.%08x - ignoring.",
1664 p_org.l_ui, p_org.l_uf,
1665 ntoa(&peer->srcadr),
1666 peer->borg.l_ui, peer->borg.l_uf);
1671 * Basic mode checks:
1673 * If there is no origin timestamp, it's either an initial packet
1674 * or we've already received a response to our query. Of course,
1675 * should 'aorg' be all-zero because this really was the original
1676 * transmit timestamp, we'll ignore this reply. There is a window
1677 * of one nanosecond once every 136 years' time where this is
1678 * possible. We currently ignore this situation.
1680 * Otherwise, check for bogus packet in basic mode.
1681 * If it is bogus, switch to interleaved mode and resynchronize,
1682 * but only after confirming the packet is not bogus in
1683 * symmetric interleaved mode.
1685 * This could also mean somebody is forging packets claiming to
1686 * be from us, attempting to cause our server to KoD us.
1688 } else if (peer->flip == 0) {
1689 INSIST(0 != hisstratum);
1690 INSIST(STRATUM_UNSPEC != hisstratum);
1693 } else if (L_ISZERO(&p_org)) {
1699 /* We allow 0org for: */
1703 /* We disallow 0org for: */
1709 case MODE_BROADCAST:
1712 peer->flash |= TEST2; /* bogus */
1715 INSIST(!"receive(): impossible hismode");
1720 "receive: %s 0 origin timestamp from %s@%s xmt %#010x.%08x",
1721 action, hm_str, ntoa(&peer->srcadr),
1722 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));
1723 } else if (!L_ISEQU(&p_org, &peer->aorg)) {
1724 /* are there cases here where we should bail? */
1725 /* Should we set TEST2 if we decide to try xleave? */
1727 peer->flash |= TEST2; /* bogus */
1729 "receive: Unexpected origin timestamp %#010x.%08x does not match aorg %#010x.%08x from %s@%s xmt %#010x.%08x",
1730 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1731 peer->aorg.l_ui, peer->aorg.l_uf,
1732 hm_str, ntoa(&peer->srcadr),
1733 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));
1734 if ( !L_ISZERO(&peer->dst)
1735 && L_ISEQU(&p_org, &peer->dst)) {
1736 /* Might be the start of an interleave */
1737 if (dynamic_interleave) {
1739 report_event(PEVNT_XLEAVE, peer, NULL);
1742 "receive: Dynamic interleave from %s@%s denied",
1743 hm_str, ntoa(&peer->srcadr));
1751 * Check for valid nonzero timestamp fields.
1753 } else if ( L_ISZERO(&p_org)
1755 || L_ISZERO(&peer->dst)) {
1756 peer->flash |= TEST3; /* unsynch */
1759 * Check for bogus packet in interleaved symmetric mode. This
1760 * can happen if a packet is lost, duplicated or crossed. If
1761 * found, flip and resynchronize.
1763 } else if ( !L_ISZERO(&peer->dst)
1764 && !L_ISEQU(&p_org, &peer->dst)) {
1766 peer->flags |= FLAG_XBOGUS;
1767 peer->flash |= TEST2; /* bogus */
1768 return; /* Bogus packet, we are done */
1774 * If this is a crypto_NAK, the server cannot authenticate a
1775 * client packet. The server might have just changed keys. Clear
1776 * the association and restart the protocol.
1778 if (crypto_nak_test == VALIDNAK) {
1779 report_event(PEVNT_AUTH, peer, "crypto_NAK");
1780 peer->flash |= TEST5; /* bad auth */
1782 if (peer->flags & FLAG_PREEMPT) {
1783 if (unpeer_crypto_nak_early) {
1790 peer_clear(peer, "AUTH");
1792 #endif /* AUTOKEY */
1796 * If the digest fails or it's missing for authenticated
1797 * associations, the client cannot authenticate a server
1798 * reply to a client packet previously sent. The loopback check
1799 * is designed to avoid a bait-and-switch attack, which was
1800 * possible in past versions. If symmetric modes, return a
1801 * crypto-NAK. The peer should restart the protocol.
1803 } else if (!AUTH(peer->keyid || has_mac ||
1804 (restrict_mask & RES_DONTTRUST), is_authentic)) {
1806 if (peer->flash & PKT_TEST_MASK) {
1808 "receive: Bad auth in packet with bad timestamps from %s denied - spoof?",
1809 ntoa(&peer->srcadr));
1813 report_event(PEVNT_AUTH, peer, "digest");
1814 peer->flash |= TEST5; /* bad auth */
1817 && ( hismode == MODE_ACTIVE
1818 || hismode == MODE_PASSIVE))
1819 fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
1820 if (peer->flags & FLAG_PREEMPT) {
1821 if (unpeer_digest_early) {
1826 else if (peer_clear_digest_early && peer->crypto) {
1827 peer_clear(peer, "AUTH");
1829 #endif /* AUTOKEY */
1834 * For broadcast packets:
1836 * HMS: This next line never made much sense to me, even
1837 * when it was up higher:
1838 * If an initial volley, bail out now and let the
1839 * client do its stuff.
1841 * If the packet has not failed authentication, then
1842 * - if the origin timestamp is nonzero this is an
1843 * interleaved broadcast, so restart the protocol.
1844 * - else, this is not an interleaved broadcast packet.
1846 if (hismode == MODE_BROADCAST) {
1847 if ( is_authentic == AUTH_OK
1848 || is_authentic == AUTH_NONE) {
1849 if (!L_ISZERO(&p_org)) {
1850 if (!(peer->flags & FLAG_XB)) {
1852 "receive: Broadcast server at %s is in interleave mode",
1853 ntoa(&peer->srcadr));
1854 peer->flags |= FLAG_XB;
1856 peer->borg = rbufp->recv_time;
1857 report_event(PEVNT_XLEAVE, peer, NULL);
1860 } else if (peer->flags & FLAG_XB) {
1862 "receive: Broadcast server at %s is no longer in interleave mode",
1863 ntoa(&peer->srcadr));
1864 peer->flags &= ~FLAG_XB;
1868 "receive: Bad broadcast auth (%d) from %s",
1869 is_authentic, ntoa(&peer->srcadr));
1873 * Now that we know the packet is correctly authenticated,
1874 * update peer->bxmt.
1881 ** Update the state variables.
1883 if (peer->flip == 0) {
1884 if (hismode != MODE_BROADCAST)
1886 peer->dst = rbufp->recv_time;
1891 * Set the peer ppoll to the maximum of the packet ppoll and the
1892 * peer minpoll. If a kiss-o'-death, set the peer minpoll to
1893 * this maximum and advance the headway to give the sender some
1894 * headroom. Very intricate.
1898 * Check for any kiss codes. Note this is only used when a server
1899 * responds to a packet request
1902 kissCode = kiss_code_check(hisleap, hisstratum, hismode, pkt->refid);
1905 * Check to see if this is a RATE Kiss Code
1906 * Currently this kiss code will accept whatever poll
1907 * rate that the server sends
1909 peer->ppoll = max(peer->minpoll, pkt->ppoll);
1910 if (kissCode == RATEKISS) {
1911 peer->selbroken++; /* Increment the KoD count */
1912 report_event(PEVNT_RATE, peer, NULL);
1913 if (pkt->ppoll > peer->minpoll)
1914 peer->minpoll = peer->ppoll;
1915 peer->burst = peer->retry = 0;
1916 peer->throttle = (NTP_SHIFT + 1) * (1 << peer->minpoll);
1917 poll_update(peer, pkt->ppoll);
1918 return; /* kiss-o'-death */
1920 if (kissCode != NOKISS) {
1921 peer->selbroken++; /* Increment the KoD count */
1922 return; /* Drop any other kiss code packets */
1933 * - this is a *cast (uni-, broad-, or m-) server packet
1934 * - and it's symmetric-key authenticated
1935 * then see if the sender's IP is trusted for this keyid.
1936 * If it is, great - nothing special to do here.
1937 * Otherwise, we should report and bail.
1939 * Autokey-authenticated packets are accepted.
1943 case MODE_SERVER: /* server mode */
1944 case MODE_BROADCAST: /* broadcast mode */
1945 case MODE_ACTIVE: /* symmetric active mode */
1946 case MODE_PASSIVE: /* symmetric passive mode */
1947 if ( is_authentic == AUTH_OK
1949 && skeyid <= NTP_MAXKEY
1950 && !authistrustedip(skeyid, &peer->srcadr)) {
1951 report_event(PEVNT_AUTH, peer, "authIP");
1957 case MODE_CLIENT: /* client mode */
1958 #if 0 /* At this point, MODE_CONTROL is overloaded by MODE_BCLIENT */
1959 case MODE_CONTROL: /* control mode */
1961 case MODE_PRIVATE: /* private mode */
1962 case MODE_BCLIENT: /* broadcast client mode */
1965 case MODE_UNSPEC: /* unspecified (old version) */
1968 "receive: Unexpected mode (%d) in packet from %s",
1969 hismode, ntoa(&peer->srcadr));
1975 * That was hard and I am sweaty, but the packet is squeaky
1976 * clean. Get on with real work.
1978 peer->timereceived = current_time;
1979 peer->timelastrec = current_time;
1980 if (is_authentic == AUTH_OK)
1981 peer->flags |= FLAG_AUTHENTIC;
1983 peer->flags &= ~FLAG_AUTHENTIC;
1987 * More autokey dance. The rules of the cha-cha are as follows:
1989 * 1. If there is no key or the key is not auto, do nothing.
1991 * 2. If this packet is in response to the one just previously
1992 * sent or from a broadcast server, do the extension fields.
1993 * Otherwise, assume bogosity and bail out.
1995 * 3. If an extension field contains a verified signature, it is
1996 * self-authenticated and we sit the dance.
1998 * 4. If this is a server reply, check only to see that the
1999 * transmitted key ID matches the received key ID.
2001 * 5. Check to see that one or more hashes of the current key ID
2002 * matches the previous key ID or ultimate original key ID
2003 * obtained from the broadcaster or symmetric peer. If no
2004 * match, sit the dance and call for new autokey values.
2006 * In case of crypto error, fire the orchestra, stop dancing and
2007 * restart the protocol.
2009 if (peer->flags & FLAG_SKEY) {
2011 * Decrement remaining autokey hashes. This isn't
2012 * perfect if a packet is lost, but results in no harm.
2014 ap = (struct autokey *)peer->recval.ptr;
2019 peer->flash |= TEST8;
2020 rval = crypto_recv(peer, rbufp);
2021 if (rval == XEVNT_OK) {
2024 if (rval == XEVNT_ERR) {
2025 report_event(PEVNT_RESTART, peer,
2027 peer_clear(peer, "CRYP");
2028 peer->flash |= TEST9; /* bad crypt */
2029 if (peer->flags & FLAG_PREEMPT) {
2030 if (unpeer_crypto_early) {
2039 * If server mode, verify the receive key ID matches
2040 * the transmit key ID.
2042 if (hismode == MODE_SERVER) {
2043 if (skeyid == peer->keyid)
2044 peer->flash &= ~TEST8;
2047 * If an extension field is present, verify only that it
2048 * has been correctly signed. We don't need a sequence
2049 * check here, but the sequence continues.
2051 } else if (!(peer->flash & TEST8)) {
2052 peer->pkeyid = skeyid;
2055 * Now the fun part. Here, skeyid is the current ID in
2056 * the packet, pkeyid is the ID in the last packet and
2057 * tkeyid is the hash of skeyid. If the autokey values
2058 * have not been received, this is an automatic error.
2059 * If so, check that the tkeyid matches pkeyid. If not,
2060 * hash tkeyid and try again. If the number of hashes
2061 * exceeds the number remaining in the sequence, declare
2062 * a successful failure and refresh the autokey values.
2064 } else if (ap != NULL) {
2067 for (i = 0; ; i++) {
2068 if ( tkeyid == peer->pkeyid
2069 || tkeyid == ap->key) {
2070 peer->flash &= ~TEST8;
2071 peer->pkeyid = skeyid;
2080 tkeyid = session_key(
2081 &rbufp->recv_srcadr, dstadr_sin,
2084 if (peer->flash & TEST8)
2085 report_event(PEVNT_AUTH, peer, "keylist");
2087 if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */
2088 peer->flash |= TEST8; /* bad autokey */
2091 * The maximum lifetime of the protocol is about one
2092 * week before restarting the Autokey protocol to
2093 * refresh certificates and leapseconds values.
2095 if (current_time > peer->refresh) {
2096 report_event(PEVNT_RESTART, peer,
2098 peer_clear(peer, "TIME");
2102 #endif /* AUTOKEY */
2105 * The dance is complete and the flash bits have been lit. Toss
2106 * the packet over the fence for processing, which may light up
2109 process_packet(peer, pkt, rbufp->recv_length);
2112 * In interleaved mode update the state variables. Also adjust the
2113 * transmit phase to avoid crossover.
2115 if (peer->flip != 0) {
2117 peer->dst = rbufp->recv_time;
2118 if (peer->nextdate - current_time < (1U << min(peer->ppoll,
2128 * process_packet - Packet Procedure, a la Section 3.4.4 of RFC-1305
2129 * Or almost, at least. If we're in here we have a reasonable
2130 * expectation that we will be having a long term
2131 * relationship with this host.
2135 register struct peer *peer,
2136 register struct pkt *pkt,
2141 double p_offset, p_del, p_disp;
2142 l_fp p_rec, p_xmt, p_org, p_reftime, ci;
2143 u_char pmode, pleap, pversion, pstratum;
2144 char statstr[NTP_MAXSTRLEN];
2147 double etemp, ftemp, td;
2154 p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
2156 p_disp = FPTOD(NTOHS_FP(pkt->rootdisp));
2157 NTOHL_FP(&pkt->reftime, &p_reftime);
2158 NTOHL_FP(&pkt->org, &p_org);
2159 NTOHL_FP(&pkt->rec, &p_rec);
2160 NTOHL_FP(&pkt->xmt, &p_xmt);
2161 pmode = PKT_MODE(pkt->li_vn_mode);
2162 pleap = PKT_LEAP(pkt->li_vn_mode);
2163 pversion = PKT_VERSION(pkt->li_vn_mode);
2164 pstratum = PKT_TO_STRATUM(pkt->stratum);
2171 * Verify the server is synchronized; that is, the leap bits,
2172 * stratum and root distance are valid.
2174 if ( pleap == LEAP_NOTINSYNC /* test 6 */
2175 || pstratum < sys_floor || pstratum >= sys_ceiling)
2176 peer->flash |= TEST6; /* bad synch or strat */
2177 if (p_del / 2 + p_disp >= MAXDISPERSE) /* test 7 */
2178 peer->flash |= TEST7; /* bad header */
2181 * If any tests fail at this point, the packet is discarded.
2182 * Note that some flashers may have already been set in the
2183 * receive() routine.
2185 if (peer->flash & PKT_TEST_MASK) {
2186 peer->seldisptoolarge++;
2187 DPRINTF(1, ("packet: flash header %04x\n",
2200 * Capture the header values in the client/peer association..
2202 record_raw_stats(&peer->srcadr, peer->dstadr ?
2203 &peer->dstadr->sin : NULL,
2204 &p_org, &p_rec, &p_xmt, &peer->dst,
2205 pleap, pversion, pmode, pstratum, pkt->ppoll, pkt->precision,
2206 p_del, p_disp, pkt->refid);
2208 peer->stratum = min(pstratum, STRATUM_UNSPEC);
2209 peer->pmode = pmode;
2210 peer->precision = pkt->precision;
2211 peer->rootdelay = p_del;
2212 peer->rootdisp = p_disp;
2213 peer->refid = pkt->refid; /* network byte order */
2214 peer->reftime = p_reftime;
2217 * First, if either burst mode is armed, enable the burst.
2218 * Compute the headway for the next packet and delay if
2219 * necessary to avoid exceeding the threshold.
2221 if (peer->retry > 0) {
2224 peer->burst = min(1 << (peer->hpoll -
2225 peer->minpoll), NTP_SHIFT) - 1;
2227 peer->burst = NTP_IBURST - 1;
2228 if (peer->burst > 0)
2229 peer->nextdate = current_time;
2231 poll_update(peer, peer->hpoll);
2236 * If the peer was previously unreachable, raise a trap. In any
2237 * case, mark it reachable.
2240 report_event(PEVNT_REACH, peer, NULL);
2241 peer->timereachable = current_time;
2246 * For a client/server association, calculate the clock offset,
2247 * roundtrip delay and dispersion. The equations are reordered
2248 * from the spec for more efficient use of temporaries. For a
2249 * broadcast association, offset the last measurement by the
2250 * computed delay during the client/server volley. Note the
2251 * computation of dispersion includes the system precision plus
2252 * that due to the frequency error since the origin time.
2254 * It is very important to respect the hazards of overflow. The
2255 * only permitted operation on raw timestamps is subtraction,
2256 * where the result is a signed quantity spanning from 68 years
2257 * in the past to 68 years in the future. To avoid loss of
2258 * precision, these calculations are done using 64-bit integer
2259 * arithmetic. However, the offset and delay calculations are
2260 * sums and differences of these first-order differences, which
2261 * if done using 64-bit integer arithmetic, would be valid over
2262 * only half that span. Since the typical first-order
2263 * differences are usually very small, they are converted to 64-
2264 * bit doubles and all remaining calculations done in floating-
2265 * double arithmetic. This preserves the accuracy while
2266 * retaining the 68-year span.
2268 * There are three interleaving schemes, basic, interleaved
2269 * symmetric and interleaved broadcast. The timestamps are
2270 * idioscyncratically different. See the onwire briefing/white
2271 * paper at www.eecis.udel.edu/~mills for details.
2273 * Interleaved symmetric mode
2274 * t1 = peer->aorg/borg, t2 = peer->rec, t3 = p_xmt,
2277 if (peer->flip != 0) {
2278 ci = p_xmt; /* t3 - t4 */
2279 L_SUB(&ci, &peer->dst);
2281 ci = p_rec; /* t2 - t1 */
2283 L_SUB(&ci, &peer->borg);
2285 L_SUB(&ci, &peer->aorg);
2288 p_offset = (t21 + t34) / 2.;
2289 if (p_del < 0 || p_del > 1.) {
2290 snprintf(statstr, sizeof(statstr),
2291 "t21 %.6f t34 %.6f", t21, t34);
2292 report_event(PEVNT_XERR, peer, statstr);
2299 } else if (peer->pmode == MODE_BROADCAST) {
2302 * Interleaved broadcast mode. Use interleaved timestamps.
2303 * t1 = peer->borg, t2 = p_org, t3 = p_org, t4 = aorg
2305 if (peer->flags & FLAG_XB) {
2306 ci = p_org; /* delay */
2307 L_SUB(&ci, &peer->aorg);
2309 ci = p_org; /* t2 - t1 */
2310 L_SUB(&ci, &peer->borg);
2313 peer->borg = peer->dst;
2314 if (t34 < 0 || t34 > 1.) {
2315 /* drop all if in the initial volley */
2316 if (FLAG_BC_VOL & peer->flags)
2317 goto bcc_init_volley_fail;
2318 snprintf(statstr, sizeof(statstr),
2319 "offset %.6f delay %.6f", t21, t34);
2320 report_event(PEVNT_XERR, peer, statstr);
2327 * Basic broadcast - use direct timestamps.
2328 * t3 = p_xmt, t4 = peer->dst
2331 ci = p_xmt; /* t3 - t4 */
2332 L_SUB(&ci, &peer->dst);
2338 * When calibration is complete and the clock is
2339 * synchronized, the bias is calculated as the difference
2340 * between the unicast timestamp and the broadcast
2341 * timestamp. This works for both basic and interleaved
2343 * [Bug 3031] Don't keep this peer when the delay
2344 * calculation gives reason to suspect clock steps.
2345 * This is assumed for delays > 50ms.
2347 if (FLAG_BC_VOL & peer->flags) {
2348 peer->flags &= ~FLAG_BC_VOL;
2349 peer->delay = fabs(peer->offset - p_offset) * 2;
2350 DPRINTF(2, ("broadcast volley: initial delay=%.6f\n",
2352 if (peer->delay > fabs(sys_bdelay)) {
2353 bcc_init_volley_fail:
2354 DPRINTF(2, ("%s", "broadcast volley: initial delay exceeds limit\n"));
2359 peer->nextdate = current_time + (1u << peer->ppoll) - 2u;
2360 p_del = peer->delay;
2361 p_offset += p_del / 2;
2365 * Basic mode, otherwise known as the old fashioned way.
2367 * t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->dst
2370 ci = p_xmt; /* t3 - t4 */
2371 L_SUB(&ci, &peer->dst);
2373 ci = p_rec; /* t2 - t1 */
2376 p_del = fabs(t21 - t34);
2377 p_offset = (t21 + t34) / 2.;
2379 p_del = max(p_del, LOGTOD(sys_precision));
2380 p_disp = LOGTOD(sys_precision) + LOGTOD(peer->precision) +
2385 * This code calculates the outbound and inbound data rates by
2386 * measuring the differences between timestamps at different
2387 * packet lengths. This is helpful in cases of large asymmetric
2388 * delays commonly experienced on deep space communication
2391 if (peer->t21_last > 0 && peer->t34_bytes > 0) {
2392 itemp = peer->t21_bytes - peer->t21_last;
2394 etemp = t21 - peer->t21;
2395 if (fabs(etemp) > 1e-6) {
2396 ftemp = itemp / etemp;
2401 itemp = len - peer->t34_bytes;
2403 etemp = -t34 - peer->t34;
2404 if (fabs(etemp) > 1e-6) {
2405 ftemp = itemp / etemp;
2413 * The following section compensates for different data rates on
2414 * the outbound (d21) and inbound (t34) directions. To do this,
2415 * it finds t such that r21 * t - r34 * (d - t) = 0, where d is
2416 * the roundtrip delay. Then it calculates the correction as a
2420 peer->t21_last = peer->t21_bytes;
2422 peer->t34_bytes = len;
2423 DPRINTF(2, ("packet: t21 %.9lf %d t34 %.9lf %d\n", peer->t21,
2424 peer->t21_bytes, peer->t34, peer->t34_bytes));
2425 if (peer->r21 > 0 && peer->r34 > 0 && p_del > 0) {
2426 if (peer->pmode != MODE_BROADCAST)
2427 td = (peer->r34 / (peer->r21 + peer->r34) -
2433 * Unfortunately, in many cases the errors are
2434 * unacceptable, so for the present the rates are not
2435 * used. In future, we might find conditions where the
2436 * calculations are useful, so this should be considered
2437 * a work in progress.
2441 DPRINTF(2, ("packet: del %.6lf r21 %.1lf r34 %.1lf %.6lf\n",
2442 p_del, peer->r21 / 1e3, peer->r34 / 1e3,
2448 * That was awesome. Now hand off to the clock filter.
2450 clock_filter(peer, p_offset + peer->bias, p_del, p_disp);
2453 * If we are in broadcast calibrate mode, return to broadcast
2454 * client mode when the client is fit and the autokey dance is
2457 if ( (FLAG_BC_VOL & peer->flags)
2458 && MODE_CLIENT == peer->hmode
2459 && !(TEST11 & peer_unfit(peer))) { /* distance exceeded */
2461 if (peer->flags & FLAG_SKEY) {
2462 if (!(~peer->crypto & CRYPTO_FLAG_ALL))
2463 peer->hmode = MODE_BCLIENT;
2465 peer->hmode = MODE_BCLIENT;
2467 #else /* !AUTOKEY follows */
2468 peer->hmode = MODE_BCLIENT;
2469 #endif /* !AUTOKEY */
2475 * clock_update - Called at system process update intervals.
2479 struct peer *peer /* peer structure pointer */
2484 #ifdef HAVE_LIBSCF_H
2486 #endif /* HAVE_LIBSCF_H */
2489 * Update the system state variables. We do this very carefully,
2490 * as the poll interval might need to be clamped differently.
2493 sys_epoch = peer->epoch;
2494 if (sys_poll < peer->minpoll)
2495 sys_poll = peer->minpoll;
2496 if (sys_poll > peer->maxpoll)
2497 sys_poll = peer->maxpoll;
2498 poll_update(peer, sys_poll);
2499 sys_stratum = min(peer->stratum + 1, STRATUM_UNSPEC);
2500 if ( peer->stratum == STRATUM_REFCLOCK
2501 || peer->stratum == STRATUM_UNSPEC)
2502 sys_refid = peer->refid;
2504 sys_refid = addr2refid(&peer->srcadr);
2506 * Root Dispersion (E) is defined (in RFC 5905) as:
2508 * E = p.epsilon_r + p.epsilon + p.psi + PHI*(s.t - p.t) + |THETA|
2511 * p.epsilon_r is the PollProc's root dispersion
2512 * p.epsilon is the PollProc's dispersion
2513 * p.psi is the PollProc's jitter
2514 * THETA is the combined offset
2516 * NB: Think Hard about where these numbers come from and
2517 * what they mean. When did peer->update happen? Has anything
2518 * interesting happened since then? What values are the most
2521 * DLM thinks this equation is probably the best of all worse choices.
2523 dtemp = peer->rootdisp
2526 + clock_phi * (current_time - peer->update)
2529 if (dtemp > sys_mindisp)
2530 sys_rootdisp = dtemp;
2532 sys_rootdisp = sys_mindisp;
2533 sys_rootdelay = peer->delay + peer->rootdelay;
2534 sys_reftime = peer->dst;
2536 DPRINTF(1, ("clock_update: at %lu sample %lu associd %d\n",
2537 current_time, peer->epoch, peer->associd));
2540 * Comes now the moment of truth. Crank the clock discipline and
2541 * see what comes out.
2543 switch (local_clock(peer, sys_offset)) {
2546 * Clock exceeds panic threshold. Life as we know it ends.
2549 #ifdef HAVE_LIBSCF_H
2551 * For Solaris enter the maintenance mode.
2553 if ((fmri = getenv("SMF_FMRI")) != NULL) {
2554 if (smf_maintain_instance(fmri, 0) < 0) {
2555 printf("smf_maintain_instance: %s\n",
2556 scf_strerror(scf_error()));
2560 * Sleep until SMF kills us.
2565 #endif /* HAVE_LIBSCF_H */
2570 * Clock was stepped. Flush all time values of all peers.
2574 set_sys_leap(LEAP_NOTINSYNC);
2575 sys_stratum = STRATUM_UNSPEC;
2576 memcpy(&sys_refid, "STEP", 4);
2579 L_CLR(&sys_reftime);
2580 sys_jitter = LOGTOD(sys_precision);
2581 leapsec_reset_frame();
2585 * Clock was slewed. Handle the leapsecond stuff.
2590 * If this is the first time the clock is set, reset the
2591 * leap bits. If crypto, the timer will goose the setup
2594 if (sys_leap == LEAP_NOTINSYNC) {
2595 set_sys_leap(LEAP_NOWARNING);
2599 #endif /* AUTOKEY */
2601 * If our parent process is waiting for the
2602 * first clock sync, send them home satisfied.
2604 #ifdef HAVE_WORKING_FORK
2605 if (waitsync_fd_to_close != -1) {
2606 close(waitsync_fd_to_close);
2607 waitsync_fd_to_close = -1;
2608 DPRINTF(1, ("notified parent --wait-sync is done\n"));
2610 #endif /* HAVE_WORKING_FORK */
2615 * If there is no leap second pending and the number of
2616 * survivor leap bits is greater than half the number of
2617 * survivors, try to schedule a leap for the end of the
2618 * current month. (This only works if no leap second for
2619 * that range is in the table, so doing this more than
2620 * once is mostly harmless.)
2622 if (leapsec == LSPROX_NOWARN) {
2623 if ( leap_vote_ins > leap_vote_del
2624 && leap_vote_ins > sys_survivors / 2) {
2626 leapsec_add_dyn(TRUE, now.l_ui, NULL);
2628 if ( leap_vote_del > leap_vote_ins
2629 && leap_vote_del > sys_survivors / 2) {
2631 leapsec_add_dyn(FALSE, now.l_ui, NULL);
2637 * Popcorn spike or step threshold exceeded. Pretend it never
2647 * poll_update - update peer poll interval
2651 struct peer *peer, /* peer structure pointer */
2659 * This routine figures out when the next poll should be sent.
2660 * That turns out to be wickedly complicated. One problem is
2661 * that sometimes the time for the next poll is in the past when
2662 * the poll interval is reduced. We watch out for races here
2663 * between the receive process and the poll process.
2665 * Clamp the poll interval between minpoll and maxpoll.
2667 hpoll = max(min(peer->maxpoll, mpoll), peer->minpoll);
2671 * If during the crypto protocol the poll interval has changed,
2672 * the lifetimes in the key list are probably bogus. Purge the
2673 * the key list and regenerate it later.
2675 if ((peer->flags & FLAG_SKEY) && hpoll != peer->hpoll)
2677 #endif /* AUTOKEY */
2678 peer->hpoll = hpoll;
2681 * There are three variables important for poll scheduling, the
2682 * current time (current_time), next scheduled time (nextdate)
2683 * and the earliest time (utemp). The earliest time is 2 s
2684 * seconds, but could be more due to rate management. When
2685 * sending in a burst, use the earliest time. When not in a
2686 * burst but with a reply pending, send at the earliest time
2687 * unless the next scheduled time has not advanced. This can
2688 * only happen if multiple replies are pending in the same
2689 * response interval. Otherwise, send at the later of the next
2690 * scheduled time and the earliest time.
2692 * Now we figure out if there is an override. If a burst is in
2693 * progress and we get called from the receive process, just
2694 * slink away. If called from the poll process, delay 1 s for a
2695 * reference clock, otherwise 2 s.
2697 utemp = current_time + max(peer->throttle - (NTP_SHIFT - 1) *
2698 (1 << peer->minpoll), ntp_minpkt);
2699 if (peer->burst > 0) {
2700 if (peer->nextdate > current_time)
2703 else if (peer->flags & FLAG_REFCLOCK)
2704 peer->nextdate = current_time + RESP_DELAY;
2705 #endif /* REFCLOCK */
2707 peer->nextdate = utemp;
2711 * If a burst is not in progress and a crypto response message
2712 * is pending, delay 2 s, but only if this is a new interval.
2714 } else if (peer->cmmd != NULL) {
2715 if (peer->nextdate > current_time) {
2716 if (peer->nextdate + ntp_minpkt != utemp)
2717 peer->nextdate = utemp;
2719 peer->nextdate = utemp;
2721 #endif /* AUTOKEY */
2724 * The ordinary case. If a retry, use minpoll; if unreachable,
2725 * use host poll; otherwise, use the minimum of host and peer
2726 * polls; In other words, oversampling is okay but
2727 * understampling is evil. Use the maximum of this value and the
2728 * headway. If the average headway is greater than the headway
2729 * threshold, increase the headway by the minimum interval.
2732 if (peer->retry > 0)
2733 hpoll = peer->minpoll;
2734 else if (!(peer->reach))
2735 hpoll = peer->hpoll;
2737 hpoll = min(peer->ppoll, peer->hpoll);
2739 if (peer->flags & FLAG_REFCLOCK)
2742 #endif /* REFCLOCK */
2743 next = ((0x1000UL | (ntp_random() & 0x0ff)) <<
2745 next += peer->outdate;
2747 peer->nextdate = next;
2749 peer->nextdate = utemp;
2750 if (peer->throttle > (1 << peer->minpoll))
2751 peer->nextdate += ntp_minpkt;
2753 DPRINTF(2, ("poll_update: at %lu %s poll %d burst %d retry %d head %d early %lu next %lu\n",
2754 current_time, ntoa(&peer->srcadr), peer->hpoll,
2755 peer->burst, peer->retry, peer->throttle,
2756 utemp - current_time, peer->nextdate -
2762 * peer_clear - clear peer filter registers. See Section 3.4.8 of the
2767 struct peer *peer, /* peer structure */
2768 const char *ident /* tally lights */
2772 l_fp bxmt = peer->bxmt; /* bcast clients retain this! */
2776 * If cryptographic credentials have been acquired, toss them to
2777 * Valhalla. Note that autokeys are ephemeral, in that they are
2778 * tossed immediately upon use. Therefore, the keylist can be
2779 * purged anytime without needing to preserve random keys. Note
2780 * that, if the peer is purged, the cryptographic variables are
2781 * purged, too. This makes it much harder to sneak in some
2782 * unauthenticated data in the clock filter.
2785 if (peer->iffval != NULL)
2786 BN_free(peer->iffval);
2787 value_free(&peer->cookval);
2788 value_free(&peer->recval);
2789 value_free(&peer->encrypt);
2790 value_free(&peer->sndval);
2791 if (peer->cmmd != NULL)
2793 if (peer->subject != NULL)
2794 free(peer->subject);
2795 if (peer->issuer != NULL)
2797 #endif /* AUTOKEY */
2800 * Clear all values, including the optional crypto values above.
2802 memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO(peer));
2803 peer->ppoll = peer->maxpoll;
2804 peer->hpoll = peer->minpoll;
2805 peer->disp = MAXDISPERSE;
2806 peer->flash = peer_unfit(peer);
2807 peer->jitter = LOGTOD(sys_precision);
2809 /* Don't throw away our broadcast replay protection */
2810 if (peer->hmode == MODE_BCLIENT)
2814 * If interleave mode, initialize the alternate origin switch.
2816 if (peer->flags & FLAG_XLEAVE)
2818 for (u = 0; u < NTP_SHIFT; u++) {
2819 peer->filter_order[u] = u;
2820 peer->filter_disp[u] = MAXDISPERSE;
2823 if (!(peer->flags & FLAG_REFCLOCK)) {
2825 peer->leap = LEAP_NOTINSYNC;
2826 peer->stratum = STRATUM_UNSPEC;
2827 memcpy(&peer->refid, ident, 4);
2833 * During initialization use the association count to spread out
2834 * the polls at one-second intervals. Passive associations'
2835 * first poll is delayed by the "discard minimum" to avoid rate
2836 * limiting. Other post-startup new or cleared associations
2837 * randomize the first poll over the minimum poll interval to
2840 peer->nextdate = peer->update = peer->outdate = current_time;
2842 peer->nextdate += peer_associations;
2843 } else if (MODE_PASSIVE == peer->hmode) {
2844 peer->nextdate += ntp_minpkt;
2846 peer->nextdate += ntp_random() % peer->minpoll;
2849 peer->refresh = current_time + (1 << NTP_REFRESH);
2850 #endif /* AUTOKEY */
2851 DPRINTF(1, ("peer_clear: at %ld next %ld associd %d refid %s\n",
2852 current_time, peer->nextdate, peer->associd,
2858 * clock_filter - add incoming clock sample to filter register and run
2859 * the filter procedure to find the best sample.
2863 struct peer *peer, /* peer structure pointer */
2864 double sample_offset, /* clock offset */
2865 double sample_delay, /* roundtrip delay */
2866 double sample_disp /* dispersion */
2869 double dst[NTP_SHIFT]; /* distance vector */
2870 int ord[NTP_SHIFT]; /* index vector */
2872 double dtemp, etemp;
2876 * A sample consists of the offset, delay, dispersion and epoch
2877 * of arrival. The offset and delay are determined by the on-
2878 * wire protocol. The dispersion grows from the last outbound
2879 * packet to the arrival of this one increased by the sum of the
2880 * peer precision and the system precision as required by the
2881 * error budget. First, shift the new arrival into the shift
2882 * register discarding the oldest one.
2884 j = peer->filter_nextpt;
2885 peer->filter_offset[j] = sample_offset;
2886 peer->filter_delay[j] = sample_delay;
2887 peer->filter_disp[j] = sample_disp;
2888 peer->filter_epoch[j] = current_time;
2889 j = (j + 1) % NTP_SHIFT;
2890 peer->filter_nextpt = j;
2893 * Update dispersions since the last update and at the same
2894 * time initialize the distance and index lists. Since samples
2895 * become increasingly uncorrelated beyond the Allan intercept,
2896 * only under exceptional cases will an older sample be used.
2897 * Therefore, the distance list uses a compound metric. If the
2898 * dispersion is greater than the maximum dispersion, clamp the
2899 * distance at that value. If the time since the last update is
2900 * less than the Allan intercept use the delay; otherwise, use
2901 * the sum of the delay and dispersion.
2903 dtemp = clock_phi * (current_time - peer->update);
2904 peer->update = current_time;
2905 for (i = NTP_SHIFT - 1; i >= 0; i--) {
2907 peer->filter_disp[j] += dtemp;
2908 if (peer->filter_disp[j] >= MAXDISPERSE) {
2909 peer->filter_disp[j] = MAXDISPERSE;
2910 dst[i] = MAXDISPERSE;
2911 } else if (peer->update - peer->filter_epoch[j] >
2912 (u_long)ULOGTOD(allan_xpt)) {
2913 dst[i] = peer->filter_delay[j] +
2914 peer->filter_disp[j];
2916 dst[i] = peer->filter_delay[j];
2919 j = (j + 1) % NTP_SHIFT;
2923 * If the clock has stabilized, sort the samples by distance.
2925 if (freq_cnt == 0) {
2926 for (i = 1; i < NTP_SHIFT; i++) {
2927 for (j = 0; j < i; j++) {
2928 if (dst[j] > dst[i]) {
2941 * Copy the index list to the association structure so ntpq
2942 * can see it later. Prune the distance list to leave only
2943 * samples less than the maximum dispersion, which disfavors
2944 * uncorrelated samples older than the Allan intercept. To
2945 * further improve the jitter estimate, of the remainder leave
2946 * only samples less than the maximum distance, but keep at
2947 * least two samples for jitter calculation.
2950 for (i = 0; i < NTP_SHIFT; i++) {
2951 peer->filter_order[i] = (u_char) ord[i];
2952 if ( dst[i] >= MAXDISPERSE
2953 || (m >= 2 && dst[i] >= sys_maxdist))
2959 * Compute the dispersion and jitter. The dispersion is weighted
2960 * exponentially by NTP_FWEIGHT (0.5) so it is normalized close
2961 * to 1.0. The jitter is the RMS differences relative to the
2962 * lowest delay sample.
2964 peer->disp = peer->jitter = 0;
2966 for (i = NTP_SHIFT - 1; i >= 0; i--) {
2968 peer->disp = NTP_FWEIGHT * (peer->disp +
2969 peer->filter_disp[j]);
2971 peer->jitter += DIFF(peer->filter_offset[j],
2972 peer->filter_offset[k]);
2976 * If no acceptable samples remain in the shift register,
2977 * quietly tiptoe home leaving only the dispersion. Otherwise,
2978 * save the offset, delay and jitter. Note the jitter must not
2979 * be less than the precision.
2985 etemp = fabs(peer->offset - peer->filter_offset[k]);
2986 peer->offset = peer->filter_offset[k];
2987 peer->delay = peer->filter_delay[k];
2989 peer->jitter /= m - 1;
2990 peer->jitter = max(SQRT(peer->jitter), LOGTOD(sys_precision));
2993 * If the the new sample and the current sample are both valid
2994 * and the difference between their offsets exceeds CLOCK_SGATE
2995 * (3) times the jitter and the interval between them is less
2996 * than twice the host poll interval, consider the new sample
2997 * a popcorn spike and ignore it.
2999 if ( peer->disp < sys_maxdist
3000 && peer->filter_disp[k] < sys_maxdist
3001 && etemp > CLOCK_SGATE * peer->jitter
3002 && peer->filter_epoch[k] - peer->epoch
3003 < 2. * ULOGTOD(peer->hpoll)) {
3004 snprintf(tbuf, sizeof(tbuf), "%.6f s", etemp);
3005 report_event(PEVNT_POPCORN, peer, tbuf);
3010 * A new minimum sample is useful only if it is later than the
3011 * last one used. In this design the maximum lifetime of any
3012 * sample is not greater than eight times the poll interval, so
3013 * the maximum interval between minimum samples is eight
3016 if (peer->filter_epoch[k] <= peer->epoch) {
3017 DPRINTF(2, ("clock_filter: old sample %lu\n", current_time -
3018 peer->filter_epoch[k]));
3021 peer->epoch = peer->filter_epoch[k];
3024 * The mitigated sample statistics are saved for later
3025 * processing. If not synchronized or not in a burst, tickle the
3026 * clock select algorithm.
3028 record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
3029 peer->offset, peer->delay, peer->disp, peer->jitter);
3030 DPRINTF(1, ("clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f\n",
3031 m, peer->offset, peer->delay, peer->disp,
3033 if (peer->burst == 0 || sys_leap == LEAP_NOTINSYNC)
3039 * clock_select - find the pick-of-the-litter clock
3041 * LOCKCLOCK: (1) If the local clock is the prefer peer, it will always
3042 * be enabled, even if declared falseticker, (2) only the prefer peer
3043 * can be selected as the system peer, (3) if the external source is
3044 * down, the system leap bits are set to 11 and the stratum set to
3058 double orphmet = 2.0 * U_INT32_MAX; /* 2x is greater than */
3059 struct endpoint endp;
3060 struct peer *osys_peer;
3061 struct peer *sys_prefer = NULL; /* prefer peer */
3062 struct peer *typesystem = NULL;
3063 struct peer *typeorphan = NULL;
3065 struct peer *typeacts = NULL;
3066 struct peer *typelocal = NULL;
3067 struct peer *typepps = NULL;
3068 #endif /* REFCLOCK */
3069 static struct endpoint *endpoint = NULL;
3070 static int *indx = NULL;
3071 static peer_select *peers = NULL;
3072 static u_int endpoint_size = 0;
3073 static u_int peers_size = 0;
3074 static u_int indx_size = 0;
3078 * Initialize and create endpoint, index and peer lists big
3079 * enough to handle all associations.
3081 osys_peer = sys_peer;
3084 set_sys_leap(LEAP_NOTINSYNC);
3085 sys_stratum = STRATUM_UNSPEC;
3086 memcpy(&sys_refid, "DOWN", 4);
3087 #endif /* LOCKCLOCK */
3090 * Allocate dynamic space depending on the number of
3094 for (peer = peer_list; peer != NULL; peer = peer->p_link)
3096 endpoint_size = ALIGNED_SIZE(nlist * 2 * sizeof(*endpoint));
3097 peers_size = ALIGNED_SIZE(nlist * sizeof(*peers));
3098 indx_size = ALIGNED_SIZE(nlist * 2 * sizeof(*indx));
3099 octets = endpoint_size + peers_size + indx_size;
3100 endpoint = erealloc(endpoint, octets);
3101 peers = INC_ALIGNED_PTR(endpoint, endpoint_size);
3102 indx = INC_ALIGNED_PTR(peers, peers_size);
3105 * Initially, we populate the island with all the rifraff peers
3106 * that happen to be lying around. Those with seriously
3107 * defective clocks are immediately booted off the island. Then,
3108 * the falsetickers are culled and put to sea. The truechimers
3109 * remaining are subject to repeated rounds where the most
3110 * unpopular at each round is kicked off. When the population
3111 * has dwindled to sys_minclock, the survivors split a million
3112 * bucks and collectively crank the chimes.
3114 nlist = nl2 = 0; /* none yet */
3115 for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3116 peer->new_status = CTL_PST_SEL_REJECT;
3119 * Leave the island immediately if the peer is
3120 * unfit to synchronize.
3122 if (peer_unfit(peer)) {
3127 * If this peer is an orphan parent, elect the
3128 * one with the lowest metric defined as the
3129 * IPv4 address or the first 64 bits of the
3130 * hashed IPv6 address. To ensure convergence
3131 * on the same selected orphan, consider as
3132 * well that this system may have the lowest
3133 * metric and be the orphan parent. If this
3134 * system wins, sys_peer will be NULL to trigger
3135 * orphan mode in timer().
3137 if (peer->stratum == sys_orphan) {
3141 if (peer->dstadr != NULL)
3142 localmet = ntohl(peer->dstadr->addr_refid);
3144 localmet = U_INT32_MAX;
3145 peermet = ntohl(addr2refid(&peer->srcadr));
3146 if (peermet < localmet && peermet < orphmet) {
3154 * If this peer could have the orphan parent
3155 * as a synchronization ancestor, exclude it
3156 * from selection to avoid forming a
3157 * synchronization loop within the orphan mesh,
3158 * triggering stratum climb to infinity
3159 * instability. Peers at stratum higher than
3160 * the orphan stratum could have the orphan
3161 * parent in ancestry so are excluded.
3162 * See http://bugs.ntp.org/2050
3164 if (peer->stratum > sys_orphan) {
3169 * The following are special cases. We deal
3172 if (!(peer->flags & FLAG_PREFER)) {
3173 switch (peer->refclktype) {
3174 case REFCLK_LOCALCLOCK:
3175 if ( current_time > orphwait
3176 && typelocal == NULL)
3181 if ( current_time > orphwait
3182 && typeacts == NULL)
3187 #endif /* REFCLOCK */
3190 * If we get this far, the peer can stay on the
3191 * island, but does not yet have the immunity
3194 peer->new_status = CTL_PST_SEL_SANE;
3195 f = root_distance(peer);
3196 peers[nlist].peer = peer;
3197 peers[nlist].error = peer->jitter;
3198 peers[nlist].synch = f;
3202 * Insert each interval endpoint on the unsorted
3206 endpoint[nl2].type = -1; /* lower end */
3207 endpoint[nl2].val = e - f;
3209 endpoint[nl2].type = 1; /* upper end */
3210 endpoint[nl2].val = e + f;
3214 * Construct sorted indx[] of endpoint[] indexes ordered by
3217 for (i = 0; i < nl2; i++)
3219 for (i = 0; i < nl2; i++) {
3220 endp = endpoint[indx[i]];
3223 for (j = i + 1; j < nl2; j++) {
3224 endp = endpoint[indx[j]];
3236 for (i = 0; i < nl2; i++)
3237 DPRINTF(3, ("select: endpoint %2d %.6f\n",
3238 endpoint[indx[i]].type, endpoint[indx[i]].val));
3241 * This is the actual algorithm that cleaves the truechimers
3242 * from the falsetickers. The original algorithm was described
3243 * in Keith Marzullo's dissertation, but has been modified for
3246 * Briefly put, we first assume there are no falsetickers, then
3247 * scan the candidate list first from the low end upwards and
3248 * then from the high end downwards. The scans stop when the
3249 * number of intersections equals the number of candidates less
3250 * the number of falsetickers. If this doesn't happen for a
3251 * given number of falsetickers, we bump the number of
3252 * falsetickers and try again. If the number of falsetickers
3253 * becomes equal to or greater than half the number of
3254 * candidates, the Albanians have won the Byzantine wars and
3255 * correct synchronization is not possible.
3257 * Here, nlist is the number of candidates and allow is the
3258 * number of falsetickers. Upon exit, the truechimers are the
3259 * survivors with offsets not less than low and not greater than
3260 * high. There may be none of them.
3264 for (allow = 0; 2 * allow < nlist; allow++) {
3267 * Bound the interval (low, high) as the smallest
3268 * interval containing points from the most sources.
3271 for (i = 0; i < nl2; i++) {
3272 low = endpoint[indx[i]].val;
3273 n -= endpoint[indx[i]].type;
3274 if (n >= nlist - allow)
3278 for (j = nl2 - 1; j >= 0; j--) {
3279 high = endpoint[indx[j]].val;
3280 n += endpoint[indx[j]].type;
3281 if (n >= nlist - allow)
3286 * If an interval containing truechimers is found, stop.
3287 * If not, increase the number of falsetickers and go
3295 * Clustering algorithm. Whittle candidate list of falsetickers,
3296 * who leave the island immediately. The TRUE peer is always a
3297 * truechimer. We must leave at least one peer to collect the
3300 * We assert the correct time is contained in the interval, but
3301 * the best offset estimate for the interval might not be
3302 * contained in the interval. For this purpose, a truechimer is
3303 * defined as the midpoint of an interval that overlaps the
3304 * intersection interval.
3307 for (i = 0; i < nlist; i++) {
3310 peer = peers[i].peer;
3313 || peer->offset + h < low
3314 || peer->offset - h > high
3315 ) && !(peer->flags & FLAG_TRUE))
3320 * Eligible PPS peers must survive the intersection
3321 * algorithm. Use the first one found, but don't
3322 * include any of them in the cluster population.
3324 if (peer->flags & FLAG_PPS) {
3325 if (typepps == NULL)
3327 if (!(peer->flags & FLAG_TSTAMP_PPS))
3330 #endif /* REFCLOCK */
3333 peers[j] = peers[i];
3339 * If no survivors remain at this point, check if the modem
3340 * driver, local driver or orphan parent in that order. If so,
3341 * nominate the first one found as the only survivor.
3342 * Otherwise, give up and leave the island to the rats.
3346 peers[0].synch = sys_mindisp;
3348 if (typeacts != NULL) {
3349 peers[0].peer = typeacts;
3351 } else if (typelocal != NULL) {
3352 peers[0].peer = typelocal;
3355 #endif /* REFCLOCK */
3356 if (typeorphan != NULL) {
3357 peers[0].peer = typeorphan;
3363 * Mark the candidates at this point as truechimers.
3365 for (i = 0; i < nlist; i++) {
3366 peers[i].peer->new_status = CTL_PST_SEL_SELCAND;
3367 DPRINTF(2, ("select: survivor %s %f\n",
3368 stoa(&peers[i].peer->srcadr), peers[i].synch));
3372 * Now, vote outliers off the island by select jitter weighted
3373 * by root distance. Continue voting as long as there are more
3374 * than sys_minclock survivors and the select jitter of the peer
3375 * with the worst metric is greater than the minimum peer
3376 * jitter. Stop if we are about to discard a TRUE or PREFER
3377 * peer, who of course have the immunity idol.
3384 for (i = 0; i < nlist; i++) {
3385 if (peers[i].error < d)
3387 peers[i].seljit = 0;
3390 for (j = 0; j < nlist; j++)
3391 f += DIFF(peers[j].peer->offset,
3392 peers[i].peer->offset);
3393 peers[i].seljit = SQRT(f / (nlist - 1));
3395 if (peers[i].seljit * peers[i].synch > e) {
3396 g = peers[i].seljit;
3397 e = peers[i].seljit * peers[i].synch;
3401 g = max(g, LOGTOD(sys_precision));
3402 if ( nlist <= max(1, sys_minclock)
3404 || ((FLAG_TRUE | FLAG_PREFER) & peers[k].peer->flags))
3407 DPRINTF(3, ("select: drop %s seljit %.6f jit %.6f\n",
3408 ntoa(&peers[k].peer->srcadr), g, d));
3409 if (nlist > sys_maxclock)
3410 peers[k].peer->new_status = CTL_PST_SEL_EXCESS;
3411 for (j = k + 1; j < nlist; j++)
3412 peers[j - 1] = peers[j];
3417 * What remains is a list usually not greater than sys_minclock
3418 * peers. Note that unsynchronized peers cannot survive this
3419 * far. Count and mark these survivors.
3421 * While at it, count the number of leap warning bits found.
3422 * This will be used later to vote the system leap warning bit.
3423 * If a leap warning bit is found on a reference clock, the vote
3426 * Choose the system peer using a hybrid metric composed of the
3427 * selection jitter scaled by the root distance augmented by
3428 * stratum scaled by sys_mindisp (.001 by default). The goal of
3429 * the small stratum factor is to avoid clockhop between a
3430 * reference clock and a network peer which has a refclock and
3431 * is using an older ntpd, which does not floor sys_rootdisp at
3434 * In contrast, ntpd 4.2.6 and earlier used stratum primarily
3435 * in selecting the system peer, using a weight of 1 second of
3436 * additional root distance per stratum. This heavy bias is no
3437 * longer appropriate, as the scaled root distance provides a
3438 * more rational metric carrying the cumulative error budget.
3444 for (i = 0; i < nlist; i++) {
3445 peer = peers[i].peer;
3447 peer->new_status = CTL_PST_SEL_SYNCCAND;
3449 if (peer->leap == LEAP_ADDSECOND) {
3450 if (peer->flags & FLAG_REFCLOCK)
3451 leap_vote_ins = nlist;
3452 else if (leap_vote_ins < nlist)
3455 if (peer->leap == LEAP_DELSECOND) {
3456 if (peer->flags & FLAG_REFCLOCK)
3457 leap_vote_del = nlist;
3458 else if (leap_vote_del < nlist)
3461 if (peer->flags & FLAG_PREFER)
3463 speermet = peers[i].seljit * peers[i].synch +
3464 peer->stratum * sys_mindisp;
3472 * Unless there are at least sys_misane survivors, leave the
3473 * building dark. Otherwise, do a clockhop dance. Ordinarily,
3474 * use the selected survivor speer. However, if the current
3475 * system peer is not speer, stay with the current system peer
3476 * as long as it doesn't get too old or too ugly.
3478 if (nlist > 0 && nlist >= sys_minsane) {
3481 typesystem = peers[speer].peer;
3482 if (osys_peer == NULL || osys_peer == typesystem) {
3484 } else if ((x = fabs(typesystem->offset -
3485 osys_peer->offset)) < sys_mindisp) {
3486 if (sys_clockhop == 0)
3487 sys_clockhop = sys_mindisp;
3490 DPRINTF(1, ("select: clockhop %d %.6f %.6f\n",
3491 j, x, sys_clockhop));
3492 if (fabs(x) < sys_clockhop)
3493 typesystem = osys_peer;
3502 * Mitigation rules of the game. We have the pick of the
3503 * litter in typesystem if any survivors are left. If
3504 * there is a prefer peer, use its offset and jitter.
3505 * Otherwise, use the combined offset and jitter of all kitters.
3507 if (typesystem != NULL) {
3508 if (sys_prefer == NULL) {
3509 typesystem->new_status = CTL_PST_SEL_SYSPEER;
3510 clock_combine(peers, sys_survivors, speer);
3512 typesystem = sys_prefer;
3514 typesystem->new_status = CTL_PST_SEL_SYSPEER;
3515 sys_offset = typesystem->offset;
3516 sys_jitter = typesystem->jitter;
3518 DPRINTF(1, ("select: combine offset %.9f jitter %.9f\n",
3519 sys_offset, sys_jitter));
3523 * If a PPS driver is lit and the combined offset is less than
3524 * 0.4 s, select the driver as the PPS peer and use its offset
3525 * and jitter. However, if this is the atom driver, use it only
3526 * if there is a prefer peer or there are no survivors and none
3529 if ( typepps != NULL
3530 && fabs(sys_offset) < 0.4
3531 && ( typepps->refclktype != REFCLK_ATOM_PPS
3532 || ( typepps->refclktype == REFCLK_ATOM_PPS
3533 && ( sys_prefer != NULL
3534 || (typesystem == NULL && sys_minsane == 0))))) {
3535 typesystem = typepps;
3537 typesystem->new_status = CTL_PST_SEL_PPS;
3538 sys_offset = typesystem->offset;
3539 sys_jitter = typesystem->jitter;
3540 DPRINTF(1, ("select: pps offset %.9f jitter %.9f\n",
3541 sys_offset, sys_jitter));
3543 #endif /* REFCLOCK */
3546 * If there are no survivors at this point, there is no
3547 * system peer. If so and this is an old update, keep the
3548 * current statistics, but do not update the clock.
3550 if (typesystem == NULL) {
3551 if (osys_peer != NULL) {
3552 if (sys_orphwait > 0)
3553 orphwait = current_time + sys_orphwait;
3554 report_event(EVNT_NOPEER, NULL, NULL);
3557 for (peer = peer_list; peer != NULL; peer = peer->p_link)
3558 peer->status = peer->new_status;
3563 * Do not use old data, as this may mess up the clock discipline
3566 if (typesystem->epoch <= sys_epoch)
3570 * We have found the alpha male. Wind the clock.
3572 if (osys_peer != typesystem)
3573 report_event(PEVNT_NEWPEER, typesystem, NULL);
3574 for (peer = peer_list; peer != NULL; peer = peer->p_link)
3575 peer->status = peer->new_status;
3576 clock_update(typesystem);
3582 peer_select * peers, /* survivor list */
3583 int npeers, /* number of survivors */
3584 int syspeer /* index of sys.peer */
3591 for (i = 0; i < npeers; i++) {
3592 x = 1. / peers[i].synch;
3594 z += x * peers[i].peer->offset;
3595 w += x * DIFF(peers[i].peer->offset,
3596 peers[syspeer].peer->offset);
3599 sys_jitter = SQRT(w / y + SQUARE(peers[syspeer].seljit));
3604 * root_distance - compute synchronization distance from peer to root
3608 struct peer *peer /* peer structure pointer */
3614 * Root Distance (LAMBDA) is defined as:
3615 * (delta + DELTA)/2 + epsilon + EPSILON + D
3618 * delta is the round-trip delay
3619 * DELTA is the root delay
3620 * epsilon is the peer dispersion
3621 * + (15 usec each second)
3622 * EPSILON is the root dispersion
3625 * NB: Think hard about why we are using these values, and what
3626 * the alternatives are, and the various pros/cons.
3628 * DLM thinks these are probably the best choices from any of the
3629 * other worse choices.
3631 dtemp = (peer->delay + peer->rootdelay) / 2
3633 + clock_phi * (current_time - peer->update)
3637 * Careful squeak here. The value returned must be greater than
3638 * the minimum root dispersion in order to avoid clockhop with
3639 * highly precise reference clocks. Note that the root distance
3640 * cannot exceed the sys_maxdist, as this is the cutoff by the
3641 * selection algorithm.
3643 if (dtemp < sys_mindisp)
3644 dtemp = sys_mindisp;
3650 * peer_xmit - send packet for persistent association.
3654 struct peer *peer /* peer structure pointer */
3657 struct pkt xpkt; /* transmit packet */
3658 size_t sendlen, authlen;
3659 keyid_t xkeyid = 0; /* transmit key ID */
3660 l_fp xmt_tx, xmt_ty;
3662 if (!peer->dstadr) /* drop peers without interface */
3665 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
3667 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
3668 xpkt.ppoll = peer->hpoll;
3669 xpkt.precision = sys_precision;
3670 xpkt.refid = sys_refid;
3671 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
3672 xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
3673 HTONL_FP(&sys_reftime, &xpkt.reftime);
3674 HTONL_FP(&peer->rec, &xpkt.org);
3675 HTONL_FP(&peer->dst, &xpkt.rec);
3678 * If the received packet contains a MAC, the transmitted packet
3679 * is authenticated and contains a MAC. If not, the transmitted
3680 * packet is not authenticated.
3682 * It is most important when autokey is in use that the local
3683 * interface IP address be known before the first packet is
3684 * sent. Otherwise, it is not possible to compute a correct MAC
3685 * the recipient will accept. Thus, the I/O semantics have to do
3686 * a little more work. In particular, the wildcard interface
3687 * might not be usable.
3689 sendlen = LEN_PKT_NOMAC;
3692 !(peer->flags & FLAG_SKEY) &&
3693 #endif /* !AUTOKEY */
3697 * Transmit a-priori timestamps
3699 get_systime(&xmt_tx);
3700 if (peer->flip == 0) { /* basic mode */
3701 peer->aorg = xmt_tx;
3702 HTONL_FP(&xmt_tx, &xpkt.xmt);
3703 } else { /* interleaved modes */
3704 if (peer->hmode == MODE_BROADCAST) { /* bcst */
3705 HTONL_FP(&xmt_tx, &xpkt.xmt);
3707 HTONL_FP(&peer->borg,
3710 HTONL_FP(&peer->aorg,
3712 } else { /* symmetric */
3714 HTONL_FP(&peer->borg,
3717 HTONL_FP(&peer->aorg,
3721 peer->t21_bytes = sendlen;
3722 sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl],
3725 peer->throttle += (1 << peer->minpoll) - 2;
3728 * Capture a-posteriori timestamps
3730 get_systime(&xmt_ty);
3731 if (peer->flip != 0) { /* interleaved modes */
3733 peer->aorg = xmt_ty;
3735 peer->borg = xmt_ty;
3736 peer->flip = -peer->flip;
3738 L_SUB(&xmt_ty, &xmt_tx);
3739 LFPTOD(&xmt_ty, peer->xleave);
3740 DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d len %zu xmt %#010x.%08x\n",
3742 peer->dstadr ? stoa(&peer->dstadr->sin) : "-",
3743 stoa(&peer->srcadr), peer->hmode, sendlen,
3744 xmt_tx.l_ui, xmt_tx.l_uf));
3749 * Authentication is enabled, so the transmitted packet must be
3750 * authenticated. If autokey is enabled, fuss with the various
3751 * modes; otherwise, symmetric key cryptography is used.
3754 if (peer->flags & FLAG_SKEY) {
3755 struct exten *exten; /* extension field */
3758 * The Public Key Dance (PKD): Cryptographic credentials
3759 * are contained in extension fields, each including a
3760 * 4-octet length/code word followed by a 4-octet
3761 * association ID and optional additional data. Optional
3762 * data includes a 4-octet data length field followed by
3763 * the data itself. Request messages are sent from a
3764 * configured association; response messages can be sent
3765 * from a configured association or can take the fast
3766 * path without ever matching an association. Response
3767 * messages have the same code as the request, but have
3768 * a response bit and possibly an error bit set. In this
3769 * implementation, a message may contain no more than
3770 * one command and one or more responses.
3772 * Cryptographic session keys include both a public and
3773 * a private componet. Request and response messages
3774 * using extension fields are always sent with the
3775 * private component set to zero. Packets without
3776 * extension fields indlude the private component when
3777 * the session key is generated.
3782 * Allocate and initialize a keylist if not
3783 * already done. Then, use the list in inverse
3784 * order, discarding keys once used. Keep the
3785 * latest key around until the next one, so
3786 * clients can use client/server packets to
3787 * compute propagation delay.
3789 * Note that once a key is used from the list,
3790 * it is retained in the key cache until the
3791 * next key is used. This is to allow a client
3792 * to retrieve the encrypted session key
3793 * identifier to verify authenticity.
3795 * If for some reason a key is no longer in the
3796 * key cache, a birthday has happened or the key
3797 * has expired, so the pseudo-random sequence is
3798 * broken. In that case, purge the keylist and
3801 if (peer->keynumber == 0)
3802 make_keylist(peer, peer->dstadr);
3805 xkeyid = peer->keylist[peer->keynumber];
3806 if (authistrusted(xkeyid))
3811 peer->keyid = xkeyid;
3813 switch (peer->hmode) {
3816 * In broadcast server mode the autokey values are
3817 * required by the broadcast clients. Push them when a
3818 * new keylist is generated; otherwise, push the
3819 * association message so the client can request them at
3822 case MODE_BROADCAST:
3823 if (peer->flags & FLAG_ASSOC)
3824 exten = crypto_args(peer, CRYPTO_AUTO |
3825 CRYPTO_RESP, peer->associd, NULL);
3827 exten = crypto_args(peer, CRYPTO_ASSOC |
3828 CRYPTO_RESP, peer->associd, NULL);
3832 * In symmetric modes the parameter, certificate,
3833 * identity, cookie and autokey exchanges are
3834 * required. The leapsecond exchange is optional. But, a
3835 * peer will not believe the other peer until the other
3836 * peer has synchronized, so the certificate exchange
3837 * might loop until then. If a peer finds a broken
3838 * autokey sequence, it uses the autokey exchange to
3839 * retrieve the autokey values. In any case, if a new
3840 * keylist is generated, the autokey values are pushed.
3846 * Parameter, certificate and identity.
3849 exten = crypto_args(peer, CRYPTO_ASSOC,
3850 peer->associd, hostval.ptr);
3851 else if (!(peer->crypto & CRYPTO_FLAG_CERT))
3852 exten = crypto_args(peer, CRYPTO_CERT,
3853 peer->associd, peer->issuer);
3854 else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
3855 exten = crypto_args(peer,
3856 crypto_ident(peer), peer->associd,
3860 * Cookie and autokey. We request the cookie
3861 * only when the this peer and the other peer
3862 * are synchronized. But, this peer needs the
3863 * autokey values when the cookie is zero. Any
3864 * time we regenerate the key list, we offer the
3865 * autokey values without being asked. If for
3866 * some reason either peer finds a broken
3867 * autokey sequence, the autokey exchange is
3868 * used to retrieve the autokey values.
3870 else if ( sys_leap != LEAP_NOTINSYNC
3871 && peer->leap != LEAP_NOTINSYNC
3872 && !(peer->crypto & CRYPTO_FLAG_COOK))
3873 exten = crypto_args(peer, CRYPTO_COOK,
3874 peer->associd, NULL);
3875 else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
3876 exten = crypto_args(peer, CRYPTO_AUTO,
3877 peer->associd, NULL);
3878 else if ( peer->flags & FLAG_ASSOC
3879 && peer->crypto & CRYPTO_FLAG_SIGN)
3880 exten = crypto_args(peer, CRYPTO_AUTO |
3881 CRYPTO_RESP, peer->assoc, NULL);
3884 * Wait for clock sync, then sign the
3885 * certificate and retrieve the leapsecond
3888 else if (sys_leap == LEAP_NOTINSYNC)
3891 else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
3892 exten = crypto_args(peer, CRYPTO_SIGN,
3893 peer->associd, hostval.ptr);
3894 else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
3895 exten = crypto_args(peer, CRYPTO_LEAP,
3896 peer->associd, NULL);
3900 * In client mode the parameter, certificate, identity,
3901 * cookie and sign exchanges are required. The
3902 * leapsecond exchange is optional. If broadcast client
3903 * mode the same exchanges are required, except that the
3904 * autokey exchange is substitutes for the cookie
3905 * exchange, since the cookie is always zero. If the
3906 * broadcast client finds a broken autokey sequence, it
3907 * uses the autokey exchange to retrieve the autokey
3913 * Parameter, certificate and identity.
3916 exten = crypto_args(peer, CRYPTO_ASSOC,
3917 peer->associd, hostval.ptr);
3918 else if (!(peer->crypto & CRYPTO_FLAG_CERT))
3919 exten = crypto_args(peer, CRYPTO_CERT,
3920 peer->associd, peer->issuer);
3921 else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
3922 exten = crypto_args(peer,
3923 crypto_ident(peer), peer->associd,
3927 * Cookie and autokey. These are requests, but
3928 * we use the peer association ID with autokey
3929 * rather than our own.
3931 else if (!(peer->crypto & CRYPTO_FLAG_COOK))
3932 exten = crypto_args(peer, CRYPTO_COOK,
3933 peer->associd, NULL);
3934 else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
3935 exten = crypto_args(peer, CRYPTO_AUTO,
3939 * Wait for clock sync, then sign the
3940 * certificate and retrieve the leapsecond
3943 else if (sys_leap == LEAP_NOTINSYNC)
3946 else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
3947 exten = crypto_args(peer, CRYPTO_SIGN,
3948 peer->associd, hostval.ptr);
3949 else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
3950 exten = crypto_args(peer, CRYPTO_LEAP,
3951 peer->associd, NULL);
3956 * Add a queued extension field if present. This is
3957 * always a request message, so the reply ID is already
3958 * in the message. If an error occurs, the error bit is
3959 * lit in the response.
3961 if (peer->cmmd != NULL) {
3964 temp32 = CRYPTO_RESP;
3965 peer->cmmd->opcode |= htonl(temp32);
3966 sendlen += crypto_xmit(peer, &xpkt, NULL,
3967 sendlen, peer->cmmd, 0);
3973 * Add an extension field created above. All but the
3974 * autokey response message are request messages.
3976 if (exten != NULL) {
3977 if (exten->opcode != 0)
3978 sendlen += crypto_xmit(peer, &xpkt,
3979 NULL, sendlen, exten, 0);
3984 * Calculate the next session key. Since extension
3985 * fields are present, the cookie value is zero.
3987 if (sendlen > (int)LEN_PKT_NOMAC) {
3988 session_key(&peer->dstadr->sin, &peer->srcadr,
3992 #endif /* AUTOKEY */
3995 * Transmit a-priori timestamps
3997 get_systime(&xmt_tx);
3998 if (peer->flip == 0) { /* basic mode */
3999 peer->aorg = xmt_tx;
4000 HTONL_FP(&xmt_tx, &xpkt.xmt);
4001 } else { /* interleaved modes */
4002 if (peer->hmode == MODE_BROADCAST) { /* bcst */
4003 HTONL_FP(&xmt_tx, &xpkt.xmt);
4005 HTONL_FP(&peer->borg, &xpkt.org);
4007 HTONL_FP(&peer->aorg, &xpkt.org);
4008 } else { /* symmetric */
4010 HTONL_FP(&peer->borg, &xpkt.xmt);
4012 HTONL_FP(&peer->aorg, &xpkt.xmt);
4015 xkeyid = peer->keyid;
4016 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
4018 report_event(PEVNT_AUTH, peer, "no key");
4019 peer->flash |= TEST5; /* auth error */
4025 if (xkeyid > NTP_MAXKEY)
4026 authtrust(xkeyid, 0);
4027 #endif /* AUTOKEY */
4028 if (sendlen > sizeof(xpkt)) {
4029 msyslog(LOG_ERR, "peer_xmit: buffer overflow %zu", sendlen);
4032 peer->t21_bytes = sendlen;
4033 sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl], &xpkt,
4036 peer->throttle += (1 << peer->minpoll) - 2;
4039 * Capture a-posteriori timestamps
4041 get_systime(&xmt_ty);
4042 if (peer->flip != 0) { /* interleaved modes */
4044 peer->aorg = xmt_ty;
4046 peer->borg = xmt_ty;
4047 peer->flip = -peer->flip;
4049 L_SUB(&xmt_ty, &xmt_tx);
4050 LFPTOD(&xmt_ty, peer->xleave);
4052 DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %zu index %d\n",
4053 current_time, latoa(peer->dstadr),
4054 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
4056 #else /* !AUTOKEY follows */
4057 DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %d\n",
4058 current_time, peer->dstadr ?
4059 ntoa(&peer->dstadr->sin) : "-",
4060 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen));
4061 #endif /* !AUTOKEY */
4070 leap_smear_add_offs(
4076 L_ADD(t, &leap_smear.offset);
4079 ** XXX: Should the smear be added to the root dispersion?
4085 #endif /* LEAP_SMEAR */
4089 * fast_xmit - Send packet for nonpersistent association. Note that
4090 * neither the source or destination can be a broadcast address.
4094 struct recvbuf *rbufp, /* receive packet pointer */
4095 int xmode, /* receive mode */
4096 keyid_t xkeyid, /* transmit key ID */
4097 int flags /* restrict mask */
4100 struct pkt xpkt; /* transmit packet structure */
4101 struct pkt *rpkt; /* receive packet structure */
4102 l_fp xmt_tx, xmt_ty;
4109 * Initialize transmit packet header fields from the receive
4110 * buffer provided. We leave the fields intact as received, but
4111 * set the peer poll at the maximum of the receive peer poll and
4112 * the system minimum poll (ntp_minpoll). This is for KoD rate
4113 * control and not strictly specification compliant, but doesn't
4116 * If the gazinta was from a multicast address, the gazoutta
4117 * must go out another way.
4119 rpkt = &rbufp->recv_pkt;
4120 if (rbufp->dstadr->flags & INT_MCASTOPEN)
4121 rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
4124 * If this is a kiss-o'-death (KoD) packet, show leap
4125 * unsynchronized, stratum zero, reference ID the four-character
4126 * kiss code and system root delay. Note we don't reveal the
4127 * local time, so these packets can't be used for
4130 if (flags & RES_KOD) {
4132 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
4133 PKT_VERSION(rpkt->li_vn_mode), xmode);
4134 xpkt.stratum = STRATUM_PKT_UNSPEC;
4135 xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
4136 xpkt.precision = rpkt->precision;
4137 memcpy(&xpkt.refid, "RATE", 4);
4138 xpkt.rootdelay = rpkt->rootdelay;
4139 xpkt.rootdisp = rpkt->rootdisp;
4140 xpkt.reftime = rpkt->reftime;
4141 xpkt.org = rpkt->xmt;
4142 xpkt.rec = rpkt->xmt;
4143 xpkt.xmt = rpkt->xmt;
4146 * This is a normal packet. Use the system variables.
4151 * Make copies of the variables which can be affected by smearing.
4154 l_fp this_recv_time;
4158 * If we are inside the leap smear interval we add the current smear offset to
4159 * the packet receive time, to the packet transmit time, and eventually to the
4160 * reftime to make sure the reftime isn't later than the transmit/receive times.
4162 xpkt.li_vn_mode = PKT_LI_VN_MODE(xmt_leap,
4163 PKT_VERSION(rpkt->li_vn_mode), xmode);
4165 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4166 xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
4167 xpkt.precision = sys_precision;
4168 xpkt.refid = sys_refid;
4169 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4170 xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
4173 this_ref_time = sys_reftime;
4174 if (leap_smear.in_progress) {
4175 leap_smear_add_offs(&this_ref_time, NULL);
4176 xpkt.refid = convertLFPToRefID(leap_smear.offset);
4177 DPRINTF(2, ("fast_xmit: leap_smear.in_progress: refid %8x, smear %s\n",
4179 lfptoa(&leap_smear.offset, 8)
4182 HTONL_FP(&this_ref_time, &xpkt.reftime);
4184 HTONL_FP(&sys_reftime, &xpkt.reftime);
4187 xpkt.org = rpkt->xmt;
4190 this_recv_time = rbufp->recv_time;
4191 if (leap_smear.in_progress)
4192 leap_smear_add_offs(&this_recv_time, NULL);
4193 HTONL_FP(&this_recv_time, &xpkt.rec);
4195 HTONL_FP(&rbufp->recv_time, &xpkt.rec);
4198 get_systime(&xmt_tx);
4200 if (leap_smear.in_progress)
4201 leap_smear_add_offs(&xmt_tx, &this_recv_time);
4203 HTONL_FP(&xmt_tx, &xpkt.xmt);
4206 #ifdef HAVE_NTP_SIGND
4207 if (flags & RES_MSSNTP) {
4208 send_via_ntp_signd(rbufp, xmode, xkeyid, flags, &xpkt);
4211 #endif /* HAVE_NTP_SIGND */
4214 * If the received packet contains a MAC, the transmitted packet
4215 * is authenticated and contains a MAC. If not, the transmitted
4216 * packet is not authenticated.
4218 sendlen = LEN_PKT_NOMAC;
4219 if (rbufp->recv_length == sendlen) {
4220 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
4222 DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d len %lu\n",
4223 current_time, stoa(&rbufp->dstadr->sin),
4224 stoa(&rbufp->recv_srcadr), xmode,
4230 * The received packet contains a MAC, so the transmitted packet
4231 * must be authenticated. For symmetric key cryptography, use
4232 * the predefined and trusted symmetric keys to generate the
4233 * cryptosum. For autokey cryptography, use the server private
4234 * value to generate the cookie, which is unique for every
4235 * source-destination-key ID combination.
4238 if (xkeyid > NTP_MAXKEY) {
4242 * The only way to get here is a reply to a legitimate
4243 * client request message, so the mode must be
4244 * MODE_SERVER. If an extension field is present, there
4245 * can be only one and that must be a command. Do what
4246 * needs, but with private value of zero so the poor
4247 * jerk can decode it. If no extension field is present,
4248 * use the cookie to generate the session key.
4250 cookie = session_key(&rbufp->recv_srcadr,
4251 &rbufp->dstadr->sin, 0, sys_private, 0);
4252 if ((size_t)rbufp->recv_length > sendlen + MAX_MAC_LEN) {
4253 session_key(&rbufp->dstadr->sin,
4254 &rbufp->recv_srcadr, xkeyid, 0, 2);
4255 temp32 = CRYPTO_RESP;
4256 rpkt->exten[0] |= htonl(temp32);
4257 sendlen += crypto_xmit(NULL, &xpkt, rbufp,
4258 sendlen, (struct exten *)rpkt->exten,
4261 session_key(&rbufp->dstadr->sin,
4262 &rbufp->recv_srcadr, xkeyid, cookie, 2);
4265 #endif /* AUTOKEY */
4266 get_systime(&xmt_tx);
4267 sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
4269 if (xkeyid > NTP_MAXKEY)
4270 authtrust(xkeyid, 0);
4271 #endif /* AUTOKEY */
4272 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
4273 get_systime(&xmt_ty);
4274 L_SUB(&xmt_ty, &xmt_tx);
4275 sys_authdelay = xmt_ty;
4276 DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d keyid %08x len %lu\n",
4277 current_time, ntoa(&rbufp->dstadr->sin),
4278 ntoa(&rbufp->recv_srcadr), xmode, xkeyid,
4284 * pool_xmit - resolve hostname or send unicast solicitation for pool.
4288 struct peer *pool /* pool solicitor association */
4292 struct pkt xpkt; /* transmit packet structure */
4293 struct addrinfo hints;
4295 struct interface * lcladr;
4296 sockaddr_u * rmtadr;
4301 if (NULL == pool->ai) {
4302 if (pool->addrs != NULL) {
4303 /* free() is used with copy_addrinfo_list() */
4308 hints.ai_family = AF(&pool->srcadr);
4309 hints.ai_socktype = SOCK_DGRAM;
4310 hints.ai_protocol = IPPROTO_UDP;
4311 /* ignore getaddrinfo_sometime() errors, we will retry */
4312 rc = getaddrinfo_sometime(
4317 &pool_name_resolved,
4318 (void *)(intptr_t)pool->associd);
4320 DPRINTF(1, ("pool DNS lookup %s started\n",
4324 "unable to start pool DNS %s: %m",
4330 /* copy_addrinfo_list ai_addr points to a sockaddr_u */
4331 rmtadr = (sockaddr_u *)(void *)pool->ai->ai_addr;
4332 pool->ai = pool->ai->ai_next;
4333 p = findexistingpeer(rmtadr, NULL, NULL, MODE_CLIENT, 0);
4334 } while (p != NULL && pool->ai != NULL);
4336 return; /* out of addresses, re-query DNS next poll */
4337 restrict_mask = restrictions(rmtadr);
4338 if (RES_FLAGS & restrict_mask)
4339 restrict_source(rmtadr, 0,
4340 current_time + POOL_SOLICIT_WINDOW + 1);
4341 lcladr = findinterface(rmtadr);
4342 memset(&xpkt, 0, sizeof(xpkt));
4343 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, pool->version,
4345 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4346 xpkt.ppoll = pool->hpoll;
4347 xpkt.precision = sys_precision;
4348 xpkt.refid = sys_refid;
4349 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4350 xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
4351 HTONL_FP(&sys_reftime, &xpkt.reftime);
4352 get_systime(&xmt_tx);
4353 pool->aorg = xmt_tx;
4354 HTONL_FP(&xmt_tx, &xpkt.xmt);
4355 sendpkt(rmtadr, lcladr, sys_ttl[pool->ttl], &xpkt,
4358 pool->throttle += (1 << pool->minpoll) - 2;
4359 DPRINTF(1, ("pool_xmit: at %ld %s->%s pool\n",
4360 current_time, latoa(lcladr), stoa(rmtadr)));
4361 msyslog(LOG_INFO, "Soliciting pool server %s", stoa(rmtadr));
4368 * group_test - test if this is the same group
4370 * host assoc return action
4371 * none none 0 mobilize *
4372 * none group 0 mobilize *
4373 * group none 0 mobilize *
4374 * group group 1 mobilize
4375 * group different 1 ignore
4376 * * ignore if notrust
4387 if (strcmp(grp, sys_groupname) == 0)
4393 if (strcmp(grp, ident) == 0)
4398 #endif /* AUTOKEY */
4408 const char * service,
4409 const struct addrinfo * hints,
4410 const struct addrinfo * res
4413 struct peer * pool; /* pool solicitor association */
4418 "error resolving pool %s: %s (%d)",
4419 name, gai_strerror(rescode), rescode);
4423 assoc = (associd_t)(intptr_t)context;
4424 pool = findpeerbyassoc(assoc);
4427 "Could not find assoc %u for pool DNS %s",
4431 DPRINTF(1, ("pool DNS %s completed\n", name));
4432 pool->addrs = copy_addrinfo_list(res);
4433 pool->ai = pool->addrs;
4442 * key_expire - purge the key list
4446 struct peer *peer /* peer structure pointer */
4451 if (peer->keylist != NULL) {
4452 for (i = 0; i <= peer->keynumber; i++)
4453 authtrust(peer->keylist[i], 0);
4454 free(peer->keylist);
4455 peer->keylist = NULL;
4457 value_free(&peer->sndval);
4458 peer->keynumber = 0;
4459 peer->flags &= ~FLAG_ASSOC;
4460 DPRINTF(1, ("key_expire: at %lu associd %d\n", current_time,
4463 #endif /* AUTOKEY */
4467 * local_refid(peer) - check peer refid to avoid selecting peers
4468 * currently synced to this ntpd.
4477 if (p->dstadr != NULL && !(INT_MCASTIF & p->dstadr->flags))
4478 unicast_ep = p->dstadr;
4480 unicast_ep = findinterface(&p->srcadr);
4482 if (unicast_ep != NULL && p->refid == unicast_ep->addr_refid)
4490 * Determine if the peer is unfit for synchronization
4492 * A peer is unfit for synchronization if
4493 * > TEST10 bad leap or stratum below floor or at or above ceiling
4494 * > TEST11 root distance exceeded for remote peer
4495 * > TEST12 a direct or indirect synchronization loop would form
4496 * > TEST13 unreachable or noselect
4498 int /* FALSE if fit, TRUE if unfit */
4500 struct peer *peer /* peer structure pointer */
4506 * A stratum error occurs if (1) the server has never been
4507 * synchronized, (2) the server stratum is below the floor or
4508 * greater than or equal to the ceiling.
4510 if ( peer->leap == LEAP_NOTINSYNC
4511 || peer->stratum < sys_floor
4512 || peer->stratum >= sys_ceiling) {
4513 rval |= TEST10; /* bad synch or stratum */
4517 * A distance error for a remote peer occurs if the root
4518 * distance is greater than or equal to the distance threshold
4519 * plus the increment due to one host poll interval.
4521 if ( !(peer->flags & FLAG_REFCLOCK)
4522 && root_distance(peer) >= sys_maxdist
4523 + clock_phi * ULOGTOD(peer->hpoll)) {
4524 rval |= TEST11; /* distance exceeded */
4528 * A loop error occurs if the remote peer is synchronized to the
4529 * local peer or if the remote peer is synchronized to the same
4530 * server as the local peer but only if the remote peer is
4531 * neither a reference clock nor an orphan.
4533 if (peer->stratum > 1 && local_refid(peer)) {
4534 rval |= TEST12; /* synchronization loop */
4538 * An unreachable error occurs if the server is unreachable or
4539 * the noselect bit is set.
4541 if (!peer->reach || (peer->flags & FLAG_NOSELECT)) {
4542 rval |= TEST13; /* unreachable */
4545 peer->flash &= ~PEER_TEST_MASK;
4546 peer->flash |= rval;
4552 * Find the precision of this particular machine
4554 #define MINSTEP 20e-9 /* minimum clock increment (s) */
4555 #define MAXSTEP 1 /* maximum clock increment (s) */
4556 #define MINCHANGES 12 /* minimum number of step samples */
4557 #define MAXLOOPS ((int)(1. / MINSTEP)) /* avoid infinite loop */
4560 * This routine measures the system precision defined as the minimum of
4561 * a sequence of differences between successive readings of the system
4562 * clock. However, if a difference is less than MINSTEP, the clock has
4563 * been read more than once during a clock tick and the difference is
4564 * ignored. We set MINSTEP greater than zero in case something happens
4565 * like a cache miss, and to tolerate underlying system clocks which
4566 * ensure each reading is strictly greater than prior readings while
4567 * using an underlying stepping (not interpolated) clock.
4569 * sys_tick and sys_precision represent the time to read the clock for
4570 * systems with high-precision clocks, and the tick interval or step
4571 * size for lower-precision stepping clocks.
4573 * This routine also measures the time to read the clock on stepping
4574 * system clocks by counting the number of readings between changes of
4575 * the underlying clock. With either type of clock, the minimum time
4576 * to read the clock is saved as sys_fuzz, and used to ensure the
4577 * get_systime() readings always increase and are fuzzed below sys_fuzz.
4580 measure_precision(void)
4583 * With sys_fuzz set to zero, get_systime() fuzzing of low bits
4584 * is effectively disabled. trunc_os_clock is FALSE to disable
4585 * get_ostime() simulation of a low-precision system clock.
4588 trunc_os_clock = FALSE;
4589 measured_tick = measure_tick_fuzz();
4590 set_sys_tick_precision(measured_tick);
4591 msyslog(LOG_INFO, "proto: precision = %.3f usec (%d)",
4592 sys_tick * 1e6, sys_precision);
4593 if (sys_fuzz < sys_tick) {
4594 msyslog(LOG_NOTICE, "proto: fuzz beneath %.3f usec",
4601 * measure_tick_fuzz()
4603 * measures the minimum time to read the clock (stored in sys_fuzz)
4604 * and returns the tick, the larger of the minimum increment observed
4605 * between successive clock readings and the time to read the clock.
4608 measure_tick_fuzz(void)
4610 l_fp minstep; /* MINSTEP as l_fp */
4611 l_fp val; /* current seconds fraction */
4612 l_fp last; /* last seconds fraction */
4613 l_fp ldiff; /* val - last */
4614 double tick; /* computed tick value */
4619 int i; /* log2 precision */
4625 DTOLFP(MINSTEP, &minstep);
4627 for (i = 0; i < MAXLOOPS && changes < MINCHANGES; i++) {
4630 L_SUB(&ldiff, &last);
4632 if (L_ISGT(&ldiff, &minstep)) {
4633 max_repeats = max(repeats, max_repeats);
4636 LFPTOD(&ldiff, diff);
4637 tick = min(diff, tick);
4642 if (changes < MINCHANGES) {
4643 msyslog(LOG_ERR, "Fatal error: precision could not be measured (MINSTEP too large?)");
4647 if (0 == max_repeats) {
4650 set_sys_fuzz(tick / max_repeats);
4658 set_sys_tick_precision(
4666 "unsupported tick %.3f > 1s ignored", tick);
4669 if (tick < measured_tick) {
4671 "proto: tick %.3f less than measured tick %.3f, ignored",
4672 tick, measured_tick);
4674 } else if (tick > measured_tick) {
4675 trunc_os_clock = TRUE;
4677 "proto: truncating system clock to multiples of %.9f",
4683 * Find the nearest power of two.
4685 for (i = 0; tick <= 1; i--)
4687 if (tick - 1 > 1 - tick / 2)
4690 sys_precision = (s_char)i;
4695 * init_proto - initialize the protocol module's data
4704 * Fill in the sys_* stuff. Default is don't listen to
4705 * broadcasting, require authentication.
4707 set_sys_leap(LEAP_NOTINSYNC);
4708 sys_stratum = STRATUM_UNSPEC;
4709 memcpy(&sys_refid, "INIT", 4);
4713 L_CLR(&sys_reftime);
4715 measure_precision();
4716 get_systime(&dummy);
4718 sys_manycastserver = 0;
4720 sys_bdelay = BDELAY_DEFAULT; /*[Bug 3031] delay cutoff */
4721 sys_authenticate = 1;
4722 sys_stattime = current_time;
4723 orphwait = current_time + sys_orphwait;
4725 for (i = 0; i < MAX_TTL; i++) {
4726 sys_ttl[i] = (u_char)((i * 256) / MAX_TTL);
4735 * proto_config - configure the protocol module
4746 * Figure out what he wants to change, then do it
4748 DPRINTF(2, ("proto_config: code %d value %lu dvalue %lf\n",
4749 item, value, dvalue));
4754 * enable and disable commands - arguments are Boolean.
4756 case PROTO_AUTHENTICATE: /* authentication (auth) */
4757 sys_authenticate = value;
4760 case PROTO_BROADCLIENT: /* broadcast client (bclient) */
4761 sys_bclient = (int)value;
4762 if (sys_bclient == 0)
4769 case PROTO_CAL: /* refclock calibrate (calibrate) */
4772 #endif /* REFCLOCK */
4774 case PROTO_KERNEL: /* kernel discipline (kernel) */
4778 case PROTO_MONITOR: /* monitoring (monitor) */
4784 msyslog(LOG_WARNING,
4785 "restrict: 'monitor' cannot be disabled while 'limited' is enabled");
4789 case PROTO_NTP: /* NTP discipline (ntp) */
4793 case PROTO_MODE7: /* mode7 management (ntpdc) */
4797 case PROTO_PPS: /* PPS discipline (pps) */
4798 hardpps_enable = value;
4801 case PROTO_FILEGEN: /* statistics (stats) */
4802 stats_control = value;
4806 * tos command - arguments are double, sometimes cast to int
4809 case PROTO_BCPOLLBSTEP: /* Broadcast Poll Backstep gate (bcpollbstep) */
4810 sys_bcpollbstep = (u_char)dvalue;
4813 case PROTO_BEACON: /* manycast beacon (beacon) */
4814 sys_beacon = (int)dvalue;
4817 case PROTO_BROADDELAY: /* default broadcast delay (bdelay) */
4818 sys_bdelay = (dvalue ? dvalue : BDELAY_DEFAULT);
4821 case PROTO_CEILING: /* stratum ceiling (ceiling) */
4822 sys_ceiling = (int)dvalue;
4825 case PROTO_COHORT: /* cohort switch (cohort) */
4826 sys_cohort = (int)dvalue;
4829 case PROTO_FLOOR: /* stratum floor (floor) */
4830 sys_floor = (int)dvalue;
4833 case PROTO_MAXCLOCK: /* maximum candidates (maxclock) */
4834 sys_maxclock = (int)dvalue;
4837 case PROTO_MAXDIST: /* select threshold (maxdist) */
4838 sys_maxdist = dvalue;
4841 case PROTO_CALLDELAY: /* modem call delay (mdelay) */
4842 break; /* NOT USED */
4844 case PROTO_MINCLOCK: /* minimum candidates (minclock) */
4845 sys_minclock = (int)dvalue;
4848 case PROTO_MINDISP: /* minimum distance (mindist) */
4849 sys_mindisp = dvalue;
4852 case PROTO_MINSANE: /* minimum survivors (minsane) */
4853 sys_minsane = (int)dvalue;
4856 case PROTO_ORPHAN: /* orphan stratum (orphan) */
4857 sys_orphan = (int)dvalue;
4860 case PROTO_ORPHWAIT: /* orphan wait (orphwait) */
4861 orphwait -= sys_orphwait;
4862 sys_orphwait = (int)dvalue;
4863 orphwait += sys_orphwait;
4867 * Miscellaneous commands
4869 case PROTO_MULTICAST_ADD: /* add group address */
4871 io_multicast_add(svalue);
4875 case PROTO_MULTICAST_DEL: /* delete group address */
4877 io_multicast_del(svalue);
4881 * Peer_clear Early policy choices
4884 case PROTO_PCEDIGEST: /* Digest */
4885 peer_clear_digest_early = value;
4889 * Unpeer Early policy choices
4892 case PROTO_UECRYPTO: /* Crypto */
4893 unpeer_crypto_early = value;
4896 case PROTO_UECRYPTONAK: /* Crypto_NAK */
4897 unpeer_crypto_nak_early = value;
4900 case PROTO_UEDIGEST: /* Digest */
4901 unpeer_digest_early = value;
4906 "proto: unsupported option %d", item);
4912 * proto_clr_stats - clear protocol stat counters
4915 proto_clr_stats(void)
4917 sys_stattime = current_time;
4926 sys_limitrejected = 0;