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 int sys_ceiling = STRATUM_UNSPEC - 1; /* cluster stratum ceiling */
142 int sys_minsane = 1; /* minimum candidates */
143 int sys_minclock = NTP_MINCLOCK; /* minimum candidates */
144 int sys_maxclock = NTP_MAXCLOCK; /* maximum candidates */
145 int sys_cohort = 0; /* cohort switch */
146 int sys_orphan = STRATUM_UNSPEC + 1; /* orphan stratum */
147 int sys_orphwait = NTP_ORPHWAIT; /* orphan wait */
148 int sys_beacon = BEACON; /* manycast beacon interval */
149 int sys_ttlmax; /* max ttl mapping vector index */
150 u_char sys_ttl[MAX_TTL]; /* ttl mapping vector */
153 * Statistics counters - first the good, then the bad
155 u_long sys_stattime; /* elapsed time */
156 u_long sys_received; /* packets received */
157 u_long sys_processed; /* packets for this host */
158 u_long sys_newversion; /* current version */
159 u_long sys_oldversion; /* old version */
160 u_long sys_restricted; /* access denied */
161 u_long sys_badlength; /* bad length or format */
162 u_long sys_badauth; /* bad authentication */
163 u_long sys_declined; /* declined */
164 u_long sys_limitrejected; /* rate exceeded */
165 u_long sys_kodsent; /* KoD sent */
168 * Mechanism knobs: how soon do we peer_clear() or unpeer()?
170 * The default way is "on-receipt". If this was a packet from a
171 * well-behaved source, on-receipt will offer the fastest recovery.
172 * If this was from a DoS attack, the default way makes it easier
173 * for a bad-guy to DoS us. So look and see what bites you harder
174 * and choose according to your environment.
176 int peer_clear_digest_early = 1; /* bad digest (TEST5) and Autokey */
177 int unpeer_crypto_early = 1; /* bad crypto (TEST9) */
178 int unpeer_crypto_nak_early = 1; /* crypto_NAK (TEST5) */
179 int unpeer_digest_early = 1; /* bad digest (TEST5) */
181 int dynamic_interleave = DYNAMIC_INTERLEAVE; /* Bug 2978 mitigation */
183 int kiss_code_check(u_char hisleap, u_char hisstratum, u_char hismode, u_int32 refid);
184 enum nak_error_codes valid_NAK(struct peer *peer, struct recvbuf *rbufp, u_char hismode);
185 static double root_distance (struct peer *);
186 static void clock_combine (peer_select *, int, int);
187 static void peer_xmit (struct peer *);
188 static void fast_xmit (struct recvbuf *, int, keyid_t, int);
189 static void pool_xmit (struct peer *);
190 static void clock_update (struct peer *);
191 static void measure_precision(void);
192 static double measure_tick_fuzz(void);
193 static int local_refid (struct peer *);
194 static int peer_unfit (struct peer *);
196 static int group_test (char *, char *);
199 void pool_name_resolved (int, int, void *, const char *,
200 const char *, const struct addrinfo *,
201 const struct addrinfo *);
204 const char * amtoa (int am);
212 sys_leap = new_sys_leap;
216 * Under certain conditions we send faked leap bits to clients, so
217 * eventually change xmt_leap below, but never change LEAP_NOTINSYNC.
219 if (xmt_leap != LEAP_NOTINSYNC) {
220 if (leap_sec_in_progress) {
221 /* always send "not sync" */
222 xmt_leap = LEAP_NOTINSYNC;
227 * If leap smear is enabled in general we must
228 * never send a leap second warning to clients,
229 * so make sure we only send "in sync".
231 if (leap_smear.enabled)
232 xmt_leap = LEAP_NOWARNING;
234 #endif /* LEAP_SMEAR */
251 if ( hismode == MODE_SERVER
252 && hisleap == LEAP_NOTINSYNC
253 && hisstratum == STRATUM_UNSPEC) {
254 if(memcmp(&refid,"RATE", 4) == 0) {
256 } else if(memcmp(&refid,"DENY", 4) == 0) {
258 } else if(memcmp(&refid,"RSTR", 4) == 0) {
260 } else if(memcmp(&refid,"X", 1) == 0) {
263 return (UNKNOWNKISS);
272 * Check that NAK is valid
277 struct recvbuf *rbufp,
281 int base_packet_length = MIN_V4_PKT_LEN;
285 l_fp p_org; /* origin timestamp */
286 const l_fp * myorg; /* selected peer origin */
289 * Check to see if there is something beyond the basic packet
291 if (rbufp->recv_length == base_packet_length) {
295 remainder_size = rbufp->recv_length - base_packet_length;
297 * Is this a potential NAK?
299 if (remainder_size != 4) {
304 * Only server responses can contain NAK's
307 if (hismode != MODE_SERVER &&
308 hismode != MODE_ACTIVE &&
309 hismode != MODE_PASSIVE
315 * Make sure that the extra field in the packet is all zeros
317 rpkt = &rbufp->recv_pkt;
318 keyid = ntohl(((u_int32 *)rpkt)[base_packet_length / 4]);
324 * Only valid if peer uses a key
326 if (!peer || !peer->keyid || !(peer->flags & FLAG_SKEY)) {
331 * The ORIGIN must match, or this cannot be a valid NAK, either.
333 NTOHL_FP(&rpkt->org, &p_org);
339 if (L_ISZERO(&p_org) ||
341 !L_ISEQU(&p_org, myorg)) {
345 /* If we ever passed all that checks, we should be safe. Well,
346 * as safe as we can ever be with an unauthenticated crypto-nak.
353 * transmit - transmit procedure called by poll timeout
357 struct peer *peer /* peer structure pointer */
363 * The polling state machine. There are two kinds of machines,
364 * those that never expect a reply (broadcast and manycast
365 * server modes) and those that do (all other modes). The dance
371 * In broadcast mode the poll interval is never changed from
374 if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
375 peer->outdate = current_time;
376 if (sys_leap != LEAP_NOTINSYNC)
378 poll_update(peer, hpoll);
383 * In manycast mode we start with unity ttl. The ttl is
384 * increased by one for each poll until either sys_maxclock
385 * servers have been found or the maximum ttl is reached. When
386 * sys_maxclock servers are found we stop polling until one or
387 * more servers have timed out or until less than sys_minclock
388 * associations turn up. In this case additional better servers
389 * are dragged in and preempt the existing ones. Once every
390 * sys_beacon seconds we are to transmit unconditionally, but
391 * this code is not quite right -- peer->unreach counts polls
392 * and is being compared with sys_beacon, so the beacons happen
393 * every sys_beacon polls.
395 if (peer->cast_flags & MDF_ACAST) {
396 peer->outdate = current_time;
397 if (peer->unreach > sys_beacon) {
401 } else if ( sys_survivors < sys_minclock
402 || peer_associations < sys_maxclock) {
403 if (peer->ttl < (u_int32)sys_ttlmax)
408 poll_update(peer, hpoll);
413 * Pool associations transmit unicast solicitations when there
414 * are less than a hard limit of 2 * sys_maxclock associations,
415 * and either less than sys_minclock survivors or less than
416 * sys_maxclock associations. The hard limit prevents unbounded
417 * growth in associations if the system clock or network quality
418 * result in survivor count dipping below sys_minclock often.
419 * This was observed testing with pool, where sys_maxclock == 12
420 * resulted in 60 associations without the hard limit. A
421 * similar hard limit on manycastclient ephemeral associations
422 * may be appropriate.
424 if (peer->cast_flags & MDF_POOL) {
425 peer->outdate = current_time;
426 if ( (peer_associations <= 2 * sys_maxclock)
427 && ( peer_associations < sys_maxclock
428 || sys_survivors < sys_minclock))
430 poll_update(peer, hpoll);
435 * In unicast modes the dance is much more intricate. It is
436 * designed to back off whenever possible to minimize network
439 if (peer->burst == 0) {
443 * Update the reachability status. If not heard for
444 * three consecutive polls, stuff infinity in the clock
447 oreach = peer->reach;
448 peer->outdate = current_time;
454 * Here the peer is unreachable. If it was
455 * previously reachable raise a trap. Send a
458 clock_filter(peer, 0., 0., MAXDISPERSE);
461 report_event(PEVNT_UNREACH, peer, NULL);
463 if ( (peer->flags & FLAG_IBURST)
465 peer->retry = NTP_RETRY;
469 * Here the peer is reachable. Send a burst if
470 * enabled and the peer is fit. Reset unreach
471 * for persistent and ephemeral associations.
472 * Unreach is also reset for survivors in
476 if (!(peer->flags & FLAG_PREEMPT))
478 if ( (peer->flags & FLAG_BURST)
480 && !peer_unfit(peer))
481 peer->retry = NTP_RETRY;
485 * Watch for timeout. If ephemeral, toss the rascal;
486 * otherwise, bump the poll interval. Note the
487 * poll_update() routine will clamp it to maxpoll.
488 * If preemptible and we have more peers than maxclock,
489 * and this peer has the minimum score of preemptibles,
492 if (peer->unreach >= NTP_UNREACH) {
494 /* ephemeral: no FLAG_CONFIG nor FLAG_PREEMPT */
495 if (!(peer->flags & (FLAG_CONFIG | FLAG_PREEMPT))) {
496 report_event(PEVNT_RESTART, peer, "timeout");
497 peer_clear(peer, "TIME");
501 if ( (peer->flags & FLAG_PREEMPT)
502 && (peer_associations > sys_maxclock)
503 && score_all(peer)) {
504 report_event(PEVNT_RESTART, peer, "timeout");
505 peer_clear(peer, "TIME");
512 if (peer->burst == 0) {
515 * If ntpdate mode and the clock has not been
516 * set and all peers have completed the burst,
517 * we declare a successful failure.
521 if (peer_ntpdate == 0) {
523 "ntpd: no servers found");
526 "ntpd: no servers found\n");
536 * Do not transmit if in broadcast client mode.
538 if (peer->hmode != MODE_BCLIENT)
540 poll_update(peer, hpoll);
554 case AM_ERR: return "AM_ERR";
555 case AM_NOMATCH: return "AM_NOMATCH";
556 case AM_PROCPKT: return "AM_PROCPKT";
557 case AM_BCST: return "AM_BCST";
558 case AM_FXMIT: return "AM_FXMIT";
559 case AM_MANYCAST: return "AM_MANYCAST";
560 case AM_NEWPASS: return "AM_NEWPASS";
561 case AM_NEWBCL: return "AM_NEWBCL";
562 case AM_POSSBCL: return "AM_POSSBCL";
565 snprintf(bp, LIB_BUFLENGTH, "AM_#%d", am);
572 * receive - receive procedure called for each packet received
576 struct recvbuf *rbufp
579 register struct peer *peer; /* peer structure pointer */
580 register struct pkt *pkt; /* receive packet pointer */
581 u_char hisversion; /* packet version */
582 u_char hisleap; /* packet leap indicator */
583 u_char hismode; /* packet mode */
584 u_char hisstratum; /* packet stratum */
585 u_short restrict_mask; /* restrict bits */
586 const char *hm_str; /* hismode string */
587 const char *am_str; /* association match string */
588 int kissCode = NOKISS; /* Kiss Code */
589 int has_mac; /* length of MAC field */
590 int authlen; /* offset of MAC field */
591 int is_authentic = AUTH_NONE; /* cryptosum ok */
592 int crypto_nak_test; /* result of crypto-NAK check */
593 int retcode = AM_NOMATCH; /* match code */
594 keyid_t skeyid = 0; /* key IDs */
595 u_int32 opcode = 0; /* extension field opcode */
596 sockaddr_u *dstadr_sin; /* active runway */
597 struct peer *peer2; /* aux peer structure pointer */
598 endpt *match_ep; /* newpeer() local address */
599 l_fp p_org; /* origin timestamp */
600 l_fp p_rec; /* receive timestamp */
601 l_fp p_xmt; /* transmit timestamp */
603 char hostname[NTP_MAXSTRLEN + 1];
604 char *groupname = NULL;
605 struct autokey *ap; /* autokey structure pointer */
606 int rval; /* cookie snatcher */
607 keyid_t pkeyid = 0, tkeyid = 0; /* key IDs */
609 #ifdef HAVE_NTP_SIGND
610 static unsigned char zero_key[16];
611 #endif /* HAVE_NTP_SIGND */
614 * Monitor the packet and get restrictions. Note that the packet
615 * length for control and private mode packets must be checked
616 * by the service routines. Some restrictions have to be handled
617 * later in order to generate a kiss-o'-death packet.
620 * Bogus port check is before anything, since it probably
621 * reveals a clogging attack.
624 if (0 == SRCPORT(&rbufp->recv_srcadr)) {
626 return; /* bogus port */
628 restrict_mask = restrictions(&rbufp->recv_srcadr);
629 pkt = &rbufp->recv_pkt;
630 DPRINTF(2, ("receive: at %ld %s<-%s flags %x restrict %03x org %#010x.%08x xmt %#010x.%08x\n",
631 current_time, stoa(&rbufp->dstadr->sin),
632 stoa(&rbufp->recv_srcadr), rbufp->dstadr->flags,
633 restrict_mask, ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
634 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
635 hisversion = PKT_VERSION(pkt->li_vn_mode);
636 hisleap = PKT_LEAP(pkt->li_vn_mode);
637 hismode = (int)PKT_MODE(pkt->li_vn_mode);
638 hisstratum = PKT_TO_STRATUM(pkt->stratum);
639 INSIST(0 != hisstratum);
641 if (restrict_mask & RES_IGNORE) {
643 return; /* ignore everything */
645 if (hismode == MODE_PRIVATE) {
646 if (!ntp_mode7 || (restrict_mask & RES_NOQUERY)) {
648 return; /* no query private */
650 process_private(rbufp, ((restrict_mask &
651 RES_NOMODIFY) == 0));
654 if (hismode == MODE_CONTROL) {
655 if (restrict_mask & RES_NOQUERY) {
657 return; /* no query control */
659 process_control(rbufp, restrict_mask);
662 if (restrict_mask & RES_DONTSERVE) {
664 return; /* no time serve */
668 * This is for testing. If restricted drop ten percent of
671 if (restrict_mask & RES_FLAKE) {
672 if ((double)ntp_random() / 0x7fffffff < .1) {
674 return; /* no flakeway */
679 * Version check must be after the query packets, since they
680 * intentionally use an early version.
682 if (hisversion == NTP_VERSION) {
683 sys_newversion++; /* new version */
684 } else if ( !(restrict_mask & RES_VERSION)
685 && hisversion >= NTP_OLDVERSION) {
686 sys_oldversion++; /* previous version */
689 return; /* old version */
693 * Figure out his mode and validate the packet. This has some
694 * legacy raunch that probably should be removed. In very early
695 * NTP versions mode 0 was equivalent to what later versions
696 * would interpret as client mode.
698 if (hismode == MODE_UNSPEC) {
699 if (hisversion == NTP_OLDVERSION) {
700 hismode = MODE_CLIENT;
703 return; /* invalid mode */
708 * Parse the extension field if present. We figure out whether
709 * an extension field is present by measuring the MAC size. If
710 * the number of words following the packet header is 0, no MAC
711 * is present and the packet is not authenticated. If 1, the
712 * packet is a crypto-NAK; if 3, the packet is authenticated
713 * with DES; if 5, the packet is authenticated with MD5; if 6,
714 * the packet is authenticated with SHA. If 2 or * 4, the packet
715 * is a runt and discarded forthwith. If greater than 6, an
716 * extension field is present, so we subtract the length of the
717 * field and go around again.
720 authlen = LEN_PKT_NOMAC;
721 has_mac = rbufp->recv_length - authlen;
722 while (has_mac > 0) {
729 if (has_mac % 4 != 0 || has_mac < (int)MIN_MAC_LEN) {
731 return; /* bad length */
733 if (has_mac <= (int)MAX_MAC_LEN) {
734 skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
738 opcode = ntohl(((u_int32 *)pkt)[authlen / 4]);
739 len = opcode & 0xffff;
742 || (int)len + authlen > rbufp->recv_length) {
744 return; /* bad length */
748 * Extract calling group name for later. If
749 * sys_groupname is non-NULL, there must be
750 * a group name provided to elicit a response.
752 if ( (opcode & 0x3fff0000) == CRYPTO_ASSOC
753 && sys_groupname != NULL) {
754 ep = (struct exten *)&((u_int32 *)pkt)[authlen / 4];
755 hostlen = ntohl(ep->vallen);
756 if ( hostlen >= sizeof(hostname)
758 offsetof(struct exten, pkt)) {
760 return; /* bad length */
762 memcpy(hostname, &ep->pkt, hostlen);
763 hostname[hostlen] = '\0';
764 groupname = strchr(hostname, '@');
765 if (groupname == NULL) {
778 * If has_mac is < 0 we had a malformed packet.
782 return; /* bad length */
786 * If authentication required, a MAC must be present.
788 if (restrict_mask & RES_DONTTRUST && has_mac == 0) {
790 return; /* access denied */
794 * Update the MRU list and finger the cloggers. It can be a
795 * little expensive, so turn it off for production use.
796 * RES_LIMITED and RES_KOD will be cleared in the returned
797 * restrict_mask unless one or both actions are warranted.
799 restrict_mask = ntp_monitor(rbufp, restrict_mask);
800 if (restrict_mask & RES_LIMITED) {
802 if ( !(restrict_mask & RES_KOD)
803 || MODE_BROADCAST == hismode
804 || MODE_SERVER == hismode) {
805 if (MODE_SERVER == hismode)
806 DPRINTF(1, ("Possibly self-induced rate limiting of MODE_SERVER from %s\n",
807 stoa(&rbufp->recv_srcadr)));
808 return; /* rate exceeded */
810 if (hismode == MODE_CLIENT)
811 fast_xmit(rbufp, MODE_SERVER, skeyid,
814 fast_xmit(rbufp, MODE_ACTIVE, skeyid,
816 return; /* rate exceeded */
818 restrict_mask &= ~RES_KOD;
821 * We have tossed out as many buggy packets as possible early in
822 * the game to reduce the exposure to a clogging attack. Now we
823 * have to burn some cycles to find the association and
824 * authenticate the packet if required. Note that we burn only
825 * digest cycles, again to reduce exposure. There may be no
826 * matching association and that's okay.
828 * More on the autokey mambo. Normally the local interface is
829 * found when the association was mobilized with respect to a
830 * designated remote address. We assume packets arriving from
831 * the remote address arrive via this interface and the local
832 * address used to construct the autokey is the unicast address
833 * of the interface. However, if the sender is a broadcaster,
834 * the interface broadcast address is used instead.
835 * Notwithstanding this technobabble, if the sender is a
836 * multicaster, the broadcast address is null, so we use the
837 * unicast address anyway. Don't ask.
839 peer = findpeer(rbufp, hismode, &retcode);
840 dstadr_sin = &rbufp->dstadr->sin;
841 NTOHL_FP(&pkt->org, &p_org);
842 NTOHL_FP(&pkt->rec, &p_rec);
843 NTOHL_FP(&pkt->xmt, &p_xmt);
844 hm_str = modetoa(hismode);
845 am_str = amtoa(retcode);
848 * Authentication is conditioned by three switches:
850 * NOPEER (RES_NOPEER) do not mobilize an association unless
852 * NOTRUST (RES_DONTTRUST) do not allow access unless
853 * authenticated (implies NOPEER)
854 * enable (sys_authenticate) master NOPEER switch, by default
857 * The NOPEER and NOTRUST can be specified on a per-client basis
858 * using the restrict command. The enable switch if on implies
859 * NOPEER for all clients. There are four outcomes:
861 * NONE The packet has no MAC.
862 * OK the packet has a MAC and authentication succeeds
863 * ERROR the packet has a MAC and authentication fails
864 * CRYPTO crypto-NAK. The MAC has four octets only.
866 * Note: The AUTH(x, y) macro is used to filter outcomes. If x
867 * is zero, acceptable outcomes of y are NONE and OK. If x is
868 * one, the only acceptable outcome of y is OK.
870 crypto_nak_test = valid_NAK(peer, rbufp, hismode);
873 * Drop any invalid crypto-NAKs
875 if (crypto_nak_test == INVALIDNAK) {
876 report_event(PEVNT_AUTH, peer, "Invalid_NAK");
880 msyslog(LOG_ERR, "Invalid-NAK error at %ld %s<-%s",
881 current_time, stoa(dstadr_sin), stoa(&rbufp->recv_srcadr));
886 restrict_mask &= ~RES_MSSNTP;
887 is_authentic = AUTH_NONE; /* not required */
888 DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s len %d org %#010x.%08x xmt %#010x.%08x NOMAC\n",
889 current_time, stoa(dstadr_sin),
890 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
892 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
893 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
894 } else if (crypto_nak_test == VALIDNAK) {
895 restrict_mask &= ~RES_MSSNTP;
896 is_authentic = AUTH_CRYPTO; /* crypto-NAK */
897 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",
898 current_time, stoa(dstadr_sin),
899 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
900 skeyid, authlen + has_mac, is_authentic,
901 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
902 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
904 #ifdef HAVE_NTP_SIGND
906 * If the signature is 20 bytes long, the last 16 of
907 * which are zero, then this is a Microsoft client
908 * wanting AD-style authentication of the server's
911 * This is described in Microsoft's WSPP docs, in MS-SNTP:
912 * http://msdn.microsoft.com/en-us/library/cc212930.aspx
914 } else if ( has_mac == MAX_MD5_LEN
915 && (restrict_mask & RES_MSSNTP)
916 && (retcode == AM_FXMIT || retcode == AM_NEWPASS)
917 && (memcmp(zero_key, (char *)pkt + authlen + 4,
918 MAX_MD5_LEN - 4) == 0)) {
919 is_authentic = AUTH_NONE;
920 #endif /* HAVE_NTP_SIGND */
923 restrict_mask &= ~RES_MSSNTP;
926 * For autokey modes, generate the session key
927 * and install in the key cache. Use the socket
928 * broadcast or unicast address as appropriate.
930 if (crypto_flags && skeyid > NTP_MAXKEY) {
933 * More on the autokey dance (AKD). A cookie is
934 * constructed from public and private values.
935 * For broadcast packets, the cookie is public
936 * (zero). For packets that match no
937 * association, the cookie is hashed from the
938 * addresses and private value. For server
939 * packets, the cookie was previously obtained
940 * from the server. For symmetric modes, the
941 * cookie was previously constructed using an
942 * agreement protocol; however, should PKI be
943 * unavailable, we construct a fake agreement as
944 * the EXOR of the peer and host cookies.
946 * hismode ephemeral persistent
947 * =======================================
950 * client sys cookie 0%
951 * server 0% sys cookie
957 if (has_mac < (int)MAX_MD5_LEN) {
961 if (hismode == MODE_BROADCAST) {
964 * For broadcaster, use the interface
965 * broadcast address when available;
966 * otherwise, use the unicast address
967 * found when the association was
968 * mobilized. However, if this is from
969 * the wildcard interface, game over.
973 ANY_INTERFACE_CHOOSE(&rbufp->recv_srcadr)) {
975 return; /* no wildcard */
978 if (!SOCK_UNSPEC(&rbufp->dstadr->bcast))
980 &rbufp->dstadr->bcast;
981 } else if (peer == NULL) {
982 pkeyid = session_key(
983 &rbufp->recv_srcadr, dstadr_sin, 0,
986 pkeyid = peer->pcookie;
990 * The session key includes both the public
991 * values and cookie. In case of an extension
992 * field, the cookie used for authentication
993 * purposes is zero. Note the hash is saved for
994 * use later in the autokey mambo.
996 if (authlen > (int)LEN_PKT_NOMAC && pkeyid != 0) {
997 session_key(&rbufp->recv_srcadr,
998 dstadr_sin, skeyid, 0, 2);
999 tkeyid = session_key(
1000 &rbufp->recv_srcadr, dstadr_sin,
1003 tkeyid = session_key(
1004 &rbufp->recv_srcadr, dstadr_sin,
1009 #endif /* AUTOKEY */
1012 * Compute the cryptosum. Note a clogging attack may
1013 * succeed in bloating the key cache. If an autokey,
1014 * purge it immediately, since we won't be needing it
1015 * again. If the packet is authentic, it can mobilize an
1016 * association. Note that there is no key zero.
1018 if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,
1020 is_authentic = AUTH_ERROR;
1022 is_authentic = AUTH_OK;
1024 if (crypto_flags && skeyid > NTP_MAXKEY)
1025 authtrust(skeyid, 0);
1026 #endif /* AUTOKEY */
1027 DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x\n",
1028 current_time, stoa(dstadr_sin),
1029 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
1030 skeyid, authlen + has_mac, is_authentic,
1031 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1032 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
1036 * The association matching rules are implemented by a set of
1037 * routines and an association table. A packet matching an
1038 * association is processed by the peer process for that
1039 * association. If there are no errors, an ephemeral association
1040 * is mobilized: a broadcast packet mobilizes a broadcast client
1041 * aassociation; a manycast server packet mobilizes a manycast
1042 * client association; a symmetric active packet mobilizes a
1043 * symmetric passive association.
1048 * This is a client mode packet not matching any association. If
1049 * an ordinary client, simply toss a server mode packet back
1050 * over the fence. If a manycast client, we have to work a
1056 * If authentication OK, send a server reply; otherwise,
1057 * send a crypto-NAK.
1059 if (!(rbufp->dstadr->flags & INT_MCASTOPEN)) {
1060 if (AUTH(restrict_mask & RES_DONTTRUST,
1062 fast_xmit(rbufp, MODE_SERVER, skeyid,
1064 } else if (is_authentic == AUTH_ERROR) {
1065 fast_xmit(rbufp, MODE_SERVER, 0,
1071 return; /* hooray */
1075 * This must be manycast. Do not respond if not
1076 * configured as a manycast server.
1078 if (!sys_manycastserver) {
1080 return; /* not enabled */
1085 * Do not respond if not the same group.
1087 if (group_test(groupname, NULL)) {
1091 #endif /* AUTOKEY */
1094 * Do not respond if we are not synchronized or our
1095 * stratum is greater than the manycaster or the
1096 * manycaster has already synchronized to us.
1098 if ( sys_leap == LEAP_NOTINSYNC
1099 || sys_stratum >= hisstratum
1100 || (!sys_cohort && sys_stratum == hisstratum + 1)
1101 || rbufp->dstadr->addr_refid == pkt->refid) {
1103 return; /* no help */
1107 * Respond only if authentication succeeds. Don't do a
1108 * crypto-NAK, as that would not be useful.
1110 if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic))
1111 fast_xmit(rbufp, MODE_SERVER, skeyid,
1113 return; /* hooray */
1116 * This is a server mode packet returned in response to a client
1117 * mode packet sent to a multicast group address (for
1118 * manycastclient) or to a unicast address (for pool). The
1119 * origin timestamp is a good nonce to reliably associate the
1120 * reply with what was sent. If there is no match, that's
1121 * curious and could be an intruder attempting to clog, so we
1124 * If the packet is authentic and the manycastclient or pool
1125 * association is found, we mobilize a client association and
1126 * copy pertinent variables from the manycastclient or pool
1127 * association to the new client association. If not, just
1128 * ignore the packet.
1130 * There is an implosion hazard at the manycast client, since
1131 * the manycast servers send the server packet immediately. If
1132 * the guy is already here, don't fire up a duplicate.
1138 * Do not respond if not the same group.
1140 if (group_test(groupname, NULL)) {
1144 #endif /* AUTOKEY */
1145 if ((peer2 = findmanycastpeer(rbufp)) == NULL) {
1147 return; /* not enabled */
1149 if (!AUTH( (!(peer2->cast_flags & MDF_POOL)
1150 && sys_authenticate)
1151 || (restrict_mask & (RES_NOPEER |
1152 RES_DONTTRUST)), is_authentic)) {
1154 return; /* access denied */
1158 * Do not respond if unsynchronized or stratum is below
1159 * the floor or at or above the ceiling.
1161 if ( hisleap == LEAP_NOTINSYNC
1162 || hisstratum < sys_floor
1163 || hisstratum >= sys_ceiling) {
1165 return; /* no help */
1167 peer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr,
1168 MODE_CLIENT, hisversion, peer2->minpoll,
1169 peer2->maxpoll, FLAG_PREEMPT |
1170 (FLAG_IBURST & peer2->flags), MDF_UCAST |
1171 MDF_UCLNT, 0, skeyid, sys_ident);
1174 return; /* ignore duplicate */
1178 * After each ephemeral pool association is spun,
1179 * accelerate the next poll for the pool solicitor so
1180 * the pool will fill promptly.
1182 if (peer2->cast_flags & MDF_POOL)
1183 peer2->nextdate = current_time + 1;
1186 * Further processing of the solicitation response would
1187 * simply detect its origin timestamp as bogus for the
1188 * brand-new association (it matches the prototype
1189 * association) and tinker with peer->nextdate delaying
1192 return; /* solicitation response handled */
1195 * This is the first packet received from a broadcast server. If
1196 * the packet is authentic and we are enabled as broadcast
1197 * client, mobilize a broadcast client association. We don't
1198 * kiss any frogs here.
1204 * Do not respond if not the same group.
1206 if (group_test(groupname, sys_ident)) {
1210 #endif /* AUTOKEY */
1211 if (sys_bclient == 0) {
1213 return; /* not enabled */
1215 if (!AUTH(sys_authenticate | (restrict_mask &
1216 (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
1218 return; /* access denied */
1222 * Do not respond if unsynchronized or stratum is below
1223 * the floor or at or above the ceiling.
1225 if ( hisleap == LEAP_NOTINSYNC
1226 || hisstratum < sys_floor
1227 || hisstratum >= sys_ceiling) {
1229 return; /* no help */
1234 * Do not respond if Autokey and the opcode is not a
1235 * CRYPTO_ASSOC response with association ID.
1237 if ( crypto_flags && skeyid > NTP_MAXKEY
1238 && (opcode & 0xffff0000) != (CRYPTO_ASSOC | CRYPTO_RESP)) {
1240 return; /* protocol error */
1242 #endif /* AUTOKEY */
1245 * Broadcasts received via a multicast address may
1246 * arrive after a unicast volley has begun
1247 * with the same remote address. newpeer() will not
1248 * find duplicate associations on other local endpoints
1249 * if a non-NULL endpoint is supplied. multicastclient
1250 * ephemeral associations are unique across all local
1253 if (!(INT_MCASTOPEN & rbufp->dstadr->flags))
1254 match_ep = rbufp->dstadr;
1259 * Determine whether to execute the initial volley.
1261 if (sys_bdelay > 0.0) {
1264 * If a two-way exchange is not possible,
1265 * neither is Autokey.
1267 if (crypto_flags && skeyid > NTP_MAXKEY) {
1269 return; /* no autokey */
1271 #endif /* AUTOKEY */
1274 * Do not execute the volley. Start out in
1275 * broadcast client mode.
1277 peer = newpeer(&rbufp->recv_srcadr, NULL,
1278 match_ep, MODE_BCLIENT, hisversion,
1279 pkt->ppoll, pkt->ppoll, FLAG_PREEMPT,
1280 MDF_BCLNT, 0, skeyid, sys_ident);
1283 return; /* ignore duplicate */
1286 peer->delay = sys_bdelay;
1293 * Execute the initial volley in order to calibrate the
1294 * propagation delay and run the Autokey protocol.
1296 * Note that the minpoll is taken from the broadcast
1297 * packet, normally 6 (64 s) and that the poll interval
1298 * is fixed at this value.
1300 peer = newpeer(&rbufp->recv_srcadr, NULL, match_ep,
1301 MODE_CLIENT, hisversion, pkt->ppoll, pkt->ppoll,
1302 FLAG_BC_VOL | FLAG_IBURST | FLAG_PREEMPT, MDF_BCLNT,
1303 0, skeyid, sys_ident);
1306 return; /* ignore duplicate */
1310 if (skeyid > NTP_MAXKEY)
1311 crypto_recv(peer, rbufp);
1312 #endif /* AUTOKEY */
1314 return; /* hooray */
1317 * This is the first packet received from a symmetric active
1318 * peer. If the packet is authentic and the first he sent,
1319 * mobilize a passive association. If not, kiss the frog.
1325 * Do not respond if not the same group.
1327 if (group_test(groupname, sys_ident)) {
1331 #endif /* AUTOKEY */
1332 if (!AUTH(sys_authenticate | (restrict_mask &
1333 (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
1336 * If authenticated but cannot mobilize an
1337 * association, send a symmetric passive
1338 * response without mobilizing an association.
1339 * This is for drat broken Windows clients. See
1340 * Microsoft KB 875424 for preferred workaround.
1342 if (AUTH(restrict_mask & RES_DONTTRUST,
1344 fast_xmit(rbufp, MODE_PASSIVE, skeyid,
1346 return; /* hooray */
1348 if (is_authentic == AUTH_ERROR) {
1349 fast_xmit(rbufp, MODE_ACTIVE, 0,
1355 * If we got here, the packet isn't part of an
1356 * existing association, it isn't correctly
1357 * authenticated, and it didn't meet either of
1358 * the previous two special cases so we should
1359 * just drop it on the floor. For example,
1360 * crypto-NAKs (is_authentic == AUTH_CRYPTO)
1361 * will make it this far. This is just
1362 * debug-printed and not logged to avoid log
1365 DPRINTF(2, ("receive: at %ld refusing to mobilize passive association"
1366 " with unknown peer %s mode %d/%s:%s keyid %08x len %d auth %d\n",
1367 current_time, stoa(&rbufp->recv_srcadr),
1368 hismode, hm_str, am_str, skeyid,
1369 (authlen + has_mac), is_authentic));
1375 * Do not respond if synchronized and if stratum is
1376 * below the floor or at or above the ceiling. Note,
1377 * this allows an unsynchronized peer to synchronize to
1378 * us. It would be very strange if he did and then was
1379 * nipped, but that could only happen if we were
1380 * operating at the top end of the range. It also means
1381 * we will spin an ephemeral association in response to
1382 * MODE_ACTIVE KoDs, which will time out eventually.
1384 if ( hisleap != LEAP_NOTINSYNC
1385 && (hisstratum < sys_floor || hisstratum >= sys_ceiling)) {
1387 return; /* no help */
1391 * The message is correctly authenticated and allowed.
1392 * Mobilize a symmetric passive association.
1394 if ((peer = newpeer(&rbufp->recv_srcadr, NULL,
1395 rbufp->dstadr, MODE_PASSIVE, hisversion, pkt->ppoll,
1396 NTP_MAXDPOLL, 0, MDF_UCAST, 0, skeyid,
1397 sys_ident)) == NULL) {
1399 return; /* ignore duplicate */
1405 * Process regular packet. Nothing special.
1411 * Do not respond if not the same group.
1413 if (group_test(groupname, peer->ident)) {
1417 #endif /* AUTOKEY */
1419 if (MODE_BROADCAST == hismode) {
1424 DPRINTF(2, ("receive: PROCPKT/BROADCAST: prev pkt %ld seconds ago, ppoll: %d, %d secs\n",
1425 (current_time - peer->timelastrec),
1426 peer->ppoll, (1 << peer->ppoll)
1428 /* Things we can check:
1430 * Did the poll interval change?
1431 * Is the poll interval in the packet in-range?
1432 * Did this packet arrive too soon?
1433 * Is the timestamp in this packet monotonic
1434 * with respect to the previous packet?
1437 /* This is noteworthy, not error-worthy */
1438 if (pkt->ppoll != peer->ppoll) {
1439 msyslog(LOG_INFO, "receive: broadcast poll from %s changed from %ud to %ud",
1440 stoa(&rbufp->recv_srcadr),
1441 peer->ppoll, pkt->ppoll);
1444 /* This is error-worthy */
1445 if (pkt->ppoll < peer->minpoll ||
1446 pkt->ppoll > peer->maxpoll ) {
1447 msyslog(LOG_INFO, "receive: broadcast poll of %ud from %s is out-of-range (%d to %d)!",
1448 pkt->ppoll, stoa(&rbufp->recv_srcadr),
1449 peer->minpoll, peer->maxpoll);
1453 /* too early? worth an error, too! */
1454 deadband = (1u << pkt->ppoll);
1455 if (FLAG_BC_VOL & peer->flags)
1456 deadband -= 3; /* allow greater fuzz after volley */
1457 if ((current_time - peer->timelastrec) < deadband) {
1458 msyslog(LOG_INFO, "receive: broadcast packet from %s arrived after %lu, not %lu seconds!",
1459 stoa(&rbufp->recv_srcadr),
1460 (current_time - peer->timelastrec),
1465 /* Alert if time from the server is non-monotonic */
1467 L_SUB(&tdiff, &peer->bxmt);
1468 if (tdiff.l_i < 0) {
1469 msyslog(LOG_INFO, "receive: broadcast packet from %s contains non-monotonic timestamp: %#010x.%08x -> %#010x.%08x",
1470 stoa(&rbufp->recv_srcadr),
1471 peer->bxmt.l_ui, peer->bxmt.l_uf,
1472 p_xmt.l_ui, p_xmt.l_uf
1480 peer->timelastrec = current_time;
1489 * A passive packet matches a passive association. This is
1490 * usually the result of reconfiguring a client on the fly. As
1491 * this association might be legitimate and this packet an
1492 * attempt to deny service, just ignore it.
1499 * For everything else there is the bit bucket.
1508 * If the association is configured for Autokey, the packet must
1509 * have a public key ID; if not, the packet must have a
1512 if ( is_authentic != AUTH_CRYPTO
1513 && ( ((peer->flags & FLAG_SKEY) && skeyid <= NTP_MAXKEY)
1514 || (!(peer->flags & FLAG_SKEY) && skeyid > NTP_MAXKEY))) {
1518 #endif /* AUTOKEY */
1521 peer->flash &= ~PKT_TEST_MASK;
1522 if (peer->flags & FLAG_XBOGUS) {
1523 peer->flags &= ~FLAG_XBOGUS;
1524 peer->flash |= TEST3;
1528 * Next comes a rigorous schedule of timestamp checking. If the
1529 * transmit timestamp is zero, the server has not initialized in
1530 * interleaved modes or is horribly broken.
1532 * A KoD packet we pay attention to cannot have a 0 transmit
1535 if (L_ISZERO(&p_xmt)) {
1536 peer->flash |= TEST3; /* unsynch */
1537 if (STRATUM_UNSPEC == hisstratum) { /* KoD packet */
1538 peer->bogusorg++; /* for TEST2 or TEST3 */
1540 "receive: Unexpected zero transmit timestamp in KoD from %s",
1541 ntoa(&peer->srcadr));
1546 * If the transmit timestamp duplicates our previous one, the
1547 * packet is a replay. This prevents the bad guys from replaying
1548 * the most recent packet, authenticated or not.
1550 } else if (L_ISEQU(&peer->xmt, &p_xmt)) {
1551 peer->flash |= TEST1; /* duplicate */
1556 * If this is a broadcast mode packet, make sure hisstratum
1557 * is appropriate. Don't do anything else here - we wait to
1558 * see if this is an interleave broadcast packet until after
1559 * we've validated the MAC that SHOULD be provided.
1561 * hisstratum should never be 0.
1562 * If hisstratum is 15, then we'll advertise as UNSPEC but
1563 * at least we'll be able to sync with the broadcast server.
1565 } else if (hismode == MODE_BROADCAST) {
1566 if ( 0 == hisstratum
1567 || STRATUM_UNSPEC <= hisstratum) {
1568 /* Is this a ++sys_declined or ??? */
1570 "receive: Unexpected stratum (%d) in broadcast from %s",
1571 hisstratum, ntoa(&peer->srcadr));
1576 * Basic KoD validation checking:
1578 * KoD packets are a mixed-blessing. Forged KoD packets
1579 * are DoS attacks. There are rare situations where we might
1580 * get a valid KoD response, though. Since KoD packets are
1581 * a special case that complicate the checks we do next, we
1582 * handle the basic KoD checks here.
1584 * Note that we expect the incoming KoD packet to have its
1585 * (nonzero) org, rec, and xmt timestamps set to the xmt timestamp
1586 * that we have previously sent out. Watch interleave mode.
1588 } else if (STRATUM_UNSPEC == hisstratum) {
1589 DEBUG_INSIST(!L_ISZERO(&p_xmt));
1590 if ( L_ISZERO(&p_org) /* We checked p_xmt above */
1591 || L_ISZERO(&p_rec)) {
1594 "receive: KoD packet from %s has a zero org or rec timestamp. Ignoring.",
1595 ntoa(&peer->srcadr));
1599 if ( !L_ISEQU(&p_xmt, &p_org)
1600 || !L_ISEQU(&p_xmt, &p_rec)) {
1603 "receive: KoD packet from %s has inconsistent xmt/org/rec timestamps. Ignoring.",
1604 ntoa(&peer->srcadr));
1608 /* Be conservative */
1609 if (peer->flip == 0 && !L_ISEQU(&p_org, &peer->aorg)) {
1612 "receive: flip 0 KoD origin timestamp %#010x.%08x from %s does not match %#010x.%08x - ignoring.",
1613 p_org.l_ui, p_org.l_uf,
1614 ntoa(&peer->srcadr),
1615 peer->aorg.l_ui, peer->aorg.l_uf);
1617 } else if (peer->flip == 1 && !L_ISEQU(&p_org, &peer->borg)) {
1620 "receive: flip 1 KoD origin timestamp %#010x.%08x from %s does not match interleave %#010x.%08x - ignoring.",
1621 p_org.l_ui, p_org.l_uf,
1622 ntoa(&peer->srcadr),
1623 peer->borg.l_ui, peer->borg.l_uf);
1628 * Basic mode checks:
1630 * If there is no origin timestamp, it's either an initial packet
1631 * or we've already received a response to our query. Of course,
1632 * should 'aorg' be all-zero because this really was the original
1633 * transmit timestamp, we'll ignore this reply. There is a window
1634 * of one nanosecond once every 136 years' time where this is
1635 * possible. We currently ignore this situation.
1637 * Otherwise, check for bogus packet in basic mode.
1638 * If it is bogus, switch to interleaved mode and resynchronize,
1639 * but only after confirming the packet is not bogus in
1640 * symmetric interleaved mode.
1642 * This could also mean somebody is forging packets claiming to
1643 * be from us, attempting to cause our server to KoD us.
1645 } else if (peer->flip == 0) {
1646 INSIST(0 != hisstratum);
1647 INSIST(STRATUM_UNSPEC != hisstratum);
1649 } else if (L_ISZERO(&p_org)) {
1651 "receive: Got 0 origin timestamp from %s@%s xmt %#010x.%08x",
1652 hm_str, ntoa(&peer->srcadr),
1653 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));
1655 } else if (!L_ISEQU(&p_org, &peer->aorg)) {
1656 /* are there cases here where we should bail? */
1657 /* Should we set TEST2 if we decide to try xleave? */
1659 peer->flash |= TEST2; /* bogus */
1661 "receive: Unexpected origin timestamp %#010x.%08x does not match aorg %#010x.%08x from %s@%s xmt %#010x.%08x",
1662 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1663 peer->aorg.l_ui, peer->aorg.l_uf,
1664 hm_str, ntoa(&peer->srcadr),
1665 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));
1666 if ( !L_ISZERO(&peer->dst)
1667 && L_ISEQU(&p_org, &peer->dst)) {
1668 /* Might be the start of an interleave */
1669 if (dynamic_interleave) {
1671 report_event(PEVNT_XLEAVE, peer, NULL);
1674 "receive: Dynamic interleave from %s@%s denied",
1675 hm_str, ntoa(&peer->srcadr));
1683 * Check for valid nonzero timestamp fields.
1685 } else if ( L_ISZERO(&p_org)
1687 || L_ISZERO(&peer->dst)) {
1688 peer->flash |= TEST3; /* unsynch */
1691 * Check for bogus packet in interleaved symmetric mode. This
1692 * can happen if a packet is lost, duplicated or crossed. If
1693 * found, flip and resynchronize.
1695 } else if ( !L_ISZERO(&peer->dst)
1696 && !L_ISEQU(&p_org, &peer->dst)) {
1698 peer->flags |= FLAG_XBOGUS;
1699 peer->flash |= TEST2; /* bogus */
1700 return; /* Bogus packet, we are done */
1706 * If this is a crypto_NAK, the server cannot authenticate a
1707 * client packet. The server might have just changed keys. Clear
1708 * the association and restart the protocol.
1710 if (crypto_nak_test == VALIDNAK) {
1711 report_event(PEVNT_AUTH, peer, "crypto_NAK");
1712 peer->flash |= TEST5; /* bad auth */
1714 if (peer->flags & FLAG_PREEMPT) {
1715 if (unpeer_crypto_nak_early) {
1722 peer_clear(peer, "AUTH");
1724 #endif /* AUTOKEY */
1728 * If the digest fails or it's missing for authenticated
1729 * associations, the client cannot authenticate a server
1730 * reply to a client packet previously sent. The loopback check
1731 * is designed to avoid a bait-and-switch attack, which was
1732 * possible in past versions. If symmetric modes, return a
1733 * crypto-NAK. The peer should restart the protocol.
1735 } else if (!AUTH(peer->keyid || has_mac ||
1736 (restrict_mask & RES_DONTTRUST), is_authentic)) {
1738 if (peer->flash & PKT_TEST_MASK) {
1740 "receive: Bad auth in packet with bad timestamps from %s denied - spoof?",
1741 ntoa(&peer->srcadr));
1745 report_event(PEVNT_AUTH, peer, "digest");
1746 peer->flash |= TEST5; /* bad auth */
1749 && ( hismode == MODE_ACTIVE
1750 || hismode == MODE_PASSIVE))
1751 fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
1752 if (peer->flags & FLAG_PREEMPT) {
1753 if (unpeer_digest_early) {
1758 else if (peer_clear_digest_early && peer->crypto) {
1759 peer_clear(peer, "AUTH");
1761 #endif /* AUTOKEY */
1766 * For broadcast packets:
1768 * HMS: This next line never made much sense to me, even
1769 * when it was up higher:
1770 * If an initial volley, bail out now and let the
1771 * client do its stuff.
1773 * If the packet has not failed authentication, then
1774 * - if the origin timestamp is nonzero this is an
1775 * interleaved broadcast, so restart the protocol.
1776 * - else, this is not an interleaved broadcast packet.
1778 if (hismode == MODE_BROADCAST) {
1779 if ( is_authentic == AUTH_OK
1780 || is_authentic == AUTH_NONE) {
1781 if (!L_ISZERO(&p_org)) {
1782 if (!(peer->flags & FLAG_XB)) {
1784 "receive: Broadcast server at %s is in interleave mode",
1785 ntoa(&peer->srcadr));
1786 peer->flags |= FLAG_XB;
1788 peer->borg = rbufp->recv_time;
1789 report_event(PEVNT_XLEAVE, peer, NULL);
1792 } else if (peer->flags & FLAG_XB) {
1794 "receive: Broadcast server at %s is no longer in interleave mode",
1795 ntoa(&peer->srcadr));
1796 peer->flags &= ~FLAG_XB;
1800 "receive: Bad broadcast auth (%d) from %s",
1801 is_authentic, ntoa(&peer->srcadr));
1807 ** Update the state variables.
1809 if (peer->flip == 0) {
1810 if (hismode != MODE_BROADCAST)
1812 peer->dst = rbufp->recv_time;
1817 * Set the peer ppoll to the maximum of the packet ppoll and the
1818 * peer minpoll. If a kiss-o'-death, set the peer minpoll to
1819 * this maximum and advance the headway to give the sender some
1820 * headroom. Very intricate.
1824 * Check for any kiss codes. Note this is only used when a server
1825 * responds to a packet request
1828 kissCode = kiss_code_check(hisleap, hisstratum, hismode, pkt->refid);
1831 * Check to see if this is a RATE Kiss Code
1832 * Currently this kiss code will accept whatever poll
1833 * rate that the server sends
1835 peer->ppoll = max(peer->minpoll, pkt->ppoll);
1836 if (kissCode == RATEKISS) {
1837 peer->selbroken++; /* Increment the KoD count */
1838 report_event(PEVNT_RATE, peer, NULL);
1839 if (pkt->ppoll > peer->minpoll)
1840 peer->minpoll = peer->ppoll;
1841 peer->burst = peer->retry = 0;
1842 peer->throttle = (NTP_SHIFT + 1) * (1 << peer->minpoll);
1843 poll_update(peer, pkt->ppoll);
1844 return; /* kiss-o'-death */
1846 if (kissCode != NOKISS) {
1847 peer->selbroken++; /* Increment the KoD count */
1848 return; /* Drop any other kiss code packets */
1859 * - this is a *cast (uni-, broad-, or m-) server packet
1860 * - and it's symmetric-key authenticated
1861 * then see if the sender's IP is trusted for this keyid.
1862 * If it is, great - nothing special to do here.
1863 * Otherwise, we should report and bail.
1865 * Autokey-authenticated packets are accepted.
1869 case MODE_SERVER: /* server mode */
1870 case MODE_BROADCAST: /* broadcast mode */
1871 case MODE_ACTIVE: /* symmetric active mode */
1872 case MODE_PASSIVE: /* symmetric passive mode */
1873 if ( is_authentic == AUTH_OK
1875 && skeyid <= NTP_MAXKEY
1876 && !authistrustedip(skeyid, &peer->srcadr)) {
1877 report_event(PEVNT_AUTH, peer, "authIP");
1883 case MODE_CLIENT: /* client mode */
1884 #if 0 /* At this point, MODE_CONTROL is overloaded by MODE_BCLIENT */
1885 case MODE_CONTROL: /* control mode */
1887 case MODE_PRIVATE: /* private mode */
1888 case MODE_BCLIENT: /* broadcast client mode */
1891 case MODE_UNSPEC: /* unspecified (old version) */
1894 "receive: Unexpected mode (%d) in packet from %s",
1895 hismode, ntoa(&peer->srcadr));
1901 * That was hard and I am sweaty, but the packet is squeaky
1902 * clean. Get on with real work.
1904 peer->timereceived = current_time;
1905 peer->timelastrec = current_time;
1906 if (is_authentic == AUTH_OK)
1907 peer->flags |= FLAG_AUTHENTIC;
1909 peer->flags &= ~FLAG_AUTHENTIC;
1913 * More autokey dance. The rules of the cha-cha are as follows:
1915 * 1. If there is no key or the key is not auto, do nothing.
1917 * 2. If this packet is in response to the one just previously
1918 * sent or from a broadcast server, do the extension fields.
1919 * Otherwise, assume bogosity and bail out.
1921 * 3. If an extension field contains a verified signature, it is
1922 * self-authenticated and we sit the dance.
1924 * 4. If this is a server reply, check only to see that the
1925 * transmitted key ID matches the received key ID.
1927 * 5. Check to see that one or more hashes of the current key ID
1928 * matches the previous key ID or ultimate original key ID
1929 * obtained from the broadcaster or symmetric peer. If no
1930 * match, sit the dance and call for new autokey values.
1932 * In case of crypto error, fire the orchestra, stop dancing and
1933 * restart the protocol.
1935 if (peer->flags & FLAG_SKEY) {
1937 * Decrement remaining autokey hashes. This isn't
1938 * perfect if a packet is lost, but results in no harm.
1940 ap = (struct autokey *)peer->recval.ptr;
1945 peer->flash |= TEST8;
1946 rval = crypto_recv(peer, rbufp);
1947 if (rval == XEVNT_OK) {
1950 if (rval == XEVNT_ERR) {
1951 report_event(PEVNT_RESTART, peer,
1953 peer_clear(peer, "CRYP");
1954 peer->flash |= TEST9; /* bad crypt */
1955 if (peer->flags & FLAG_PREEMPT) {
1956 if (unpeer_crypto_early) {
1965 * If server mode, verify the receive key ID matches
1966 * the transmit key ID.
1968 if (hismode == MODE_SERVER) {
1969 if (skeyid == peer->keyid)
1970 peer->flash &= ~TEST8;
1973 * If an extension field is present, verify only that it
1974 * has been correctly signed. We don't need a sequence
1975 * check here, but the sequence continues.
1977 } else if (!(peer->flash & TEST8)) {
1978 peer->pkeyid = skeyid;
1981 * Now the fun part. Here, skeyid is the current ID in
1982 * the packet, pkeyid is the ID in the last packet and
1983 * tkeyid is the hash of skeyid. If the autokey values
1984 * have not been received, this is an automatic error.
1985 * If so, check that the tkeyid matches pkeyid. If not,
1986 * hash tkeyid and try again. If the number of hashes
1987 * exceeds the number remaining in the sequence, declare
1988 * a successful failure and refresh the autokey values.
1990 } else if (ap != NULL) {
1993 for (i = 0; ; i++) {
1994 if ( tkeyid == peer->pkeyid
1995 || tkeyid == ap->key) {
1996 peer->flash &= ~TEST8;
1997 peer->pkeyid = skeyid;
2006 tkeyid = session_key(
2007 &rbufp->recv_srcadr, dstadr_sin,
2010 if (peer->flash & TEST8)
2011 report_event(PEVNT_AUTH, peer, "keylist");
2013 if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */
2014 peer->flash |= TEST8; /* bad autokey */
2017 * The maximum lifetime of the protocol is about one
2018 * week before restarting the Autokey protocol to
2019 * refresh certificates and leapseconds values.
2021 if (current_time > peer->refresh) {
2022 report_event(PEVNT_RESTART, peer,
2024 peer_clear(peer, "TIME");
2028 #endif /* AUTOKEY */
2031 * The dance is complete and the flash bits have been lit. Toss
2032 * the packet over the fence for processing, which may light up
2035 process_packet(peer, pkt, rbufp->recv_length);
2038 * In interleaved mode update the state variables. Also adjust the
2039 * transmit phase to avoid crossover.
2041 if (peer->flip != 0) {
2043 peer->dst = rbufp->recv_time;
2044 if (peer->nextdate - current_time < (1U << min(peer->ppoll,
2054 * process_packet - Packet Procedure, a la Section 3.4.4 of RFC-1305
2055 * Or almost, at least. If we're in here we have a reasonable
2056 * expectation that we will be having a long term
2057 * relationship with this host.
2061 register struct peer *peer,
2062 register struct pkt *pkt,
2067 double p_offset, p_del, p_disp;
2068 l_fp p_rec, p_xmt, p_org, p_reftime, ci;
2069 u_char pmode, pleap, pversion, pstratum;
2070 char statstr[NTP_MAXSTRLEN];
2073 double etemp, ftemp, td;
2080 p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
2082 p_disp = FPTOD(NTOHS_FP(pkt->rootdisp));
2083 NTOHL_FP(&pkt->reftime, &p_reftime);
2084 NTOHL_FP(&pkt->org, &p_org);
2085 NTOHL_FP(&pkt->rec, &p_rec);
2086 NTOHL_FP(&pkt->xmt, &p_xmt);
2087 pmode = PKT_MODE(pkt->li_vn_mode);
2088 pleap = PKT_LEAP(pkt->li_vn_mode);
2089 pversion = PKT_VERSION(pkt->li_vn_mode);
2090 pstratum = PKT_TO_STRATUM(pkt->stratum);
2097 * Verify the server is synchronized; that is, the leap bits,
2098 * stratum and root distance are valid.
2100 if ( pleap == LEAP_NOTINSYNC /* test 6 */
2101 || pstratum < sys_floor || pstratum >= sys_ceiling)
2102 peer->flash |= TEST6; /* bad synch or strat */
2103 if (p_del / 2 + p_disp >= MAXDISPERSE) /* test 7 */
2104 peer->flash |= TEST7; /* bad header */
2107 * If any tests fail at this point, the packet is discarded.
2108 * Note that some flashers may have already been set in the
2109 * receive() routine.
2111 if (peer->flash & PKT_TEST_MASK) {
2112 peer->seldisptoolarge++;
2113 DPRINTF(1, ("packet: flash header %04x\n",
2126 * Capture the header values in the client/peer association..
2128 record_raw_stats(&peer->srcadr, peer->dstadr ?
2129 &peer->dstadr->sin : NULL,
2130 &p_org, &p_rec, &p_xmt, &peer->dst,
2131 pleap, pversion, pmode, pstratum, pkt->ppoll, pkt->precision,
2132 p_del, p_disp, pkt->refid);
2134 peer->stratum = min(pstratum, STRATUM_UNSPEC);
2135 peer->pmode = pmode;
2136 peer->precision = pkt->precision;
2137 peer->rootdelay = p_del;
2138 peer->rootdisp = p_disp;
2139 peer->refid = pkt->refid; /* network byte order */
2140 peer->reftime = p_reftime;
2143 * First, if either burst mode is armed, enable the burst.
2144 * Compute the headway for the next packet and delay if
2145 * necessary to avoid exceeding the threshold.
2147 if (peer->retry > 0) {
2150 peer->burst = min(1 << (peer->hpoll -
2151 peer->minpoll), NTP_SHIFT) - 1;
2153 peer->burst = NTP_IBURST - 1;
2154 if (peer->burst > 0)
2155 peer->nextdate = current_time;
2157 poll_update(peer, peer->hpoll);
2162 * If the peer was previously unreachable, raise a trap. In any
2163 * case, mark it reachable.
2166 report_event(PEVNT_REACH, peer, NULL);
2167 peer->timereachable = current_time;
2172 * For a client/server association, calculate the clock offset,
2173 * roundtrip delay and dispersion. The equations are reordered
2174 * from the spec for more efficient use of temporaries. For a
2175 * broadcast association, offset the last measurement by the
2176 * computed delay during the client/server volley. Note the
2177 * computation of dispersion includes the system precision plus
2178 * that due to the frequency error since the origin time.
2180 * It is very important to respect the hazards of overflow. The
2181 * only permitted operation on raw timestamps is subtraction,
2182 * where the result is a signed quantity spanning from 68 years
2183 * in the past to 68 years in the future. To avoid loss of
2184 * precision, these calculations are done using 64-bit integer
2185 * arithmetic. However, the offset and delay calculations are
2186 * sums and differences of these first-order differences, which
2187 * if done using 64-bit integer arithmetic, would be valid over
2188 * only half that span. Since the typical first-order
2189 * differences are usually very small, they are converted to 64-
2190 * bit doubles and all remaining calculations done in floating-
2191 * double arithmetic. This preserves the accuracy while
2192 * retaining the 68-year span.
2194 * There are three interleaving schemes, basic, interleaved
2195 * symmetric and interleaved broadcast. The timestamps are
2196 * idioscyncratically different. See the onwire briefing/white
2197 * paper at www.eecis.udel.edu/~mills for details.
2199 * Interleaved symmetric mode
2200 * t1 = peer->aorg/borg, t2 = peer->rec, t3 = p_xmt,
2203 if (peer->flip != 0) {
2204 ci = p_xmt; /* t3 - t4 */
2205 L_SUB(&ci, &peer->dst);
2207 ci = p_rec; /* t2 - t1 */
2209 L_SUB(&ci, &peer->borg);
2211 L_SUB(&ci, &peer->aorg);
2214 p_offset = (t21 + t34) / 2.;
2215 if (p_del < 0 || p_del > 1.) {
2216 snprintf(statstr, sizeof(statstr),
2217 "t21 %.6f t34 %.6f", t21, t34);
2218 report_event(PEVNT_XERR, peer, statstr);
2225 } else if (peer->pmode == MODE_BROADCAST) {
2228 * Interleaved broadcast mode. Use interleaved timestamps.
2229 * t1 = peer->borg, t2 = p_org, t3 = p_org, t4 = aorg
2231 if (peer->flags & FLAG_XB) {
2232 ci = p_org; /* delay */
2233 L_SUB(&ci, &peer->aorg);
2235 ci = p_org; /* t2 - t1 */
2236 L_SUB(&ci, &peer->borg);
2239 peer->borg = peer->dst;
2240 if (t34 < 0 || t34 > 1.) {
2241 /* drop all if in the initial volley */
2242 if (FLAG_BC_VOL & peer->flags)
2243 goto bcc_init_volley_fail;
2244 snprintf(statstr, sizeof(statstr),
2245 "offset %.6f delay %.6f", t21, t34);
2246 report_event(PEVNT_XERR, peer, statstr);
2253 * Basic broadcast - use direct timestamps.
2254 * t3 = p_xmt, t4 = peer->dst
2257 ci = p_xmt; /* t3 - t4 */
2258 L_SUB(&ci, &peer->dst);
2264 * When calibration is complete and the clock is
2265 * synchronized, the bias is calculated as the difference
2266 * between the unicast timestamp and the broadcast
2267 * timestamp. This works for both basic and interleaved
2269 * [Bug 3031] Don't keep this peer when the delay
2270 * calculation gives reason to suspect clock steps.
2271 * This is assumed for delays > 50ms.
2273 if (FLAG_BC_VOL & peer->flags) {
2274 peer->flags &= ~FLAG_BC_VOL;
2275 peer->delay = fabs(peer->offset - p_offset) * 2;
2276 DPRINTF(2, ("broadcast volley: initial delay=%.6f\n",
2278 if (peer->delay > fabs(sys_bdelay)) {
2279 bcc_init_volley_fail:
2280 DPRINTF(2, ("%s", "broadcast volley: initial delay exceeds limit\n"));
2285 peer->nextdate = current_time + (1u << peer->ppoll) - 2u;
2286 p_del = peer->delay;
2287 p_offset += p_del / 2;
2291 * Basic mode, otherwise known as the old fashioned way.
2293 * t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->dst
2296 ci = p_xmt; /* t3 - t4 */
2297 L_SUB(&ci, &peer->dst);
2299 ci = p_rec; /* t2 - t1 */
2302 p_del = fabs(t21 - t34);
2303 p_offset = (t21 + t34) / 2.;
2305 p_del = max(p_del, LOGTOD(sys_precision));
2306 p_disp = LOGTOD(sys_precision) + LOGTOD(peer->precision) +
2311 * This code calculates the outbound and inbound data rates by
2312 * measuring the differences between timestamps at different
2313 * packet lengths. This is helpful in cases of large asymmetric
2314 * delays commonly experienced on deep space communication
2317 if (peer->t21_last > 0 && peer->t34_bytes > 0) {
2318 itemp = peer->t21_bytes - peer->t21_last;
2320 etemp = t21 - peer->t21;
2321 if (fabs(etemp) > 1e-6) {
2322 ftemp = itemp / etemp;
2327 itemp = len - peer->t34_bytes;
2329 etemp = -t34 - peer->t34;
2330 if (fabs(etemp) > 1e-6) {
2331 ftemp = itemp / etemp;
2339 * The following section compensates for different data rates on
2340 * the outbound (d21) and inbound (t34) directions. To do this,
2341 * it finds t such that r21 * t - r34 * (d - t) = 0, where d is
2342 * the roundtrip delay. Then it calculates the correction as a
2346 peer->t21_last = peer->t21_bytes;
2348 peer->t34_bytes = len;
2349 DPRINTF(2, ("packet: t21 %.9lf %d t34 %.9lf %d\n", peer->t21,
2350 peer->t21_bytes, peer->t34, peer->t34_bytes));
2351 if (peer->r21 > 0 && peer->r34 > 0 && p_del > 0) {
2352 if (peer->pmode != MODE_BROADCAST)
2353 td = (peer->r34 / (peer->r21 + peer->r34) -
2359 * Unfortunately, in many cases the errors are
2360 * unacceptable, so for the present the rates are not
2361 * used. In future, we might find conditions where the
2362 * calculations are useful, so this should be considered
2363 * a work in progress.
2367 DPRINTF(2, ("packet: del %.6lf r21 %.1lf r34 %.1lf %.6lf\n",
2368 p_del, peer->r21 / 1e3, peer->r34 / 1e3,
2374 * That was awesome. Now hand off to the clock filter.
2376 clock_filter(peer, p_offset + peer->bias, p_del, p_disp);
2379 * If we are in broadcast calibrate mode, return to broadcast
2380 * client mode when the client is fit and the autokey dance is
2383 if ( (FLAG_BC_VOL & peer->flags)
2384 && MODE_CLIENT == peer->hmode
2385 && !(TEST11 & peer_unfit(peer))) { /* distance exceeded */
2387 if (peer->flags & FLAG_SKEY) {
2388 if (!(~peer->crypto & CRYPTO_FLAG_ALL))
2389 peer->hmode = MODE_BCLIENT;
2391 peer->hmode = MODE_BCLIENT;
2393 #else /* !AUTOKEY follows */
2394 peer->hmode = MODE_BCLIENT;
2395 #endif /* !AUTOKEY */
2401 * clock_update - Called at system process update intervals.
2405 struct peer *peer /* peer structure pointer */
2410 #ifdef HAVE_LIBSCF_H
2412 #endif /* HAVE_LIBSCF_H */
2415 * Update the system state variables. We do this very carefully,
2416 * as the poll interval might need to be clamped differently.
2419 sys_epoch = peer->epoch;
2420 if (sys_poll < peer->minpoll)
2421 sys_poll = peer->minpoll;
2422 if (sys_poll > peer->maxpoll)
2423 sys_poll = peer->maxpoll;
2424 poll_update(peer, sys_poll);
2425 sys_stratum = min(peer->stratum + 1, STRATUM_UNSPEC);
2426 if ( peer->stratum == STRATUM_REFCLOCK
2427 || peer->stratum == STRATUM_UNSPEC)
2428 sys_refid = peer->refid;
2430 sys_refid = addr2refid(&peer->srcadr);
2432 * Root Dispersion (E) is defined (in RFC 5905) as:
2434 * E = p.epsilon_r + p.epsilon + p.psi + PHI*(s.t - p.t) + |THETA|
2437 * p.epsilon_r is the PollProc's root dispersion
2438 * p.epsilon is the PollProc's dispersion
2439 * p.psi is the PollProc's jitter
2440 * THETA is the combined offset
2442 * NB: Think Hard about where these numbers come from and
2443 * what they mean. When did peer->update happen? Has anything
2444 * interesting happened since then? What values are the most
2447 * DLM thinks this equation is probably the best of all worse choices.
2449 dtemp = peer->rootdisp
2452 + clock_phi * (current_time - peer->update)
2455 if (dtemp > sys_mindisp)
2456 sys_rootdisp = dtemp;
2458 sys_rootdisp = sys_mindisp;
2459 sys_rootdelay = peer->delay + peer->rootdelay;
2460 sys_reftime = peer->dst;
2462 DPRINTF(1, ("clock_update: at %lu sample %lu associd %d\n",
2463 current_time, peer->epoch, peer->associd));
2466 * Comes now the moment of truth. Crank the clock discipline and
2467 * see what comes out.
2469 switch (local_clock(peer, sys_offset)) {
2472 * Clock exceeds panic threshold. Life as we know it ends.
2475 #ifdef HAVE_LIBSCF_H
2477 * For Solaris enter the maintenance mode.
2479 if ((fmri = getenv("SMF_FMRI")) != NULL) {
2480 if (smf_maintain_instance(fmri, 0) < 0) {
2481 printf("smf_maintain_instance: %s\n",
2482 scf_strerror(scf_error()));
2486 * Sleep until SMF kills us.
2491 #endif /* HAVE_LIBSCF_H */
2496 * Clock was stepped. Flush all time values of all peers.
2500 set_sys_leap(LEAP_NOTINSYNC);
2501 sys_stratum = STRATUM_UNSPEC;
2502 memcpy(&sys_refid, "STEP", 4);
2505 L_CLR(&sys_reftime);
2506 sys_jitter = LOGTOD(sys_precision);
2507 leapsec_reset_frame();
2511 * Clock was slewed. Handle the leapsecond stuff.
2516 * If this is the first time the clock is set, reset the
2517 * leap bits. If crypto, the timer will goose the setup
2520 if (sys_leap == LEAP_NOTINSYNC) {
2521 set_sys_leap(LEAP_NOWARNING);
2525 #endif /* AUTOKEY */
2527 * If our parent process is waiting for the
2528 * first clock sync, send them home satisfied.
2530 #ifdef HAVE_WORKING_FORK
2531 if (waitsync_fd_to_close != -1) {
2532 close(waitsync_fd_to_close);
2533 waitsync_fd_to_close = -1;
2534 DPRINTF(1, ("notified parent --wait-sync is done\n"));
2536 #endif /* HAVE_WORKING_FORK */
2541 * If there is no leap second pending and the number of
2542 * survivor leap bits is greater than half the number of
2543 * survivors, try to schedule a leap for the end of the
2544 * current month. (This only works if no leap second for
2545 * that range is in the table, so doing this more than
2546 * once is mostly harmless.)
2548 if (leapsec == LSPROX_NOWARN) {
2549 if ( leap_vote_ins > leap_vote_del
2550 && leap_vote_ins > sys_survivors / 2) {
2552 leapsec_add_dyn(TRUE, now.l_ui, NULL);
2554 if ( leap_vote_del > leap_vote_ins
2555 && leap_vote_del > sys_survivors / 2) {
2557 leapsec_add_dyn(FALSE, now.l_ui, NULL);
2563 * Popcorn spike or step threshold exceeded. Pretend it never
2573 * poll_update - update peer poll interval
2577 struct peer *peer, /* peer structure pointer */
2585 * This routine figures out when the next poll should be sent.
2586 * That turns out to be wickedly complicated. One problem is
2587 * that sometimes the time for the next poll is in the past when
2588 * the poll interval is reduced. We watch out for races here
2589 * between the receive process and the poll process.
2591 * Clamp the poll interval between minpoll and maxpoll.
2593 hpoll = max(min(peer->maxpoll, mpoll), peer->minpoll);
2597 * If during the crypto protocol the poll interval has changed,
2598 * the lifetimes in the key list are probably bogus. Purge the
2599 * the key list and regenerate it later.
2601 if ((peer->flags & FLAG_SKEY) && hpoll != peer->hpoll)
2603 #endif /* AUTOKEY */
2604 peer->hpoll = hpoll;
2607 * There are three variables important for poll scheduling, the
2608 * current time (current_time), next scheduled time (nextdate)
2609 * and the earliest time (utemp). The earliest time is 2 s
2610 * seconds, but could be more due to rate management. When
2611 * sending in a burst, use the earliest time. When not in a
2612 * burst but with a reply pending, send at the earliest time
2613 * unless the next scheduled time has not advanced. This can
2614 * only happen if multiple replies are pending in the same
2615 * response interval. Otherwise, send at the later of the next
2616 * scheduled time and the earliest time.
2618 * Now we figure out if there is an override. If a burst is in
2619 * progress and we get called from the receive process, just
2620 * slink away. If called from the poll process, delay 1 s for a
2621 * reference clock, otherwise 2 s.
2623 utemp = current_time + max(peer->throttle - (NTP_SHIFT - 1) *
2624 (1 << peer->minpoll), ntp_minpkt);
2625 if (peer->burst > 0) {
2626 if (peer->nextdate > current_time)
2629 else if (peer->flags & FLAG_REFCLOCK)
2630 peer->nextdate = current_time + RESP_DELAY;
2631 #endif /* REFCLOCK */
2633 peer->nextdate = utemp;
2637 * If a burst is not in progress and a crypto response message
2638 * is pending, delay 2 s, but only if this is a new interval.
2640 } else if (peer->cmmd != NULL) {
2641 if (peer->nextdate > current_time) {
2642 if (peer->nextdate + ntp_minpkt != utemp)
2643 peer->nextdate = utemp;
2645 peer->nextdate = utemp;
2647 #endif /* AUTOKEY */
2650 * The ordinary case. If a retry, use minpoll; if unreachable,
2651 * use host poll; otherwise, use the minimum of host and peer
2652 * polls; In other words, oversampling is okay but
2653 * understampling is evil. Use the maximum of this value and the
2654 * headway. If the average headway is greater than the headway
2655 * threshold, increase the headway by the minimum interval.
2658 if (peer->retry > 0)
2659 hpoll = peer->minpoll;
2660 else if (!(peer->reach))
2661 hpoll = peer->hpoll;
2663 hpoll = min(peer->ppoll, peer->hpoll);
2665 if (peer->flags & FLAG_REFCLOCK)
2668 #endif /* REFCLOCK */
2669 next = ((0x1000UL | (ntp_random() & 0x0ff)) <<
2671 next += peer->outdate;
2673 peer->nextdate = next;
2675 peer->nextdate = utemp;
2676 if (peer->throttle > (1 << peer->minpoll))
2677 peer->nextdate += ntp_minpkt;
2679 DPRINTF(2, ("poll_update: at %lu %s poll %d burst %d retry %d head %d early %lu next %lu\n",
2680 current_time, ntoa(&peer->srcadr), peer->hpoll,
2681 peer->burst, peer->retry, peer->throttle,
2682 utemp - current_time, peer->nextdate -
2688 * peer_clear - clear peer filter registers. See Section 3.4.8 of the
2693 struct peer *peer, /* peer structure */
2694 const char *ident /* tally lights */
2701 * If cryptographic credentials have been acquired, toss them to
2702 * Valhalla. Note that autokeys are ephemeral, in that they are
2703 * tossed immediately upon use. Therefore, the keylist can be
2704 * purged anytime without needing to preserve random keys. Note
2705 * that, if the peer is purged, the cryptographic variables are
2706 * purged, too. This makes it much harder to sneak in some
2707 * unauthenticated data in the clock filter.
2710 if (peer->iffval != NULL)
2711 BN_free(peer->iffval);
2712 value_free(&peer->cookval);
2713 value_free(&peer->recval);
2714 value_free(&peer->encrypt);
2715 value_free(&peer->sndval);
2716 if (peer->cmmd != NULL)
2718 if (peer->subject != NULL)
2719 free(peer->subject);
2720 if (peer->issuer != NULL)
2722 #endif /* AUTOKEY */
2725 * Clear all values, including the optional crypto values above.
2727 memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO(peer));
2728 peer->ppoll = peer->maxpoll;
2729 peer->hpoll = peer->minpoll;
2730 peer->disp = MAXDISPERSE;
2731 peer->flash = peer_unfit(peer);
2732 peer->jitter = LOGTOD(sys_precision);
2735 * If interleave mode, initialize the alternate origin switch.
2737 if (peer->flags & FLAG_XLEAVE)
2739 for (u = 0; u < NTP_SHIFT; u++) {
2740 peer->filter_order[u] = u;
2741 peer->filter_disp[u] = MAXDISPERSE;
2744 if (!(peer->flags & FLAG_REFCLOCK)) {
2746 peer->leap = LEAP_NOTINSYNC;
2747 peer->stratum = STRATUM_UNSPEC;
2748 memcpy(&peer->refid, ident, 4);
2754 * During initialization use the association count to spread out
2755 * the polls at one-second intervals. Passive associations'
2756 * first poll is delayed by the "discard minimum" to avoid rate
2757 * limiting. Other post-startup new or cleared associations
2758 * randomize the first poll over the minimum poll interval to
2761 peer->nextdate = peer->update = peer->outdate = current_time;
2763 peer->nextdate += peer_associations;
2764 } else if (MODE_PASSIVE == peer->hmode) {
2765 peer->nextdate += ntp_minpkt;
2767 peer->nextdate += ntp_random() % peer->minpoll;
2770 peer->refresh = current_time + (1 << NTP_REFRESH);
2771 #endif /* AUTOKEY */
2772 DPRINTF(1, ("peer_clear: at %ld next %ld associd %d refid %s\n",
2773 current_time, peer->nextdate, peer->associd,
2779 * clock_filter - add incoming clock sample to filter register and run
2780 * the filter procedure to find the best sample.
2784 struct peer *peer, /* peer structure pointer */
2785 double sample_offset, /* clock offset */
2786 double sample_delay, /* roundtrip delay */
2787 double sample_disp /* dispersion */
2790 double dst[NTP_SHIFT]; /* distance vector */
2791 int ord[NTP_SHIFT]; /* index vector */
2793 double dtemp, etemp;
2797 * A sample consists of the offset, delay, dispersion and epoch
2798 * of arrival. The offset and delay are determined by the on-
2799 * wire protocol. The dispersion grows from the last outbound
2800 * packet to the arrival of this one increased by the sum of the
2801 * peer precision and the system precision as required by the
2802 * error budget. First, shift the new arrival into the shift
2803 * register discarding the oldest one.
2805 j = peer->filter_nextpt;
2806 peer->filter_offset[j] = sample_offset;
2807 peer->filter_delay[j] = sample_delay;
2808 peer->filter_disp[j] = sample_disp;
2809 peer->filter_epoch[j] = current_time;
2810 j = (j + 1) % NTP_SHIFT;
2811 peer->filter_nextpt = j;
2814 * Update dispersions since the last update and at the same
2815 * time initialize the distance and index lists. Since samples
2816 * become increasingly uncorrelated beyond the Allan intercept,
2817 * only under exceptional cases will an older sample be used.
2818 * Therefore, the distance list uses a compound metric. If the
2819 * dispersion is greater than the maximum dispersion, clamp the
2820 * distance at that value. If the time since the last update is
2821 * less than the Allan intercept use the delay; otherwise, use
2822 * the sum of the delay and dispersion.
2824 dtemp = clock_phi * (current_time - peer->update);
2825 peer->update = current_time;
2826 for (i = NTP_SHIFT - 1; i >= 0; i--) {
2828 peer->filter_disp[j] += dtemp;
2829 if (peer->filter_disp[j] >= MAXDISPERSE) {
2830 peer->filter_disp[j] = MAXDISPERSE;
2831 dst[i] = MAXDISPERSE;
2832 } else if (peer->update - peer->filter_epoch[j] >
2833 (u_long)ULOGTOD(allan_xpt)) {
2834 dst[i] = peer->filter_delay[j] +
2835 peer->filter_disp[j];
2837 dst[i] = peer->filter_delay[j];
2840 j = (j + 1) % NTP_SHIFT;
2844 * If the clock has stabilized, sort the samples by distance.
2846 if (freq_cnt == 0) {
2847 for (i = 1; i < NTP_SHIFT; i++) {
2848 for (j = 0; j < i; j++) {
2849 if (dst[j] > dst[i]) {
2862 * Copy the index list to the association structure so ntpq
2863 * can see it later. Prune the distance list to leave only
2864 * samples less than the maximum dispersion, which disfavors
2865 * uncorrelated samples older than the Allan intercept. To
2866 * further improve the jitter estimate, of the remainder leave
2867 * only samples less than the maximum distance, but keep at
2868 * least two samples for jitter calculation.
2871 for (i = 0; i < NTP_SHIFT; i++) {
2872 peer->filter_order[i] = (u_char) ord[i];
2873 if ( dst[i] >= MAXDISPERSE
2874 || (m >= 2 && dst[i] >= sys_maxdist))
2880 * Compute the dispersion and jitter. The dispersion is weighted
2881 * exponentially by NTP_FWEIGHT (0.5) so it is normalized close
2882 * to 1.0. The jitter is the RMS differences relative to the
2883 * lowest delay sample.
2885 peer->disp = peer->jitter = 0;
2887 for (i = NTP_SHIFT - 1; i >= 0; i--) {
2889 peer->disp = NTP_FWEIGHT * (peer->disp +
2890 peer->filter_disp[j]);
2892 peer->jitter += DIFF(peer->filter_offset[j],
2893 peer->filter_offset[k]);
2897 * If no acceptable samples remain in the shift register,
2898 * quietly tiptoe home leaving only the dispersion. Otherwise,
2899 * save the offset, delay and jitter. Note the jitter must not
2900 * be less than the precision.
2906 etemp = fabs(peer->offset - peer->filter_offset[k]);
2907 peer->offset = peer->filter_offset[k];
2908 peer->delay = peer->filter_delay[k];
2910 peer->jitter /= m - 1;
2911 peer->jitter = max(SQRT(peer->jitter), LOGTOD(sys_precision));
2914 * If the the new sample and the current sample are both valid
2915 * and the difference between their offsets exceeds CLOCK_SGATE
2916 * (3) times the jitter and the interval between them is less
2917 * than twice the host poll interval, consider the new sample
2918 * a popcorn spike and ignore it.
2920 if ( peer->disp < sys_maxdist
2921 && peer->filter_disp[k] < sys_maxdist
2922 && etemp > CLOCK_SGATE * peer->jitter
2923 && peer->filter_epoch[k] - peer->epoch
2924 < 2. * ULOGTOD(peer->hpoll)) {
2925 snprintf(tbuf, sizeof(tbuf), "%.6f s", etemp);
2926 report_event(PEVNT_POPCORN, peer, tbuf);
2931 * A new minimum sample is useful only if it is later than the
2932 * last one used. In this design the maximum lifetime of any
2933 * sample is not greater than eight times the poll interval, so
2934 * the maximum interval between minimum samples is eight
2937 if (peer->filter_epoch[k] <= peer->epoch) {
2938 DPRINTF(2, ("clock_filter: old sample %lu\n", current_time -
2939 peer->filter_epoch[k]));
2942 peer->epoch = peer->filter_epoch[k];
2945 * The mitigated sample statistics are saved for later
2946 * processing. If not synchronized or not in a burst, tickle the
2947 * clock select algorithm.
2949 record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
2950 peer->offset, peer->delay, peer->disp, peer->jitter);
2951 DPRINTF(1, ("clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f\n",
2952 m, peer->offset, peer->delay, peer->disp,
2954 if (peer->burst == 0 || sys_leap == LEAP_NOTINSYNC)
2960 * clock_select - find the pick-of-the-litter clock
2962 * LOCKCLOCK: (1) If the local clock is the prefer peer, it will always
2963 * be enabled, even if declared falseticker, (2) only the prefer peer
2964 * can be selected as the system peer, (3) if the external source is
2965 * down, the system leap bits are set to 11 and the stratum set to
2979 double orphmet = 2.0 * U_INT32_MAX; /* 2x is greater than */
2980 struct endpoint endp;
2981 struct peer *osys_peer;
2982 struct peer *sys_prefer = NULL; /* prefer peer */
2983 struct peer *typesystem = NULL;
2984 struct peer *typeorphan = NULL;
2986 struct peer *typeacts = NULL;
2987 struct peer *typelocal = NULL;
2988 struct peer *typepps = NULL;
2989 #endif /* REFCLOCK */
2990 static struct endpoint *endpoint = NULL;
2991 static int *indx = NULL;
2992 static peer_select *peers = NULL;
2993 static u_int endpoint_size = 0;
2994 static u_int peers_size = 0;
2995 static u_int indx_size = 0;
2999 * Initialize and create endpoint, index and peer lists big
3000 * enough to handle all associations.
3002 osys_peer = sys_peer;
3005 set_sys_leap(LEAP_NOTINSYNC);
3006 sys_stratum = STRATUM_UNSPEC;
3007 memcpy(&sys_refid, "DOWN", 4);
3008 #endif /* LOCKCLOCK */
3011 * Allocate dynamic space depending on the number of
3015 for (peer = peer_list; peer != NULL; peer = peer->p_link)
3017 endpoint_size = ALIGNED_SIZE(nlist * 2 * sizeof(*endpoint));
3018 peers_size = ALIGNED_SIZE(nlist * sizeof(*peers));
3019 indx_size = ALIGNED_SIZE(nlist * 2 * sizeof(*indx));
3020 octets = endpoint_size + peers_size + indx_size;
3021 endpoint = erealloc(endpoint, octets);
3022 peers = INC_ALIGNED_PTR(endpoint, endpoint_size);
3023 indx = INC_ALIGNED_PTR(peers, peers_size);
3026 * Initially, we populate the island with all the rifraff peers
3027 * that happen to be lying around. Those with seriously
3028 * defective clocks are immediately booted off the island. Then,
3029 * the falsetickers are culled and put to sea. The truechimers
3030 * remaining are subject to repeated rounds where the most
3031 * unpopular at each round is kicked off. When the population
3032 * has dwindled to sys_minclock, the survivors split a million
3033 * bucks and collectively crank the chimes.
3035 nlist = nl2 = 0; /* none yet */
3036 for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3037 peer->new_status = CTL_PST_SEL_REJECT;
3040 * Leave the island immediately if the peer is
3041 * unfit to synchronize.
3043 if (peer_unfit(peer))
3047 * If this peer is an orphan parent, elect the
3048 * one with the lowest metric defined as the
3049 * IPv4 address or the first 64 bits of the
3050 * hashed IPv6 address. To ensure convergence
3051 * on the same selected orphan, consider as
3052 * well that this system may have the lowest
3053 * metric and be the orphan parent. If this
3054 * system wins, sys_peer will be NULL to trigger
3055 * orphan mode in timer().
3057 if (peer->stratum == sys_orphan) {
3061 if (peer->dstadr != NULL)
3062 localmet = ntohl(peer->dstadr->addr_refid);
3064 localmet = U_INT32_MAX;
3065 peermet = ntohl(addr2refid(&peer->srcadr));
3066 if (peermet < localmet && peermet < orphmet) {
3074 * If this peer could have the orphan parent
3075 * as a synchronization ancestor, exclude it
3076 * from selection to avoid forming a
3077 * synchronization loop within the orphan mesh,
3078 * triggering stratum climb to infinity
3079 * instability. Peers at stratum higher than
3080 * the orphan stratum could have the orphan
3081 * parent in ancestry so are excluded.
3082 * See http://bugs.ntp.org/2050
3084 if (peer->stratum > sys_orphan)
3088 * The following are special cases. We deal
3091 if (!(peer->flags & FLAG_PREFER)) {
3092 switch (peer->refclktype) {
3093 case REFCLK_LOCALCLOCK:
3094 if ( current_time > orphwait
3095 && typelocal == NULL)
3100 if ( current_time > orphwait
3101 && typeacts == NULL)
3106 #endif /* REFCLOCK */
3109 * If we get this far, the peer can stay on the
3110 * island, but does not yet have the immunity
3113 peer->new_status = CTL_PST_SEL_SANE;
3114 f = root_distance(peer);
3115 peers[nlist].peer = peer;
3116 peers[nlist].error = peer->jitter;
3117 peers[nlist].synch = f;
3121 * Insert each interval endpoint on the unsorted
3125 endpoint[nl2].type = -1; /* lower end */
3126 endpoint[nl2].val = e - f;
3128 endpoint[nl2].type = 1; /* upper end */
3129 endpoint[nl2].val = e + f;
3133 * Construct sorted indx[] of endpoint[] indexes ordered by
3136 for (i = 0; i < nl2; i++)
3138 for (i = 0; i < nl2; i++) {
3139 endp = endpoint[indx[i]];
3142 for (j = i + 1; j < nl2; j++) {
3143 endp = endpoint[indx[j]];
3155 for (i = 0; i < nl2; i++)
3156 DPRINTF(3, ("select: endpoint %2d %.6f\n",
3157 endpoint[indx[i]].type, endpoint[indx[i]].val));
3160 * This is the actual algorithm that cleaves the truechimers
3161 * from the falsetickers. The original algorithm was described
3162 * in Keith Marzullo's dissertation, but has been modified for
3165 * Briefly put, we first assume there are no falsetickers, then
3166 * scan the candidate list first from the low end upwards and
3167 * then from the high end downwards. The scans stop when the
3168 * number of intersections equals the number of candidates less
3169 * the number of falsetickers. If this doesn't happen for a
3170 * given number of falsetickers, we bump the number of
3171 * falsetickers and try again. If the number of falsetickers
3172 * becomes equal to or greater than half the number of
3173 * candidates, the Albanians have won the Byzantine wars and
3174 * correct synchronization is not possible.
3176 * Here, nlist is the number of candidates and allow is the
3177 * number of falsetickers. Upon exit, the truechimers are the
3178 * survivors with offsets not less than low and not greater than
3179 * high. There may be none of them.
3183 for (allow = 0; 2 * allow < nlist; allow++) {
3186 * Bound the interval (low, high) as the smallest
3187 * interval containing points from the most sources.
3190 for (i = 0; i < nl2; i++) {
3191 low = endpoint[indx[i]].val;
3192 n -= endpoint[indx[i]].type;
3193 if (n >= nlist - allow)
3197 for (j = nl2 - 1; j >= 0; j--) {
3198 high = endpoint[indx[j]].val;
3199 n += endpoint[indx[j]].type;
3200 if (n >= nlist - allow)
3205 * If an interval containing truechimers is found, stop.
3206 * If not, increase the number of falsetickers and go
3214 * Clustering algorithm. Whittle candidate list of falsetickers,
3215 * who leave the island immediately. The TRUE peer is always a
3216 * truechimer. We must leave at least one peer to collect the
3219 * We assert the correct time is contained in the interval, but
3220 * the best offset estimate for the interval might not be
3221 * contained in the interval. For this purpose, a truechimer is
3222 * defined as the midpoint of an interval that overlaps the
3223 * intersection interval.
3226 for (i = 0; i < nlist; i++) {
3229 peer = peers[i].peer;
3232 || peer->offset + h < low
3233 || peer->offset - h > high
3234 ) && !(peer->flags & FLAG_TRUE))
3239 * Eligible PPS peers must survive the intersection
3240 * algorithm. Use the first one found, but don't
3241 * include any of them in the cluster population.
3243 if (peer->flags & FLAG_PPS) {
3244 if (typepps == NULL)
3246 if (!(peer->flags & FLAG_TSTAMP_PPS))
3249 #endif /* REFCLOCK */
3252 peers[j] = peers[i];
3258 * If no survivors remain at this point, check if the modem
3259 * driver, local driver or orphan parent in that order. If so,
3260 * nominate the first one found as the only survivor.
3261 * Otherwise, give up and leave the island to the rats.
3265 peers[0].synch = sys_mindisp;
3267 if (typeacts != NULL) {
3268 peers[0].peer = typeacts;
3270 } else if (typelocal != NULL) {
3271 peers[0].peer = typelocal;
3274 #endif /* REFCLOCK */
3275 if (typeorphan != NULL) {
3276 peers[0].peer = typeorphan;
3282 * Mark the candidates at this point as truechimers.
3284 for (i = 0; i < nlist; i++) {
3285 peers[i].peer->new_status = CTL_PST_SEL_SELCAND;
3286 DPRINTF(2, ("select: survivor %s %f\n",
3287 stoa(&peers[i].peer->srcadr), peers[i].synch));
3291 * Now, vote outliers off the island by select jitter weighted
3292 * by root distance. Continue voting as long as there are more
3293 * than sys_minclock survivors and the select jitter of the peer
3294 * with the worst metric is greater than the minimum peer
3295 * jitter. Stop if we are about to discard a TRUE or PREFER
3296 * peer, who of course have the immunity idol.
3303 for (i = 0; i < nlist; i++) {
3304 if (peers[i].error < d)
3306 peers[i].seljit = 0;
3309 for (j = 0; j < nlist; j++)
3310 f += DIFF(peers[j].peer->offset,
3311 peers[i].peer->offset);
3312 peers[i].seljit = SQRT(f / (nlist - 1));
3314 if (peers[i].seljit * peers[i].synch > e) {
3315 g = peers[i].seljit;
3316 e = peers[i].seljit * peers[i].synch;
3320 g = max(g, LOGTOD(sys_precision));
3321 if ( nlist <= max(1, sys_minclock)
3323 || ((FLAG_TRUE | FLAG_PREFER) & peers[k].peer->flags))
3326 DPRINTF(3, ("select: drop %s seljit %.6f jit %.6f\n",
3327 ntoa(&peers[k].peer->srcadr), g, d));
3328 if (nlist > sys_maxclock)
3329 peers[k].peer->new_status = CTL_PST_SEL_EXCESS;
3330 for (j = k + 1; j < nlist; j++)
3331 peers[j - 1] = peers[j];
3336 * What remains is a list usually not greater than sys_minclock
3337 * peers. Note that unsynchronized peers cannot survive this
3338 * far. Count and mark these survivors.
3340 * While at it, count the number of leap warning bits found.
3341 * This will be used later to vote the system leap warning bit.
3342 * If a leap warning bit is found on a reference clock, the vote
3345 * Choose the system peer using a hybrid metric composed of the
3346 * selection jitter scaled by the root distance augmented by
3347 * stratum scaled by sys_mindisp (.001 by default). The goal of
3348 * the small stratum factor is to avoid clockhop between a
3349 * reference clock and a network peer which has a refclock and
3350 * is using an older ntpd, which does not floor sys_rootdisp at
3353 * In contrast, ntpd 4.2.6 and earlier used stratum primarily
3354 * in selecting the system peer, using a weight of 1 second of
3355 * additional root distance per stratum. This heavy bias is no
3356 * longer appropriate, as the scaled root distance provides a
3357 * more rational metric carrying the cumulative error budget.
3363 for (i = 0; i < nlist; i++) {
3364 peer = peers[i].peer;
3366 peer->new_status = CTL_PST_SEL_SYNCCAND;
3368 if (peer->leap == LEAP_ADDSECOND) {
3369 if (peer->flags & FLAG_REFCLOCK)
3370 leap_vote_ins = nlist;
3371 else if (leap_vote_ins < nlist)
3374 if (peer->leap == LEAP_DELSECOND) {
3375 if (peer->flags & FLAG_REFCLOCK)
3376 leap_vote_del = nlist;
3377 else if (leap_vote_del < nlist)
3380 if (peer->flags & FLAG_PREFER)
3382 speermet = peers[i].seljit * peers[i].synch +
3383 peer->stratum * sys_mindisp;
3391 * Unless there are at least sys_misane survivors, leave the
3392 * building dark. Otherwise, do a clockhop dance. Ordinarily,
3393 * use the selected survivor speer. However, if the current
3394 * system peer is not speer, stay with the current system peer
3395 * as long as it doesn't get too old or too ugly.
3397 if (nlist > 0 && nlist >= sys_minsane) {
3400 typesystem = peers[speer].peer;
3401 if (osys_peer == NULL || osys_peer == typesystem) {
3403 } else if ((x = fabs(typesystem->offset -
3404 osys_peer->offset)) < sys_mindisp) {
3405 if (sys_clockhop == 0)
3406 sys_clockhop = sys_mindisp;
3409 DPRINTF(1, ("select: clockhop %d %.6f %.6f\n",
3410 j, x, sys_clockhop));
3411 if (fabs(x) < sys_clockhop)
3412 typesystem = osys_peer;
3421 * Mitigation rules of the game. We have the pick of the
3422 * litter in typesystem if any survivors are left. If
3423 * there is a prefer peer, use its offset and jitter.
3424 * Otherwise, use the combined offset and jitter of all kitters.
3426 if (typesystem != NULL) {
3427 if (sys_prefer == NULL) {
3428 typesystem->new_status = CTL_PST_SEL_SYSPEER;
3429 clock_combine(peers, sys_survivors, speer);
3431 typesystem = sys_prefer;
3433 typesystem->new_status = CTL_PST_SEL_SYSPEER;
3434 sys_offset = typesystem->offset;
3435 sys_jitter = typesystem->jitter;
3437 DPRINTF(1, ("select: combine offset %.9f jitter %.9f\n",
3438 sys_offset, sys_jitter));
3442 * If a PPS driver is lit and the combined offset is less than
3443 * 0.4 s, select the driver as the PPS peer and use its offset
3444 * and jitter. However, if this is the atom driver, use it only
3445 * if there is a prefer peer or there are no survivors and none
3448 if ( typepps != NULL
3449 && fabs(sys_offset) < 0.4
3450 && ( typepps->refclktype != REFCLK_ATOM_PPS
3451 || ( typepps->refclktype == REFCLK_ATOM_PPS
3452 && ( sys_prefer != NULL
3453 || (typesystem == NULL && sys_minsane == 0))))) {
3454 typesystem = typepps;
3456 typesystem->new_status = CTL_PST_SEL_PPS;
3457 sys_offset = typesystem->offset;
3458 sys_jitter = typesystem->jitter;
3459 DPRINTF(1, ("select: pps offset %.9f jitter %.9f\n",
3460 sys_offset, sys_jitter));
3462 #endif /* REFCLOCK */
3465 * If there are no survivors at this point, there is no
3466 * system peer. If so and this is an old update, keep the
3467 * current statistics, but do not update the clock.
3469 if (typesystem == NULL) {
3470 if (osys_peer != NULL) {
3471 if (sys_orphwait > 0)
3472 orphwait = current_time + sys_orphwait;
3473 report_event(EVNT_NOPEER, NULL, NULL);
3476 for (peer = peer_list; peer != NULL; peer = peer->p_link)
3477 peer->status = peer->new_status;
3482 * Do not use old data, as this may mess up the clock discipline
3485 if (typesystem->epoch <= sys_epoch)
3489 * We have found the alpha male. Wind the clock.
3491 if (osys_peer != typesystem)
3492 report_event(PEVNT_NEWPEER, typesystem, NULL);
3493 for (peer = peer_list; peer != NULL; peer = peer->p_link)
3494 peer->status = peer->new_status;
3495 clock_update(typesystem);
3501 peer_select * peers, /* survivor list */
3502 int npeers, /* number of survivors */
3503 int syspeer /* index of sys.peer */
3510 for (i = 0; i < npeers; i++) {
3511 x = 1. / peers[i].synch;
3513 z += x * peers[i].peer->offset;
3514 w += x * DIFF(peers[i].peer->offset,
3515 peers[syspeer].peer->offset);
3518 sys_jitter = SQRT(w / y + SQUARE(peers[syspeer].seljit));
3523 * root_distance - compute synchronization distance from peer to root
3527 struct peer *peer /* peer structure pointer */
3533 * Root Distance (LAMBDA) is defined as:
3534 * (delta + DELTA)/2 + epsilon + EPSILON + phi
3537 * delta is the round-trip delay
3538 * DELTA is the root delay
3539 * epsilon is the remote server precision + local precision
3540 * + (15 usec each second)
3541 * EPSILON is the root dispersion
3542 * phi is the peer jitter statistic
3544 * NB: Think hard about why we are using these values, and what
3545 * the alternatives are, and the various pros/cons.
3547 * DLM thinks these are probably the best choices from any of the
3548 * other worse choices.
3550 dtemp = (peer->delay + peer->rootdelay) / 2
3551 + LOGTOD(peer->precision)
3552 + LOGTOD(sys_precision)
3553 + clock_phi * (current_time - peer->update)
3557 * Careful squeak here. The value returned must be greater than
3558 * the minimum root dispersion in order to avoid clockhop with
3559 * highly precise reference clocks. Note that the root distance
3560 * cannot exceed the sys_maxdist, as this is the cutoff by the
3561 * selection algorithm.
3563 if (dtemp < sys_mindisp)
3564 dtemp = sys_mindisp;
3570 * peer_xmit - send packet for persistent association.
3574 struct peer *peer /* peer structure pointer */
3577 struct pkt xpkt; /* transmit packet */
3578 size_t sendlen, authlen;
3579 keyid_t xkeyid = 0; /* transmit key ID */
3580 l_fp xmt_tx, xmt_ty;
3582 if (!peer->dstadr) /* drop peers without interface */
3585 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
3587 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
3588 xpkt.ppoll = peer->hpoll;
3589 xpkt.precision = sys_precision;
3590 xpkt.refid = sys_refid;
3591 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
3592 xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
3593 HTONL_FP(&sys_reftime, &xpkt.reftime);
3594 HTONL_FP(&peer->rec, &xpkt.org);
3595 HTONL_FP(&peer->dst, &xpkt.rec);
3598 * If the received packet contains a MAC, the transmitted packet
3599 * is authenticated and contains a MAC. If not, the transmitted
3600 * packet is not authenticated.
3602 * It is most important when autokey is in use that the local
3603 * interface IP address be known before the first packet is
3604 * sent. Otherwise, it is not possible to compute a correct MAC
3605 * the recipient will accept. Thus, the I/O semantics have to do
3606 * a little more work. In particular, the wildcard interface
3607 * might not be usable.
3609 sendlen = LEN_PKT_NOMAC;
3612 !(peer->flags & FLAG_SKEY) &&
3613 #endif /* !AUTOKEY */
3617 * Transmit a-priori timestamps
3619 get_systime(&xmt_tx);
3620 if (peer->flip == 0) { /* basic mode */
3621 peer->aorg = xmt_tx;
3622 HTONL_FP(&xmt_tx, &xpkt.xmt);
3623 } else { /* interleaved modes */
3624 if (peer->hmode == MODE_BROADCAST) { /* bcst */
3625 HTONL_FP(&xmt_tx, &xpkt.xmt);
3627 HTONL_FP(&peer->borg,
3630 HTONL_FP(&peer->aorg,
3632 } else { /* symmetric */
3634 HTONL_FP(&peer->borg,
3637 HTONL_FP(&peer->aorg,
3641 peer->t21_bytes = sendlen;
3642 sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl],
3645 peer->throttle += (1 << peer->minpoll) - 2;
3648 * Capture a-posteriori timestamps
3650 get_systime(&xmt_ty);
3651 if (peer->flip != 0) { /* interleaved modes */
3653 peer->aorg = xmt_ty;
3655 peer->borg = xmt_ty;
3656 peer->flip = -peer->flip;
3658 L_SUB(&xmt_ty, &xmt_tx);
3659 LFPTOD(&xmt_ty, peer->xleave);
3660 DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d len %zu xmt %#010x.%08x\n",
3662 peer->dstadr ? stoa(&peer->dstadr->sin) : "-",
3663 stoa(&peer->srcadr), peer->hmode, sendlen,
3664 xmt_tx.l_ui, xmt_tx.l_uf));
3669 * Authentication is enabled, so the transmitted packet must be
3670 * authenticated. If autokey is enabled, fuss with the various
3671 * modes; otherwise, symmetric key cryptography is used.
3674 if (peer->flags & FLAG_SKEY) {
3675 struct exten *exten; /* extension field */
3678 * The Public Key Dance (PKD): Cryptographic credentials
3679 * are contained in extension fields, each including a
3680 * 4-octet length/code word followed by a 4-octet
3681 * association ID and optional additional data. Optional
3682 * data includes a 4-octet data length field followed by
3683 * the data itself. Request messages are sent from a
3684 * configured association; response messages can be sent
3685 * from a configured association or can take the fast
3686 * path without ever matching an association. Response
3687 * messages have the same code as the request, but have
3688 * a response bit and possibly an error bit set. In this
3689 * implementation, a message may contain no more than
3690 * one command and one or more responses.
3692 * Cryptographic session keys include both a public and
3693 * a private componet. Request and response messages
3694 * using extension fields are always sent with the
3695 * private component set to zero. Packets without
3696 * extension fields indlude the private component when
3697 * the session key is generated.
3702 * Allocate and initialize a keylist if not
3703 * already done. Then, use the list in inverse
3704 * order, discarding keys once used. Keep the
3705 * latest key around until the next one, so
3706 * clients can use client/server packets to
3707 * compute propagation delay.
3709 * Note that once a key is used from the list,
3710 * it is retained in the key cache until the
3711 * next key is used. This is to allow a client
3712 * to retrieve the encrypted session key
3713 * identifier to verify authenticity.
3715 * If for some reason a key is no longer in the
3716 * key cache, a birthday has happened or the key
3717 * has expired, so the pseudo-random sequence is
3718 * broken. In that case, purge the keylist and
3721 if (peer->keynumber == 0)
3722 make_keylist(peer, peer->dstadr);
3725 xkeyid = peer->keylist[peer->keynumber];
3726 if (authistrusted(xkeyid))
3731 peer->keyid = xkeyid;
3733 switch (peer->hmode) {
3736 * In broadcast server mode the autokey values are
3737 * required by the broadcast clients. Push them when a
3738 * new keylist is generated; otherwise, push the
3739 * association message so the client can request them at
3742 case MODE_BROADCAST:
3743 if (peer->flags & FLAG_ASSOC)
3744 exten = crypto_args(peer, CRYPTO_AUTO |
3745 CRYPTO_RESP, peer->associd, NULL);
3747 exten = crypto_args(peer, CRYPTO_ASSOC |
3748 CRYPTO_RESP, peer->associd, NULL);
3752 * In symmetric modes the parameter, certificate,
3753 * identity, cookie and autokey exchanges are
3754 * required. The leapsecond exchange is optional. But, a
3755 * peer will not believe the other peer until the other
3756 * peer has synchronized, so the certificate exchange
3757 * might loop until then. If a peer finds a broken
3758 * autokey sequence, it uses the autokey exchange to
3759 * retrieve the autokey values. In any case, if a new
3760 * keylist is generated, the autokey values are pushed.
3766 * Parameter, certificate and identity.
3769 exten = crypto_args(peer, CRYPTO_ASSOC,
3770 peer->associd, hostval.ptr);
3771 else if (!(peer->crypto & CRYPTO_FLAG_CERT))
3772 exten = crypto_args(peer, CRYPTO_CERT,
3773 peer->associd, peer->issuer);
3774 else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
3775 exten = crypto_args(peer,
3776 crypto_ident(peer), peer->associd,
3780 * Cookie and autokey. We request the cookie
3781 * only when the this peer and the other peer
3782 * are synchronized. But, this peer needs the
3783 * autokey values when the cookie is zero. Any
3784 * time we regenerate the key list, we offer the
3785 * autokey values without being asked. If for
3786 * some reason either peer finds a broken
3787 * autokey sequence, the autokey exchange is
3788 * used to retrieve the autokey values.
3790 else if ( sys_leap != LEAP_NOTINSYNC
3791 && peer->leap != LEAP_NOTINSYNC
3792 && !(peer->crypto & CRYPTO_FLAG_COOK))
3793 exten = crypto_args(peer, CRYPTO_COOK,
3794 peer->associd, NULL);
3795 else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
3796 exten = crypto_args(peer, CRYPTO_AUTO,
3797 peer->associd, NULL);
3798 else if ( peer->flags & FLAG_ASSOC
3799 && peer->crypto & CRYPTO_FLAG_SIGN)
3800 exten = crypto_args(peer, CRYPTO_AUTO |
3801 CRYPTO_RESP, peer->assoc, NULL);
3804 * Wait for clock sync, then sign the
3805 * certificate and retrieve the leapsecond
3808 else if (sys_leap == LEAP_NOTINSYNC)
3811 else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
3812 exten = crypto_args(peer, CRYPTO_SIGN,
3813 peer->associd, hostval.ptr);
3814 else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
3815 exten = crypto_args(peer, CRYPTO_LEAP,
3816 peer->associd, NULL);
3820 * In client mode the parameter, certificate, identity,
3821 * cookie and sign exchanges are required. The
3822 * leapsecond exchange is optional. If broadcast client
3823 * mode the same exchanges are required, except that the
3824 * autokey exchange is substitutes for the cookie
3825 * exchange, since the cookie is always zero. If the
3826 * broadcast client finds a broken autokey sequence, it
3827 * uses the autokey exchange to retrieve the autokey
3833 * Parameter, certificate and identity.
3836 exten = crypto_args(peer, CRYPTO_ASSOC,
3837 peer->associd, hostval.ptr);
3838 else if (!(peer->crypto & CRYPTO_FLAG_CERT))
3839 exten = crypto_args(peer, CRYPTO_CERT,
3840 peer->associd, peer->issuer);
3841 else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
3842 exten = crypto_args(peer,
3843 crypto_ident(peer), peer->associd,
3847 * Cookie and autokey. These are requests, but
3848 * we use the peer association ID with autokey
3849 * rather than our own.
3851 else if (!(peer->crypto & CRYPTO_FLAG_COOK))
3852 exten = crypto_args(peer, CRYPTO_COOK,
3853 peer->associd, NULL);
3854 else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
3855 exten = crypto_args(peer, CRYPTO_AUTO,
3859 * Wait for clock sync, then sign the
3860 * certificate and retrieve the leapsecond
3863 else if (sys_leap == LEAP_NOTINSYNC)
3866 else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
3867 exten = crypto_args(peer, CRYPTO_SIGN,
3868 peer->associd, hostval.ptr);
3869 else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
3870 exten = crypto_args(peer, CRYPTO_LEAP,
3871 peer->associd, NULL);
3876 * Add a queued extension field if present. This is
3877 * always a request message, so the reply ID is already
3878 * in the message. If an error occurs, the error bit is
3879 * lit in the response.
3881 if (peer->cmmd != NULL) {
3884 temp32 = CRYPTO_RESP;
3885 peer->cmmd->opcode |= htonl(temp32);
3886 sendlen += crypto_xmit(peer, &xpkt, NULL,
3887 sendlen, peer->cmmd, 0);
3893 * Add an extension field created above. All but the
3894 * autokey response message are request messages.
3896 if (exten != NULL) {
3897 if (exten->opcode != 0)
3898 sendlen += crypto_xmit(peer, &xpkt,
3899 NULL, sendlen, exten, 0);
3904 * Calculate the next session key. Since extension
3905 * fields are present, the cookie value is zero.
3907 if (sendlen > (int)LEN_PKT_NOMAC) {
3908 session_key(&peer->dstadr->sin, &peer->srcadr,
3912 #endif /* AUTOKEY */
3915 * Transmit a-priori timestamps
3917 get_systime(&xmt_tx);
3918 if (peer->flip == 0) { /* basic mode */
3919 peer->aorg = xmt_tx;
3920 HTONL_FP(&xmt_tx, &xpkt.xmt);
3921 } else { /* interleaved modes */
3922 if (peer->hmode == MODE_BROADCAST) { /* bcst */
3923 HTONL_FP(&xmt_tx, &xpkt.xmt);
3925 HTONL_FP(&peer->borg, &xpkt.org);
3927 HTONL_FP(&peer->aorg, &xpkt.org);
3928 } else { /* symmetric */
3930 HTONL_FP(&peer->borg, &xpkt.xmt);
3932 HTONL_FP(&peer->aorg, &xpkt.xmt);
3935 xkeyid = peer->keyid;
3936 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
3938 report_event(PEVNT_AUTH, peer, "no key");
3939 peer->flash |= TEST5; /* auth error */
3945 if (xkeyid > NTP_MAXKEY)
3946 authtrust(xkeyid, 0);
3947 #endif /* AUTOKEY */
3948 if (sendlen > sizeof(xpkt)) {
3949 msyslog(LOG_ERR, "peer_xmit: buffer overflow %zu", sendlen);
3952 peer->t21_bytes = sendlen;
3953 sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl], &xpkt,
3956 peer->throttle += (1 << peer->minpoll) - 2;
3959 * Capture a-posteriori timestamps
3961 get_systime(&xmt_ty);
3962 if (peer->flip != 0) { /* interleaved modes */
3964 peer->aorg = xmt_ty;
3966 peer->borg = xmt_ty;
3967 peer->flip = -peer->flip;
3969 L_SUB(&xmt_ty, &xmt_tx);
3970 LFPTOD(&xmt_ty, peer->xleave);
3972 DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %zu index %d\n",
3973 current_time, latoa(peer->dstadr),
3974 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
3976 #else /* !AUTOKEY follows */
3977 DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %d\n",
3978 current_time, peer->dstadr ?
3979 ntoa(&peer->dstadr->sin) : "-",
3980 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen));
3981 #endif /* !AUTOKEY */
3990 leap_smear_add_offs(
3996 L_ADD(t, &leap_smear.offset);
4001 #endif /* LEAP_SMEAR */
4005 * fast_xmit - Send packet for nonpersistent association. Note that
4006 * neither the source or destination can be a broadcast address.
4010 struct recvbuf *rbufp, /* receive packet pointer */
4011 int xmode, /* receive mode */
4012 keyid_t xkeyid, /* transmit key ID */
4013 int flags /* restrict mask */
4016 struct pkt xpkt; /* transmit packet structure */
4017 struct pkt *rpkt; /* receive packet structure */
4018 l_fp xmt_tx, xmt_ty;
4025 * Initialize transmit packet header fields from the receive
4026 * buffer provided. We leave the fields intact as received, but
4027 * set the peer poll at the maximum of the receive peer poll and
4028 * the system minimum poll (ntp_minpoll). This is for KoD rate
4029 * control and not strictly specification compliant, but doesn't
4032 * If the gazinta was from a multicast address, the gazoutta
4033 * must go out another way.
4035 rpkt = &rbufp->recv_pkt;
4036 if (rbufp->dstadr->flags & INT_MCASTOPEN)
4037 rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
4040 * If this is a kiss-o'-death (KoD) packet, show leap
4041 * unsynchronized, stratum zero, reference ID the four-character
4042 * kiss code and system root delay. Note we don't reveal the
4043 * local time, so these packets can't be used for
4046 if (flags & RES_KOD) {
4048 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
4049 PKT_VERSION(rpkt->li_vn_mode), xmode);
4050 xpkt.stratum = STRATUM_PKT_UNSPEC;
4051 xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
4052 xpkt.precision = rpkt->precision;
4053 memcpy(&xpkt.refid, "RATE", 4);
4054 xpkt.rootdelay = rpkt->rootdelay;
4055 xpkt.rootdisp = rpkt->rootdisp;
4056 xpkt.reftime = rpkt->reftime;
4057 xpkt.org = rpkt->xmt;
4058 xpkt.rec = rpkt->xmt;
4059 xpkt.xmt = rpkt->xmt;
4062 * This is a normal packet. Use the system variables.
4067 * Make copies of the variables which can be affected by smearing.
4070 l_fp this_recv_time;
4074 * If we are inside the leap smear interval we add the current smear offset to
4075 * the packet receive time, to the packet transmit time, and eventually to the
4076 * reftime to make sure the reftime isn't later than the transmit/receive times.
4078 xpkt.li_vn_mode = PKT_LI_VN_MODE(xmt_leap,
4079 PKT_VERSION(rpkt->li_vn_mode), xmode);
4081 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4082 xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
4083 xpkt.precision = sys_precision;
4084 xpkt.refid = sys_refid;
4085 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4086 xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
4089 this_ref_time = sys_reftime;
4090 if (leap_smear.in_progress) {
4091 leap_smear_add_offs(&this_ref_time, NULL);
4092 xpkt.refid = convertLFPToRefID(leap_smear.offset);
4093 DPRINTF(2, ("fast_xmit: leap_smear.in_progress: refid %8x, smear %s\n",
4095 lfptoa(&leap_smear.offset, 8)
4098 HTONL_FP(&this_ref_time, &xpkt.reftime);
4100 HTONL_FP(&sys_reftime, &xpkt.reftime);
4103 xpkt.org = rpkt->xmt;
4106 this_recv_time = rbufp->recv_time;
4107 if (leap_smear.in_progress)
4108 leap_smear_add_offs(&this_recv_time, NULL);
4109 HTONL_FP(&this_recv_time, &xpkt.rec);
4111 HTONL_FP(&rbufp->recv_time, &xpkt.rec);
4114 get_systime(&xmt_tx);
4116 if (leap_smear.in_progress)
4117 leap_smear_add_offs(&xmt_tx, &this_recv_time);
4119 HTONL_FP(&xmt_tx, &xpkt.xmt);
4122 #ifdef HAVE_NTP_SIGND
4123 if (flags & RES_MSSNTP) {
4124 send_via_ntp_signd(rbufp, xmode, xkeyid, flags, &xpkt);
4127 #endif /* HAVE_NTP_SIGND */
4130 * If the received packet contains a MAC, the transmitted packet
4131 * is authenticated and contains a MAC. If not, the transmitted
4132 * packet is not authenticated.
4134 sendlen = LEN_PKT_NOMAC;
4135 if (rbufp->recv_length == sendlen) {
4136 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
4138 DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d len %lu\n",
4139 current_time, stoa(&rbufp->dstadr->sin),
4140 stoa(&rbufp->recv_srcadr), xmode,
4146 * The received packet contains a MAC, so the transmitted packet
4147 * must be authenticated. For symmetric key cryptography, use
4148 * the predefined and trusted symmetric keys to generate the
4149 * cryptosum. For autokey cryptography, use the server private
4150 * value to generate the cookie, which is unique for every
4151 * source-destination-key ID combination.
4154 if (xkeyid > NTP_MAXKEY) {
4158 * The only way to get here is a reply to a legitimate
4159 * client request message, so the mode must be
4160 * MODE_SERVER. If an extension field is present, there
4161 * can be only one and that must be a command. Do what
4162 * needs, but with private value of zero so the poor
4163 * jerk can decode it. If no extension field is present,
4164 * use the cookie to generate the session key.
4166 cookie = session_key(&rbufp->recv_srcadr,
4167 &rbufp->dstadr->sin, 0, sys_private, 0);
4168 if ((size_t)rbufp->recv_length > sendlen + MAX_MAC_LEN) {
4169 session_key(&rbufp->dstadr->sin,
4170 &rbufp->recv_srcadr, xkeyid, 0, 2);
4171 temp32 = CRYPTO_RESP;
4172 rpkt->exten[0] |= htonl(temp32);
4173 sendlen += crypto_xmit(NULL, &xpkt, rbufp,
4174 sendlen, (struct exten *)rpkt->exten,
4177 session_key(&rbufp->dstadr->sin,
4178 &rbufp->recv_srcadr, xkeyid, cookie, 2);
4181 #endif /* AUTOKEY */
4182 get_systime(&xmt_tx);
4183 sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
4185 if (xkeyid > NTP_MAXKEY)
4186 authtrust(xkeyid, 0);
4187 #endif /* AUTOKEY */
4188 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
4189 get_systime(&xmt_ty);
4190 L_SUB(&xmt_ty, &xmt_tx);
4191 sys_authdelay = xmt_ty;
4192 DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d keyid %08x len %lu\n",
4193 current_time, ntoa(&rbufp->dstadr->sin),
4194 ntoa(&rbufp->recv_srcadr), xmode, xkeyid,
4200 * pool_xmit - resolve hostname or send unicast solicitation for pool.
4204 struct peer *pool /* pool solicitor association */
4208 struct pkt xpkt; /* transmit packet structure */
4209 struct addrinfo hints;
4211 struct interface * lcladr;
4212 sockaddr_u * rmtadr;
4217 if (NULL == pool->ai) {
4218 if (pool->addrs != NULL) {
4219 /* free() is used with copy_addrinfo_list() */
4224 hints.ai_family = AF(&pool->srcadr);
4225 hints.ai_socktype = SOCK_DGRAM;
4226 hints.ai_protocol = IPPROTO_UDP;
4227 /* ignore getaddrinfo_sometime() errors, we will retry */
4228 rc = getaddrinfo_sometime(
4233 &pool_name_resolved,
4234 (void *)(intptr_t)pool->associd);
4236 DPRINTF(1, ("pool DNS lookup %s started\n",
4240 "unable to start pool DNS %s: %m",
4246 /* copy_addrinfo_list ai_addr points to a sockaddr_u */
4247 rmtadr = (sockaddr_u *)(void *)pool->ai->ai_addr;
4248 pool->ai = pool->ai->ai_next;
4249 p = findexistingpeer(rmtadr, NULL, NULL, MODE_CLIENT, 0);
4250 } while (p != NULL && pool->ai != NULL);
4252 return; /* out of addresses, re-query DNS next poll */
4253 restrict_mask = restrictions(rmtadr);
4254 if (RES_FLAGS & restrict_mask)
4255 restrict_source(rmtadr, 0,
4256 current_time + POOL_SOLICIT_WINDOW + 1);
4257 lcladr = findinterface(rmtadr);
4258 memset(&xpkt, 0, sizeof(xpkt));
4259 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, pool->version,
4261 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4262 xpkt.ppoll = pool->hpoll;
4263 xpkt.precision = sys_precision;
4264 xpkt.refid = sys_refid;
4265 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4266 xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
4267 HTONL_FP(&sys_reftime, &xpkt.reftime);
4268 get_systime(&xmt_tx);
4269 pool->aorg = xmt_tx;
4270 HTONL_FP(&xmt_tx, &xpkt.xmt);
4271 sendpkt(rmtadr, lcladr, sys_ttl[pool->ttl], &xpkt,
4274 pool->throttle += (1 << pool->minpoll) - 2;
4275 DPRINTF(1, ("pool_xmit: at %ld %s->%s pool\n",
4276 current_time, latoa(lcladr), stoa(rmtadr)));
4277 msyslog(LOG_INFO, "Soliciting pool server %s", stoa(rmtadr));
4284 * group_test - test if this is the same group
4286 * host assoc return action
4287 * none none 0 mobilize *
4288 * none group 0 mobilize *
4289 * group none 0 mobilize *
4290 * group group 1 mobilize
4291 * group different 1 ignore
4292 * * ignore if notrust
4303 if (strcmp(grp, sys_groupname) == 0)
4309 if (strcmp(grp, ident) == 0)
4314 #endif /* AUTOKEY */
4324 const char * service,
4325 const struct addrinfo * hints,
4326 const struct addrinfo * res
4329 struct peer * pool; /* pool solicitor association */
4334 "error resolving pool %s: %s (%d)",
4335 name, gai_strerror(rescode), rescode);
4339 assoc = (associd_t)(intptr_t)context;
4340 pool = findpeerbyassoc(assoc);
4343 "Could not find assoc %u for pool DNS %s",
4347 DPRINTF(1, ("pool DNS %s completed\n", name));
4348 pool->addrs = copy_addrinfo_list(res);
4349 pool->ai = pool->addrs;
4358 * key_expire - purge the key list
4362 struct peer *peer /* peer structure pointer */
4367 if (peer->keylist != NULL) {
4368 for (i = 0; i <= peer->keynumber; i++)
4369 authtrust(peer->keylist[i], 0);
4370 free(peer->keylist);
4371 peer->keylist = NULL;
4373 value_free(&peer->sndval);
4374 peer->keynumber = 0;
4375 peer->flags &= ~FLAG_ASSOC;
4376 DPRINTF(1, ("key_expire: at %lu associd %d\n", current_time,
4379 #endif /* AUTOKEY */
4383 * local_refid(peer) - check peer refid to avoid selecting peers
4384 * currently synced to this ntpd.
4393 if (p->dstadr != NULL && !(INT_MCASTIF & p->dstadr->flags))
4394 unicast_ep = p->dstadr;
4396 unicast_ep = findinterface(&p->srcadr);
4398 if (unicast_ep != NULL && p->refid == unicast_ep->addr_refid)
4406 * Determine if the peer is unfit for synchronization
4408 * A peer is unfit for synchronization if
4409 * > TEST10 bad leap or stratum below floor or at or above ceiling
4410 * > TEST11 root distance exceeded for remote peer
4411 * > TEST12 a direct or indirect synchronization loop would form
4412 * > TEST13 unreachable or noselect
4414 int /* FALSE if fit, TRUE if unfit */
4416 struct peer *peer /* peer structure pointer */
4422 * A stratum error occurs if (1) the server has never been
4423 * synchronized, (2) the server stratum is below the floor or
4424 * greater than or equal to the ceiling.
4426 if ( peer->leap == LEAP_NOTINSYNC
4427 || peer->stratum < sys_floor
4428 || peer->stratum >= sys_ceiling)
4429 rval |= TEST10; /* bad synch or stratum */
4432 * A distance error for a remote peer occurs if the root
4433 * distance is greater than or equal to the distance threshold
4434 * plus the increment due to one host poll interval.
4436 if ( !(peer->flags & FLAG_REFCLOCK)
4437 && root_distance(peer) >= sys_maxdist
4438 + clock_phi * ULOGTOD(peer->hpoll))
4439 rval |= TEST11; /* distance exceeded */
4442 * A loop error occurs if the remote peer is synchronized to the
4443 * local peer or if the remote peer is synchronized to the same
4444 * server as the local peer but only if the remote peer is
4445 * neither a reference clock nor an orphan.
4447 if (peer->stratum > 1 && local_refid(peer))
4448 rval |= TEST12; /* synchronization loop */
4451 * An unreachable error occurs if the server is unreachable or
4452 * the noselect bit is set.
4454 if (!peer->reach || (peer->flags & FLAG_NOSELECT))
4455 rval |= TEST13; /* unreachable */
4457 peer->flash &= ~PEER_TEST_MASK;
4458 peer->flash |= rval;
4464 * Find the precision of this particular machine
4466 #define MINSTEP 20e-9 /* minimum clock increment (s) */
4467 #define MAXSTEP 1 /* maximum clock increment (s) */
4468 #define MINCHANGES 12 /* minimum number of step samples */
4469 #define MAXLOOPS ((int)(1. / MINSTEP)) /* avoid infinite loop */
4472 * This routine measures the system precision defined as the minimum of
4473 * a sequence of differences between successive readings of the system
4474 * clock. However, if a difference is less than MINSTEP, the clock has
4475 * been read more than once during a clock tick and the difference is
4476 * ignored. We set MINSTEP greater than zero in case something happens
4477 * like a cache miss, and to tolerate underlying system clocks which
4478 * ensure each reading is strictly greater than prior readings while
4479 * using an underlying stepping (not interpolated) clock.
4481 * sys_tick and sys_precision represent the time to read the clock for
4482 * systems with high-precision clocks, and the tick interval or step
4483 * size for lower-precision stepping clocks.
4485 * This routine also measures the time to read the clock on stepping
4486 * system clocks by counting the number of readings between changes of
4487 * the underlying clock. With either type of clock, the minimum time
4488 * to read the clock is saved as sys_fuzz, and used to ensure the
4489 * get_systime() readings always increase and are fuzzed below sys_fuzz.
4492 measure_precision(void)
4495 * With sys_fuzz set to zero, get_systime() fuzzing of low bits
4496 * is effectively disabled. trunc_os_clock is FALSE to disable
4497 * get_ostime() simulation of a low-precision system clock.
4500 trunc_os_clock = FALSE;
4501 measured_tick = measure_tick_fuzz();
4502 set_sys_tick_precision(measured_tick);
4503 msyslog(LOG_INFO, "proto: precision = %.3f usec (%d)",
4504 sys_tick * 1e6, sys_precision);
4505 if (sys_fuzz < sys_tick) {
4506 msyslog(LOG_NOTICE, "proto: fuzz beneath %.3f usec",
4513 * measure_tick_fuzz()
4515 * measures the minimum time to read the clock (stored in sys_fuzz)
4516 * and returns the tick, the larger of the minimum increment observed
4517 * between successive clock readings and the time to read the clock.
4520 measure_tick_fuzz(void)
4522 l_fp minstep; /* MINSTEP as l_fp */
4523 l_fp val; /* current seconds fraction */
4524 l_fp last; /* last seconds fraction */
4525 l_fp ldiff; /* val - last */
4526 double tick; /* computed tick value */
4531 int i; /* log2 precision */
4537 DTOLFP(MINSTEP, &minstep);
4539 for (i = 0; i < MAXLOOPS && changes < MINCHANGES; i++) {
4542 L_SUB(&ldiff, &last);
4544 if (L_ISGT(&ldiff, &minstep)) {
4545 max_repeats = max(repeats, max_repeats);
4548 LFPTOD(&ldiff, diff);
4549 tick = min(diff, tick);
4554 if (changes < MINCHANGES) {
4555 msyslog(LOG_ERR, "Fatal error: precision could not be measured (MINSTEP too large?)");
4559 if (0 == max_repeats) {
4562 set_sys_fuzz(tick / max_repeats);
4570 set_sys_tick_precision(
4578 "unsupported tick %.3f > 1s ignored", tick);
4581 if (tick < measured_tick) {
4583 "proto: tick %.3f less than measured tick %.3f, ignored",
4584 tick, measured_tick);
4586 } else if (tick > measured_tick) {
4587 trunc_os_clock = TRUE;
4589 "proto: truncating system clock to multiples of %.9f",
4595 * Find the nearest power of two.
4597 for (i = 0; tick <= 1; i--)
4599 if (tick - 1 > 1 - tick / 2)
4602 sys_precision = (s_char)i;
4607 * init_proto - initialize the protocol module's data
4616 * Fill in the sys_* stuff. Default is don't listen to
4617 * broadcasting, require authentication.
4619 set_sys_leap(LEAP_NOTINSYNC);
4620 sys_stratum = STRATUM_UNSPEC;
4621 memcpy(&sys_refid, "INIT", 4);
4625 L_CLR(&sys_reftime);
4627 measure_precision();
4628 get_systime(&dummy);
4630 sys_manycastserver = 0;
4632 sys_bdelay = BDELAY_DEFAULT; /*[Bug 3031] delay cutoff */
4633 sys_authenticate = 1;
4634 sys_stattime = current_time;
4635 orphwait = current_time + sys_orphwait;
4637 for (i = 0; i < MAX_TTL; i++) {
4638 sys_ttl[i] = (u_char)((i * 256) / MAX_TTL);
4647 * proto_config - configure the protocol module
4658 * Figure out what he wants to change, then do it
4660 DPRINTF(2, ("proto_config: code %d value %lu dvalue %lf\n",
4661 item, value, dvalue));
4666 * enable and disable commands - arguments are Boolean.
4668 case PROTO_AUTHENTICATE: /* authentication (auth) */
4669 sys_authenticate = value;
4672 case PROTO_BROADCLIENT: /* broadcast client (bclient) */
4673 sys_bclient = (int)value;
4674 if (sys_bclient == 0)
4681 case PROTO_CAL: /* refclock calibrate (calibrate) */
4684 #endif /* REFCLOCK */
4686 case PROTO_KERNEL: /* kernel discipline (kernel) */
4690 case PROTO_MONITOR: /* monitoring (monitor) */
4696 msyslog(LOG_WARNING,
4697 "restrict: 'monitor' cannot be disabled while 'limited' is enabled");
4701 case PROTO_NTP: /* NTP discipline (ntp) */
4705 case PROTO_MODE7: /* mode7 management (ntpdc) */
4709 case PROTO_PPS: /* PPS discipline (pps) */
4710 hardpps_enable = value;
4713 case PROTO_FILEGEN: /* statistics (stats) */
4714 stats_control = value;
4718 * tos command - arguments are double, sometimes cast to int
4720 case PROTO_BEACON: /* manycast beacon (beacon) */
4721 sys_beacon = (int)dvalue;
4724 case PROTO_BROADDELAY: /* default broadcast delay (bdelay) */
4725 sys_bdelay = (dvalue ? dvalue : BDELAY_DEFAULT);
4728 case PROTO_CEILING: /* stratum ceiling (ceiling) */
4729 sys_ceiling = (int)dvalue;
4732 case PROTO_COHORT: /* cohort switch (cohort) */
4733 sys_cohort = (int)dvalue;
4736 case PROTO_FLOOR: /* stratum floor (floor) */
4737 sys_floor = (int)dvalue;
4740 case PROTO_MAXCLOCK: /* maximum candidates (maxclock) */
4741 sys_maxclock = (int)dvalue;
4744 case PROTO_MAXDIST: /* select threshold (maxdist) */
4745 sys_maxdist = dvalue;
4748 case PROTO_CALLDELAY: /* modem call delay (mdelay) */
4749 break; /* NOT USED */
4751 case PROTO_MINCLOCK: /* minimum candidates (minclock) */
4752 sys_minclock = (int)dvalue;
4755 case PROTO_MINDISP: /* minimum distance (mindist) */
4756 sys_mindisp = dvalue;
4759 case PROTO_MINSANE: /* minimum survivors (minsane) */
4760 sys_minsane = (int)dvalue;
4763 case PROTO_ORPHAN: /* orphan stratum (orphan) */
4764 sys_orphan = (int)dvalue;
4767 case PROTO_ORPHWAIT: /* orphan wait (orphwait) */
4768 orphwait -= sys_orphwait;
4769 sys_orphwait = (int)dvalue;
4770 orphwait += sys_orphwait;
4774 * Miscellaneous commands
4776 case PROTO_MULTICAST_ADD: /* add group address */
4778 io_multicast_add(svalue);
4782 case PROTO_MULTICAST_DEL: /* delete group address */
4784 io_multicast_del(svalue);
4788 * Peer_clear Early policy choices
4791 case PROTO_PCEDIGEST: /* Digest */
4792 peer_clear_digest_early = value;
4796 * Unpeer Early policy choices
4799 case PROTO_UECRYPTO: /* Crypto */
4800 unpeer_crypto_early = value;
4803 case PROTO_UECRYPTONAK: /* Crypto_NAK */
4804 unpeer_crypto_nak_early = value;
4807 case PROTO_UEDIGEST: /* Digest */
4808 unpeer_digest_early = value;
4813 "proto: unsupported option %d", item);
4819 * proto_clr_stats - clear protocol stat counters
4822 proto_clr_stats(void)
4824 sys_stattime = current_time;
4833 sys_limitrejected = 0;