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 * System variables are declared here. See Section 3.2 of the
31 u_char sys_leap; /* system leap indicator */
32 u_char sys_stratum; /* stratum of system */
33 s_char sys_precision; /* local clock precision */
34 double sys_rootdelay; /* roundtrip delay to primary source */
35 double sys_rootdispersion; /* dispersion to primary source */
36 u_int32 sys_refid; /* reference source for local clock */
37 u_int32 sys_peer_refid; /* hashed refid of our current peer */
38 static double sys_offset; /* current local clock offset */
39 l_fp sys_reftime; /* time we were last updated */
40 struct peer *sys_peer; /* our current peer */
41 struct peer *sys_prefer; /* our cherished peer */
42 int sys_kod; /* kod credit */
43 int sys_kod_rate = 2; /* max kod packets per second */
45 u_long sys_automax; /* maximum session key lifetime */
49 * Nonspecified system state variables.
51 int sys_bclient; /* broadcast client enable */
52 double sys_bdelay; /* broadcast client default delay */
53 int sys_calldelay; /* modem callup delay (s) */
54 int sys_authenticate; /* requre authentication for config */
55 l_fp sys_authdelay; /* authentication delay */
56 static u_long sys_authdly[2]; /* authentication delay shift reg */
57 static u_char leap_consensus; /* consensus of survivor leap bits */
58 static double sys_selerr; /* select error (squares) */
59 static double sys_syserr; /* system error (squares) */
60 keyid_t sys_private; /* private value for session seed */
61 int sys_manycastserver; /* respond to manycast client pkts */
62 int peer_ntpdate; /* active peers in ntpdate mode */
63 int sys_survivors; /* truest of the truechimers */
65 char *sys_hostname; /* gethostname() name */
69 * TOS and multicast mapping stuff
71 int sys_floor = 1; /* cluster stratum floor */
72 int sys_ceiling = STRATUM_UNSPEC; /* cluster stratum ceiling*/
73 int sys_minsane = 1; /* minimum candidates */
74 int sys_minclock = NTP_MINCLOCK; /* minimum survivors */
75 int sys_cohort = 0; /* cohort switch */
76 int sys_ttlmax; /* max ttl mapping vector index */
77 u_char sys_ttl[MAX_TTL]; /* ttl mapping vector */
82 u_long sys_stattime; /* time since reset */
83 u_long sys_received; /* packets received */
84 u_long sys_processed; /* packets processed */
85 u_long sys_newversionpkt; /* current version */
86 u_long sys_oldversionpkt; /* recent version */
87 u_long sys_unknownversion; /* invalid version */
88 u_long sys_restricted; /* access denied */
89 u_long sys_badlength; /* bad length or format */
90 u_long sys_badauth; /* bad authentication */
91 u_long sys_limitrejected; /* rate exceeded */
93 static double root_distance P((struct peer *));
94 static double clock_combine P((struct peer **, int));
95 static void peer_xmit P((struct peer *));
96 static void fast_xmit P((struct recvbuf *, int, keyid_t, int));
97 static void clock_update P((void));
98 int default_get_precision P((void));
99 static int peer_unfit P((struct peer *));
102 * transmit - Transmit Procedure. See Section 3.4.2 of the
107 struct peer *peer /* peer structure pointer */
114 * The polling state machine. There are two kinds of machines,
115 * those that never expect a reply (broadcast and manycast
116 * server modes) and those that do (all other modes). The dance
120 if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
123 * In broadcast mode the poll interval is fixed
126 hpoll = peer->minpoll;
127 } else if (peer->cast_flags & MDF_ACAST) {
130 * In manycast mode we start with the minpoll interval
131 * and ttl. However, the actual poll interval is eight
132 * times the nominal poll interval shown here. If fewer
133 * than sys_minclock servers are found, the ttl is
134 * increased by one and we try again. If this continues
135 * to the max ttl, the poll interval is bumped by one
136 * and we try again. If at least sys_minclock servers
137 * are found, the poll interval increases with the
138 * system poll interval to the max and we continue
139 * indefinately. However, about once per day when the
140 * agreement parameters are refreshed, the manycast
141 * clients are reset and we start from the beginning.
142 * This is to catch and clamp the ttl to the lowest
143 * practical value and avoid knocking on spurious doors.
145 if (sys_survivors < sys_minclock && peer->ttl <
152 * For associations expecting a reply, the watchdog
153 * counter is bumped by one if the peer has not been
154 * heard since the previous poll. If the counter reaches
155 * the max, the poll interval is doubled and the peer is
156 * demobilized if not configured.
159 if (peer->unreach >= NTP_UNREACH) {
161 if (peer->flags & FLAG_CONFIG) {
164 * If nothing is likely to change in
165 * future, flash the access denied bit
166 * so we won't bother the dude again.
168 if (memcmp((char *)&peer->refid,
170 memcmp((char *)&peer->refid,
172 peer->flash |= TEST4;
178 if (peer->burst == 0) {
181 oreach = peer->reach;
183 peer->hyst *= HYST_TC;
184 if (peer->reach == 0) {
187 * If this association has become
188 * unreachable, clear it and raise a
192 report_event(EVNT_UNREACH,
194 peer->timereachable =
196 if (peer->flags & FLAG_CONFIG) {
204 if (peer->flags & FLAG_IBURST)
205 peer->burst = NTP_BURST;
208 * Here the peer is reachable. If it has
209 * not been heard for three consecutive
210 * polls, stuff the clock filter. Next,
211 * determine the poll interval. If the
212 * peer is unfit for synchronization,
213 * increase it by one; otherwise, use
214 * the system poll interval.
216 if (!(peer->reach & 0x07)) {
217 clock_filter(peer, 0., 0.,
221 if (peer_unfit(peer))
225 if (peer->flags & FLAG_BURST)
226 peer->burst = NTP_BURST;
231 * Source rate control. If we are restrained,
232 * each burst consists of only one packet.
234 if (memcmp((char *)&peer->refid, "RSTR", 4) ==
239 if (peer->burst == 0) {
241 * If a broadcast client at this point,
242 * the burst has concluded, so we switch
243 * to client mode and purge the keylist,
244 * since no further transmissions will
247 if (peer->cast_flags & MDF_BCLNT) {
248 peer->hmode = MODE_BCLIENT;
253 poll_update(peer, hpoll);
257 * If ntpdate mode and the clock has not
258 * been set and all peers have completed
259 * the burst, we declare a successful
264 if (peer_ntpdate > 0) {
270 "no reply; clock not set");
273 poll_update(peer, hpoll);
278 peer->outdate = current_time;
281 * Do not transmit if in broadcast cclient mode or access has
284 if (peer->hmode == MODE_BCLIENT || peer->flash & TEST4) {
285 poll_update(peer, hpoll);
289 * Do not transmit in broadcast mode unless we are synchronized.
291 } else if (peer->hmode == MODE_BROADCAST && sys_peer == NULL) {
292 poll_update(peer, hpoll);
296 poll_update(peer, hpoll);
300 * receive - Receive Procedure. See section 3.4.3 in the specification.
304 struct recvbuf *rbufp
307 register struct peer *peer; /* peer structure pointer */
308 register struct pkt *pkt; /* receive packet pointer */
309 int hismode; /* packet mode */
310 int restrict_mask; /* restrict bits */
311 int has_mac; /* length of MAC field */
312 int authlen; /* offset of MAC field */
313 int is_authentic; /* cryptosum ok */
314 keyid_t skeyid = 0; /* key ID */
315 struct sockaddr_storage *dstadr_sin; /* active runway */
316 struct peer *peer2; /* aux peer structure pointer */
317 l_fp p_org; /* originate timestamp */
318 l_fp p_xmt; /* transmit timestamp */
320 keyid_t tkeyid = 0; /* temporary key ID */
321 keyid_t pkeyid = 0; /* previous key ID */
322 struct autokey *ap; /* autokey structure pointer */
323 int rval; /* cookie snatcher */
325 int retcode = AM_NOMATCH;
328 * Monitor the packet and get restrictions. Note that the packet
329 * length for control and private mode packets must be checked
330 * by the service routines. Note that no statistics counters are
331 * recorded for restrict violations, since these counters are in
332 * the restriction routine. Note the careful distinctions here
333 * between a packet with a format error and a packet that is
334 * simply discarded without prejudice. Some restrictions have to
335 * be handled later in order to generate a kiss-of-death packet.
338 * Bogus port check is before anything, since it probably
339 * reveals a clogging attack.
342 if (SRCPORT(&rbufp->recv_srcadr) == 0) {
344 return; /* bogus port */
347 restrict_mask = restrictions(&rbufp->recv_srcadr);
350 printf("receive: at %ld %s<-%s restrict %03x\n",
351 current_time, stoa(&rbufp->dstadr->sin),
352 stoa(&rbufp->recv_srcadr), restrict_mask);
354 if (restrict_mask & RES_IGNORE) {
356 return; /* no anything */
358 pkt = &rbufp->recv_pkt;
359 hismode = (int)PKT_MODE(pkt->li_vn_mode);
360 if (hismode == MODE_PRIVATE) {
361 if (restrict_mask & RES_NOQUERY) {
363 return; /* no query private */
365 process_private(rbufp, ((restrict_mask &
366 RES_NOMODIFY) == 0));
369 if (hismode == MODE_CONTROL) {
370 if (restrict_mask & RES_NOQUERY) {
372 return; /* no query control */
374 process_control(rbufp, restrict_mask);
377 if (restrict_mask & RES_DONTSERVE) {
379 return; /* no time */
381 if (rbufp->recv_length < LEN_PKT_NOMAC) {
383 return; /* runt packet */
387 * Version check must be after the query packets, since they
388 * intentionally use early version.
390 if (PKT_VERSION(pkt->li_vn_mode) == NTP_VERSION) {
391 sys_newversionpkt++; /* new version */
392 } else if (!(restrict_mask & RES_VERSION) &&
393 PKT_VERSION(pkt->li_vn_mode) >= NTP_OLDVERSION) {
394 sys_oldversionpkt++; /* previous version */
396 sys_unknownversion++;
397 return; /* old version */
401 * Figure out his mode and validate the packet. This has some
402 * legacy raunch that probably should be removed. In very early
403 * NTP versions mode 0 was equivalent to what later versions
404 * would interpret as client mode.
406 if (hismode == MODE_UNSPEC) {
407 if (PKT_VERSION(pkt->li_vn_mode) == NTP_OLDVERSION) {
408 hismode = MODE_CLIENT;
411 return; /* invalid mode */
416 * Discard broadcast if not enabled as broadcast client. If
417 * Autokey, the wildcard interface cannot be used, so dump
418 * packets gettiing off the bus at that stop as well. This means
419 * that some systems with broken interface code, specifically
420 * Linux, will not work with Autokey.
422 if (hismode == MODE_BROADCAST) {
423 if (!sys_bclient || restrict_mask & RES_NOPEER) {
425 return; /* no client */
428 if (crypto_flags && rbufp->dstadr == any_interface) {
430 return; /* no client */
436 * Parse the extension field if present. We figure out whether
437 * an extension field is present by measuring the MAC size. If
438 * the number of words following the packet header is 0 or 1, no
439 * MAC is present and the packet is not authenticated. If 1, the
440 * packet is a reply to a previous request that failed to
441 * authenticate. If 3, the packet is authenticated with DES; if
442 * 5, the packet is authenticated with MD5. If greater than 5,
443 * an extension field is present. If 2 or 4, the packet is a
444 * runt and goes poof! with a brilliant flash.
446 authlen = LEN_PKT_NOMAC;
447 has_mac = rbufp->recv_length - authlen;
448 while (has_mac > 0) {
451 if (has_mac % 4 != 0 || has_mac < 0) {
453 return; /* bad MAC length */
455 if (has_mac == 1 * 4 || has_mac == 3 * 4 || has_mac ==
457 skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
460 } else if (has_mac > MAX_MAC_LEN) {
461 temp = ntohl(((u_int32 *)pkt)[authlen / 4]) &
463 if (temp < 4 || temp > NTP_MAXEXTEN || temp % 4
466 return; /* bad MAC length */
472 return; /* bad MAC length */
480 * We have tossed out as many buggy packets as possible early in
481 * the game to reduce the exposure to a clogging attack. Now we
482 * have to burn some cycles to find the association and
483 * authenticate the packet if required. Note that we burn only
484 * MD5 cycles, again to reduce exposure. There may be no
485 * matching association and that's okay.
487 * More on the autokey mambo. Normally the local interface is
488 * found when the association was mobilized with respect to a
489 * designated remote address. We assume packets arriving from
490 * the remote address arrive via this interface and the local
491 * address used to construct the autokey is the unicast address
492 * of the interface. However, if the sender is a broadcaster,
493 * the interface broadcast address is used instead.
494 * Notwithstanding this technobabble, if the sender is a
495 * multicaster, the broadcast address is null, so we use the
496 * unicast address anyway. Don't ask.
498 peer = findpeer(&rbufp->recv_srcadr, rbufp->dstadr, rbufp->fd,
501 dstadr_sin = &rbufp->dstadr->sin;
505 printf("receive: at %ld %s<-%s mode %d code %d\n",
506 current_time, stoa(&rbufp->dstadr->sin),
507 stoa(&rbufp->recv_srcadr), hismode,
513 * For autokey modes, generate the session key
514 * and install in the key cache. Use the socket
515 * broadcast or unicast address as appropriate.
517 if (skeyid > NTP_MAXKEY) {
520 * More on the autokey dance (AKD). A cookie is
521 * constructed from public and private values.
522 * For broadcast packets, the cookie is public
523 * (zero). For packets that match no
524 * association, the cookie is hashed from the
525 * addresses and private value. For server
526 * packets, the cookie was previously obtained
527 * from the server. For symmetric modes, the
528 * cookie was previously constructed using an
529 * agreement protocol; however, should PKI be
530 * unavailable, we construct a fake agreement as
531 * the EXOR of the peer and host cookies.
533 * hismode ephemeral persistent
534 * =======================================
537 * client sys cookie 0%
538 * server 0% sys cookie
544 if (hismode == MODE_BROADCAST) {
547 * For broadcaster, use the interface
548 * broadcast address when available;
549 * otherwise, use the unicast address
550 * found when the association was
554 if (!SOCKNUL(&rbufp->dstadr->bcast))
556 &rbufp->dstadr->bcast;
557 } else if (peer == NULL) {
558 pkeyid = session_key(
559 &rbufp->recv_srcadr, dstadr_sin, 0,
562 pkeyid = peer->pcookie;
566 * The session key includes both the public
567 * values and cookie. In case of an extension
568 * field, the cookie used for authentication
569 * purposes is zero. Note the hash is saved for
570 * use later in the autokey mambo.
572 if (authlen > LEN_PKT_NOMAC && pkeyid != 0) {
573 session_key(&rbufp->recv_srcadr,
574 dstadr_sin, skeyid, 0, 2);
575 tkeyid = session_key(
576 &rbufp->recv_srcadr, dstadr_sin,
579 tkeyid = session_key(
580 &rbufp->recv_srcadr, dstadr_sin,
588 * Compute the cryptosum. Note a clogging attack may
589 * succeed in bloating the key cache. If an autokey,
590 * purge it immediately, since we won't be needing it
591 * again. If the packet is authentic, it may mobilize an
594 if (authdecrypt(skeyid, (u_int32 *)pkt, authlen,
597 restrict_mask &= ~RES_DONTTRUST;
602 if (skeyid > NTP_MAXKEY)
603 authtrust(skeyid, 0);
608 "receive: at %ld %s<-%s mode %d code %d keyid %08x len %d mac %d auth %d\n",
609 current_time, stoa(dstadr_sin),
610 stoa(&rbufp->recv_srcadr), hismode, retcode,
611 skeyid, authlen, has_mac,
617 * The association matching rules are implemented by a set of
618 * routines and a table in ntp_peer.c. A packet matching an
619 * association is processed by that association. If not and
620 * certain conditions prevail, then an ephemeral association is
621 * mobilized: a broadcast packet mobilizes a broadcast client
622 * aassociation; a manycast server packet mobilizes a manycast
623 * client association; a symmetric active packet mobilizes a
624 * symmetric passive association. And, the adventure
631 * This is a client mode packet not matching a known
632 * association. If from a manycast client we run a few
633 * sanity checks before deciding to send a unicast
634 * server response. Otherwise, it must be a client
635 * request, so send a server response and go home.
637 if (sys_manycastserver && (rbufp->dstadr->flags &
641 * There is no reason to respond to a request if
642 * our time is worse than the manycaster or it
643 * has already synchronized to us.
645 if (sys_peer == NULL ||
646 PKT_TO_STRATUM(pkt->stratum) <
647 sys_stratum || (sys_cohort &&
648 PKT_TO_STRATUM(pkt->stratum) ==
650 rbufp->dstadr->addr_refid == pkt->refid)
651 return; /* manycast dropped */
655 * Note that we don't require an authentication check
656 * here, since we can't set the system clock; but, we do
657 * send a crypto-NAK to tell the caller about this.
659 if (has_mac && !is_authentic)
660 fast_xmit(rbufp, MODE_SERVER, 0, restrict_mask);
662 fast_xmit(rbufp, MODE_SERVER, skeyid,
669 * This is a server mode packet returned in response to
670 * a client mode packet sent to a multicast group
671 * address. The originate timestamp is a good nonce to
672 * reliably associate the reply with what was sent. If
673 * there is no match, that's curious and could be an
674 * intruder attempting to clog, so we just ignore it.
676 * First, make sure the packet is authentic and not
677 * restricted. If so and the manycast association is
678 * found, we mobilize a client association and copy
679 * pertinent variables from the manycast association to
680 * the new client association.
682 * There is an implosion hazard at the manycast client,
683 * since the manycast servers send the server packet
684 * immediately. If the guy is already here, don't fire
687 if (restrict_mask & RES_DONTTRUST) {
689 return; /* no trust */
692 if (sys_authenticate && !is_authentic)
693 return; /* bad auth */
695 if ((peer2 = findmanycastpeer(rbufp)) == NULL)
696 return; /* no assoc match */
698 if ((peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
699 MODE_CLIENT, PKT_VERSION(pkt->li_vn_mode),
700 NTP_MINDPOLL, NTP_MAXDPOLL, FLAG_IBURST, MDF_UCAST |
701 MDF_ACLNT, 0, skeyid)) == NULL)
702 return; /* system error */
705 * We don't need these, but it warms the billboards.
707 peer->ttl = peer2->ttl;
713 * This is the first packet received from a symmetric
714 * active peer. First, make sure it is authentic and not
715 * restricted. If so, mobilize a passive association.
716 * If authentication fails send a crypto-NAK; otherwise,
719 if (restrict_mask & RES_DONTTRUST) {
721 return; /* no trust */
723 if (sys_authenticate && !is_authentic) {
724 fast_xmit(rbufp, MODE_PASSIVE, 0,
726 return; /* bad auth */
728 if ((peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
729 MODE_PASSIVE, PKT_VERSION(pkt->li_vn_mode),
730 NTP_MINDPOLL, NTP_MAXDPOLL, 0, MDF_UCAST, 0,
732 return; /* system error */
739 * This is the first packet received from a broadcast
740 * server. First, make sure it is authentic and not
741 * restricted and that we are a broadcast client. If so,
742 * mobilize a broadcast client association. We don't
743 * kiss any frogs here.
745 if (restrict_mask & RES_DONTTRUST) {
747 return; /* no trust */
749 if (sys_authenticate && !is_authentic)
750 return; /* bad auth */
753 return; /* not a client */
755 if ((peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
756 MODE_CLIENT, PKT_VERSION(pkt->li_vn_mode),
757 NTP_MINDPOLL, NTP_MAXDPOLL, FLAG_MCAST |
758 FLAG_IBURST, MDF_BCLNT, 0, skeyid)) == NULL)
759 return; /* system error */
762 * Danger looms. If this is autokey, go process the
763 * extension fields. If something goes wrong, abandon
764 * ship and don't trust subsequent packets.
767 if ((rval = crypto_recv(peer, rbufp)) !=
769 struct sockaddr_storage mskadr_sin;
773 SET_HOSTMASK(&mskadr_sin,
774 rbufp->recv_srcadr.ss_family);
775 hack_restrict(RESTRICT_FLAGS,
776 &rbufp->recv_srcadr, &mskadr_sin,
777 0, RES_DONTTRUST | RES_TIMEOUT);
781 "packet: bad exten %x\n",
792 * This is a broadcast packet received in client mode.
793 * It could happen if the initial client/server volley
794 * is not complete before the next broadcast packet is
795 * received. Be liberal in what we accept.
800 * This is a symmetric mode packet received in symmetric
801 * mode, a server packet received in client mode or a
802 * broadcast packet received in broadcast client mode.
803 * If it is restricted, this is very strange because it
804 * is rude to send a packet to a restricted address. If
805 * anyway, flash a restrain kiss and skedaddle to
806 * Seattle. If not authentic, leave a light on and
810 if (restrict_mask & RES_DONTTRUST) {
812 if (peer->flags & FLAG_CONFIG)
813 peer_clear(peer, "RSTR");
816 return; /* no trust */
818 if (has_mac && !is_authentic)
819 peer->flash |= TEST5; /* bad auth */
825 * Invalid mode combination. This happens when a passive
826 * mode packet arrives and matches another passive
827 * association or no association at all, or when a
828 * server mode packet arrives and matches a broadcast
829 * client association. This is usually the result of
830 * reconfiguring a client on-fly. If authenticated
831 * passive mode packet, send a crypto-NAK; otherwise,
834 if (has_mac && hismode == MODE_PASSIVE)
835 fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
838 printf("receive: bad protocol %d\n", retcode);
844 * We do a little homework. Note we can get here with an
845 * authentication error. We Need to do this in order to validate
846 * a crypto-NAK later. Note the order of processing; it is very
847 * important to avoid livelocks, deadlocks and lockpicks.
849 peer->timereceived = current_time;
851 if (peer->flash & TEST5)
852 peer->flags &= ~FLAG_AUTHENTIC;
854 peer->flags |= FLAG_AUTHENTIC;
855 NTOHL_FP(&pkt->org, &p_org);
856 NTOHL_FP(&pkt->xmt, &p_xmt);
859 * If the packet is an old duplicate, we let it through so the
860 * extension fields will be processed.
862 if (L_ISEQU(&peer->org, &p_xmt)) { /* test 1 */
863 peer->flash |= TEST1; /* dupe */
867 * For broadcast server mode, loopback checking is disabled. An
868 * authentication error probably means the server restarted or
869 * rolled a new private value. If so, dump the association
870 * and wait for the next message.
872 } else if (hismode == MODE_BROADCAST) {
873 if (peer->flash & TEST5) {
880 * For server and symmetric modes, if the association transmit
881 * timestamp matches the packet originate timestamp, loopback is
882 * confirmed. Note in symmetric modes this also happens when the
883 * first packet from the active peer arrives at the newly
884 * mobilized passive peer. An authentication error probably
885 * means the server or peer restarted or rolled a new private
886 * value, but could be an intruder trying to stir up trouble.
887 * However, if this is a crypto-NAK, we know it is authentic, so
888 * dump the association and wait for the next message.
890 } else if (L_ISEQU(&peer->xmt, &p_org)) {
891 if (peer->flash & TEST5) {
892 if (has_mac == 4 && pkt->exten[0] == 0) {
893 if (peer->flags & FLAG_CONFIG)
894 peer_clear(peer, "AUTH");
903 * If the client or passive peer has never transmitted anything,
904 * this is either the first message from a symmetric peer or
905 * possibly a duplicate received before the transmit timeout.
908 } else if (L_ISZERO(&peer->xmt)) {
912 * Now it gets interesting. We have transmitted at least one
913 * packet. If the packet originate timestamp is nonzero, it
914 * does not match the association transmit timestamp, which is a
915 * loopback error. This error might mean a manycast server has
916 * answered a manycast honk from us and we already have an
917 * association for him, in which case quietly drop the packet
918 * here. It might mean an old duplicate, dropped packet or
919 * intruder replay, in which case we drop it later after
920 * extension field processing, but never let it touch the time
923 } else if (!L_ISZERO(&p_org)) {
924 if (peer->cast_flags & MDF_ACLNT)
925 return; /* not a client */
927 peer->flash |= TEST2;
931 * The packet originate timestamp is zero, meaning the other guy
932 * either didn't receive the first packet or died and restarted.
933 * If the association originate timestamp is zero, this is the
934 * first packet received, so we pass it on.
936 } else if (L_ISZERO(&peer->org)) {
940 * The other guy has restarted and we are still on the wire. We
941 * should demobilize/clear and get out of Dodge. If this is
942 * symmetric mode, we should also send a crypto-NAK.
945 if (hismode == MODE_ACTIVE)
946 fast_xmit(rbufp, MODE_PASSIVE, 0,
948 else if (hismode == MODE_PASSIVE)
949 fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
952 printf("receive: dropped %03x\n", peer->flash);
954 if (peer->flags & FLAG_CONFIG)
955 peer_clear(peer, "DROP");
960 if (peer->flash & ~TEST2) {
966 * More autokey dance. The rules of the cha-cha are as follows:
968 * 1. If there is no key or the key is not auto, do nothing.
970 * 2. If this packet is in response to the one just previously
971 * sent or from a broadcast server, do the extension fields.
972 * Otherwise, assume bogosity and bail out.
974 * 3. If an extension field contains a verified signature, it is
975 * self-authenticated and we sit the dance.
977 * 4. If this is a server reply, check only to see that the
978 * transmitted key ID matches the received key ID.
980 * 5. Check to see that one or more hashes of the current key ID
981 * matches the previous key ID or ultimate original key ID
982 * obtained from the broadcaster or symmetric peer. If no
983 * match, sit the dance and wait for timeout.
985 if (crypto_flags && (peer->flags & FLAG_SKEY)) {
986 peer->flash |= TEST10;
987 rval = crypto_recv(peer, rbufp);
988 if (rval != XEVNT_OK) {
991 } else if (hismode == MODE_SERVER) {
992 if (skeyid == peer->keyid)
993 peer->flash &= ~TEST10;
994 } else if (!peer->flash & TEST10) {
995 peer->pkeyid = skeyid;
996 } else if ((ap = (struct autokey *)peer->recval.ptr) !=
1000 for (i = 0; ; i++) {
1001 if (tkeyid == peer->pkeyid ||
1002 tkeyid == ap->key) {
1003 peer->flash &= ~TEST10;
1004 peer->pkeyid = skeyid;
1009 tkeyid = session_key(
1010 &rbufp->recv_srcadr, dstadr_sin,
1014 if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 11 */
1015 peer->flash |= TEST11; /* not proventic */
1018 * If the transmit queue is nonempty, clamp the host
1019 * poll interval to the packet poll interval.
1021 if (peer->cmmd != 0) {
1022 peer->ppoll = pkt->ppoll;
1023 poll_update(peer, 0);
1027 * If the return code from extension field processing is
1028 * not okay, we scrub the association and start over.
1030 if (rval != XEVNT_OK) {
1033 * If the return code is bad, the crypto machine
1034 * may be jammed or an intruder may lurk. First,
1035 * we demobilize the association, then see if
1036 * the error is recoverable.
1038 if (peer->flags & FLAG_CONFIG)
1039 peer_clear(peer, "CRYP");
1044 printf("packet: bad exten %x\n", rval);
1050 * If TEST10 is lit, the autokey sequence has broken,
1051 * which probably means the server has refreshed its
1052 * private value. We reset the poll interval to the
1053 & minimum and scrub the association clean.
1055 if (peer->flash & TEST10 && peer->crypto &
1057 poll_update(peer, peer->minpoll);
1061 "packet: bad auto %03x\n",
1064 if (peer->flags & FLAG_CONFIG)
1065 peer_clear(peer, "AUTO");
1071 #endif /* OPENSSL */
1074 * We have survived the gaunt. Forward to the packet routine. If
1075 * a symmetric passive association has been mobilized and the
1076 * association doesn't deserve to live, it will die in the
1077 * transmit routine if not reachable after timeout. However, if
1078 * either symmetric mode and the crypto code has something
1079 * urgent to say, we expedite the response.
1081 process_packet(peer, pkt, &rbufp->recv_time);
1086 * process_packet - Packet Procedure, a la Section 3.4.4 of the
1087 * specification. Or almost, at least. If we're in here we have a
1088 * reasonable expectation that we will be having a long term
1089 * relationship with this host.
1093 register struct peer *peer,
1094 register struct pkt *pkt,
1099 double p_offset, p_del, p_disp;
1101 l_fp p_rec, p_xmt, p_org, p_reftime;
1103 u_char pmode, pleap, pstratum;
1106 * Swap header fields and keep the books. The books amount to
1107 * the receive timestamp and poll interval in the header. We
1108 * need these even if there are other problems in order to crank
1109 * up the state machine.
1113 p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
1114 p_disp = FPTOD(NTOHS_FP(pkt->rootdispersion));
1115 NTOHL_FP(&pkt->reftime, &p_reftime);
1116 NTOHL_FP(&pkt->rec, &p_rec);
1117 NTOHL_FP(&pkt->xmt, &p_xmt);
1118 pmode = PKT_MODE(pkt->li_vn_mode);
1119 pleap = PKT_LEAP(pkt->li_vn_mode);
1120 if (pmode != MODE_BROADCAST)
1121 NTOHL_FP(&pkt->org, &p_org);
1124 pstratum = PKT_TO_STRATUM(pkt->stratum);
1127 * Test for unsynchronized server.
1129 if (L_ISHIS(&peer->org, &p_xmt)) /* count old packets */
1131 if (pmode != MODE_BROADCAST && (L_ISZERO(&p_rec) ||
1132 L_ISZERO(&p_org))) /* test 3 */
1133 peer->flash |= TEST3; /* unsynch */
1134 if (L_ISZERO(&p_xmt)) /* test 3 */
1135 peer->flash |= TEST3; /* unsynch */
1138 * If any tests fail, the packet is discarded leaving only the
1139 * timestamps, which are enough to get the protocol started. The
1140 * originate timestamp is copied from the packet transmit
1141 * timestamp and the receive timestamp is copied from the
1142 * packet receive timestamp. If okay so far, we save the leap,
1143 * stratum and refid for billboards.
1146 peer->rec = *recv_ts;
1150 printf("packet: bad data %03x from address: %s\n",
1151 peer->flash, stoa(&peer->srcadr));
1156 peer->stratum = pstratum;
1157 peer->refid = pkt->refid;
1160 * Test for valid peer data (tests 6-8)
1163 L_SUB(&ci, &p_reftime);
1165 if (pleap == LEAP_NOTINSYNC || /* test 6 */
1166 pstratum >= STRATUM_UNSPEC || dtemp < 0)
1167 peer->flash |= TEST6; /* bad synch */
1168 if (!(peer->flags & FLAG_CONFIG) && sys_peer != NULL) { /* test 7 */
1169 if (pstratum > sys_stratum && pmode != MODE_ACTIVE)
1170 peer->flash |= TEST7; /* bad stratum */
1172 if (p_del < 0 || p_disp < 0 || p_del / /* test 8 */
1173 2 + p_disp >= MAXDISPERSE)
1174 peer->flash |= TEST8; /* bad peer values */
1177 * If any tests fail at this point, the packet is discarded.
1182 printf("packet: bad header %03x\n",
1189 * The header is valid. Capture the remaining header values and
1190 * mark as reachable.
1192 record_raw_stats(&peer->srcadr, &peer->dstadr->sin, &p_org,
1193 &p_rec, &p_xmt, &peer->rec);
1194 peer->pmode = pmode;
1195 peer->ppoll = pkt->ppoll;
1196 peer->precision = pkt->precision;
1197 peer->rootdelay = p_del;
1198 peer->rootdispersion = p_disp;
1199 peer->reftime = p_reftime;
1200 if (!(peer->reach)) {
1201 report_event(EVNT_REACH, peer);
1202 peer->timereachable = current_time;
1206 poll_update(peer, 0);
1209 * If running in a client/server association, calculate the
1210 * clock offset c, roundtrip delay d and dispersion e. We use
1211 * the equations (reordered from those in the spec). Note that,
1212 * in a broadcast association, org has been set to the time of
1213 * last reception. Note the computation of dispersion includes
1214 * the system precision plus that due to the frequency error
1215 * since the originate time.
1217 * Let t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->rec:
1219 t34 = p_xmt; /* t3 - t4 */
1220 L_SUB(&t34, &peer->rec);
1221 t21 = p_rec; /* t2 - t1 */
1222 L_SUB(&t21, &p_org);
1223 ci = peer->rec; /* t4 - t1 */
1225 LFPTOD(&ci, p_disp);
1226 p_disp = clock_phi * max(p_disp, LOGTOD(sys_precision));
1229 * If running in a broadcast association, the clock offset is
1230 * (t1 - t0) corrected by the one-way delay, but we can't
1231 * measure that directly. Therefore, we start up in MODE_CLIENT
1232 * mode, set FLAG_MCAST and exchange eight messages to determine
1233 * the clock offset. When the last message is sent, we switch to
1234 * MODE_BCLIENT mode. The next broadcast message after that
1235 * computes the broadcast offset and clears FLAG_MCAST.
1238 if (pmode == MODE_BROADCAST) {
1239 if (peer->flags & FLAG_MCAST) {
1240 LFPTOD(&ci, p_offset);
1241 peer->estbdelay = peer->offset - p_offset;
1242 if (peer->hmode == MODE_CLIENT)
1245 peer->flags &= ~FLAG_MCAST;
1247 DTOLFP(peer->estbdelay, &t34);
1249 p_del = peer->delay;
1251 L_ADD(&ci, &t21); /* (t2 - t1) + (t3 - t4) */
1253 L_SUB(&t21, &t34); /* (t2 - t1) - (t3 - t4) */
1254 LFPTOD(&t21, p_del);
1256 p_del = max(p_del, LOGTOD(sys_precision));
1257 LFPTOD(&ci, p_offset);
1258 if ((peer->rootdelay + p_del) / 2. + peer->rootdispersion +
1259 p_disp >= MAXDISPERSE) /* test 9 */
1260 peer->flash |= TEST9; /* bad root distance */
1263 * If any flasher bits remain set at this point, abandon ship.
1264 * Otherwise, forward to the clock filter.
1269 printf("packet: bad packet data %03x\n",
1274 clock_filter(peer, p_offset, p_del, p_disp);
1276 record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
1277 peer->offset, peer->delay, peer->disp,
1278 SQRT(peer->jitter));
1283 * clock_update - Called at system process update intervals.
1292 * Reset/adjust the system clock. Do this only if there is a
1293 * system peer and the peer epoch is not older than the last
1296 if (sys_peer == NULL)
1298 if (sys_peer->epoch <= last_time)
1302 printf("clock_update: at %ld assoc %d \n", current_time,
1306 ostratum = sys_stratum;
1307 switch (local_clock(sys_peer, sys_offset, sys_syserr)) {
1310 * Clock is too screwed up. Just exit for now.
1313 report_event(EVNT_SYSFAULT, NULL);
1318 * Clock was stepped. Flush all time values of all peers.
1323 sys_stratum = STRATUM_UNSPEC;
1324 memcpy(&sys_refid, "STEP", 4);
1325 sys_poll = NTP_MINPOLL;
1326 report_event(EVNT_CLOCKRESET, NULL);
1328 if (oleap != LEAP_NOTINSYNC)
1330 #endif /* OPENSSL */
1334 * Update the system stratum, leap bits, root delay, root
1335 * dispersion, reference ID and reference time. We also update
1336 * select dispersion and max frequency error. If the leap
1337 * changes, we gotta reroll the keys.
1340 sys_stratum = (u_char) (sys_peer->stratum + 1);
1341 if (sys_stratum == 1 || sys_stratum == STRATUM_UNSPEC)
1342 sys_refid = sys_peer->refid;
1344 sys_refid = sys_peer_refid;
1345 sys_reftime = sys_peer->rec;
1346 sys_rootdelay = sys_peer->rootdelay + sys_peer->delay;
1347 sys_leap = leap_consensus;
1348 if (oleap == LEAP_NOTINSYNC) {
1349 report_event(EVNT_SYNCCHG, NULL);
1352 #endif /* OPENSSL */
1355 if (ostratum != sys_stratum)
1356 report_event(EVNT_PEERSTCHG, NULL);
1361 * poll_update - update peer poll interval
1371 #endif /* OPENSSL */
1374 * A little foxtrot to determine what controls the poll
1375 * interval. If the peer is reachable, but the last four polls
1376 * have not been answered, use the minimum. If declared
1377 * truechimer, use the system poll interval. This allows each
1378 * association to ramp up the poll interval for useless sources
1379 * and to clamp it to the minimum when first starting up.
1382 oldpoll = peer->kpoll;
1383 #endif /* OPENSSL */
1385 if (hpoll > peer->maxpoll)
1386 peer->hpoll = peer->maxpoll;
1387 else if (hpoll < peer->minpoll)
1388 peer->hpoll = peer->minpoll;
1390 peer->hpoll = (u_char)hpoll;
1394 * Bit of adventure here. If during a burst and not a poll, just
1395 * slink away. If a poll, figure what the next poll should be.
1396 * If a burst is pending and a reference clock or a pending
1397 * crypto response, delay for one second. If the first sent in a
1398 * burst, delay ten seconds for the modem to come up. For others
1399 * in the burst, delay two seconds.
1401 * In case of manycast server, make the poll interval, which is
1402 * axtually the manycast beacon interval, eight times the system
1403 * poll interval. Normally when the host poll interval settles
1404 * up to 1024 s, the beacon interval settles up to 2.3 hours.
1407 if (peer->cmmd != NULL && (sys_leap != LEAP_NOTINSYNC ||
1409 peer->nextdate = current_time + RESP_DELAY;
1410 } else if (peer->burst > 0) {
1412 if (peer->burst > 0) {
1413 #endif /* OPENSSL */
1414 if (hpoll == 0 && peer->nextdate != current_time)
1417 else if (peer->flags & FLAG_REFCLOCK)
1418 peer->nextdate += RESP_DELAY;
1420 else if (peer->flags & (FLAG_IBURST | FLAG_BURST) &&
1421 peer->burst == NTP_BURST)
1422 peer->nextdate += sys_calldelay;
1424 peer->nextdate += BURST_DELAY;
1425 } else if (peer->cast_flags & MDF_ACAST) {
1426 if (sys_survivors >= sys_minclock || peer->ttl >=
1428 peer->kpoll = (u_char) (peer->hpoll + 3);
1430 peer->kpoll = peer->hpoll;
1431 peer->nextdate = peer->outdate + RANDPOLL(peer->kpoll);
1433 peer->kpoll = (u_char) max(min(peer->ppoll,
1434 peer->hpoll), peer->minpoll);
1435 peer->nextdate = peer->outdate + RANDPOLL(peer->kpoll);
1437 if (peer->nextdate < current_time)
1438 peer->nextdate = current_time;
1441 * Bit of crass arrogance at this point. If the poll interval
1442 * has changed and we have a keylist, the lifetimes in the
1443 * keylist are probably bogus. In this case purge the keylist
1444 * and regenerate it later.
1446 if (peer->kpoll != oldpoll)
1448 #endif /* OPENSSL */
1451 printf("poll_update: at %lu %s flags %04x poll %d burst %d last %lu next %lu\n",
1452 current_time, ntoa(&peer->srcadr), peer->flags,
1453 peer->kpoll, peer->burst, peer->outdate,
1460 * clear - clear peer filter registers. See Section 3.4.8 of the spec.
1464 struct peer *peer, /* peer structure */
1465 char *ident /* tally lights */
1471 * If cryptographic credentials have been acquired, toss them to
1472 * Valhalla. Note that autokeys are ephemeral, in that they are
1473 * tossed immediately upon use. Therefore, the keylist can be
1474 * purged anytime without needing to preserve random keys. Note
1475 * that, if the peer is purged, the cryptographic variables are
1476 * purged, too. This makes it much harder to sneak in some
1477 * unauthenticated data in the clock filter.
1479 oreach = peer->reach;
1482 if (peer->pkey != NULL)
1483 EVP_PKEY_free(peer->pkey);
1484 if (peer->ident_pkey != NULL)
1485 EVP_PKEY_free(peer->ident_pkey);
1486 if (peer->subject != NULL)
1487 free(peer->subject);
1488 if (peer->issuer != NULL)
1490 if (peer->iffval != NULL)
1491 BN_free(peer->iffval);
1492 if (peer->grpkey != NULL)
1493 BN_free(peer->grpkey);
1494 if (peer->cmmd != NULL)
1496 value_free(&peer->cookval);
1497 value_free(&peer->recval);
1498 value_free(&peer->tai_leap);
1499 value_free(&peer->encrypt);
1500 value_free(&peer->sndval);
1501 #endif /* OPENSSL */
1504 * Wipe the association clean and initialize the nonzero values.
1506 memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO);
1507 if (peer == sys_peer)
1509 peer->estbdelay = sys_bdelay;
1510 peer->hpoll = peer->kpoll = peer->minpoll;
1511 peer->ppoll = peer->maxpoll;
1512 peer->jitter = MAXDISPERSE;
1513 peer->epoch = current_time;
1515 if (!(peer->flags & FLAG_REFCLOCK)) {
1516 peer->leap = LEAP_NOTINSYNC;
1517 peer->stratum = STRATUM_UNSPEC;
1518 memcpy(&peer->refid, ident, 4);
1521 peer->leap = LEAP_NOTINSYNC;
1522 peer->stratum = STRATUM_UNSPEC;
1523 memcpy(&peer->refid, ident, 4);
1525 for (i = 0; i < NTP_SHIFT; i++) {
1526 peer->filter_order[i] = i;
1527 peer->filter_disp[i] = MAXDISPERSE;
1528 peer->filter_epoch[i] = current_time;
1532 * If he dies as a broadcast client, he comes back to life as
1533 * a broadcast client in client mode in order to recover the
1534 * initial autokey values.
1536 if (peer->cast_flags & MDF_BCLNT) {
1537 peer->flags |= FLAG_MCAST;
1538 peer->hmode = MODE_CLIENT;
1542 * Randomize the first poll to avoid bunching, but only if the
1543 * rascal has never been heard. During initialization use the
1544 * association count to spread out the polls at one-second
1547 peer->nextdate = peer->update = peer->outdate = current_time;
1550 poll_update(peer, 0);
1551 else if (initializing)
1552 peer->nextdate = current_time + peer_associations;
1554 peer->nextdate = current_time + (u_int)RANDOM %
1558 printf("peer_clear: at %ld assoc ID %d refid %s\n",
1559 current_time, peer->associd, ident);
1565 * clock_filter - add incoming clock sample to filter register and run
1566 * the filter procedure to find the best sample.
1570 struct peer *peer, /* peer structure pointer */
1571 double sample_offset, /* clock offset */
1572 double sample_delay, /* roundtrip delay */
1573 double sample_disp /* dispersion */
1576 double dst[NTP_SHIFT]; /* distance vector */
1577 int ord[NTP_SHIFT]; /* index vector */
1579 double dsp, jit, dtemp, etemp;
1582 * Shift the new sample into the register and discard the oldest
1583 * one. The new offset and delay come directly from the
1584 * timestamp calculations. The dispersion grows from the last
1585 * outbound packet or reference clock update to the present time
1586 * and increased by the sum of the peer precision and the system
1587 * precision. The delay can sometimes swing negative due to
1588 * frequency skew, so it is clamped non-negative.
1590 dsp = min(LOGTOD(peer->precision) + LOGTOD(sys_precision) +
1591 sample_disp, MAXDISPERSE);
1592 j = peer->filter_nextpt;
1593 peer->filter_offset[j] = sample_offset;
1594 peer->filter_delay[j] = max(0, sample_delay);
1595 peer->filter_disp[j] = dsp;
1596 j++; j %= NTP_SHIFT;
1597 peer->filter_nextpt = (u_short) j;
1600 * Update dispersions since the last update and at the same
1601 * time initialize the distance and index lists. The distance
1602 * list uses a compound metric. If the sample is valid and
1603 * younger than the minimum Allan intercept, use delay;
1604 * otherwise, use biased dispersion.
1606 dtemp = clock_phi * (current_time - peer->update);
1607 peer->update = current_time;
1608 for (i = NTP_SHIFT - 1; i >= 0; i--) {
1610 peer->filter_disp[j] += dtemp;
1611 if (peer->filter_disp[j] >= MAXDISPERSE)
1612 peer->filter_disp[j] = MAXDISPERSE;
1613 if (peer->filter_disp[j] >= MAXDISPERSE)
1614 dst[i] = MAXDISPERSE;
1615 else if (peer->update - peer->filter_epoch[j] >
1617 dst[i] = MAXDISTANCE + peer->filter_disp[j];
1619 dst[i] = peer->filter_delay[j];
1621 j++; j %= NTP_SHIFT;
1623 peer->filter_epoch[j] = current_time;
1626 * Sort the samples in both lists by distance.
1628 for (i = 1; i < NTP_SHIFT; i++) {
1629 for (j = 0; j < i; j++) {
1630 if (dst[j] > dst[i]) {
1642 * Copy the index list to the association structure so ntpq
1643 * can see it later. Prune the distance list to samples less
1644 * than MAXDISTANCE, but keep at least two valid samples for
1645 * jitter calculation.
1648 for (i = 0; i < NTP_SHIFT; i++) {
1649 peer->filter_order[i] = (u_char) ord[i];
1650 if (dst[i] >= MAXDISPERSE || (m >= 2 && dst[i] >=
1657 * Compute the dispersion and jitter squares. The dispersion
1658 * is weighted exponentially by NTP_FWEIGHT (0.5) so it is
1659 * normalized close to 1.0. The jitter is the mean of the square
1660 * differences relative to the lowest delay sample. If no
1661 * acceptable samples remain in the shift register, quietly
1662 * tiptoe home leaving only the dispersion.
1667 for (i = NTP_SHIFT - 1; i >= 0; i--) {
1670 peer->disp = NTP_FWEIGHT * (peer->disp +
1671 peer->filter_disp[j]);
1673 jit += DIFF(peer->filter_offset[j],
1674 peer->filter_offset[k]);
1678 * If no acceptable samples remain in the shift register,
1679 * quietly tiptoe home leaving only the dispersion. Otherwise,
1680 * save the offset, delay and jitter average. Note the jitter
1681 * must not be less than the system precision.
1685 etemp = fabs(peer->offset - peer->filter_offset[k]);
1686 dtemp = sqrt(peer->jitter);
1687 peer->offset = peer->filter_offset[k];
1688 peer->delay = peer->filter_delay[k];
1691 peer->jitter = max(jit, SQUARE(LOGTOD(sys_precision)));
1694 * A new sample is useful only if it is younger than the last
1695 * one used, but only if the sucker has been synchronized.
1697 if (peer->filter_epoch[k] <= peer->epoch && sys_leap !=
1701 printf("clock_filter: discard %lu\n",
1702 peer->epoch - peer->filter_epoch[k]);
1708 * If the difference between the last offset and the current one
1709 * exceeds the jitter by CLOCK_SGATE and the interval since the
1710 * last update is less than twice the system poll interval,
1711 * consider the update a popcorn spike and ignore it.
1713 if (m > 1 && etemp > CLOCK_SGATE * dtemp &&
1714 (long)(peer->filter_epoch[k] - peer->epoch) < (1 << (sys_poll +
1718 printf("clock_filter: popcorn %.6f %.6f\n",
1725 * The mitigated sample statistics are saved for later
1728 peer->epoch = peer->filter_epoch[k];
1732 "clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f, age %lu\n",
1733 m, peer->offset, peer->delay, peer->disp,
1734 SQRT(peer->jitter), peer->update - peer->epoch);
1740 * clock_select - find the pick-of-the-litter clock
1742 * LOCKCLOCK: If the local clock is the prefer peer, it will always be
1743 * enabled, even if declared falseticker, (2) only the prefer peer can
1744 * be selected as the system peer, (3) if the external source is down,
1745 * the system leap bits are set to 11 and the stratum set to infinity.
1755 int allow, sw, osurv;
1757 double synch[NTP_MAXCLOCK], error[NTP_MAXCLOCK];
1758 struct peer *osys_peer;
1759 struct peer *typeacts = NULL;
1760 struct peer *typelocal = NULL;
1761 struct peer *typepps = NULL;
1762 struct peer *typesystem = NULL;
1764 static int list_alloc = 0;
1765 static struct endpoint *endpoint = NULL;
1766 static int *indx = NULL;
1767 static struct peer **peer_list = NULL;
1768 static u_int endpoint_size = 0;
1769 static u_int indx_size = 0;
1770 static u_int peer_list_size = 0;
1773 * Initialize and create endpoint, index and peer lists big
1774 * enough to handle all associations.
1776 osys_peer = sys_peer;
1778 osurv = sys_survivors;
1782 sys_leap = LEAP_NOTINSYNC;
1783 sys_stratum = STRATUM_UNSPEC;
1784 memcpy(&sys_refid, "DOWN", 4);
1785 #endif /* LOCKCLOCK */
1787 for (n = 0; n < HASH_SIZE; n++)
1788 nlist += peer_hash_count[n];
1789 if (nlist > list_alloc) {
1790 if (list_alloc > 0) {
1795 while (list_alloc < nlist) {
1797 endpoint_size += 5 * 3 * sizeof(*endpoint);
1798 indx_size += 5 * 3 * sizeof(*indx);
1799 peer_list_size += 5 * sizeof(*peer_list);
1801 endpoint = emalloc(endpoint_size);
1802 indx = emalloc(indx_size);
1803 peer_list = emalloc(peer_list_size);
1807 * Initially, we populate the island with all the rifraff peers
1808 * that happen to be lying around. Those with seriously
1809 * defective clocks are immediately booted off the island. Then,
1810 * the falsetickers are culled and put to sea. The truechimers
1811 * remaining are subject to repeated rounds where the most
1812 * unpopular at each round is kicked off. When the population
1813 * has dwindled to sys_minclock, the survivors split a million
1814 * bucks and collectively crank the chimes.
1816 nlist = nl3 = 0; /* none yet */
1817 for (n = 0; n < HASH_SIZE; n++) {
1818 for (peer = peer_hash[n]; peer != NULL; peer =
1820 peer->flags &= ~FLAG_SYSPEER;
1821 peer->status = CTL_PST_SEL_REJECT;
1824 * Leave the island immediately if the peer is
1825 * unfit to synchronize.
1827 if (peer_unfit(peer))
1831 * Don't allow the local clock or modem drivers
1832 * in the kitchen at this point, unless the
1833 * prefer peer. Do that later, but only if
1834 * nobody else is around. These guys are all
1835 * configured, so we never throw them away.
1837 if (peer->refclktype == REFCLK_LOCALCLOCK
1838 #if defined(VMS) && defined(VMS_LOCALUNIT)
1839 /* wjm: VMS_LOCALUNIT taken seriously */
1840 && REFCLOCKUNIT(&peer->srcadr) !=
1842 #endif /* VMS && VMS_LOCALUNIT */
1845 if (!(peer->flags & FLAG_PREFER))
1846 continue; /* no local clock */
1850 #endif /* LOCKCLOCK */
1852 if (peer->sstclktype == CTL_SST_TS_TELEPHONE) {
1854 if (!(peer->flags & FLAG_PREFER))
1855 continue; /* no acts */
1859 * If we get this far, the peer can stay on the
1860 * island, but does not yet have the immunity
1863 peer->status = CTL_PST_SEL_SANE;
1864 peer_list[nlist++] = peer;
1867 * Insert each interval endpoint on the sorted
1870 e = peer->offset; /* Upper end */
1871 f = root_distance(peer);
1873 for (i = nl3 - 1; i >= 0; i--) {
1874 if (e >= endpoint[indx[i]].val)
1876 indx[i + 3] = indx[i];
1879 endpoint[nl3].type = 1;
1880 endpoint[nl3++].val = e;
1882 e = e - f; /* Center point */
1883 for (; i >= 0; i--) {
1884 if (e >= endpoint[indx[i]].val)
1886 indx[i + 2] = indx[i];
1889 endpoint[nl3].type = 0;
1890 endpoint[nl3++].val = e;
1892 e = e - f; /* Lower end */
1893 for (; i >= 0; i--) {
1894 if (e >= endpoint[indx[i]].val)
1896 indx[i + 1] = indx[i];
1899 endpoint[nl3].type = -1;
1900 endpoint[nl3++].val = e;
1905 for (i = 0; i < nl3; i++)
1906 printf("select: endpoint %2d %.6f\n",
1907 endpoint[indx[i]].type,
1908 endpoint[indx[i]].val);
1911 * This is the actual algorithm that cleaves the truechimers
1912 * from the falsetickers. The original algorithm was described
1913 * in Keith Marzullo's dissertation, but has been modified for
1916 * Briefly put, we first assume there are no falsetickers, then
1917 * scan the candidate list first from the low end upwards and
1918 * then from the high end downwards. The scans stop when the
1919 * number of intersections equals the number of candidates less
1920 * the number of falsetickers. If this doesn't happen for a
1921 * given number of falsetickers, we bump the number of
1922 * falsetickers and try again. If the number of falsetickers
1923 * becomes equal to or greater than half the number of
1924 * candidates, the Albanians have won the Byzantine wars and
1925 * correct synchronization is not possible.
1927 * Here, nlist is the number of candidates and allow is the
1928 * number of falsetickers.
1932 for (allow = 0; 2 * allow < nlist; allow++) {
1936 * Bound the interval (low, high) as the largest
1937 * interval containing points from presumed truechimers.
1941 for (i = 0; i < nl3; i++) {
1942 low = endpoint[indx[i]].val;
1943 n -= endpoint[indx[i]].type;
1944 if (n >= nlist - allow)
1946 if (endpoint[indx[i]].type == 0)
1950 for (j = nl3 - 1; j >= 0; j--) {
1951 high = endpoint[indx[j]].val;
1952 n += endpoint[indx[j]].type;
1953 if (n >= nlist - allow)
1955 if (endpoint[indx[j]].type == 0)
1960 * If the number of candidates found outside the
1961 * interval is greater than the number of falsetickers,
1962 * then at least one truechimer is outside the interval,
1963 * so go around again. This is what makes this algorithm
1964 * different than Marzullo's.
1970 * If an interval containing truechimers is found, stop.
1971 * If not, increase the number of falsetickers and go
1979 * If no survivors remain at this point, check if the local
1980 * clock or modem drivers have been found. If so, nominate one
1981 * of them as the only survivor. Otherwise, give up and leave
1982 * the island to the rats.
1985 if (typeacts != 0) {
1986 typeacts->status = CTL_PST_SEL_SANE;
1987 peer_list[0] = typeacts;
1989 } else if (typelocal != 0) {
1990 typelocal->status = CTL_PST_SEL_SANE;
1991 peer_list[0] = typelocal;
1994 if (osys_peer != NULL) {
1995 sys_poll = NTP_MINPOLL;
1996 NLOG(NLOG_SYNCSTATUS)
1998 "no servers reachable");
1999 report_event(EVNT_PEERSTCHG, NULL);
2008 * We can only trust the survivors if the number of candidates
2009 * sys_minsane is at least the number required to detect and
2010 * cast out one falsticker. For the Byzantine agreement
2011 * algorithm used here, that number is 4; however, the default
2012 * sys_minsane is 1 to speed initial synchronization. Careful
2013 * operators will tinker the value to 4 and use at least that
2014 * number of synchronization sources.
2016 if (nlist < sys_minsane)
2020 * Clustering algorithm. Construct candidate list in order first
2021 * by stratum then by root distance, but keep only the best
2022 * NTP_MAXCLOCK of them. Scan the list to find falsetickers, who
2023 * leave the island immediately. If a falseticker is not
2024 * configured, his association raft is drowned as well, but only
2025 * if at at least eight poll intervals have gone. We must leave
2026 * at least one peer to collect the million bucks.
2028 * Note the hysteresis gimmick that increases the effective
2029 * distance for those rascals that have not made the final cut.
2030 * This is to discourage clockhopping. Note also the prejudice
2031 * against lower stratum peers if the floor is elevated.
2034 for (i = 0; i < nlist; i++) {
2035 peer = peer_list[i];
2036 if (nlist > 1 && (peer->offset <= low || peer->offset >=
2038 if (!(peer->flags & FLAG_CONFIG))
2042 peer->status = CTL_PST_SEL_DISTSYSPEER;
2046 if (d > sys_ceiling)
2048 d = root_distance(peer) + d * MAXDISTANCE;
2049 d *= 1. - peer->hyst;
2050 if (j >= NTP_MAXCLOCK) {
2051 if (d >= synch[j - 1])
2056 for (k = j; k > 0; k--) {
2057 if (d >= synch[k - 1])
2059 peer_list[k] = peer_list[k - 1];
2060 error[k] = error[k - 1];
2061 synch[k] = synch[k - 1];
2063 peer_list[k] = peer;
2064 error[k] = peer->jitter;
2072 printf("clock_select: empty intersection interval\n");
2076 for (i = 0; i < nlist; i++) {
2077 peer_list[i]->status = CTL_PST_SEL_SELCAND;
2081 printf("select: %s distance %.6f jitter %.6f\n",
2082 ntoa(&peer_list[i]->srcadr), synch[i],
2088 * Now, vote outlyers off the island by select jitter weighted
2089 * by root dispersion. Continue voting as long as there are more
2090 * than sys_minclock survivors and the minimum select jitter
2091 * squared is greater than the maximum peer jitter squared. Stop
2092 * if we are about to discard a prefer peer, who of course has
2093 * the immunity idol.
2099 for (i = 0; i < nlist; i++) {
2104 for (j = 0; j < nlist; j++)
2105 f += DIFF(peer_list[j]->offset,
2106 peer_list[i]->offset);
2109 if (f * synch[i] > e) {
2115 f = max(sys_selerr, SQUARE(LOGTOD(sys_precision)));
2116 if (nlist <= sys_minclock || f <= d ||
2117 peer_list[k]->flags & FLAG_PREFER)
2122 "select: drop %s select %.6f jitter %.6f\n",
2123 ntoa(&peer_list[k]->srcadr),
2124 SQRT(sys_selerr), SQRT(d));
2126 if (!(peer_list[k]->flags & FLAG_CONFIG) &&
2127 peer_list[k]->hmode == MODE_CLIENT)
2128 unpeer(peer_list[k]);
2129 for (j = k + 1; j < nlist; j++) {
2130 peer_list[j - 1] = peer_list[j];
2131 error[j - 1] = error[j];
2137 * What remains is a list usually not greater than sys_minclock
2138 * peers. We want only a peer at the lowest stratum to become
2139 * the system peer, although all survivors are eligible for the
2140 * combining algorithm. First record their order, diddle the
2141 * flags and clamp the poll intervals. Then, consider each peer
2142 * in turn and OR the leap bits on the assumption that, if some
2143 * of them honk nonzero bits, they must know what they are
2144 * doing. Check for prefer and pps peers at any stratum. Check
2145 * if the old system peer is among the peers at the lowest
2146 * stratum. Note that the head of the list is at the lowest
2147 * stratum and that unsynchronized peers cannot survive this
2150 * Fiddle for hysteresis. Pump it up for a peer only if the peer
2151 * stratum is at least the floor and there are enough survivors.
2152 * This minimizes the pain when tossing out rascals beneath the
2153 * floorboard. Don't count peers with stratum above the ceiling.
2154 * Manycast is sooo complicated.
2157 for (i = nlist - 1; i >= 0; i--) {
2158 peer = peer_list[i];
2159 leap_consensus |= peer->leap;
2160 peer->status = CTL_PST_SEL_SYNCCAND;
2162 peer->flags |= FLAG_SYSPEER;
2163 if (peer->stratum >= sys_floor && osurv >= sys_minclock)
2167 if (peer->stratum <= sys_ceiling)
2169 if (peer->flags & FLAG_PREFER)
2171 if (peer->refclktype == REFCLK_ATOM_PPS &&
2172 peer->stratum < STRATUM_UNSPEC)
2174 if (peer->stratum == peer_list[0]->stratum && peer ==
2180 * In manycast client mode we may have spooked a sizeable number
2181 * of peers that we don't need. If there are at least
2182 * sys_minclock of them, the manycast message will be turned
2183 * off. By the time we get here we nay be ready to prune some of
2184 * them back, but we want to make sure all the candicates have
2185 * had a chance. If they didn't pass the sanity and intersection
2186 * tests, they have already been voted off the island.
2188 if (sys_survivors < sys_minclock && osurv >= sys_minclock)
2192 * Mitigation rules of the game. There are several types of
2193 * peers that make a difference here: (1) prefer local peers
2194 * (type REFCLK_LOCALCLOCK with FLAG_PREFER) or prefer modem
2195 * peers (type REFCLK_NIST_ATOM etc with FLAG_PREFER), (2) pps
2196 * peers (type REFCLK_ATOM_PPS), (3) remaining prefer peers
2197 * (flag FLAG_PREFER), (4) the existing system peer, if any, (5)
2198 * the head of the survivor list. Note that only one peer can be
2199 * declared prefer. The order of preference is in the order
2200 * stated. Note that all of these must be at the lowest stratum,
2201 * i.e., the stratum of the head of the survivor list.
2204 sw = sys_prefer->refclktype == REFCLK_LOCALCLOCK ||
2205 sys_prefer->sstclktype == CTL_SST_TS_TELEPHONE ||
2210 sys_peer = sys_prefer;
2211 sys_peer->status = CTL_PST_SEL_SYSPEER;
2212 sys_offset = sys_peer->offset;
2213 sys_syserr = sys_peer->jitter;
2216 printf("select: prefer offset %.6f\n",
2223 sys_peer->status = CTL_PST_SEL_PPS;
2224 sys_offset = sys_peer->offset;
2225 sys_syserr = sys_peer->jitter;
2228 msyslog(LOG_INFO, "pps sync enabled");
2229 pps_control = current_time;
2232 printf("select: pps offset %.6f\n",
2237 sys_peer = osys_peer;
2239 sys_peer = peer_list[0];
2240 sys_peer->status = CTL_PST_SEL_SYSPEER;
2242 sys_offset = clock_combine(peer_list, nlist);
2243 sys_syserr = sys_peer->jitter + sys_selerr;
2246 printf("select: combine offset %.6f\n",
2250 #endif /* LOCKCLOCK */
2251 if (osys_peer != sys_peer) {
2254 if (sys_peer == NULL)
2257 sys_peer_refid = addr2refid(&sys_peer->srcadr);
2258 report_event(EVNT_PEERSTCHG, NULL);
2261 if (ISREFCLOCKADR(&sys_peer->srcadr))
2262 src = refnumtoa(&sys_peer->srcadr);
2265 src = ntoa(&sys_peer->srcadr);
2266 NLOG(NLOG_SYNCSTATUS)
2267 msyslog(LOG_INFO, "synchronized to %s, stratum=%d", src,
2274 * clock_combine - combine offsets from selected peers
2278 struct peer **peers,
2286 for (i = 0; i < npeers; i++) {
2287 x = root_distance(peers[i]);
2289 z += peers[i]->offset / x;
2295 * root_distance - compute synchronization distance from peer to root
2303 * Careful squeak here. The value returned must be greater than
2304 * zero blamed on the peer jitter, which must be at least the
2305 * square of sys_precision.
2307 return ((peer->rootdelay + peer->delay) / 2 +
2308 peer->rootdispersion + peer->disp + clock_phi *
2309 (current_time - peer->update) + SQRT(peer->jitter));
2313 * peer_xmit - send packet for persistent association.
2317 struct peer *peer /* peer structure pointer */
2320 struct pkt xpkt; /* transmit packet */
2321 int sendlen, authlen;
2322 keyid_t xkeyid = 0; /* transmit key ID */
2326 * Initialize transmit packet header fields.
2328 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
2330 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
2331 xpkt.ppoll = peer->hpoll;
2332 xpkt.precision = sys_precision;
2333 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
2334 xpkt.rootdispersion = HTONS_FP(DTOUFP(sys_rootdispersion));
2335 xpkt.refid = sys_refid;
2336 HTONL_FP(&sys_reftime, &xpkt.reftime);
2337 HTONL_FP(&peer->org, &xpkt.org);
2338 HTONL_FP(&peer->rec, &xpkt.rec);
2341 * If the received packet contains a MAC, the transmitted packet
2342 * is authenticated and contains a MAC. If not, the transmitted
2343 * packet is not authenticated.
2345 * In the current I/O semantics the default interface is set
2346 * until after receiving a packet and setting the right
2347 * interface. So, the first packet goes out unauthenticated.
2348 * That's why the really icky test next is here.
2350 sendlen = LEN_PKT_NOMAC;
2351 if (!(peer->flags & FLAG_AUTHENABLE)) {
2352 get_systime(&peer->xmt);
2353 HTONL_FP(&peer->xmt, &xpkt.xmt);
2354 sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl],
2359 printf("transmit: at %ld %s->%s mode %d\n",
2360 current_time, stoa(&peer->dstadr->sin),
2361 stoa(&peer->srcadr), peer->hmode);
2367 * The received packet contains a MAC, so the transmitted packet
2368 * must be authenticated. If autokey is enabled, fuss with the
2369 * various modes; otherwise, private key cryptography is used.
2372 if (crypto_flags && (peer->flags & FLAG_SKEY)) {
2373 struct exten *exten; /* extension field */
2377 * The Public Key Dance (PKD): Cryptographic credentials
2378 * are contained in extension fields, each including a
2379 * 4-octet length/code word followed by a 4-octet
2380 * association ID and optional additional data. Optional
2381 * data includes a 4-octet data length field followed by
2382 * the data itself. Request messages are sent from a
2383 * configured association; response messages can be sent
2384 * from a configured association or can take the fast
2385 * path without ever matching an association. Response
2386 * messages have the same code as the request, but have
2387 * a response bit and possibly an error bit set. In this
2388 * implementation, a message may contain no more than
2389 * one command and no more than one response.
2391 * Cryptographic session keys include both a public and
2392 * a private componet. Request and response messages
2393 * using extension fields are always sent with the
2394 * private component set to zero. Packets without
2395 * extension fields indlude the private component when
2396 * the session key is generated.
2401 * Allocate and initialize a keylist if not
2402 * already done. Then, use the list in inverse
2403 * order, discarding keys once used. Keep the
2404 * latest key around until the next one, so
2405 * clients can use client/server packets to
2406 * compute propagation delay.
2408 * Note that once a key is used from the list,
2409 * it is retained in the key cache until the
2410 * next key is used. This is to allow a client
2411 * to retrieve the encrypted session key
2412 * identifier to verify authenticity.
2414 * If for some reason a key is no longer in the
2415 * key cache, a birthday has happened and the
2416 * pseudo-random sequence is probably broken. In
2417 * that case, purge the keylist and regenerate
2420 if (peer->keynumber == 0)
2421 make_keylist(peer, peer->dstadr);
2424 xkeyid = peer->keylist[peer->keynumber];
2425 if (authistrusted(xkeyid))
2430 peer->keyid = xkeyid;
2431 switch (peer->hmode) {
2434 * In broadcast server mode the autokey values are
2435 * required by the broadcast clients. Push them when a
2436 * new keylist is generated; otherwise, push the
2437 * association message so the client can request them at
2440 case MODE_BROADCAST:
2441 if (peer->flags & FLAG_ASSOC)
2442 exten = crypto_args(peer, CRYPTO_AUTO |
2445 exten = crypto_args(peer, CRYPTO_ASSOC |
2447 sendlen += crypto_xmit(&xpkt, &peer->srcadr,
2453 * In symmetric modes the digest, certificate, agreement
2454 * parameters, cookie and autokey values are required.
2455 * The leapsecond table is optional. But, a passive peer
2456 * will not believe the active peer until the latter has
2457 * synchronized, so the agreement must be postponed
2458 * until then. In any case, if a new keylist is
2459 * generated, the autokey values are pushed.
2463 if (peer->cmmd != NULL) {
2464 peer->cmmd->associd =
2465 htonl(peer->associd);
2466 sendlen += crypto_xmit(&xpkt,
2467 &peer->srcadr, sendlen, peer->cmmd,
2474 exten = crypto_args(peer, CRYPTO_ASSOC,
2476 else if (!(peer->crypto & CRYPTO_FLAG_VALID))
2477 exten = crypto_args(peer, CRYPTO_CERT,
2481 * Identity. Note we have to sign the
2482 * certificate before the cookie to avoid a
2483 * deadlock when the passive peer is walking the
2484 * certificate trail. Awesome.
2486 else if ((opcode = crypto_ident(peer)) != 0)
2487 exten = crypto_args(peer, opcode, NULL);
2488 else if (sys_leap != LEAP_NOTINSYNC &&
2489 !(peer->crypto & CRYPTO_FLAG_SIGN))
2490 exten = crypto_args(peer, CRYPTO_SIGN,
2494 * Autokey. We request the cookie only when the
2495 * server and client are synchronized and
2496 * signatures work both ways. On the other hand,
2497 * the active peer needs the autokey values
2498 * before then and when the passive peer is
2499 * waiting for the active peer to synchronize.
2500 * Any time we regenerate the key list, we offer
2501 * the autokey values without being asked.
2503 else if (sys_leap != LEAP_NOTINSYNC &&
2504 peer->leap != LEAP_NOTINSYNC &&
2505 !(peer->crypto & CRYPTO_FLAG_AGREE))
2506 exten = crypto_args(peer, CRYPTO_COOK,
2508 else if (peer->flags & FLAG_ASSOC)
2509 exten = crypto_args(peer, CRYPTO_AUTO |
2511 else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
2512 exten = crypto_args(peer, CRYPTO_AUTO,
2516 * Postamble. We trade leapseconds only when the
2517 * server and client are synchronized.
2519 else if (sys_leap != LEAP_NOTINSYNC &&
2520 peer->leap != LEAP_NOTINSYNC &&
2521 peer->crypto & CRYPTO_FLAG_TAI &&
2522 !(peer->crypto & CRYPTO_FLAG_LEAP))
2523 exten = crypto_args(peer, CRYPTO_TAI,
2525 if (exten != NULL) {
2526 sendlen += crypto_xmit(&xpkt,
2527 &peer->srcadr, sendlen, exten, 0);
2533 * In client mode the digest, certificate, agreement
2534 * parameters and cookie are required. The leapsecond
2535 * table is optional. If broadcast client mode, the
2536 * autokey values are required as well. In broadcast
2537 * client mode, these values must be acquired during the
2538 * client/server exchange to avoid having to wait until
2539 * the next key list regeneration. Otherwise, the poor
2540 * dude may die a lingering death until becoming
2541 * unreachable and attempting rebirth.
2543 * If neither the server or client have the agreement
2544 * parameters, the protocol transmits the cookie in the
2545 * clear. If the server has the parameters, the client
2546 * requests them and the protocol blinds it using the
2547 * agreed key. It is a protocol error if the client has
2548 * the parameters but the server does not.
2551 if (peer->cmmd != NULL) {
2552 peer->cmmd->associd =
2553 htonl(peer->associd);
2554 sendlen += crypto_xmit(&xpkt,
2555 &peer->srcadr, sendlen, peer->cmmd,
2562 exten = crypto_args(peer, CRYPTO_ASSOC,
2564 else if (!(peer->crypto & CRYPTO_FLAG_VALID))
2565 exten = crypto_args(peer, CRYPTO_CERT,
2571 else if ((opcode = crypto_ident(peer)) != 0)
2572 exten = crypto_args(peer, opcode, NULL);
2577 else if (!(peer->crypto & CRYPTO_FLAG_AGREE))
2578 exten = crypto_args(peer, CRYPTO_COOK,
2580 else if (!(peer->crypto & CRYPTO_FLAG_AUTO) &&
2581 (peer->cast_flags & MDF_BCLNT))
2582 exten = crypto_args(peer, CRYPTO_AUTO,
2586 * Postamble. We can sign the certificate here,
2587 * since there is no chance of deadlock.
2589 else if (sys_leap != LEAP_NOTINSYNC &&
2590 !(peer->crypto & CRYPTO_FLAG_SIGN))
2591 exten = crypto_args(peer, CRYPTO_SIGN,
2593 else if (sys_leap != LEAP_NOTINSYNC &&
2594 peer->crypto & CRYPTO_FLAG_TAI &&
2595 !(peer->crypto & CRYPTO_FLAG_LEAP))
2596 exten = crypto_args(peer, CRYPTO_TAI,
2598 if (exten != NULL) {
2599 sendlen += crypto_xmit(&xpkt,
2600 &peer->srcadr, sendlen, exten, 0);
2607 * If extension fields are present, we must use a
2608 * private value of zero and force min poll interval.
2611 if (sendlen > LEN_PKT_NOMAC)
2612 session_key(&peer->dstadr->sin, &peer->srcadr,
2615 #endif /* OPENSSL */
2616 xkeyid = peer->keyid;
2617 get_systime(&peer->xmt);
2618 L_ADD(&peer->xmt, &sys_authdelay);
2619 HTONL_FP(&peer->xmt, &xpkt.xmt);
2620 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2623 "transmit: encryption key %d not found", xkeyid);
2624 if (peer->flags & FLAG_CONFIG)
2625 peer_clear(peer, "NKEY");
2632 if (xkeyid > NTP_MAXKEY)
2633 authtrust(xkeyid, 0);
2634 #endif /* OPENSSL */
2635 get_systime(&xmt_tx);
2636 if (sendlen > sizeof(xpkt)) {
2637 msyslog(LOG_ERR, "buffer overflow %u", sendlen);
2640 sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl], &xpkt,
2644 * Calculate the encryption delay. Keep the minimum over
2645 * the latest two samples.
2647 L_SUB(&xmt_tx, &peer->xmt);
2648 L_ADD(&xmt_tx, &sys_authdelay);
2649 sys_authdly[1] = sys_authdly[0];
2650 sys_authdly[0] = xmt_tx.l_uf;
2651 if (sys_authdly[0] < sys_authdly[1])
2652 sys_authdelay.l_uf = sys_authdly[0];
2654 sys_authdelay.l_uf = sys_authdly[1];
2660 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d index %d\n",
2661 current_time, ntoa(&peer->dstadr->sin),
2662 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen -
2663 authlen, authlen, peer->keynumber);
2669 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
2670 current_time, ntoa(&peer->dstadr->sin),
2671 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen -
2674 #endif /* OPENSSL */
2679 * fast_xmit - Send packet for nonpersistent association. Note that
2680 * neither the source or destination can be a broadcast address.
2684 struct recvbuf *rbufp, /* receive packet pointer */
2685 int xmode, /* transmit mode */
2686 keyid_t xkeyid, /* transmit key ID */
2687 int mask /* restrict mask */
2690 struct pkt xpkt; /* transmit packet structure */
2691 struct pkt *rpkt; /* receive packet structure */
2692 l_fp xmt_ts; /* timestamp */
2693 l_fp xmt_tx; /* timestamp after authent */
2694 int sendlen, authlen;
2700 * Initialize transmit packet header fields from the receive
2701 * buffer provided. We leave some fields intact as received. If
2702 * the gazinta was from a multicast address, the gazouta must go
2705 rpkt = &rbufp->recv_pkt;
2706 if (rbufp->dstadr->flags & INT_MULTICAST)
2707 rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
2710 * If the packet has picked up a restriction due to either
2711 * access denied or rate exceeded, decide what to do with it.
2713 if (mask & (RES_DONTTRUST | RES_LIMITED)) {
2714 char *code = "????";
2716 if (mask & RES_LIMITED) {
2717 sys_limitrejected++;
2719 } else if (mask & RES_DONTTRUST) {
2725 * Here we light up a kiss-of-death packet. Note the
2726 * rate limit on these packets. Once a second initialize
2727 * a bucket counter. Every packet sent decrements the
2728 * counter until reaching zero. If the counter is zero,
2731 if (sys_kod == 0 || !(mask & RES_DEMOBILIZE))
2735 memcpy(&xpkt.refid, code, 4);
2736 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
2737 PKT_VERSION(rpkt->li_vn_mode), xmode);
2738 xpkt.stratum = STRATUM_UNSPEC;
2740 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
2741 PKT_VERSION(rpkt->li_vn_mode), xmode);
2742 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
2743 xpkt.refid = sys_refid;
2745 xpkt.ppoll = rpkt->ppoll;
2746 xpkt.precision = sys_precision;
2747 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
2748 xpkt.rootdispersion =
2749 HTONS_FP(DTOUFP(sys_rootdispersion));
2750 HTONL_FP(&sys_reftime, &xpkt.reftime);
2751 xpkt.org = rpkt->xmt;
2752 HTONL_FP(&rbufp->recv_time, &xpkt.rec);
2755 * If the received packet contains a MAC, the transmitted packet
2756 * is authenticated and contains a MAC. If not, the transmitted
2757 * packet is not authenticated.
2759 sendlen = LEN_PKT_NOMAC;
2760 if (rbufp->recv_length == sendlen) {
2761 get_systime(&xmt_ts);
2762 HTONL_FP(&xmt_ts, &xpkt.xmt);
2763 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
2767 printf("transmit: at %ld %s->%s mode %d\n",
2768 current_time, stoa(&rbufp->dstadr->sin),
2769 stoa(&rbufp->recv_srcadr), xmode);
2775 * The received packet contains a MAC, so the transmitted packet
2776 * must be authenticated. For private-key cryptography, use the
2777 * predefined private keys to generate the cryptosum. For
2778 * autokey cryptography, use the server private value to
2779 * generate the cookie, which is unique for every source-
2780 * destination-key ID combination.
2783 if (xkeyid > NTP_MAXKEY) {
2787 * The only way to get here is a reply to a legitimate
2788 * client request message, so the mode must be
2789 * MODE_SERVER. If an extension field is present, there
2790 * can be only one and that must be a command. Do what
2791 * needs, but with private value of zero so the poor
2792 * jerk can decode it. If no extension field is present,
2793 * use the cookie to generate the session key.
2795 cookie = session_key(&rbufp->recv_srcadr,
2796 &rbufp->dstadr->sin, 0, sys_private, 0);
2797 if (rbufp->recv_length >= (int)(sendlen + MAX_MAC_LEN + 2 *
2799 session_key(&rbufp->dstadr->sin,
2800 &rbufp->recv_srcadr, xkeyid, 0, 2);
2801 temp32 = CRYPTO_RESP;
2802 rpkt->exten[0] |= htonl(temp32);
2803 sendlen += crypto_xmit(&xpkt,
2804 &rbufp->recv_srcadr, sendlen,
2805 (struct exten *)rpkt->exten, cookie);
2807 session_key(&rbufp->dstadr->sin,
2808 &rbufp->recv_srcadr, xkeyid, cookie, 2);
2811 #endif /* OPENSSL */
2812 get_systime(&xmt_ts);
2813 L_ADD(&xmt_ts, &sys_authdelay);
2814 HTONL_FP(&xmt_ts, &xpkt.xmt);
2815 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2818 if (xkeyid > NTP_MAXKEY)
2819 authtrust(xkeyid, 0);
2820 #endif /* OPENSSL */
2821 get_systime(&xmt_tx);
2822 if (sendlen > sizeof(xpkt)) {
2823 msyslog(LOG_ERR, "buffer overflow %u", sendlen);
2826 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
2829 * Calculate the encryption delay. Keep the minimum over the
2830 * latest two samples.
2832 L_SUB(&xmt_tx, &xmt_ts);
2833 L_ADD(&xmt_tx, &sys_authdelay);
2834 sys_authdly[1] = sys_authdly[0];
2835 sys_authdly[0] = xmt_tx.l_uf;
2836 if (sys_authdly[0] < sys_authdly[1])
2837 sys_authdelay.l_uf = sys_authdly[0];
2839 sys_authdelay.l_uf = sys_authdly[1];
2843 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
2844 current_time, ntoa(&rbufp->dstadr->sin),
2845 ntoa(&rbufp->recv_srcadr), xmode, xkeyid, sendlen -
2853 * key_expire - purge the key list
2857 struct peer *peer /* peer structure pointer */
2862 if (peer->keylist != NULL) {
2863 for (i = 0; i <= peer->keynumber; i++)
2864 authtrust(peer->keylist[i], 0);
2865 free(peer->keylist);
2866 peer->keylist = NULL;
2868 value_free(&peer->sndval);
2869 peer->keynumber = 0;
2872 printf("key_expire: at %lu\n", current_time);
2875 #endif /* OPENSSL */
2879 * Determine if the peer is unfit for synchronization
2881 * A peer is unfit for synchronization if
2883 * > a synchronization loop would form
2884 * > never been synchronized
2885 * > stratum undefined or too high
2886 * > too long without synchronization
2887 * > designated noselect
2889 static int /* 0 if no, 1 if yes */
2891 struct peer *peer /* peer structure pointer */
2894 return (!peer->reach || (peer->stratum > 1 && peer->refid ==
2895 peer->dstadr->addr_refid) || peer->leap == LEAP_NOTINSYNC ||
2896 peer->stratum >= STRATUM_UNSPEC || root_distance(peer) >=
2897 MAXDISTANCE + 2. * clock_phi * ULOGTOD(sys_poll) ||
2898 peer->flags & FLAG_NOSELECT );
2903 * Find the precision of this particular machine
2905 #define MINSTEP 100e-9 /* minimum clock increment (s) */
2906 #define MAXSTEP 20e-3 /* maximum clock increment (s) */
2907 #define MINLOOPS 5 /* minimum number of step samples */
2910 * This routine calculates the system precision, defined as the minimum
2911 * of a sequency of differences between successive readings of the
2912 * system clock. However, if the system clock can be read more than once
2913 * during a tick interval, the difference can be zero or one LSB unit,
2914 * where the LSB corresponds to one nanosecond or one microsecond.
2915 * Conceivably, if some other process preempts this one and reads the
2916 * clock, the difference can be more than one LSB unit.
2918 * For hardware clock frequencies of 10 MHz or less, we assume the
2919 * logical clock advances only at the hardware clock tick. For higher
2920 * frequencies, we assume the logical clock can advance no more than 100
2921 * nanoseconds between ticks.
2924 default_get_precision(void)
2926 l_fp val; /* current seconds fraction */
2927 l_fp last; /* last seconds fraction */
2928 l_fp diff; /* difference */
2929 double tick; /* computed tick value */
2930 double dtemp; /* scratch */
2931 int i; /* log2 precision */
2934 * Loop to find tick value in nanoseconds. Toss out outlyer
2935 * values less than the minimun tick value. In wacky cases, use
2936 * the default maximum value.
2940 for (i = 0; i < MINLOOPS;) {
2943 L_SUB(&diff, &last);
2945 LFPTOD(&diff, dtemp);
2946 if (dtemp < MINSTEP)
2954 * Find the nearest power of two.
2957 msyslog(LOG_INFO, "precision = %.3f usec", tick * 1e6);
2958 for (i = 0; tick <= 1; i++)
2960 if (tick - 1. > 1. - tick / 2)
2967 * kod_proto - called once per second to limit kiss-of-death packets
2972 sys_kod = sys_kod_rate;
2977 * init_proto - initialize the protocol module's data
2986 * Fill in the sys_* stuff. Default is don't listen to
2987 * broadcasting, authenticate.
2989 sys_leap = LEAP_NOTINSYNC;
2990 sys_stratum = STRATUM_UNSPEC;
2991 memcpy(&sys_refid, "INIT", 4);
2992 sys_precision = (s_char)default_get_precision();
2993 sys_jitter = LOGTOD(sys_precision);
2995 sys_rootdispersion = 0;
2996 L_CLR(&sys_reftime);
2999 get_systime(&dummy);
3000 sys_manycastserver = 0;
3002 sys_bdelay = DEFBROADDELAY;
3003 sys_calldelay = BURST_DELAY;
3004 sys_authenticate = 1;
3005 L_CLR(&sys_authdelay);
3006 sys_authdly[0] = sys_authdly[1] = 0;
3009 for (i = 0; i < MAX_TTL; i++) {
3010 sys_ttl[i] = (u_char)((i * 256) / MAX_TTL);
3014 sys_automax = 1 << NTP_AUTOMAX;
3015 #endif /* OPENSSL */
3018 * Default these to enable
3021 #ifndef KERNEL_FLL_BUG
3030 * proto_config - configure the protocol module
3037 struct sockaddr_storage* svalue
3041 * Figure out what he wants to change, then do it
3046 * Turn on/off kernel discipline.
3049 kern_enable = (int)value;
3053 * Turn on/off clock discipline.
3056 ntp_enable = (int)value;
3060 * Turn on/off monitoring.
3070 * Turn on/off statistics.
3073 stats_control = (int)value;
3077 * Turn on/off facility to listen to broadcasts.
3079 case PROTO_BROADCLIENT:
3080 sys_bclient = (int)value;
3088 * Add muliticast group address.
3090 case PROTO_MULTICAST_ADD:
3092 io_multicast_add(*svalue);
3096 * Delete multicast group address.
3098 case PROTO_MULTICAST_DEL:
3100 io_multicast_del(*svalue);
3104 * Set default broadcast delay.
3106 case PROTO_BROADDELAY:
3107 sys_bdelay = dvalue;
3111 * Set modem call delay.
3113 case PROTO_CALLDELAY:
3114 sys_calldelay = (int)value;
3118 * Require authentication to mobilize ephemeral associations.
3120 case PROTO_AUTHENTICATE:
3121 sys_authenticate = (int)value;
3125 * Turn on/off PPS discipline.
3128 pps_enable = (int)value;
3132 * Set the minimum number of survivors.
3134 case PROTO_MINCLOCK:
3135 sys_minclock = (int)dvalue;
3139 * Set the minimum number of candidates.
3142 sys_minsane = (int)dvalue;
3146 * Set the stratum floor.
3149 sys_floor = (int)dvalue;
3153 * Set the stratum ceiling.
3156 sys_ceiling = (int)dvalue;
3160 * Set the cohort switch.
3163 sys_cohort= (int)dvalue;
3166 * Set the adjtime() resolution (s).
3174 * Turn on/off refclock calibrate
3177 cal_enable = (int)value;
3186 "proto_config: illegal item %d, value %ld",
3193 * proto_clr_stats - clear protocol stat counters
3196 proto_clr_stats(void)
3198 sys_stattime = current_time;
3201 sys_newversionpkt = 0;
3202 sys_oldversionpkt = 0;
3203 sys_unknownversion = 0;
3207 sys_limitrejected = 0;