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"
19 #if defined(VMS) && defined(VMS_LOCALUNIT) /*wjm*/
20 #include "ntp_refclock.h"
23 #if defined(__FreeBSD__) && __FreeBSD__ >= 3
24 #include <sys/sysctl.h>
28 * This macro defines the authentication state. If x is 1 authentication
29 * is required; othewise it is optional.
31 #define AUTH(x, y) ((x) ? (y) == AUTH_OK : (y) == AUTH_OK || \
35 * System variables are declared here. See Section 3.2 of the
38 u_char sys_leap; /* system leap indicator */
39 u_char sys_stratum; /* stratum of system */
40 s_char sys_precision; /* local clock precision (log2 s) */
41 double sys_rootdelay; /* roundtrip delay to primary source */
42 double sys_rootdispersion; /* dispersion to primary source */
43 u_int32 sys_refid; /* source/loop in network byte order */
44 static double sys_offset; /* current local clock offset */
45 l_fp sys_reftime; /* time we were last updated */
46 struct peer *sys_peer; /* our current peer */
47 struct peer *sys_pps; /* our PPS peer */
48 struct peer *sys_prefer; /* our cherished peer */
49 int sys_kod; /* kod credit */
50 int sys_kod_rate = 2; /* max kod packets per second */
52 u_long sys_automax; /* maximum session key lifetime */
56 * Nonspecified system state variables.
58 int sys_bclient; /* broadcast client enable */
59 double sys_bdelay; /* broadcast client default delay */
60 int sys_calldelay; /* modem callup delay (s) */
61 int sys_authenticate; /* requre authentication for config */
62 l_fp sys_authdelay; /* authentication delay */
63 static u_long sys_authdly[2]; /* authentication delay shift reg */
64 static double sys_mindisp = MINDISPERSE; /* min disp increment (s) */
65 static double sys_maxdist = MAXDISTANCE; /* selection threshold (s) */
66 double sys_jitter; /* system jitter (s) */
67 static int sys_hopper; /* anticlockhop counter */
68 static int sys_maxhop = MAXHOP; /* anticlockhop counter threshold */
69 int leap_next; /* leap consensus */
70 keyid_t sys_private; /* private value for session seed */
71 int sys_manycastserver; /* respond to manycast client pkts */
72 int peer_ntpdate; /* active peers in ntpdate mode */
73 int sys_survivors; /* truest of the truechimers */
75 char *sys_hostname; /* gethostname() name */
79 * TOS and multicast mapping stuff
81 int sys_floor = 0; /* cluster stratum floor */
82 int sys_ceiling = STRATUM_UNSPEC; /* cluster stratum ceiling */
83 int sys_minsane = 1; /* minimum candidates */
84 int sys_minclock = NTP_MINCLOCK; /* minimum survivors */
85 int sys_maxclock = NTP_MAXCLOCK; /* maximum candidates */
86 int sys_cohort = 0; /* cohort switch */
87 int sys_orphan = STRATUM_UNSPEC + 1; /* orphan stratum */
88 double sys_orphandelay = 0; /* orphan root delay */
89 int sys_beacon = BEACON; /* manycast beacon interval */
90 int sys_ttlmax; /* max ttl mapping vector index */
91 u_char sys_ttl[MAX_TTL]; /* ttl mapping vector */
96 u_long sys_stattime; /* time since reset */
97 u_long sys_received; /* packets received */
98 u_long sys_processed; /* packets processed */
99 u_long sys_newversionpkt; /* current version */
100 u_long sys_oldversionpkt; /* recent version */
101 u_long sys_unknownversion; /* invalid version */
102 u_long sys_restricted; /* access denied */
103 u_long sys_badlength; /* bad length or format */
104 u_long sys_badauth; /* bad authentication */
105 u_long sys_limitrejected; /* rate exceeded */
107 static double root_distance P((struct peer *));
108 static void clock_combine P((struct peer **, int));
109 static void peer_xmit P((struct peer *));
110 static void fast_xmit P((struct recvbuf *, int, keyid_t,
112 static void clock_update P((void));
113 static int default_get_precision P((void));
114 static int peer_unfit P((struct peer *));
118 * transmit - Transmit Procedure. See Section 3.4.2 of the
123 struct peer *peer /* peer structure pointer */
129 * The polling state machine. There are two kinds of machines,
130 * those that never expect a reply (broadcast and manycast
131 * server modes) and those that do (all other modes). The dance
135 * Orphan mode is active when enabled and when no servers less
136 * than the orphan statum are available. In this mode packets
137 * are sent at the orphan stratum. An orphan with no other
138 * synchronization source is an orphan parent. It assumes root
139 * delay zero and reference ID the loopback address. All others
140 * are orphan children with root delay randomized over a 1-s
141 * range. The root delay is used by the election algorithm to
142 * select the order of synchronization.
145 if (sys_orphan < STRATUM_UNSPEC && sys_peer == NULL) {
146 sys_leap = LEAP_NOWARNING;
147 sys_stratum = sys_orphan;
148 sys_refid = htonl(LOOPBACKADR);
150 sys_rootdispersion = 0;
154 * In broadcast mode the poll interval is never changed from
157 if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
158 peer->outdate = current_time;
160 poll_update(peer, hpoll);
165 * In manycast mode we start with unity ttl. The ttl is
166 * increased by one for each poll until either sys_maxclock
167 * servers have been found or the maximum ttl is reached. When
168 * sys_maxclock servers are found we stop polling until one or
169 * more servers have timed out or until less than minpoll
170 * associations turn up. In this case additional better servers
171 * are dragged in and preempt the existing ones.
173 if (peer->cast_flags & MDF_ACAST) {
174 peer->outdate = current_time;
175 if (peer->unreach > sys_beacon) {
179 } else if (sys_survivors < sys_minclock ||
180 peer_preempt < sys_maxclock) {
181 if (peer->ttl < sys_ttlmax)
186 poll_update(peer, hpoll);
191 * In unicast modes the dance is much more intricate. It is
192 * desigmed to back off whenever possible to minimize network
195 if (peer->burst == 0) {
199 * Update the reachability status. If not heard for
200 * three consecutive polls, stuff infinity in the clock
203 oreach = peer->reach;
204 peer->outdate = current_time;
205 if (peer == sys_peer)
208 if (!(peer->reach & 0x07))
209 clock_filter(peer, 0., 0., MAXDISPERSE);
213 * Here the peer is unreachable. If it was
214 * previously reachable, raise a trap.
217 report_event(EVNT_UNREACH, peer);
218 peer->timereachable = current_time;
222 * Send a burst if enabled, but only once after
223 * a peer becomes unreachable. If the prempt
224 * flag is dim, bump the unreach counter by one;
225 * otherwise, bump it by three.
227 if (peer->flags & FLAG_IBURST &&
228 peer->unreach == 0) {
229 peer->burst = NTP_BURST;
231 if (!(peer->flags & FLAG_PREEMPT))
238 * Here the peer is reachable. Set the poll
239 * interval to the system poll interval. Send a
240 * burst only if enabled and the peer is fit.
242 * Respond to the peer evaluation produced by
243 * the selection algorithm. If less than the
244 * outlyer level, up the unreach by three. If
245 * there are excess associations, up the unreach
246 * by two if not a candidate and by one if so.
248 if (!(peer->flags & FLAG_PREEMPT)) {
250 } else if (peer->status < CTL_PST_SEL_SELCAND) {
252 } else if (peer_preempt > sys_maxclock) {
253 if (peer->status < CTL_PST_SEL_SYNCCAND)
261 if (peer->flags & FLAG_BURST &&
263 peer->burst = NTP_BURST;
267 * Watch for timeout. If ephemeral or preemptable, toss
268 * the rascal; otherwise, bump the poll interval.
270 if (peer->unreach >= NTP_UNREACH) {
271 if (peer->flags & FLAG_PREEMPT ||
272 !(peer->flags & FLAG_CONFIG)) {
273 peer_clear(peer, "TIME");
284 * If a broadcast client at this point, the burst has
285 * concluded, so we switch to client mode and purge the
286 * keylist, since no further transmissions will be made.
288 if (peer->burst == 0) {
289 if (peer->cast_flags & MDF_BCLNT) {
290 peer->hmode = MODE_BCLIENT;
297 * If ntpdate mode and the clock has not been
298 * set and all peers have completed the burst,
299 * we declare a successful failure.
303 if (peer_ntpdate == 0) {
305 "no reply; clock not set");
313 * Do not transmit if in broadcast client mode.
315 if (peer->hmode != MODE_BCLIENT)
317 poll_update(peer, hpoll);
322 * receive - Receive Procedure. See section 3.4.3 in the specification.
326 struct recvbuf *rbufp
329 register struct peer *peer; /* peer structure pointer */
330 register struct pkt *pkt; /* receive packet pointer */
331 int hisversion; /* packet version */
332 int hisleap; /* packet leap indicator */
333 int hismode; /* packet mode */
334 int hisstratum; /* packet stratum */
335 int restrict_mask; /* restrict bits */
336 int has_mac; /* length of MAC field */
337 int authlen; /* offset of MAC field */
338 int is_authentic = 0; /* cryptosum ok */
339 keyid_t skeyid = 0; /* key ID */
340 struct sockaddr_storage *dstadr_sin; /* active runway */
341 struct peer *peer2; /* aux peer structure pointer */
342 l_fp p_org; /* origin timestamp */
343 l_fp p_rec; /* receive timestamp */
344 l_fp p_xmt; /* transmit timestamp */
346 keyid_t tkeyid = 0; /* temporary key ID */
347 keyid_t pkeyid = 0; /* previous key ID */
348 struct autokey *ap; /* autokey structure pointer */
349 int rval; /* cookie snatcher */
351 int retcode = AM_NOMATCH;
355 * Monitor the packet and get restrictions. Note that the packet
356 * length for control and private mode packets must be checked
357 * by the service routines. Note that no statistics counters are
358 * recorded for restrict violations, since these counters are in
359 * the restriction routine. Note the careful distinctions here
360 * between a packet with a format error and a packet that is
361 * simply discarded without prejudice. Some restrictions have to
362 * be handled later in order to generate a kiss-of-death packet.
365 * Bogus port check is before anything, since it probably
366 * reveals a clogging attack.
369 if (SRCPORT(&rbufp->recv_srcadr) == 0) {
371 return; /* bogus port */
373 at_listhead = ntp_monitor(rbufp);
374 restrict_mask = restrictions(&rbufp->recv_srcadr, at_listhead);
377 printf("receive: at %ld %s<-%s flags %x restrict %03x\n",
378 current_time, stoa(&rbufp->dstadr->sin),
379 stoa(&rbufp->recv_srcadr),
380 rbufp->dstadr->flags, restrict_mask);
382 if (restrict_mask & RES_IGNORE) {
384 return; /* ignore everything */
386 pkt = &rbufp->recv_pkt;
387 hisversion = PKT_VERSION(pkt->li_vn_mode);
388 hisleap = PKT_LEAP(pkt->li_vn_mode);
389 hismode = (int)PKT_MODE(pkt->li_vn_mode);
390 hisstratum = PKT_TO_STRATUM(pkt->stratum);
391 if (hismode == MODE_PRIVATE) {
392 if (restrict_mask & RES_NOQUERY) {
394 return; /* no query private */
396 process_private(rbufp, ((restrict_mask &
397 RES_NOMODIFY) == 0));
400 if (hismode == MODE_CONTROL) {
401 if (restrict_mask & RES_NOQUERY) {
403 return; /* no query control */
405 process_control(rbufp, restrict_mask);
408 if (restrict_mask & RES_DONTSERVE) {
410 return; /* no time */
412 if (rbufp->recv_length < LEN_PKT_NOMAC) {
414 return; /* runt packet */
418 * Version check must be after the query packets, since they
419 * intentionally use early version.
421 if (hisversion == NTP_VERSION) {
422 sys_newversionpkt++; /* new version */
423 } else if (!(restrict_mask & RES_VERSION) && hisversion >=
425 sys_oldversionpkt++; /* previous version */
427 sys_unknownversion++;
428 return; /* old version */
432 * Figure out his mode and validate the packet. This has some
433 * legacy raunch that probably should be removed. In very early
434 * NTP versions mode 0 was equivalent to what later versions
435 * would interpret as client mode.
437 if (hismode == MODE_UNSPEC) {
438 if (hisversion == NTP_OLDVERSION) {
439 hismode = MODE_CLIENT;
442 return; /* invalid mode */
447 * Parse the extension field if present. We figure out whether
448 * an extension field is present by measuring the MAC size. If
449 * the number of words following the packet header is 0, no MAC
450 * is present and the packet is not authenticated. If 1, the
451 * packet is a crypto-NAK; if 3, the packet is authenticated
452 * with DES; if 5, the packet is authenticated with MD5. If 2 or
453 * 4, the packet is a runt and discarded forthwith. If greater
454 * than 5, an extension field is present, so we subtract the
455 * length of the field and go around again.
457 authlen = LEN_PKT_NOMAC;
458 has_mac = rbufp->recv_length - authlen;
459 while (has_mac > 0) {
462 if (has_mac % 4 != 0 || has_mac < 0) {
464 return; /* bad MAC length */
466 if (has_mac == 1 * 4 || has_mac == 3 * 4 || has_mac ==
468 skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
471 } else if (has_mac > MAX_MAC_LEN) {
472 temp = ntohl(((u_int32 *)pkt)[authlen / 4]) &
474 if (temp < 4 || temp > NTP_MAXEXTEN || temp % 4
477 return; /* bad MAC length */
483 return; /* bad MAC length */
491 * We have tossed out as many buggy packets as possible early in
492 * the game to reduce the exposure to a clogging attack. Now we
493 * have to burn some cycles to find the association and
494 * authenticate the packet if required. Note that we burn only
495 * MD5 cycles, again to reduce exposure. There may be no
496 * matching association and that's okay.
498 * More on the autokey mambo. Normally the local interface is
499 * found when the association was mobilized with respect to a
500 * designated remote address. We assume packets arriving from
501 * the remote address arrive via this interface and the local
502 * address used to construct the autokey is the unicast address
503 * of the interface. However, if the sender is a broadcaster,
504 * the interface broadcast address is used instead.
505 & Notwithstanding this technobabble, if the sender is a
506 * multicaster, the broadcast address is null, so we use the
507 * unicast address anyway. Don't ask.
509 peer = findpeer(&rbufp->recv_srcadr, rbufp->dstadr, hismode,
511 dstadr_sin = &rbufp->dstadr->sin;
512 NTOHL_FP(&pkt->org, &p_org);
513 NTOHL_FP(&pkt->rec, &p_rec);
514 NTOHL_FP(&pkt->xmt, &p_xmt);
517 * Authentication is conditioned by three switches:
519 * NOPEER (RES_NOPEER) do not mobilize an association unless
521 * NOTRUST (RES_DONTTRUST) do not allow access unless
522 * authenticated (implies NOPEER)
523 * enable (sys_authenticate) master NOPEER switch, by default
526 * The NOPEER and NOTRUST can be specified on a per-client basis
527 * using the restrict command. The enable switch if on implies
528 * NOPEER for all clients. There are four outcomes:
530 * NONE The packet has no MAC.
531 * OK the packet has a MAC and authentication succeeds
532 * ERROR the packet has a MAC and authentication fails
533 * CRYPTO crypto-NAK. The MAC has four octets only.
535 * Note: The AUTH(x, y) macro is used to filter outcomes. If x
536 * is zero, acceptable outcomes of y are NONE and OK. If x is
537 * one, the only acceptable outcome of y is OK.
540 is_authentic = AUTH_NONE; /* not required */
543 printf("receive: at %ld %s<-%s mode %d code %d auth %d\n",
544 current_time, stoa(dstadr_sin),
545 stoa(&rbufp->recv_srcadr), hismode, retcode,
548 } else if (has_mac == 4) {
549 is_authentic = AUTH_CRYPTO; /* crypto-NAK */
553 "receive: at %ld %s<-%s mode %d code %d keyid %08x len %d mac %d auth %d\n",
554 current_time, stoa(dstadr_sin),
555 stoa(&rbufp->recv_srcadr), hismode, retcode,
556 skeyid, authlen, has_mac, is_authentic);
561 * For autokey modes, generate the session key
562 * and install in the key cache. Use the socket
563 * broadcast or unicast address as appropriate.
565 if (skeyid > NTP_MAXKEY) {
568 * More on the autokey dance (AKD). A cookie is
569 * constructed from public and private values.
570 * For broadcast packets, the cookie is public
571 * (zero). For packets that match no
572 * association, the cookie is hashed from the
573 * addresses and private value. For server
574 * packets, the cookie was previously obtained
575 * from the server. For symmetric modes, the
576 * cookie was previously constructed using an
577 * agreement protocol; however, should PKI be
578 * unavailable, we construct a fake agreement as
579 * the EXOR of the peer and host cookies.
581 * hismode ephemeral persistent
582 * =======================================
585 * client sys cookie 0%
586 * server 0% sys cookie
592 if (hismode == MODE_BROADCAST) {
595 * For broadcaster, use the interface
596 * broadcast address when available;
597 * otherwise, use the unicast address
598 * found when the association was
599 * mobilized. However, if this is from
600 * the wildcard interface, game over.
602 if (crypto_flags && rbufp->dstadr ==
605 return; /* no wildcard */
608 if (!SOCKNUL(&rbufp->dstadr->bcast))
610 &rbufp->dstadr->bcast;
611 } else if (peer == NULL) {
612 pkeyid = session_key(
613 &rbufp->recv_srcadr, dstadr_sin, 0,
616 pkeyid = peer->pcookie;
620 * The session key includes both the public
621 * values and cookie. In case of an extension
622 * field, the cookie used for authentication
623 * purposes is zero. Note the hash is saved for
624 * use later in the autokey mambo.
626 if (authlen > LEN_PKT_NOMAC && pkeyid != 0) {
627 session_key(&rbufp->recv_srcadr,
628 dstadr_sin, skeyid, 0, 2);
629 tkeyid = session_key(
630 &rbufp->recv_srcadr, dstadr_sin,
633 tkeyid = session_key(
634 &rbufp->recv_srcadr, dstadr_sin,
642 * Compute the cryptosum. Note a clogging attack may
643 * succeed in bloating the key cache. If an autokey,
644 * purge it immediately, since we won't be needing it
645 * again. If the packet is authentic, it can mobilize an
646 * association. Note that there is no key zero.
648 if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,
650 is_authentic = AUTH_ERROR;
653 is_authentic = AUTH_OK;
656 if (skeyid > NTP_MAXKEY)
657 authtrust(skeyid, 0);
662 "receive: at %ld %s<-%s mode %d code %d keyid %08x len %d mac %d auth %d\n",
663 current_time, stoa(dstadr_sin),
664 stoa(&rbufp->recv_srcadr), hismode, retcode,
665 skeyid, authlen, has_mac, is_authentic);
670 * The association matching rules are implemented by a set of
671 * routines and an association table. A packet matching an
672 * association is processed by the peer process for that
673 * association. If there are no errors, an ephemeral association
674 * is mobilized: a broadcast packet mobilizes a broadcast client
675 * aassociation; a manycast server packet mobilizes a manycast
676 * client association; a symmetric active packet mobilizes a
677 * symmetric passive association.
682 * This is a client mode packet not matching any association. If
683 * an ordinary client, simply toss a server mode packet back
684 * over the fence. If a manycast client, we have to work a
690 * The vanilla case is when this is not a multicast
691 * interface. If authentication succeeds, return a
692 * server mode packet; if not and the key ID is nonzero,
693 * return a crypto-NAK.
695 if (!(rbufp->dstadr->flags & INT_MCASTOPEN)) {
696 if (AUTH(restrict_mask & RES_DONTTRUST,
698 fast_xmit(rbufp, MODE_SERVER, skeyid,
700 else if (is_authentic == AUTH_ERROR)
701 fast_xmit(rbufp, MODE_SERVER, 0,
707 * This must be manycast. Do not respond if not
708 * configured as a manycast server.
710 if (!sys_manycastserver) {
712 return; /* not enabled */
716 * Do not respond if unsynchronized or stratum is below
717 * the floor or at or above the ceiling.
719 if (sys_leap == LEAP_NOTINSYNC || sys_stratum <
720 sys_floor || sys_stratum >= sys_ceiling)
721 return; /* bad stratum */
724 * Do not respond if our stratum is greater than the
725 * manycaster or it has already synchronized to us.
727 if (sys_peer == NULL || hisstratum < sys_stratum ||
728 (sys_cohort && hisstratum == sys_stratum) ||
729 rbufp->dstadr->addr_refid == pkt->refid)
730 return; /* no help */
733 * Respond only if authentication succeeds. Don't do a
734 * crypto-NAK, as that would not be useful.
736 if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic))
737 fast_xmit(rbufp, MODE_SERVER, skeyid,
743 * This is a server mode packet returned in response to a client
744 * mode packet sent to a multicast group address. The origin
745 * timestamp is a good nonce to reliably associate the reply
746 * with what was sent. If there is no match, that's curious and
747 * could be an intruder attempting to clog, so we just ignore
750 * If the packet is authentic and the manycast association is
751 * found, we mobilize a client association and copy pertinent
752 * variables from the manycast association to the new client
753 * association. If not, just ignore the packet.
755 * There is an implosion hazard at the manycast client, since
756 * the manycast servers send the server packet immediately. If
757 * the guy is already here, don't fire up a duplicate.
760 if (!AUTH(sys_authenticate | (restrict_mask &
761 (RES_NOPEER | RES_DONTTRUST)), is_authentic))
762 return; /* bad auth */
764 if ((peer2 = findmanycastpeer(rbufp)) == NULL) {
766 return; /* not enabled */
768 if ((peer = newpeer(&rbufp->recv_srcadr,
769 rbufp->dstadr, MODE_CLIENT,
770 hisversion, NTP_MINDPOLL, NTP_MAXDPOLL,
771 FLAG_IBURST | FLAG_PREEMPT, MDF_UCAST | MDF_ACLNT,
773 return; /* system error */
776 * We don't need these, but it warms the billboards.
778 peer->ttl = peer2->ttl;
782 * This is the first packet received from a broadcast server. If
783 * the packet is authentic and we are enabled as broadcast
784 * client, mobilize a broadcast client association. We don't
785 * kiss any frogs here.
788 if (!AUTH(sys_authenticate | (restrict_mask &
789 (RES_NOPEER | RES_DONTTRUST)), is_authentic))
790 return; /* bad auth */
793 * Do not respond if unsynchronized or stratum is below
794 * the floor or at or above the ceiling.
796 if (hisleap == LEAP_NOTINSYNC || hisstratum <
797 sys_floor || hisstratum >= sys_ceiling)
798 return; /* bad stratum */
800 switch (sys_bclient) {
803 * If not enabled, just skedaddle.
807 return; /* not enabled */
810 * Execute the initial volley in order to calibrate the
811 * propagation delay and run the Autokey protocol, if
815 if ((peer = newpeer(&rbufp->recv_srcadr,
816 rbufp->dstadr, MODE_CLIENT, hisversion,
817 NTP_MINDPOLL, NTP_MAXDPOLL, FLAG_MCAST |
818 FLAG_IBURST, MDF_BCLNT, 0, skeyid)) ==
820 return; /* system error */
822 if (skeyid > NTP_MAXKEY)
823 crypto_recv(peer, rbufp);
829 * Do not execute the initial volley.
834 * If a two-way exchange is not possible,
835 * neither is Autokey.
837 if (skeyid > NTP_MAXKEY) {
839 "receive: autokey requires two-way communication");
840 return; /* no autokey */
843 if ((peer = newpeer(&rbufp->recv_srcadr,
844 rbufp->dstadr, MODE_BCLIENT, hisversion,
845 NTP_MINDPOLL, NTP_MAXDPOLL, 0, MDF_BCLNT, 0,
847 return; /* system error */
852 * This is the first packet received from a symmetric active
853 * peer. If the packet is authentic and the first he sent,
854 * mobilize a passive association. If not, kiss the frog.
859 * If the inbound packet is correctly authenticated and
860 * enabled, a symmetric passive association is
861 * mobilized. If not but correctly authenticated, a
862 * symmetric active response is sent. If authentication
863 * fails, send a crypto-NAK packet.
865 if (!AUTH(restrict_mask & RES_DONTTRUST, is_authentic))
867 if (is_authentic == AUTH_ERROR)
868 fast_xmit(rbufp, MODE_ACTIVE, 0,
870 return; /* bad auth */
872 if (!AUTH(sys_authenticate | (restrict_mask &
873 RES_NOPEER), is_authentic)) {
874 fast_xmit(rbufp, MODE_ACTIVE, skeyid,
880 * Do not respond if stratum is below the floor.
882 if (hisstratum < sys_floor)
883 return; /* bad stratum */
885 if ((peer = newpeer(&rbufp->recv_srcadr,
886 rbufp->dstadr, MODE_PASSIVE, hisversion,
887 NTP_MINDPOLL, NTP_MAXDPOLL, 0, MDF_UCAST, 0,
889 return; /* system error */
893 * Process regular packet. Nothing special.
899 * A passive packet matches a passive association. This is
900 * usually the result of reconfiguring a client on the fly. As
901 * this association might be legitamate and this packet an
902 * attempt to deny service, just ignore it.
908 * For everything else there is the bit bucket.
913 peer->flash &= ~PKT_TEST_MASK;
916 * Next comes a rigorous schedule of timestamp checking. If the
917 * transmit timestamp is zero, the server is horribly broken.
919 if (L_ISZERO(&p_xmt)) {
920 return; /* read rfc1305 */
923 * If the transmit timestamp duplicates a previous one, the
924 * packet is a replay. This prevents the bad guys from replaying
925 * the most recent packet, authenticated or not.
927 } else if (L_ISEQU(&peer->org, &p_xmt)) {
928 peer->flash |= TEST1;
930 return; /* duplicate packet */
934 * If this is a broadcast mode packet, skip further checking.
936 } else if (hismode != MODE_BROADCAST) {
937 if (L_ISZERO(&p_org))
938 peer->flash |= TEST3; /* protocol unsynch */
939 else if (!L_ISEQU(&p_org, &peer->xmt))
940 peer->flash |= TEST2; /* bogus packet */
944 * Update the origin and destination timestamps. If
945 * unsynchronized or bogus abandon ship. If the crypto machine
946 * breaks, light the crypto bit and plaint the log.
949 peer->rec = rbufp->recv_time;
950 if (peer->flash & PKT_TEST_MASK) {
952 if (crypto_flags && (peer->flags & FLAG_SKEY)) {
953 rval = crypto_recv(peer, rbufp);
954 if (rval != XEVNT_OK) {
955 peer_clear(peer, "CRYP");
956 peer->flash |= TEST9; /* crypto error */
960 return; /* unsynch */
964 * The timestamps are valid and the receive packet matches the
965 * last one sent. If the packet is a crypto-NAK, the server
966 * might have just changed keys. We reset the association
967 * and restart the protocol.
969 if (is_authentic == AUTH_CRYPTO) {
970 peer_clear(peer, "AUTH");
971 return; /* crypto-NAK */
974 * If the association is authenticated, the key ID is nonzero
975 * and received packets must be authenticated. This is designed
976 * to avoid a bait-and-switch attack, which was possible in past
977 * versions. If symmetric modes, return a crypto-NAK. The peer
978 * should restart the protocol.
980 } else if (!AUTH(peer->keyid || (restrict_mask & RES_DONTTRUST),
982 peer->flash |= TEST5;
983 if (hismode == MODE_ACTIVE || hismode == MODE_PASSIVE)
984 fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
985 return; /* bad auth */
989 * That was hard and I am sweaty, but the packet is squeaky
990 * clean. Get on with real work.
993 peer->timereceived = current_time;
994 if (is_authentic == AUTH_OK)
995 peer->flags |= FLAG_AUTHENTIC;
997 peer->flags &= ~FLAG_AUTHENTIC;
1000 * More autokey dance. The rules of the cha-cha are as follows:
1002 * 1. If there is no key or the key is not auto, do nothing.
1004 * 2. If this packet is in response to the one just previously
1005 * sent or from a broadcast server, do the extension fields.
1006 * Otherwise, assume bogosity and bail out.
1008 * 3. If an extension field contains a verified signature, it is
1009 * self-authenticated and we sit the dance.
1011 * 4. If this is a server reply, check only to see that the
1012 * transmitted key ID matches the received key ID.
1014 * 5. Check to see that one or more hashes of the current key ID
1015 * matches the previous key ID or ultimate original key ID
1016 * obtained from the broadcaster or symmetric peer. If no
1017 * match, sit the dance and wait for timeout.
1019 * In case of crypto error, fire the orchestra and stop dancing.
1020 * This is considered a permanant error, so light the crypto bit
1021 * to suppress further requests. If preemptable or ephemeral,
1024 if (crypto_flags && (peer->flags & FLAG_SKEY)) {
1025 peer->flash |= TEST8;
1026 rval = crypto_recv(peer, rbufp);
1027 if (rval != XEVNT_OK) {
1028 peer_clear(peer, "CRYP");
1029 peer->flash |= TEST9; /* crypto error */
1030 if (peer->flags & FLAG_PREEMPT ||
1031 !(peer->flags & FLAG_CONFIG))
1035 } else if (hismode == MODE_SERVER) {
1036 if (skeyid == peer->keyid)
1037 peer->flash &= ~TEST8;
1038 } else if (!(peer->flash & TEST8)) {
1039 peer->pkeyid = skeyid;
1040 } else if ((ap = (struct autokey *)peer->recval.ptr) !=
1044 for (i = 0; ; i++) {
1045 if (tkeyid == peer->pkeyid ||
1046 tkeyid == ap->key) {
1047 peer->flash &= ~TEST8;
1048 peer->pkeyid = skeyid;
1053 tkeyid = session_key(
1054 &rbufp->recv_srcadr, dstadr_sin,
1058 if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */
1059 peer->flash |= TEST8; /* not proventic */
1062 * If the transmit queue is nonempty, clamp the host
1063 * poll interval to the packet poll interval.
1065 if (peer->cmmd != 0) {
1066 peer->ppoll = pkt->ppoll;
1067 poll_update(peer, peer->hpoll);
1070 #endif /* OPENSSL */
1073 * The dance is complete and the flash bits have been lit. Toss
1074 * the packet over the fence for processing, which may light up
1077 process_packet(peer, pkt);
1080 * Well, that was nice. If TEST4 is lit, either the crypto
1081 * machine jammed or a kiss-o'-death packet flew in, either of
1084 if (peer->flash & TEST4) {
1085 msyslog(LOG_INFO, "receive: fatal error %04x for %s",
1086 peer->flash, stoa(&peer->srcadr));
1093 * process_packet - Packet Procedure, a la Section 3.4.4 of the
1094 * specification. Or almost, at least. If we're in here we have a
1095 * reasonable expectation that we will be having a long term
1096 * relationship with this host.
1100 register struct peer *peer,
1101 register struct pkt *pkt
1105 double p_offset, p_del, p_disp;
1106 l_fp p_rec, p_xmt, p_org, p_reftime;
1108 u_char pmode, pleap, pstratum;
1112 p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
1113 p_disp = FPTOD(NTOHS_FP(pkt->rootdispersion));
1114 NTOHL_FP(&pkt->reftime, &p_reftime);
1115 NTOHL_FP(&pkt->rec, &p_rec);
1116 NTOHL_FP(&pkt->xmt, &p_xmt);
1117 pmode = PKT_MODE(pkt->li_vn_mode);
1118 pleap = PKT_LEAP(pkt->li_vn_mode);
1119 if (pmode != MODE_BROADCAST)
1120 NTOHL_FP(&pkt->org, &p_org);
1123 pstratum = PKT_TO_STRATUM(pkt->stratum);
1126 * Test for kiss-o'death packet)
1128 if (pleap == LEAP_NOTINSYNC && pstratum == STRATUM_UNSPEC) {
1129 if (memcmp(&pkt->refid, "DENY", 4) == 0) {
1130 peer_clear(peer, "DENY");
1131 peer->flash |= TEST4; /* access denied */
1136 * Capture the header values.
1138 record_raw_stats(&peer->srcadr, peer->dstadr ? &peer->dstadr->sin : NULL, &p_org,
1139 &p_rec, &p_xmt, &peer->rec);
1141 peer->stratum = min(pstratum, STRATUM_UNSPEC);
1142 peer->pmode = pmode;
1143 peer->ppoll = pkt->ppoll;
1144 peer->precision = pkt->precision;
1145 peer->rootdelay = p_del;
1146 peer->rootdispersion = p_disp;
1147 peer->refid = pkt->refid; /* network byte order */
1148 peer->reftime = p_reftime;
1151 * Verify the server is synchronized; that is, the leap bits and
1152 * stratum are valid, the root delay and root dispersion are
1153 * valid and the reference timestamp is not later than the
1154 * transmit timestamp.
1156 if (pleap == LEAP_NOTINSYNC || /* test 6 */
1157 pstratum < sys_floor || pstratum >= sys_ceiling)
1158 peer->flash |= TEST6; /* peer not synch */
1159 if (p_del < 0 || p_disp < 0 || p_del / /* test 7 */
1160 2 + p_disp >= MAXDISPERSE || !L_ISHIS(&p_xmt, &p_reftime))
1161 peer->flash |= TEST7; /* bad header */
1164 * If any tests fail at this point, the packet is discarded.
1165 * Note that some flashers may have already been set in the
1166 * receive() routine.
1168 if (peer->flash & PKT_TEST_MASK) {
1171 printf("packet: flash header %04x\n",
1176 if (!(peer->reach)) {
1177 report_event(EVNT_REACH, peer);
1178 peer->timereachable = current_time;
1180 poll_update(peer, peer->hpoll);
1184 * For a client/server association, calculate the clock offset,
1185 * roundtrip delay and dispersion. The equations are reordered
1186 * from the spec for more efficient use of temporaries. For a
1187 * broadcast association, offset the last measurement by the
1188 * computed delay during the client/server volley. Note that
1189 * org has been set to the time of last reception. Note the
1190 * computation of dispersion includes the system precision plus
1191 * that due to the frequency error since the origin time.
1193 * It is very important to respect the hazards of overflow. The
1194 * only permitted operation on raw timestamps is subtraction,
1195 * where the result is a signed quantity spanning from 68 years
1196 * in the past to 68 years in the future. To avoid loss of
1197 * precision, these calculations are done using 64-bit integer
1198 * arithmetic. However, the offset and delay calculations are
1199 * sums and differences of these first-order differences, which
1200 * if done using 64-bit integer arithmetic, would be valid over
1201 * only half that span. Since the typical first-order
1202 * differences are usually very small, they are converted to 64-
1203 * bit doubles and all remaining calculations done in floating-
1204 * point arithmetic. This preserves the accuracy while retaining
1207 * Let t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->rec:
1209 ci = p_xmt; /* t3 - t4 */
1210 L_SUB(&ci, &peer->rec);
1212 ci = p_rec; /* t2 - t1 */
1215 ci = peer->rec; /* t4 - t1 */
1219 * If running in a broadcast association, the clock offset is
1220 * (t1 - t0) corrected by the one-way delay, but we can't
1221 * measure that directly. Therefore, we start up in MODE_CLIENT
1222 * mode, set FLAG_MCAST and exchange eight messages to determine
1223 * the clock offset. When the last message is sent, we switch to
1224 * MODE_BCLIENT mode. The next broadcast message after that
1225 * computes the broadcast offset and clears FLAG_MCAST.
1227 if (pmode == MODE_BROADCAST) {
1229 if (peer->flags & FLAG_MCAST) {
1230 peer->estbdelay = peer->offset - p_offset;
1231 if (peer->hmode == MODE_CLIENT)
1234 peer->flags &= ~(FLAG_MCAST | FLAG_BURST);
1236 p_offset += peer->estbdelay;
1237 p_del = peer->delay;
1240 p_offset = (t21 + t34) / 2.;
1242 LFPTOD(&ci, p_disp);
1243 p_disp = LOGTOD(sys_precision) +
1244 LOGTOD(peer->precision) + clock_phi * p_disp;
1246 p_del = max(p_del, LOGTOD(sys_precision));
1247 clock_filter(peer, p_offset, p_del, p_disp);
1248 record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
1249 peer->offset, peer->delay, peer->disp, peer->jitter);
1254 * clock_update - Called at system process update intervals.
1264 * There must be a system peer at this point. If we just changed
1265 * the system peer, but have a newer sample from the old one,
1266 * wait until newer data are available.
1268 if (sys_poll < sys_peer->minpoll)
1269 sys_poll = sys_peer->minpoll;
1270 if (sys_poll > sys_peer->maxpoll)
1271 sys_poll = sys_peer->maxpoll;
1272 poll_update(sys_peer, sys_poll);
1273 if (sys_peer->epoch <= sys_clocktime)
1278 printf("clock_update: at %ld assoc %d \n", current_time,
1282 ostratum = sys_stratum;
1283 switch (local_clock(sys_peer, sys_offset)) {
1286 * Clock exceeds panic threshold. Life as we know it ends.
1289 report_event(EVNT_SYSFAULT, NULL);
1294 * Clock was stepped. Flush all time values of all peers.
1298 sys_leap = LEAP_NOTINSYNC;
1299 sys_stratum = STRATUM_UNSPEC;
1302 sys_rootdispersion = 0;
1303 memcpy(&sys_refid, "STEP", 4);
1304 report_event(EVNT_CLOCKRESET, NULL);
1308 * Clock was slewed. Update the system stratum, leap bits, root
1309 * delay, root dispersion, reference ID and reference time. If
1310 * the leap changes, we gotta reroll the keys. Except for
1311 * reference clocks, the minimum dispersion increment is not
1312 * less than sys_mindisp.
1315 sys_leap = leap_next;
1316 sys_stratum = min(sys_peer->stratum + 1,
1318 sys_reftime = sys_peer->rec;
1321 * In orphan mode the stratum defaults to the orphan
1322 * stratum. The root delay is set to a random value
1323 * generated at startup. The root dispersion is set from
1324 * the peer dispersion; the peer root dispersion is
1327 dtemp = sys_peer->disp + clock_phi * (current_time -
1328 sys_peer->update) + sys_jitter +
1329 fabs(sys_peer->offset);
1331 if (!(sys_peer->flags & FLAG_REFCLOCK) && dtemp <
1333 dtemp = sys_mindisp;
1335 if (dtemp < sys_mindisp)
1336 dtemp = sys_mindisp;
1337 #endif /* REFCLOCK */
1338 if (sys_stratum >= sys_orphan) {
1339 sys_stratum = sys_orphan;
1340 sys_rootdelay = sys_peer->delay;
1341 sys_rootdispersion = dtemp;
1343 sys_rootdelay = sys_peer->delay +
1344 sys_peer->rootdelay;
1345 sys_rootdispersion = dtemp +
1346 sys_peer->rootdispersion;
1348 if (oleap == LEAP_NOTINSYNC) {
1349 report_event(EVNT_SYNCCHG, NULL);
1353 #endif /* OPENSSL */
1357 * Popcorn spike or step threshold exceeded. Pretend it never
1363 if (ostratum != sys_stratum)
1364 report_event(EVNT_PEERSTCHG, NULL);
1369 * poll_update - update peer poll interval
1380 * This routine figures out when the next poll should be sent.
1381 * That turns out to be wickedly complicated. The big problem is
1382 * that sometimes the time for the next poll is in the past.
1383 * Watch out for races here between the receive process and the
1384 * poll process. The key assertion is that, if nextdate equals
1385 * current_time, the call is from the poll process; otherwise,
1386 * it is from the receive process.
1388 * First, bracket the poll interval according to the type of
1389 * association and options. If a fixed interval is configured,
1390 * use minpoll. This primarily is for reference clocks, but
1391 * works for any association.
1393 if (peer->flags & FLAG_FIXPOLL) {
1394 hpoll = peer->minpoll;
1397 * The ordinary case; clamp the poll interval between minpoll
1401 hpoll = max(min(peer->maxpoll, mpoll), peer->minpoll);
1405 * Bit of crass arrogance at this point. If the poll interval
1406 * has changed and we have a keylist, the lifetimes in the
1407 * keylist are probably bogus. In this case purge the keylist
1408 * and regenerate it later.
1410 if (hpoll != peer->hpoll)
1412 #endif /* OPENSSL */
1413 peer->hpoll = hpoll;
1416 * Now we figure out if there is an override. If during the
1417 * crypto protocol and a message is pending, make it wait not
1418 * more than two seconds.
1421 if (peer->cmmd != NULL && (sys_leap != LEAP_NOTINSYNC ||
1423 peer->nextdate = current_time + RESP_DELAY;
1426 * If we get called from the receive routine while a burst is
1427 * pending, just slink away. If from the poll routine and a
1428 * reference clock or a pending crypto response, delay for one
1429 * second. If this is the first sent in a burst, wait for the
1430 * modem to come up. For others in the burst, delay two seconds.
1432 } else if (peer->burst > 0) {
1434 if (peer->burst > 0) {
1435 #endif /* OPENSSL */
1436 if (peer->nextdate != current_time)
1439 else if (peer->flags & FLAG_REFCLOCK)
1440 peer->nextdate += RESP_DELAY;
1441 #endif /* REFCLOCK */
1442 else if (peer->flags & (FLAG_IBURST | FLAG_BURST) &&
1443 peer->burst == NTP_BURST)
1444 peer->nextdate += sys_calldelay;
1446 peer->nextdate += BURST_DELAY;
1448 * The ordinary case; use the minimum of the host and peer
1449 * intervals, but not less than minpoll. In other words,
1450 * oversampling is okay but understampling is evil.
1453 peer->nextdate = peer->outdate +
1454 RANDPOLL(max(min(peer->ppoll, hpoll),
1459 * If the time for the next poll has already happened, bring it
1460 * up to the next second after this one. This way the only way
1461 * to get nexdate == current time is from the poll routine.
1463 if (peer->nextdate <= current_time)
1464 peer->nextdate = current_time + 1;
1467 printf("poll_update: at %lu %s flags %04x poll %d burst %d last %lu next %lu\n",
1468 current_time, ntoa(&peer->srcadr), peer->flags,
1469 peer->hpoll, peer->burst, peer->outdate,
1475 * peer_crypto_clear - discard crypto information
1483 * If cryptographic credentials have been acquired, toss them to
1484 * Valhalla. Note that autokeys are ephemeral, in that they are
1485 * tossed immediately upon use. Therefore, the keylist can be
1486 * purged anytime without needing to preserve random keys. Note
1487 * that, if the peer is purged, the cryptographic variables are
1488 * purged, too. This makes it much harder to sneak in some
1489 * unauthenticated data in the clock filter.
1491 DPRINTF(1, ("peer_crypto_clear: at %ld next %ld assoc ID %d\n",
1492 current_time, peer->nextdate, peer->associd));
1498 if (peer->pkey != NULL)
1499 EVP_PKEY_free(peer->pkey);
1502 peer->digest = NULL; /* XXX MEMLEAK? check whether this needs to be freed in any way - never was freed */
1504 if (peer->subject != NULL)
1505 free(peer->subject);
1506 peer->subject = NULL;
1508 if (peer->issuer != NULL)
1510 peer->issuer = NULL;
1516 if (peer->ident_pkey != NULL)
1517 EVP_PKEY_free(peer->ident_pkey);
1518 peer->ident_pkey = NULL;
1520 memset(&peer->fstamp, 0, sizeof(peer->fstamp));
1522 if (peer->iffval != NULL)
1523 BN_free(peer->iffval);
1524 peer->iffval = NULL;
1526 if (peer->grpkey != NULL)
1527 BN_free(peer->grpkey);
1528 peer->grpkey = NULL;
1530 value_free(&peer->cookval);
1531 value_free(&peer->recval);
1533 if (peer->cmmd != NULL) {
1540 value_free(&peer->encrypt);
1541 #endif /* OPENSSL */
1545 * peer_clear - clear peer filter registers. See Section 3.4.8 of the spec.
1549 struct peer *peer, /* peer structure */
1550 char *ident /* tally lights */
1555 peer_crypto_clear(peer);
1557 if (peer == sys_peer)
1561 * Wipe the association clean and initialize the nonzero values.
1563 memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO);
1564 peer->estbdelay = sys_bdelay;
1565 peer->ppoll = peer->maxpoll;
1566 peer->hpoll = peer->minpoll;
1567 peer->disp = MAXDISPERSE;
1568 peer->jitter = LOGTOD(sys_precision);
1569 for (i = 0; i < NTP_SHIFT; i++) {
1570 peer->filter_order[i] = i;
1571 peer->filter_disp[i] = MAXDISPERSE;
1574 if (!(peer->flags & FLAG_REFCLOCK)) {
1575 peer->leap = LEAP_NOTINSYNC;
1576 peer->stratum = STRATUM_UNSPEC;
1577 memcpy(&peer->refid, ident, 4);
1580 peer->leap = LEAP_NOTINSYNC;
1581 peer->stratum = STRATUM_UNSPEC;
1582 memcpy(&peer->refid, ident, 4);
1583 #endif /* REFCLOCK */
1586 * During initialization use the association count to spread out
1587 * the polls at one-second intervals. Othersie, randomize over
1588 * the minimum poll interval in order to avoid broadcast
1591 peer->nextdate = peer->update = peer->outdate = current_time;
1593 peer->nextdate += peer_associations;
1594 else if (peer->hmode == MODE_PASSIVE)
1595 peer->nextdate += RESP_DELAY;
1597 peer->nextdate += (ntp_random() & ((1 << NTP_MINDPOLL) -
1600 DPRINTF(1, ("peer_clear: at %ld next %ld assoc ID %d refid %s\n",
1601 current_time, peer->nextdate, peer->associd, ident));
1606 * clock_filter - add incoming clock sample to filter register and run
1607 * the filter procedure to find the best sample.
1611 struct peer *peer, /* peer structure pointer */
1612 double sample_offset, /* clock offset */
1613 double sample_delay, /* roundtrip delay */
1614 double sample_disp /* dispersion */
1617 double dst[NTP_SHIFT]; /* distance vector */
1618 int ord[NTP_SHIFT]; /* index vector */
1620 double dtemp, etemp;
1623 * Shift the new sample into the register and discard the oldest
1624 * one. The new offset and delay come directly from the
1625 * timestamp calculations. The dispersion grows from the last
1626 * outbound packet or reference clock update to the present time
1627 * and increased by the sum of the peer precision and the system
1628 * precision. The delay can sometimes swing negative due to
1629 * frequency skew, so it is clamped non-negative.
1631 j = peer->filter_nextpt;
1632 peer->filter_offset[j] = sample_offset;
1633 peer->filter_delay[j] = max(0, sample_delay);
1634 peer->filter_disp[j] = sample_disp;
1635 peer->filter_epoch[j] = current_time;
1636 j = (j + 1) % NTP_SHIFT;
1637 peer->filter_nextpt = j;
1640 * Update dispersions since the last update and at the same
1641 * time initialize the distance and index lists. The distance
1642 * list uses a compound metric. If the sample is valid and
1643 * younger than the minimum Allan intercept, use delay;
1644 * otherwise, use biased dispersion.
1646 dtemp = clock_phi * (current_time - peer->update);
1647 peer->update = current_time;
1648 for (i = NTP_SHIFT - 1; i >= 0; i--) {
1650 peer->filter_disp[j] += dtemp;
1651 if (peer->filter_disp[j] >= MAXDISPERSE)
1652 peer->filter_disp[j] = MAXDISPERSE;
1653 if (peer->filter_disp[j] >= MAXDISPERSE)
1654 dst[i] = MAXDISPERSE;
1655 else if (peer->update - peer->filter_epoch[j] >
1657 dst[i] = sys_maxdist + peer->filter_disp[j];
1659 dst[i] = peer->filter_delay[j];
1661 j++; j %= NTP_SHIFT;
1665 * If the clock discipline has stabilized, sort the samples in
1666 * both lists by distance. Note, we do not displace a higher
1667 * distance sample by a lower distance one unless lower by at
1668 * least the precision.
1671 for (i = 1; i < NTP_SHIFT; i++) {
1672 for (j = 0; j < i; j++) {
1673 if (dst[j] > dst[i] +
1674 LOGTOD(sys_precision)) {
1687 * Copy the index list to the association structure so ntpq
1688 * can see it later. Prune the distance list to samples less
1689 * than max distance, but keep at least two valid samples for
1690 * jitter calculation.
1693 for (i = 0; i < NTP_SHIFT; i++) {
1694 peer->filter_order[i] = (u_char) ord[i];
1695 if (dst[i] >= MAXDISPERSE || (m >= 2 && dst[i] >=
1702 * Compute the dispersion and jitter. The dispersion is weighted
1703 * exponentially by NTP_FWEIGHT (0.5) so it is normalized close
1704 * to 1.0. The jitter is the RMS differences relative to the
1705 * lowest delay sample. If no acceptable samples remain in the
1706 * shift register, quietly tiptoe home leaving only the
1709 peer->disp = peer->jitter = 0;
1711 for (i = NTP_SHIFT - 1; i >= 0; i--) {
1713 peer->disp = NTP_FWEIGHT * (peer->disp +
1714 peer->filter_disp[j]);
1716 peer->jitter += DIFF(peer->filter_offset[j],
1717 peer->filter_offset[k]);
1721 * If no acceptable samples remain in the shift register,
1722 * quietly tiptoe home leaving only the dispersion. Otherwise,
1723 * save the offset, delay and jitter. Note the jitter must not
1724 * be less than the precision.
1729 etemp = fabs(peer->offset - peer->filter_offset[k]);
1730 peer->offset = peer->filter_offset[k];
1731 peer->delay = peer->filter_delay[k];
1733 peer->jitter /= m - 1;
1734 peer->jitter = max(SQRT(peer->jitter), LOGTOD(sys_precision));
1737 * A new sample is useful only if it is younger than the last
1738 * one used. Note the order is FIFO if the clock discipline has
1741 if (peer->filter_epoch[k] <= peer->epoch) {
1744 printf("clock_filter: discard %lu\n",
1745 peer->epoch - peer->filter_epoch[k]);
1751 * If the difference between the last offset and the current one
1752 * exceeds the jitter by CLOCK_SGATE and the interval since the
1753 * last update is less than twice the system poll interval,
1754 * consider the update a popcorn spike and ignore it.
1756 if (etemp > CLOCK_SGATE * peer->jitter && m > 1 &&
1757 peer->filter_epoch[k] - peer->epoch < 2. *
1758 ULOGTOD(sys_poll)) {
1761 printf("clock_filter: popcorn %.6f %.6f\n",
1768 * The mitigated sample statistics are saved for later
1769 * processing. If not in a burst, tickle the select.
1771 peer->epoch = peer->filter_epoch[k];
1775 "clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f, age %lu\n",
1776 m, peer->offset, peer->delay, peer->disp,
1777 peer->jitter, current_time - peer->epoch);
1779 if (peer->burst == 0 || sys_leap == LEAP_NOTINSYNC)
1785 * clock_select - find the pick-of-the-litter clock
1787 * LOCKCLOCK: If the local clock is the prefer peer, it will always be
1788 * enabled, even if declared falseticker, (2) only the prefer peer can
1789 * be selected as the system peer, (3) if the external source is down,
1790 * the system leap bits are set to 11 and the stratum set to infinity.
1802 double synch[NTP_MAXASSOC], error[NTP_MAXASSOC];
1803 struct peer *osys_peer;
1804 struct peer *typeacts = NULL;
1805 struct peer *typelocal = NULL;
1806 struct peer *typesystem = NULL;
1808 static int list_alloc = 0;
1809 static struct endpoint *endpoint = NULL;
1810 static int *indx = NULL;
1811 static struct peer **peer_list = NULL;
1812 static u_int endpoint_size = 0;
1813 static u_int indx_size = 0;
1814 static u_int peer_list_size = 0;
1817 * Initialize and create endpoint, index and peer lists big
1818 * enough to handle all associations.
1820 osys_peer = sys_peer;
1824 osurv = sys_survivors;
1827 sys_leap = LEAP_NOTINSYNC;
1828 sys_stratum = STRATUM_UNSPEC;
1829 memcpy(&sys_refid, "DOWN", 4);
1830 #endif /* LOCKCLOCK */
1832 for (n = 0; n < NTP_HASH_SIZE; n++)
1833 nlist += peer_hash_count[n];
1834 if (nlist > list_alloc) {
1835 if (list_alloc > 0) {
1840 while (list_alloc < nlist) {
1842 endpoint_size += 5 * 3 * sizeof(*endpoint);
1843 indx_size += 5 * 3 * sizeof(*indx);
1844 peer_list_size += 5 * sizeof(*peer_list);
1846 endpoint = (struct endpoint *)emalloc(endpoint_size);
1847 indx = (int *)emalloc(indx_size);
1848 peer_list = (struct peer **)emalloc(peer_list_size);
1852 * Initially, we populate the island with all the rifraff peers
1853 * that happen to be lying around. Those with seriously
1854 * defective clocks are immediately booted off the island. Then,
1855 * the falsetickers are culled and put to sea. The truechimers
1856 * remaining are subject to repeated rounds where the most
1857 * unpopular at each round is kicked off. When the population
1858 * has dwindled to sys_minclock, the survivors split a million
1859 * bucks and collectively crank the chimes.
1861 nlist = nl3 = 0; /* none yet */
1862 for (n = 0; n < NTP_HASH_SIZE; n++) {
1863 for (peer = peer_hash[n]; peer != NULL; peer =
1865 peer->flags &= ~FLAG_SYSPEER;
1866 peer->status = CTL_PST_SEL_REJECT;
1869 * Leave the island immediately if the peer is
1870 * unfit to synchronize.
1872 if (peer_unfit(peer))
1876 * Don't allow the local clock or modem drivers
1877 * in the kitchen at this point, unless the
1878 * prefer peer. Do that later, but only if
1879 * nobody else is around. These guys are all
1880 * configured, so we never throw them away.
1883 if (peer->refclktype == REFCLK_LOCALCLOCK
1884 #if defined(VMS) && defined(VMS_LOCALUNIT)
1885 /* wjm: VMS_LOCALUNIT taken seriously */
1886 && REFCLOCKUNIT(&peer->srcadr) !=
1888 #endif /* VMS && VMS_LOCALUNIT */
1892 if (!(peer->flags & FLAG_PREFER))
1893 continue; /* no local clock */
1894 #endif /* LOCKCLOCK */
1896 if (peer->sstclktype == CTL_SST_TS_TELEPHONE) {
1898 if (!(peer->flags & FLAG_PREFER))
1899 continue; /* no acts */
1901 #endif /* REFCLOCK */
1904 * If we get this far, the peer can stay on the
1905 * island, but does not yet have the immunity
1908 peer->status = CTL_PST_SEL_SANE;
1909 peer_list[nlist++] = peer;
1912 * Insert each interval endpoint on the sorted
1915 e = peer->offset; /* Upper end */
1916 f = root_distance(peer);
1918 for (i = nl3 - 1; i >= 0; i--) {
1919 if (e >= endpoint[indx[i]].val)
1922 indx[i + 3] = indx[i];
1925 endpoint[nl3].type = 1;
1926 endpoint[nl3++].val = e;
1928 e = e - f; /* Center point */
1929 for (; i >= 0; i--) {
1930 if (e >= endpoint[indx[i]].val)
1933 indx[i + 2] = indx[i];
1936 endpoint[nl3].type = 0;
1937 endpoint[nl3++].val = e;
1939 e = e - f; /* Lower end */
1940 for (; i >= 0; i--) {
1941 if (e >= endpoint[indx[i]].val)
1944 indx[i + 1] = indx[i];
1947 endpoint[nl3].type = -1;
1948 endpoint[nl3++].val = e;
1953 for (i = 0; i < nl3; i++)
1954 printf("select: endpoint %2d %.6f\n",
1955 endpoint[indx[i]].type,
1956 endpoint[indx[i]].val);
1959 * This is the actual algorithm that cleaves the truechimers
1960 * from the falsetickers. The original algorithm was described
1961 * in Keith Marzullo's dissertation, but has been modified for
1964 * Briefly put, we first assume there are no falsetickers, then
1965 * scan the candidate list first from the low end upwards and
1966 * then from the high end downwards. The scans stop when the
1967 * number of intersections equals the number of candidates less
1968 * the number of falsetickers. If this doesn't happen for a
1969 * given number of falsetickers, we bump the number of
1970 * falsetickers and try again. If the number of falsetickers
1971 * becomes equal to or greater than half the number of
1972 * candidates, the Albanians have won the Byzantine wars and
1973 * correct synchronization is not possible.
1975 * Here, nlist is the number of candidates and allow is the
1976 * number of falsetickers. Upon exit, the truechimers are the
1977 * susvivors with offsets not less than low and not greater than
1978 * high. There may be none of them.
1982 for (allow = 0; 2 * allow < nlist; allow++) {
1986 * Bound the interval (low, high) as the largest
1987 * interval containing points from presumed truechimers.
1991 for (i = 0; i < nl3; i++) {
1992 low = endpoint[indx[i]].val;
1993 n -= endpoint[indx[i]].type;
1994 if (n >= nlist - allow)
1996 if (endpoint[indx[i]].type == 0)
2000 for (j = nl3 - 1; j >= 0; j--) {
2001 high = endpoint[indx[j]].val;
2002 n += endpoint[indx[j]].type;
2003 if (n >= nlist - allow)
2005 if (endpoint[indx[j]].type == 0)
2010 * If the number of candidates found outside the
2011 * interval is greater than the number of falsetickers,
2012 * then at least one truechimer is outside the interval,
2013 * so go around again. This is what makes this algorithm
2014 * different than Marzullo's.
2020 * If an interval containing truechimers is found, stop.
2021 * If not, increase the number of falsetickers and go
2029 * Clustering algorithm. Construct candidate list in order first
2030 * by stratum then by root distance, but keep only the best
2031 * NTP_MAXASSOC of them. Scan the list to find falsetickers, who
2032 * leave the island immediately. The TRUE peer is always a
2033 * truechimer. We must leave at least one peer to collect the
2034 * million bucks. If in orphan mode, rascals found with lower
2035 * stratum are guaranteed a seat on the bus.
2038 for (i = 0; i < nlist; i++) {
2039 peer = peer_list[i];
2040 if (nlist > 1 && (peer->offset <= low || peer->offset >=
2041 high) && !(peer->flags & FLAG_TRUE) &&
2042 !(sys_stratum >= sys_orphan && peer->stratum <
2046 peer->status = CTL_PST_SEL_DISTSYSPEER;
2049 * The order metric is formed from the stratum times
2050 * max distance (1.) plus the root distance. It strongly
2051 * favors the lowest stratum, but a higher stratum peer
2052 * can capture the clock if the low stratum dominant
2053 * hasn't been heard for awhile.
2055 d = root_distance(peer) + peer->stratum * sys_maxdist;
2056 if (j >= NTP_MAXASSOC) {
2057 if (d >= synch[j - 1])
2062 for (k = j; k > 0; k--) {
2063 if (d >= synch[k - 1])
2066 peer_list[k] = peer_list[k - 1];
2067 error[k] = error[k - 1];
2068 synch[k] = synch[k - 1];
2070 peer_list[k] = peer;
2071 error[k] = peer->jitter;
2078 * If no survivors remain at this point, check if the local
2079 * clock or modem drivers have been found. If so, nominate one
2080 * of them as the only survivor. Otherwise, give up and leave
2081 * the island to the rats.
2084 if (typeacts != 0) {
2085 typeacts->status = CTL_PST_SEL_DISTSYSPEER;
2086 peer_list[0] = typeacts;
2088 } else if (typelocal != 0) {
2089 typelocal->status = CTL_PST_SEL_DISTSYSPEER;
2090 peer_list[0] = typelocal;
2093 if (osys_peer != NULL) {
2094 NLOG(NLOG_SYNCSTATUS)
2096 "no servers reachable");
2097 report_event(EVNT_PEERSTCHG, NULL);
2103 * We can only trust the survivors if the number of candidates
2104 * sys_minsane is at least the number required to detect and
2105 * cast out one falsticker. For the Byzantine agreement
2106 * algorithm used here, that number is 4; however, the default
2107 * sys_minsane is 1 to speed initial synchronization. Careful
2108 * operators will tinker a higher value and use at least that
2109 * number of synchronization sources.
2111 if (nlist < sys_minsane)
2114 for (i = 0; i < nlist; i++)
2115 peer_list[i]->status = CTL_PST_SEL_SELCAND;
2118 * Now, vote outlyers off the island by select jitter weighted
2119 * by root distance. Continue voting as long as there are more
2120 * than sys_minclock survivors and the minimum select jitter is
2121 * greater than the maximum peer jitter. Stop if we are about to
2122 * discard a TRUE or PREFER peer, who of course has the
2130 for (i = 0; i < nlist; i++) {
2135 for (j = 0; j < nlist; j++)
2136 f += DIFF(peer_list[j]->offset,
2137 peer_list[i]->offset);
2138 f = SQRT(f / (nlist - 1));
2140 if (f * synch[i] > e) {
2146 f = max(f, LOGTOD(sys_precision));
2147 if (nlist <= sys_minclock || f <= d ||
2148 peer_list[k]->flags & (FLAG_TRUE | FLAG_PREFER))
2153 "select: drop %s select %.6f jitter %.6f\n",
2154 ntoa(&peer_list[k]->srcadr), g, d);
2156 for (j = k + 1; j < nlist; j++) {
2157 peer_list[j - 1] = peer_list[j];
2158 error[j - 1] = error[j];
2164 * What remains is a list usually not greater than sys_minclock
2165 * peers. We want only a peer at the lowest stratum to become
2166 * the system peer, although all survivors are eligible for the
2167 * combining algorithm. Consider each peer in turn and OR the
2168 * leap bits on the assumption that, if some of them honk
2169 * nonzero bits, they must know what they are doing. Check for
2170 * prefer and pps peers at any stratum. Note that the head of
2171 * the list is at the lowest stratum and that unsynchronized
2172 * peers cannot survive this far.
2175 for (i = 0; i < nlist; i++) {
2176 peer = peer_list[i];
2178 leap_next |= peer->leap;
2179 peer->status = CTL_PST_SEL_SYNCCAND;
2180 if (peer->flags & FLAG_PREFER)
2182 if (peer == osys_peer)
2185 if (peer->refclktype == REFCLK_ATOM_PPS)
2187 #endif /* REFCLOCK */
2190 printf("cluster: survivor %s metric %.6f\n",
2191 ntoa(&peer_list[i]->srcadr), synch[i]);
2196 * Anticlockhop provision. Keep the current system peer if it is
2197 * a survivor but not first in the list. But do that only HOPPER
2200 if (osys_peer == NULL || typesystem == NULL || typesystem ==
2201 peer_list[0] || sys_hopper > sys_maxhop) {
2202 typesystem = peer_list[0];
2209 * Mitigation rules of the game. There are several types of
2210 * peers that can be selected here: (1) orphan, (2) prefer peer
2211 * (flag FLAG_PREFER) (3) pps peers (type REFCLK_ATOM_PPS), (4)
2212 * the existing system peer, if any, and (5) the head of the
2215 if (typesystem->stratum >= sys_orphan) {
2218 * If in orphan mode, choose the system peer. If the
2219 * lowest distance, we are the orphan parent and the
2222 sys_peer = typesystem;
2223 sys_peer->status = CTL_PST_SEL_SYSPEER;
2224 if (sys_orphandelay < sys_peer->rootdelay) {
2226 sys_refid = htonl(LOOPBACKADR);
2228 sys_offset = sys_peer->offset;
2229 sys_refid = addr2refid(&sys_peer->srcadr);
2231 sys_jitter = LOGTOD(sys_precision);
2234 printf("select: orphan offset %.6f\n",
2237 } else if (sys_prefer) {
2240 * If a pps peer is present, choose it; otherwise,
2241 * choose the prefer peer.
2245 sys_peer->status = CTL_PST_SEL_PPS;
2246 sys_offset = sys_peer->offset;
2250 "pps sync enabled");
2251 pps_control = current_time;
2254 printf("select: pps offset %.6f\n",
2258 sys_peer = sys_prefer;
2259 sys_peer->status = CTL_PST_SEL_SYSPEER;
2260 sys_offset = sys_peer->offset;
2263 printf("select: prefer offset %.6f\n",
2267 if (sys_peer->stratum == STRATUM_REFCLOCK ||
2268 sys_peer->stratum == STRATUM_UNSPEC)
2269 sys_refid = sys_peer->refid;
2271 sys_refid = addr2refid(&sys_peer->srcadr);
2272 sys_jitter = sys_peer->jitter;
2276 * Otherwise, choose the anticlockhopper.
2278 sys_peer = typesystem;
2279 sys_peer->status = CTL_PST_SEL_SYSPEER;
2280 clock_combine(peer_list, nlist);
2281 if (sys_peer->stratum == STRATUM_REFCLOCK ||
2282 sys_peer->stratum == STRATUM_UNSPEC)
2283 sys_refid = sys_peer->refid;
2285 sys_refid = addr2refid(&sys_peer->srcadr);
2286 sys_jitter = SQRT(SQUARE(sys_peer->jitter) +
2287 SQUARE(sys_jitter));
2290 printf("select: combine offset %.6f\n",
2296 * We have found the alpha male.
2298 sys_peer->flags |= FLAG_SYSPEER;
2299 if (osys_peer != sys_peer) {
2302 report_event(EVNT_PEERSTCHG, NULL);
2305 if (sys_peer->flags & FLAG_REFCLOCK)
2306 src = refnumtoa(&sys_peer->srcadr);
2308 #endif /* REFCLOCK */
2309 src = ntoa(&sys_peer->srcadr);
2310 NLOG(NLOG_SYNCSTATUS)
2311 msyslog(LOG_INFO, "synchronized to %s, stratum %d",
2312 src, sys_peer->stratum);
2319 * clock_combine - compute system offset and jitter from selected peers
2323 struct peer **peers, /* survivor list */
2324 int npeers /* number of survivors */
2331 for (i = 0; i < npeers; i++) {
2332 x = root_distance(peers[i]);
2334 z += peers[i]->offset / x;
2335 w += SQUARE(peers[i]->offset - peers[0]->offset) / x;
2338 sys_jitter = SQRT(w / y);
2342 * root_distance - compute synchronization distance from peer to root
2352 * Careful squeak here. The value returned must be greater than
2353 * the minimum root dispersion in order to avoid clockhop with
2354 * highly precise reference clocks. In orphan mode lose the peer
2355 * root delay, as that is used by the election algorithm.
2357 if (peer->stratum >= sys_orphan)
2360 dist = peer->rootdelay;
2361 dist += max(sys_mindisp, dist + peer->delay) / 2 +
2362 peer->rootdispersion + peer->disp + clock_phi *
2363 (current_time - peer->update) + peer->jitter;
2368 * peer_xmit - send packet for persistent association.
2372 struct peer *peer /* peer structure pointer */
2375 struct pkt xpkt; /* transmit packet */
2376 int sendlen, authlen;
2377 keyid_t xkeyid = 0; /* transmit key ID */
2380 if (!peer->dstadr) /* don't bother with peers without interface */
2384 * This is deliciously complicated. There are three cases.
2386 * case leap stratum refid delay dispersion
2388 * normal system system system system system
2389 * orphan child 00 orphan system orphan system
2390 * orphan parent 00 orphan loopbk 0 0
2393 * This is a normal packet. Use the system variables.
2395 if (sys_stratum < sys_orphan) {
2396 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
2397 peer->version, peer->hmode);
2398 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
2399 xpkt.refid = sys_refid;
2400 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
2401 xpkt.rootdispersion =
2402 HTONS_FP(DTOUFP(sys_rootdispersion));
2405 * This is a orphan child packet. The host is synchronized to an
2406 * orphan parent. Show leap synchronized, orphan stratum, system
2407 * reference ID, orphan root delay and system root dispersion.
2409 } else if (sys_peer != NULL) {
2410 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOWARNING,
2411 peer->version, peer->hmode);
2412 xpkt.stratum = STRATUM_TO_PKT(sys_orphan);
2413 xpkt.refid = htonl(LOOPBACKADR);
2414 xpkt.rootdelay = HTONS_FP(DTOFP(sys_orphandelay));
2415 xpkt.rootdispersion =
2416 HTONS_FP(DTOUFP(sys_rootdispersion));
2419 * This is an orphan parent. Show leap synchronized, orphan
2420 * stratum, loopack reference ID and zero root delay and root
2424 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOWARNING,
2425 peer->version, peer->hmode);
2426 xpkt.stratum = STRATUM_TO_PKT(sys_orphan);
2427 xpkt.refid = sys_refid;
2429 xpkt.rootdispersion = 0;
2431 xpkt.ppoll = peer->hpoll;
2432 xpkt.precision = sys_precision;
2433 HTONL_FP(&sys_reftime, &xpkt.reftime);
2434 HTONL_FP(&peer->org, &xpkt.org);
2435 HTONL_FP(&peer->rec, &xpkt.rec);
2438 * If the received packet contains a MAC, the transmitted packet
2439 * is authenticated and contains a MAC. If not, the transmitted
2440 * packet is not authenticated.
2442 * It is most important when autokey is in use that the local
2443 * interface IP address be known before the first packet is
2444 * sent. Otherwise, it is not possible to compute a correct MAC
2445 * the recipient will accept. Thus, the I/O semantics have to do
2446 * a little more work. In particular, the wildcard interface
2447 * might not be usable.
2449 sendlen = LEN_PKT_NOMAC;
2450 if (!(peer->flags & FLAG_AUTHENABLE)) {
2451 get_systime(&peer->xmt);
2452 HTONL_FP(&peer->xmt, &xpkt.xmt);
2453 sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl],
2458 printf("transmit: at %ld %s->%s mode %d\n",
2459 current_time, peer->dstadr ? stoa(&peer->dstadr->sin) : "-",
2460 stoa(&peer->srcadr), peer->hmode);
2466 * The received packet contains a MAC, so the transmitted packet
2467 * must be authenticated. If autokey is enabled, fuss with the
2468 * various modes; otherwise, symmetric key cryptography is used.
2471 if (crypto_flags && (peer->flags & FLAG_SKEY)) {
2472 struct exten *exten; /* extension field */
2475 * The Public Key Dance (PKD): Cryptographic credentials
2476 * are contained in extension fields, each including a
2477 * 4-octet length/code word followed by a 4-octet
2478 * association ID and optional additional data. Optional
2479 * data includes a 4-octet data length field followed by
2480 * the data itself. Request messages are sent from a
2481 * configured association; response messages can be sent
2482 * from a configured association or can take the fast
2483 * path without ever matching an association. Response
2484 * messages have the same code as the request, but have
2485 * a response bit and possibly an error bit set. In this
2486 * implementation, a message may contain no more than
2487 * one command and no more than one response.
2489 * Cryptographic session keys include both a public and
2490 * a private componet. Request and response messages
2491 * using extension fields are always sent with the
2492 * private component set to zero. Packets without
2493 * extension fields indlude the private component when
2494 * the session key is generated.
2499 * Allocate and initialize a keylist if not
2500 * already done. Then, use the list in inverse
2501 * order, discarding keys once used. Keep the
2502 * latest key around until the next one, so
2503 * clients can use client/server packets to
2504 * compute propagation delay.
2506 * Note that once a key is used from the list,
2507 * it is retained in the key cache until the
2508 * next key is used. This is to allow a client
2509 * to retrieve the encrypted session key
2510 * identifier to verify authenticity.
2512 * If for some reason a key is no longer in the
2513 * key cache, a birthday has happened and the
2514 * pseudo-random sequence is probably broken. In
2515 * that case, purge the keylist and regenerate
2518 if (peer->keynumber == 0)
2519 make_keylist(peer, peer->dstadr);
2522 xkeyid = peer->keylist[peer->keynumber];
2523 if (authistrusted(xkeyid))
2528 peer->keyid = xkeyid;
2530 switch (peer->hmode) {
2533 * In broadcast server mode the autokey values are
2534 * required by the broadcast clients. Push them when a
2535 * new keylist is generated; otherwise, push the
2536 * association message so the client can request them at
2539 case MODE_BROADCAST:
2540 if (peer->flags & FLAG_ASSOC)
2541 exten = crypto_args(peer, CRYPTO_AUTO |
2544 exten = crypto_args(peer, CRYPTO_ASSOC |
2549 * In symmetric modes the digest, certificate, agreement
2550 * parameters, cookie and autokey values are required.
2551 * The leapsecond table is optional. But, a passive peer
2552 * will not believe the active peer until the latter has
2553 * synchronized, so the agreement must be postponed
2554 * until then. In any case, if a new keylist is
2555 * generated, the autokey values are pushed.
2557 * If the crypto bit is lit, don't send requests.
2561 if (peer->flash & TEST9)
2564 * Parameter and certificate.
2567 exten = crypto_args(peer, CRYPTO_ASSOC,
2569 else if (!(peer->crypto & CRYPTO_FLAG_VALID))
2570 exten = crypto_args(peer, CRYPTO_CERT,
2574 * Identity. Note we have to sign the
2575 * certificate before the cookie to avoid a
2576 * deadlock when the passive peer is walking the
2577 * certificate trail. Awesome.
2579 else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
2580 exten = crypto_args(peer,
2581 crypto_ident(peer), NULL);
2582 else if (sys_leap != LEAP_NOTINSYNC &&
2583 !(peer->crypto & CRYPTO_FLAG_SIGN))
2584 exten = crypto_args(peer, CRYPTO_SIGN,
2588 * Autokey. We request the cookie only when the
2589 * server and client are synchronized and
2590 * signatures work both ways. On the other hand,
2591 * the active peer needs the autokey values
2592 * before then and when the passive peer is
2593 * waiting for the active peer to synchronize.
2594 * Any time we regenerate the key list, we offer
2595 * the autokey values without being asked.
2597 else if (sys_leap != LEAP_NOTINSYNC &&
2598 peer->leap != LEAP_NOTINSYNC &&
2599 !(peer->crypto & CRYPTO_FLAG_AGREE))
2600 exten = crypto_args(peer, CRYPTO_COOK,
2602 else if (peer->flags & FLAG_ASSOC)
2603 exten = crypto_args(peer, CRYPTO_AUTO |
2605 else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
2606 exten = crypto_args(peer, CRYPTO_AUTO,
2610 * Postamble. We trade leapseconds only when the
2611 * server and client are synchronized.
2613 else if (sys_leap != LEAP_NOTINSYNC &&
2614 peer->leap != LEAP_NOTINSYNC &&
2615 peer->crypto & CRYPTO_FLAG_TAI &&
2616 !(peer->crypto & CRYPTO_FLAG_LEAP))
2617 exten = crypto_args(peer, CRYPTO_TAI,
2622 * In client mode the digest, certificate, agreement
2623 * parameters and cookie are required. The leapsecond
2624 * table is optional. If broadcast client mode, the
2625 * autokey values are required as well. In broadcast
2626 * client mode, these values must be acquired during the
2627 * client/server exchange to avoid having to wait until
2628 * the next key list regeneration. Otherwise, the poor
2629 * dude may die a lingering death until becoming
2630 * unreachable and attempting rebirth.
2632 * If neither the server or client have the agreement
2633 * parameters, the protocol transmits the cookie in the
2634 * clear. If the server has the parameters, the client
2635 * requests them and the protocol blinds it using the
2636 * agreed key. It is a protocol error if the client has
2637 * the parameters but the server does not.
2639 * If the crypto bit is lit, don't send requests.
2642 if (peer->flash & TEST9)
2645 * Parameter and certificate.
2648 exten = crypto_args(peer, CRYPTO_ASSOC,
2650 else if (!(peer->crypto & CRYPTO_FLAG_VALID))
2651 exten = crypto_args(peer, CRYPTO_CERT,
2657 else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
2658 exten = crypto_args(peer,
2659 crypto_ident(peer), NULL);
2664 else if (!(peer->crypto & CRYPTO_FLAG_AGREE))
2665 exten = crypto_args(peer, CRYPTO_COOK,
2667 else if (!(peer->crypto & CRYPTO_FLAG_AUTO) &&
2668 (peer->cast_flags & MDF_BCLNT))
2669 exten = crypto_args(peer, CRYPTO_AUTO,
2673 * Postamble. We can sign the certificate here,
2674 * since there is no chance of deadlock.
2676 else if (sys_leap != LEAP_NOTINSYNC &&
2677 !(peer->crypto & CRYPTO_FLAG_SIGN))
2678 exten = crypto_args(peer, CRYPTO_SIGN,
2680 else if (sys_leap != LEAP_NOTINSYNC &&
2681 peer->crypto & CRYPTO_FLAG_TAI &&
2682 !(peer->crypto & CRYPTO_FLAG_LEAP))
2683 exten = crypto_args(peer, CRYPTO_TAI,
2689 * Build the extension fields as directed. A response to
2690 * a request is always sent, even if an error. If an
2691 * error occurs when sending a request, the crypto
2692 * machinery broke or was misconfigured. In that case
2693 * light the crypto bit to suppress further requests.
2695 if (peer->cmmd != NULL) {
2696 peer->cmmd->associd = htonl(peer->associd);
2697 sendlen += crypto_xmit(&xpkt, &peer->srcadr,
2698 sendlen, peer->cmmd, 0);
2702 if (exten != NULL) {
2705 if (exten->opcode != 0) {
2706 ltemp = crypto_xmit(&xpkt,
2707 &peer->srcadr, sendlen, exten, 0);
2709 peer->flash |= TEST9; /* crypto error */
2719 * If extension fields are present, we must use a
2720 * private cookie value of zero. Don't send if the
2721 * crypto bit is set and no extension field is present,
2722 * but in that case give back the key. Most intricate.
2724 if (sendlen > LEN_PKT_NOMAC) {
2725 session_key(&peer->dstadr->sin, &peer->srcadr,
2727 } else if (peer->flash & TEST9) {
2728 authtrust(xkeyid, 0);
2732 #endif /* OPENSSL */
2735 * Stash the transmit timestamp corrected for the encryption
2736 * delay. If autokey, give back the key, as we use keys only
2737 * once. Check for errors such as missing keys, buffer overflow,
2740 xkeyid = peer->keyid;
2741 get_systime(&peer->xmt);
2742 L_ADD(&peer->xmt, &sys_authdelay);
2743 HTONL_FP(&peer->xmt, &xpkt.xmt);
2744 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2746 msyslog(LOG_INFO, "transmit: %s key %u not found",
2747 stoa(&peer->srcadr), xkeyid);
2748 peer->flash |= TEST9; /* no key found */
2753 if (xkeyid > NTP_MAXKEY)
2754 authtrust(xkeyid, 0);
2755 #endif /* OPENSSL */
2756 get_systime(&xmt_tx);
2757 if (sendlen > sizeof(xpkt)) {
2758 msyslog(LOG_ERR, "buffer overflow %u", sendlen);
2761 sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl], &xpkt,
2765 * Calculate the encryption delay. Keep the minimum over
2766 * the latest two samples.
2768 L_SUB(&xmt_tx, &peer->xmt);
2769 L_ADD(&xmt_tx, &sys_authdelay);
2770 sys_authdly[1] = sys_authdly[0];
2771 sys_authdly[0] = xmt_tx.l_uf;
2772 if (sys_authdly[0] < sys_authdly[1])
2773 sys_authdelay.l_uf = sys_authdly[0];
2775 sys_authdelay.l_uf = sys_authdly[1];
2781 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d index %d\n",
2782 current_time, peer->dstadr ? ntoa(&peer->dstadr->sin) : "-",
2783 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen -
2784 authlen, authlen, peer->keynumber);
2790 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
2791 current_time, peer->dstadr ? ntoa(&peer->dstadr->sin) : "-",
2792 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen -
2795 #endif /* OPENSSL */
2800 * fast_xmit - Send packet for nonpersistent association. Note that
2801 * neither the source or destination can be a broadcast address.
2805 struct recvbuf *rbufp, /* receive packet pointer */
2806 int xmode, /* transmit mode */
2807 keyid_t xkeyid, /* transmit key ID */
2808 int mask /* restrict mask */
2811 struct pkt xpkt; /* transmit packet structure */
2812 struct pkt *rpkt; /* receive packet structure */
2813 l_fp xmt_ts; /* timestamp */
2814 l_fp xmt_tx; /* timestamp after authent */
2815 int sendlen, authlen;
2821 * Initialize transmit packet header fields from the receive
2822 * buffer provided. We leave some fields intact as received. If
2823 * the gazinta was from a multicast address, the gazoutta must
2824 * go out another way.
2826 * The root delay field is special. If the system stratum is
2827 * less than the orphan stratum, send the real root delay.
2828 * Otherwise, if there is no system peer, send the orphan delay.
2829 * Otherwise, we must be an orphan parent, so send zero.
2831 rpkt = &rbufp->recv_pkt;
2832 if (rbufp->dstadr->flags & INT_MCASTOPEN)
2833 rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
2836 * This is deliciously complicated. There are four cases.
2838 * case leap stratum refid delay dispersion
2840 * KoD 11 16 KISS system system
2841 * normal system system system system system
2842 * orphan child 00 orphan system orphan system
2843 * orphan parent 00 orphan loopbk 0 0
2846 * This is a kiss-of-death (KoD) packet. Show leap
2847 * unsynchronized, stratum zero, reference ID the four-character
2848 * kiss code and system root delay. Note the rate limit on these
2849 * packets. Once a second initialize a bucket counter. Every
2850 * packet sent decrements the counter until reaching zero. If
2851 * the counter is zero, drop the kiss.
2853 if (mask & RES_LIMITED) {
2854 sys_limitrejected++;
2855 if (sys_kod == 0 || !(mask & RES_DEMOBILIZE))
2859 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
2860 PKT_VERSION(rpkt->li_vn_mode), xmode);
2861 xpkt.stratum = STRATUM_UNSPEC;
2862 memcpy(&xpkt.refid, "RATE", 4);
2863 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
2864 xpkt.rootdispersion =
2865 HTONS_FP(DTOUFP(sys_rootdispersion));
2868 * This is a normal packet. Use the system variables.
2870 } else if (sys_stratum < sys_orphan) {
2871 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
2872 PKT_VERSION(rpkt->li_vn_mode), xmode);
2873 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
2874 xpkt.refid = sys_refid;
2875 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
2876 xpkt.rootdispersion =
2877 HTONS_FP(DTOUFP(sys_rootdispersion));
2880 * This is a orphan child packet. The host is synchronized to an
2881 * orphan parent. Show leap synchronized, orphan stratum, system
2882 * reference ID and orphan root delay.
2884 } else if (sys_peer != NULL) {
2885 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOWARNING,
2886 PKT_VERSION(rpkt->li_vn_mode), xmode);
2887 xpkt.stratum = STRATUM_TO_PKT(sys_orphan);
2888 xpkt.refid = sys_refid;
2889 xpkt.rootdelay = HTONS_FP(DTOFP(sys_orphandelay));
2890 xpkt.rootdispersion =
2891 HTONS_FP(DTOUFP(sys_rootdispersion));
2894 * This is an orphan parent. Show leap synchronized, orphan
2895 * stratum, loopack reference ID and zero root delay.
2898 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOWARNING,
2899 PKT_VERSION(rpkt->li_vn_mode), xmode);
2900 xpkt.stratum = STRATUM_TO_PKT(sys_orphan);
2901 xpkt.refid = htonl(LOOPBACKADR);
2902 xpkt.rootdelay = HTONS_FP(DTOFP(0));
2903 xpkt.rootdispersion = HTONS_FP(DTOFP(0));
2905 xpkt.ppoll = rpkt->ppoll;
2906 xpkt.precision = sys_precision;
2907 xpkt.rootdispersion = HTONS_FP(DTOUFP(sys_rootdispersion));
2908 HTONL_FP(&sys_reftime, &xpkt.reftime);
2909 xpkt.org = rpkt->xmt;
2910 HTONL_FP(&rbufp->recv_time, &xpkt.rec);
2913 * If the received packet contains a MAC, the transmitted packet
2914 * is authenticated and contains a MAC. If not, the transmitted
2915 * packet is not authenticated.
2917 sendlen = LEN_PKT_NOMAC;
2918 if (rbufp->recv_length == sendlen) {
2919 get_systime(&xmt_ts);
2920 HTONL_FP(&xmt_ts, &xpkt.xmt);
2921 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
2925 printf("transmit: at %ld %s->%s mode %d\n",
2926 current_time, stoa(&rbufp->dstadr->sin),
2927 stoa(&rbufp->recv_srcadr), xmode);
2933 * The received packet contains a MAC, so the transmitted packet
2934 * must be authenticated. For symmetric key cryptography, use
2935 * the predefined and trusted symmetric keys to generate the
2936 * cryptosum. For autokey cryptography, use the server private
2937 * value to generate the cookie, which is unique for every
2938 * source-destination-key ID combination.
2941 if (xkeyid > NTP_MAXKEY) {
2945 * The only way to get here is a reply to a legitimate
2946 * client request message, so the mode must be
2947 * MODE_SERVER. If an extension field is present, there
2948 * can be only one and that must be a command. Do what
2949 * needs, but with private value of zero so the poor
2950 * jerk can decode it. If no extension field is present,
2951 * use the cookie to generate the session key.
2953 cookie = session_key(&rbufp->recv_srcadr,
2954 &rbufp->dstadr->sin, 0, sys_private, 0);
2955 if (rbufp->recv_length >= (int)(sendlen + MAX_MAC_LEN +
2956 2 * sizeof(u_int32))) {
2957 session_key(&rbufp->dstadr->sin,
2958 &rbufp->recv_srcadr, xkeyid, 0, 2);
2959 temp32 = CRYPTO_RESP;
2960 rpkt->exten[0] |= htonl(temp32);
2961 sendlen += crypto_xmit(&xpkt,
2962 &rbufp->recv_srcadr, sendlen,
2963 (struct exten *)rpkt->exten, cookie);
2965 session_key(&rbufp->dstadr->sin,
2966 &rbufp->recv_srcadr, xkeyid, cookie, 2);
2969 #endif /* OPENSSL */
2970 get_systime(&xmt_ts);
2971 L_ADD(&xmt_ts, &sys_authdelay);
2972 HTONL_FP(&xmt_ts, &xpkt.xmt);
2973 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2976 if (xkeyid > NTP_MAXKEY)
2977 authtrust(xkeyid, 0);
2978 #endif /* OPENSSL */
2979 get_systime(&xmt_tx);
2980 if (sendlen > sizeof(xpkt)) {
2981 msyslog(LOG_ERR, "buffer overflow %u", sendlen);
2984 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
2987 * Calculate the encryption delay. Keep the minimum over the
2988 * latest two samples.
2990 L_SUB(&xmt_tx, &xmt_ts);
2991 L_ADD(&xmt_tx, &sys_authdelay);
2992 sys_authdly[1] = sys_authdly[0];
2993 sys_authdly[0] = xmt_tx.l_uf;
2994 if (sys_authdly[0] < sys_authdly[1])
2995 sys_authdelay.l_uf = sys_authdly[0];
2997 sys_authdelay.l_uf = sys_authdly[1];
3001 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
3002 current_time, ntoa(&rbufp->dstadr->sin),
3003 ntoa(&rbufp->recv_srcadr), xmode, xkeyid, sendlen -
3011 * key_expire - purge the key list
3015 struct peer *peer /* peer structure pointer */
3020 if (peer->keylist != NULL) {
3021 for (i = 0; i <= peer->keynumber; i++)
3022 authtrust(peer->keylist[i], 0);
3023 free(peer->keylist);
3024 peer->keylist = NULL;
3026 value_free(&peer->sndval);
3027 peer->keynumber = 0;
3030 printf("key_expire: at %lu\n", current_time);
3033 #endif /* OPENSSL */
3037 * Determine if the peer is unfit for synchronization
3039 * A peer is unfit for synchronization if
3040 * > TEST10 bad leap or stratum below floor or at or above ceiling
3041 * > TEST11 root distance exceeded
3042 * > TEST12 a direct or indirect synchronization loop would form
3043 * > TEST13 unreachable or noselect
3045 int /* FALSE if fit, TRUE if unfit */
3047 struct peer *peer /* peer structure pointer */
3053 * A stratum error occurs if (1) the server has never been
3054 * synchronized, (2) the server stratum is below the floor or
3055 * greater than or equal to the ceiling, (3) the system stratum
3056 * is below the orphan stratum and the server stratum is greater
3057 * than or equal to the orphan stratum.
3059 if (peer->leap == LEAP_NOTINSYNC || peer->stratum < sys_floor ||
3060 peer->stratum >= sys_ceiling || (sys_stratum < sys_orphan &&
3061 peer->stratum >= sys_orphan))
3062 rval |= TEST10; /* stratum out of bounds */
3065 * A distance error occurs if the root distance is greater than
3066 * or equal to the distance threshold plus the increment due to
3067 * one poll interval.
3069 if (root_distance(peer) >= sys_maxdist + clock_phi *
3071 rval |= TEST11; /* distance exceeded */
3074 * A loop error occurs if the remote peer is synchronized to the
3075 * local peer of if the remote peer is synchronized to the same
3076 * server as the local peer, but only if the remote peer is not
3077 * the orphan parent.
3079 if (peer->stratum > 1 && peer->refid != htonl(LOOPBACKADR) &&
3080 ((!peer->dstadr || peer->refid == peer->dstadr->addr_refid) ||
3081 peer->refid == sys_refid))
3082 rval |= TEST12; /* synch loop */
3085 * An unreachable error occurs if the server is unreachable or
3086 * the noselect bit is set.
3088 if (!peer->reach || peer->flags & FLAG_NOSELECT)
3089 rval |= TEST13; /* unreachable */
3091 peer->flash &= ~PEER_TEST_MASK;
3092 peer->flash |= rval;
3098 * Find the precision of this particular machine
3100 #define MINSTEP 100e-9 /* minimum clock increment (s) */
3101 #define MAXSTEP 20e-3 /* maximum clock increment (s) */
3102 #define MINLOOPS 5 /* minimum number of step samples */
3105 * This routine calculates the system precision, defined as the minimum
3106 * of a sequence of differences between successive readings of the
3107 * system clock. However, if the system clock can be read more than once
3108 * during a tick interval, the difference can be zero or one LSB unit,
3109 * where the LSB corresponds to one nanosecond or one microsecond.
3110 * Conceivably, if some other process preempts this one and reads the
3111 * clock, the difference can be more than one LSB unit.
3113 * For hardware clock frequencies of 10 MHz or less, we assume the
3114 * logical clock advances only at the hardware clock tick. For higher
3115 * frequencies, we assume the logical clock can advance no more than 100
3116 * nanoseconds between ticks.
3119 default_get_precision(void)
3121 l_fp val; /* current seconds fraction */
3122 l_fp last; /* last seconds fraction */
3123 l_fp diff; /* difference */
3124 double tick; /* computed tick value */
3125 double dtemp; /* scratch */
3126 int i; /* log2 precision */
3129 * Loop to find tick value in nanoseconds. Toss out outlyer
3130 * values less than the minimun tick value. In wacky cases, use
3131 * the default maximum value.
3135 for (i = 0; i < MINLOOPS;) {
3138 L_SUB(&diff, &last);
3140 LFPTOD(&diff, dtemp);
3141 if (dtemp < MINSTEP)
3149 * Find the nearest power of two.
3152 msyslog(LOG_INFO, "precision = %.3f usec", tick * 1e6);
3153 for (i = 0; tick <= 1; i++)
3155 if (tick - 1. > 1. - tick / 2)
3162 * kod_proto - called once per second to limit kiss-of-death packets
3167 sys_kod = sys_kod_rate;
3172 * init_proto - initialize the protocol module's data
3181 * Fill in the sys_* stuff. Default is don't listen to
3182 * broadcasting, authenticate.
3184 sys_leap = LEAP_NOTINSYNC;
3185 sys_stratum = STRATUM_UNSPEC;
3186 memcpy(&sys_refid, "INIT", 4);
3187 sys_precision = (s_char)default_get_precision();
3188 sys_jitter = LOGTOD(sys_precision);
3190 sys_orphandelay = (double)(ntp_random() & 0xffff) / 65536. *
3192 sys_rootdispersion = 0;
3193 L_CLR(&sys_reftime);
3196 get_systime(&dummy);
3197 sys_manycastserver = 0;
3199 sys_bdelay = DEFBROADDELAY;
3200 sys_calldelay = BURST_DELAY;
3201 sys_authenticate = 1;
3202 L_CLR(&sys_authdelay);
3203 sys_authdly[0] = sys_authdly[1] = 0;
3206 for (i = 0; i < MAX_TTL; i++) {
3207 sys_ttl[i] = (u_char)((i * 256) / MAX_TTL);
3211 sys_automax = 1 << NTP_AUTOMAX;
3212 #endif /* OPENSSL */
3215 * Default these to enable
3218 #ifndef KERNEL_FLL_BUG
3227 * proto_config - configure the protocol module
3234 struct sockaddr_storage* svalue
3238 * Figure out what he wants to change, then do it
3243 * Turn on/off kernel discipline.
3246 kern_enable = (int)value;
3250 * Turn on/off clock discipline.
3253 ntp_enable = (int)value;
3257 * Turn on/off monitoring.
3267 * Turn on/off statistics.
3270 stats_control = (int)value;
3274 * Turn on/off enable broadcasts.
3276 case PROTO_BROADCLIENT:
3277 sys_bclient = (int)value;
3278 if (sys_bclient == 0)
3285 * Turn on/off PPS discipline.
3288 pps_enable = (int)value;
3292 * Add muliticast group address.
3294 case PROTO_MULTICAST_ADD:
3296 io_multicast_add(*svalue);
3301 * Delete multicast group address.
3303 case PROTO_MULTICAST_DEL:
3305 io_multicast_del(*svalue);
3309 * Set default broadcast delay.
3311 case PROTO_BROADDELAY:
3312 sys_bdelay = dvalue;
3316 * Set modem call delay.
3318 case PROTO_CALLDELAY:
3319 sys_calldelay = (int)value;
3323 * Turn on/off authentication to mobilize ephemeral
3326 case PROTO_AUTHENTICATE:
3327 sys_authenticate = (int)value;
3331 * Set minimum number of survivors.
3333 case PROTO_MINCLOCK:
3334 sys_minclock = (int)dvalue;
3338 * Set maximum number of preemptable associations.
3340 case PROTO_MAXCLOCK:
3341 sys_maxclock = (int)dvalue;
3345 * Set minimum number of survivors.
3348 sys_minsane = (int)dvalue;
3352 * Set stratum floor.
3355 sys_floor = (int)dvalue;
3359 * Set stratum ceiling.
3362 sys_ceiling = (int)dvalue;
3366 * Set orphan stratum.
3369 sys_orphan = (int)dvalue;
3373 * Set cohort switch.
3376 sys_cohort = (int)dvalue;
3380 * Set minimum dispersion increment.
3383 sys_mindisp = dvalue;
3387 * Set maximum distance (select threshold).
3390 sys_maxdist = dvalue;
3394 * Set anticlockhop threshold.
3397 sys_maxhop = (int)dvalue;
3401 * Set adjtime() resolution (s).
3408 * Set manycast beacon interval.
3411 sys_beacon = (int)dvalue;
3416 * Turn on/off refclock calibrate
3419 cal_enable = (int)value;
3421 #endif /* REFCLOCK */
3428 "proto_config: illegal item %d, value %ld", item,
3435 * proto_clr_stats - clear protocol stat counters
3438 proto_clr_stats(void)
3440 sys_stattime = current_time;
3443 sys_newversionpkt = 0;
3444 sys_oldversionpkt = 0;
3445 sys_unknownversion = 0;
3449 sys_limitrejected = 0;