~ubuntu-branches/debian/squeeze/ntp/squeeze-201010051545

« back to all changes in this revision

Viewing changes to ntpd/ntp_proto.c

  • Committer: Bazaar Package Importer
  • Author(s): Kurt Roeckx
  • Date: 2009-01-05 21:10:03 UTC
  • mfrom: (1.2.4 upstream)
  • Revision ID: james.westby@ubuntu.com-20090105211003-mh6zc3um4k1uhsj7
Tags: 1:4.2.4p4+dfsg-8
It did not properly check the return value of EVP_VerifyFinal
which results in an malformed DSA signature being treated as
a good signature rather than as an error.  (CVE-2009-0021)

Show diffs side-by-side

added added

removed removed

Lines of Context:
25
25
#endif
26
26
 
27
27
/*
 
28
 * This macro defines the authentication state. If x is 1 authentication
 
29
 * is required; othewise it is optional.
 
30
 */
 
31
#define AUTH(x, y)      ((x) ? (y) == AUTH_OK : (y) == AUTH_OK || \
 
32
                            (y) == AUTH_NONE)
 
33
 
 
34
/*
28
35
 * System variables are declared here. See Section 3.2 of the
29
36
 * specification.
30
37
 */
31
38
u_char  sys_leap;               /* system leap indicator */
32
39
u_char  sys_stratum;            /* stratum of system */
33
 
s_char  sys_precision;          /* local clock precision */
 
40
s_char  sys_precision;          /* local clock precision (log2 s) */
34
41
double  sys_rootdelay;          /* roundtrip delay to primary source */
35
42
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 */
 
43
u_int32 sys_refid;              /* source/loop in network byte order */
38
44
static  double sys_offset;      /* current local clock offset */
39
45
l_fp    sys_reftime;            /* time we were last updated */
40
46
struct  peer *sys_peer;         /* our current peer */
 
47
struct  peer *sys_pps;          /* our PPS peer */
41
48
struct  peer *sys_prefer;       /* our cherished peer */
42
49
int     sys_kod;                /* kod credit */
43
50
int     sys_kod_rate = 2;       /* max kod packets per second */
44
 
u_long  sys_clocktime;          /* last system clock update */
45
51
#ifdef OPENSSL
46
52
u_long  sys_automax;            /* maximum session key lifetime */
47
53
#endif /* OPENSSL */
55
61
int     sys_authenticate;       /* requre authentication for config */
56
62
l_fp    sys_authdelay;          /* authentication delay */
57
63
static  u_long sys_authdly[2];  /* authentication delay shift reg */
58
 
static  u_char leap_consensus;  /* consensus of survivor leap bits */
59
 
static  double sys_selerr;      /* select error (squares) */
60
 
double  sys_error;              /* system error (s) */
 
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 */
61
70
keyid_t sys_private;            /* private value for session seed */
62
71
int     sys_manycastserver;     /* respond to manycast client pkts */
63
72
int     peer_ntpdate;           /* active peers in ntpdate mode */
69
78
/*
70
79
 * TOS and multicast mapping stuff
71
80
 */
72
 
int     sys_floor = 1;          /* cluster stratum floor */
73
 
int     sys_ceiling = STRATUM_UNSPEC; /* cluster stratum ceiling*/
 
81
int     sys_floor = 0;          /* cluster stratum floor */
 
82
int     sys_ceiling = STRATUM_UNSPEC; /* cluster stratum ceiling */
74
83
int     sys_minsane = 1;        /* minimum candidates */
75
84
int     sys_minclock = NTP_MINCLOCK; /* minimum survivors */
 
85
int     sys_maxclock = NTP_MAXCLOCK; /* maximum candidates */
76
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 */
77
90
int     sys_ttlmax;             /* max ttl mapping vector index */
78
91
u_char  sys_ttl[MAX_TTL];       /* ttl mapping vector */
79
92
 
92
105
u_long  sys_limitrejected;      /* rate exceeded */
93
106
 
94
107
static  double  root_distance   P((struct peer *));
95
 
static  double  clock_combine   P((struct peer **, int));
 
108
static  void    clock_combine   P((struct peer **, int));
96
109
static  void    peer_xmit       P((struct peer *));
97
 
static  void    fast_xmit       P((struct recvbuf *, int, keyid_t, int));
 
110
static  void    fast_xmit       P((struct recvbuf *, int, keyid_t,
 
111
                                    int));
98
112
static  void    clock_update    P((void));
99
 
int     default_get_precision   P((void));
 
113
static  int     default_get_precision   P((void));
100
114
static  int     peer_unfit      P((struct peer *));
101
115
 
 
116
 
102
117
/*
103
118
 * transmit - Transmit Procedure. See Section 3.4.2 of the
104
119
 *      specification.
116
131
         * server modes) and those that do (all other modes). The dance
117
132
         * is intricate...
118
133
         */
 
134
        /*
 
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.
 
143
         */
119
144
        hpoll = peer->hpoll;
 
145
        if (sys_orphan < STRATUM_UNSPEC && sys_peer == NULL) {
 
146
                sys_leap = LEAP_NOWARNING;
 
147
                sys_stratum = sys_orphan;
 
148
                sys_refid = htonl(LOOPBACKADR);
 
149
                sys_rootdelay = 0;
 
150
                sys_rootdispersion = 0;
 
151
        }
 
152
 
 
153
        /*
 
154
         * In broadcast mode the poll interval is never changed from
 
155
         * minpoll.
 
156
         */
120
157
        if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
121
 
 
122
 
                /*
123
 
                 * In broadcast mode the poll interval is never changed
124
 
                 * from minpoll.
125
 
                 */
126
 
                /* fall through */;
127
 
 
128
 
        } else if (peer->cast_flags & MDF_ACAST) {
129
 
 
130
 
                /*
131
 
                 * In manycast mode we start with the minpoll interval
132
 
                 * and unity ttl. The ttl is increased by one for each
133
 
                 * poll until either enough servers have been found or
134
 
                 * the maximum ttl is reached. About once per day when
135
 
                 * the agreement parameters are refreshed, the manycast
136
 
                 * clients are reset and we start from the beginning.
137
 
                 * This is to catch and clamp the ttl to the lowest
138
 
                 * practical value and avoid knocking on spurious doors.
139
 
                 */
140
 
                if (sys_survivors < sys_minclock && peer->ttl <
141
 
                    sys_ttlmax)
142
 
                        peer->ttl++;
 
158
                peer->outdate = current_time;
 
159
                peer_xmit(peer);
 
160
                poll_update(peer, hpoll);
 
161
                return;
 
162
        }
 
163
 
 
164
        /*
 
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.
 
172
         */
 
173
        if (peer->cast_flags & MDF_ACAST) {
 
174
                peer->outdate = current_time;
 
175
                if (peer->unreach > sys_beacon) {
 
176
                        peer->unreach = 0;
 
177
                        peer->ttl = 0;
 
178
                        peer_xmit(peer);
 
179
                } else if (sys_survivors < sys_minclock ||
 
180
                    peer_preempt < sys_maxclock) {
 
181
                        if (peer->ttl < sys_ttlmax)
 
182
                                peer->ttl++;
 
183
                        peer_xmit(peer);
 
184
                }
 
185
                peer->unreach++;
 
186
                poll_update(peer, hpoll);
 
187
                return;
 
188
        }
 
189
 
 
190
        /*
 
191
         * In unicast modes the dance is much more intricate. It is
 
192
         * desigmed to back off whenever possible to minimize network
 
193
         * traffic.
 
194
         */
 
195
        if (peer->burst == 0) {
 
196
                u_char oreach;
 
197
 
 
198
                /*
 
199
                 * Update the reachability status. If not heard for
 
200
                 * three consecutive polls, stuff infinity in the clock
 
201
                 * filter. 
 
202
                 */
 
203
                oreach = peer->reach;
 
204
                peer->outdate = current_time;
 
205
                if (peer == sys_peer)
 
206
                        sys_hopper++;
 
207
                peer->reach <<= 1;
 
208
                if (!(peer->reach & 0x07))
 
209
                        clock_filter(peer, 0., 0., MAXDISPERSE);
 
210
                if (!peer->reach) {
 
211
 
 
212
                        /*
 
213
                         * Here the peer is unreachable. If it was
 
214
                         * previously reachable, raise a trap.
 
215
                         */
 
216
                        if (oreach) {
 
217
                                report_event(EVNT_UNREACH, peer);
 
218
                                peer->timereachable = current_time;
 
219
                        }
 
220
 
 
221
                        /*
 
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.
 
226
                         */
 
227
                        if (peer->flags & FLAG_IBURST &&
 
228
                            peer->unreach == 0) {
 
229
                                peer->burst = NTP_BURST;
 
230
                        }
 
231
                        if (!(peer->flags & FLAG_PREEMPT))      
 
232
                                peer->unreach++;
 
233
                        else
 
234
                                peer->unreach += 3;
 
235
                } else {
 
236
 
 
237
                        /*
 
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.
 
241
                         *
 
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.
 
247
                         */
 
248
                        if (!(peer->flags & FLAG_PREEMPT)) {
 
249
                                peer->unreach = 0;
 
250
                        } else if (peer->status < CTL_PST_SEL_SELCAND) {
 
251
                                peer->unreach += 3;
 
252
                        } else if (peer_preempt > sys_maxclock) {
 
253
                                if (peer->status < CTL_PST_SEL_SYNCCAND)
 
254
                                        peer->unreach += 2;
 
255
                                else
 
256
                                        peer->unreach++;
 
257
                        } else {
 
258
                                peer->unreach = 0;
 
259
                        }
 
260
                        hpoll = sys_poll;
 
261
                        if (peer->flags & FLAG_BURST &&
 
262
                            !peer_unfit(peer))
 
263
                                peer->burst = NTP_BURST;
 
264
                }
 
265
 
 
266
                /*
 
267
                 * Watch for timeout. If ephemeral or preemptable, toss
 
268
                 * the rascal; otherwise, bump the poll interval.
 
269
                 */ 
 
270
                if (peer->unreach >= NTP_UNREACH) {
 
271
                        if (peer->flags & FLAG_PREEMPT ||
 
272
                            !(peer->flags & FLAG_CONFIG)) {
 
273
                                peer_clear(peer, "TIME");
 
274
                                unpeer(peer);
 
275
                                return;
 
276
                        } else {
 
277
                                hpoll++;
 
278
                        }
 
279
                }
143
280
        } else {
 
281
                peer->burst--;
 
282
 
 
283
                /*
 
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.
 
287
                 */
144
288
                if (peer->burst == 0) {
145
 
                        u_char oreach;
146
 
 
147
 
                        oreach = peer->reach;
148
 
                        peer->reach <<= 1;
149
 
                        peer->hyst *= HYST_TC;
150
 
                        if (peer->reach == 0) {
151
 
 
152
 
                                /*
153
 
                                 * If this association has become
154
 
                                 * unreachable, clear it and raise a
155
 
                                 * trap.
156
 
                                 */
157
 
                                if (oreach != 0) {
158
 
                                        report_event(EVNT_UNREACH,
159
 
                                            peer);
160
 
                                        peer->timereachable =
161
 
                                            current_time;
162
 
                                        if (peer->flags & FLAG_CONFIG) {
163
 
                                                peer_clear(peer,
164
 
                                                    "INIT");
165
 
                                        } else {
166
 
                                                unpeer(peer);
167
 
                                                return;
168
 
                                        }
169
 
                                }
170
 
 
171
 
                                /*
172
 
                                 * If a configured association has been
173
 
                                 * unreachable for a long time, double
174
 
                                 * it at each poll and send a single
175
 
                                 * packet instead of a burst. If not
176
 
                                 * configured, off it. If it flashes
177
 
                                 * authentic error, mark it
178
 
                                 * cryptographically dead.
179
 
                                 */
180
 
                                if (peer->unreach < NTP_UNREACH) {
181
 
                                        peer->unreach++;
182
 
                                        if (peer->flags & FLAG_IBURST &&
183
 
                                            !(peer->flash & TEST5))
184
 
                                                peer->burst = NTP_BURST;
185
 
                                } else if (!(peer->flags &
186
 
                                    FLAG_CONFIG)) {
187
 
                                        unpeer(peer);
188
 
                                        return;
189
 
 
190
 
                                } else if (peer->flash & TEST5) {
191
 
                                        peer_clear(peer, "CRYPTO");
192
 
                                        peer->flash += TEST4;
193
 
                                } else {
194
 
                                        if (hpoll < peer->maxpoll)
195
 
                                                hpoll++;
196
 
                                }
197
 
                        } else {
198
 
                                /*
199
 
                                 * Here the peer is reachable. If it has
200
 
                                 * not been heard for three consecutive
201
 
                                 * polls, stuff infinity in the clock
202
 
                                 * filter. Next, determine the poll
203
 
                                 * interval. If the peer is unfit for
204
 
                                 * synchronization, increase it by one;
205
 
                                 * else, use the system poll interval,
206
 
                                 * but clamp it within bounds for this
207
 
                                 * peer. 
208
 
                                 */
209
 
                                peer->unreach = 0;
210
 
                                if (!(peer->reach & 0x07))
211
 
                                        clock_filter(peer, 0., 0.,
212
 
                                            MAXDISPERSE);
213
 
                                if (peer_unfit(peer)) {
214
 
                                        if (hpoll < peer->maxpoll)
215
 
                                                hpoll++;
216
 
                                } else {
217
 
                                        hpoll = sys_poll;
218
 
                                        if (hpoll > peer->maxpoll)
219
 
                                                hpoll = peer->maxpoll;
220
 
                                        else if (hpoll < peer->minpoll)
221
 
                                                hpoll = peer->minpoll;
222
 
                                        if (peer->flags & FLAG_BURST)
223
 
                                                peer->burst = NTP_BURST;
224
 
                                }
 
289
                        if (peer->cast_flags & MDF_BCLNT) {
 
290
                                peer->hmode = MODE_BCLIENT;
 
291
#ifdef OPENSSL
 
292
                                key_expire(peer);
 
293
#endif /* OPENSSL */
225
294
                        }
226
 
                } else {
227
295
 
228
296
                        /*
229
 
                         * Call-gap control. If we are restrained, each
230
 
                         * burst consists of only one packet.
 
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.
231
300
                         */
232
 
                        if (memcmp(&peer->refid, "RSTR", 4) == 0)
233
 
                                peer->burst = 0;
234
 
                        else
235
 
                                peer->burst--;
236
 
                        if (peer->burst == 0) {
237
 
 
238
 
                                /*
239
 
                                 * If a broadcast client at this point,
240
 
                                 * the burst has concluded, so we switch
241
 
                                 * to client mode and purge the keylist,
242
 
                                 * since no further transmissions will
243
 
                                 * be made.
244
 
                                 */
245
 
                                if (peer->cast_flags & MDF_BCLNT) {
246
 
                                        peer->hmode = MODE_BCLIENT;
247
 
#ifdef OPENSSL
248
 
                                        key_expire(peer);
249
 
#endif /* OPENSSL */
250
 
                                }
251
 
 
252
 
                                /*
253
 
                                 * If ntpdate mode and the clock has not
254
 
                                 * been set and all peers have completed
255
 
                                 * the burst, we declare a successful
256
 
                                 * failure.
257
 
                                 */
258
 
                                if (mode_ntpdate) {
259
 
                                        peer_ntpdate--;
260
 
                                        if (peer_ntpdate == 0) {
261
 
                                                msyslog(LOG_NOTICE,
262
 
                                                    "no reply; clock not set");
263
 
                                                exit (0);
264
 
                                        }
265
 
                                }
266
 
                                clock_select();
267
 
                                poll_update(peer, hpoll);
268
 
                                return;
 
301
                        if (mode_ntpdate) {
 
302
                                peer_ntpdate--;
 
303
                                if (peer_ntpdate == 0) {
 
304
                                        msyslog(LOG_NOTICE,
 
305
                                            "no reply; clock not set");
 
306
                                        exit (0);
 
307
                                }
269
308
                        }
270
309
                }
271
310
        }
272
 
        peer->outdate = peer->nextdate = current_time;
273
311
 
274
312
        /*
275
313
         * Do not transmit if in broadcast client mode. 
276
314
         */
277
 
        if (peer->hmode == MODE_BCLIENT) {
278
 
                poll_update(peer, hpoll);
279
 
                return;
280
 
 
281
 
        /*
282
 
         * Do not transmit in broadcast mode unless we are synchronized.
283
 
         */
284
 
        } else if (peer->hmode == MODE_BROADCAST && sys_peer == NULL) {
285
 
                poll_update(peer, hpoll);
286
 
                return;
287
 
        }
288
 
 
289
 
        /*
290
 
         * Do not transmit if in access-deny or crypto jail. Clamp the
291
 
         * poll to minimum if a get out of jail free card shows up.
292
 
         */
293
 
        if (peer->flash & TEST4) {
294
 
                if (!(peer->flags & FLAG_CONFIG)) {
295
 
                        unpeer(peer);
296
 
                        return;
297
 
                }
298
 
                poll_update(peer, peer->minpoll);
299
 
        } else {
 
315
        if (peer->hmode != MODE_BCLIENT)
300
316
                peer_xmit(peer);
301
 
                poll_update(peer, hpoll);
302
 
        }
 
317
        poll_update(peer, hpoll);
303
318
}
304
319
 
 
320
 
305
321
/*
306
322
 * receive - Receive Procedure.  See section 3.4.3 in the specification.
307
323
 */
312
328
{
313
329
        register struct peer *peer;     /* peer structure pointer */
314
330
        register struct pkt *pkt;       /* receive packet pointer */
 
331
        int     hisversion;             /* packet version */
 
332
        int     hisleap;                /* packet leap indicator */
315
333
        int     hismode;                /* packet mode */
 
334
        int     hisstratum;             /* packet stratum */
316
335
        int     restrict_mask;          /* restrict bits */
317
336
        int     has_mac;                /* length of MAC field */
318
337
        int     authlen;                /* offset of MAC field */
319
 
        int     is_authentic;           /* cryptosum ok */
 
338
        int     is_authentic = 0;       /* cryptosum ok */
320
339
        keyid_t skeyid = 0;             /* key ID */
321
340
        struct sockaddr_storage *dstadr_sin; /* active runway */
322
341
        struct peer *peer2;             /* aux peer structure pointer */
323
 
        l_fp    p_org;                  /* originate timestamp */
 
342
        l_fp    p_org;                  /* origin timestamp */
 
343
        l_fp    p_rec;                  /* receive timestamp */
324
344
        l_fp    p_xmt;                  /* transmit timestamp */
325
345
#ifdef OPENSSL
326
346
        keyid_t tkeyid = 0;             /* temporary key ID */
329
349
        int     rval;                   /* cookie snatcher */
330
350
#endif /* OPENSSL */
331
351
        int retcode = AM_NOMATCH;
 
352
        int     at_listhead;
332
353
 
333
354
        /*
334
355
         * Monitor the packet and get restrictions. Note that the packet
349
370
                sys_badlength++;
350
371
                return;                         /* bogus port */
351
372
        }
352
 
        ntp_monitor(rbufp);
353
 
        restrict_mask = restrictions(&rbufp->recv_srcadr);
 
373
        at_listhead = ntp_monitor(rbufp);
 
374
        restrict_mask = restrictions(&rbufp->recv_srcadr, at_listhead);
354
375
#ifdef DEBUG
355
376
        if (debug > 1)
356
 
                printf("receive: at %ld %s<-%s restrict %03x\n",
 
377
                printf("receive: at %ld %s<-%s flags %x restrict %03x\n",
357
378
                    current_time, stoa(&rbufp->dstadr->sin),
358
 
                    stoa(&rbufp->recv_srcadr), restrict_mask);
 
379
                    stoa(&rbufp->recv_srcadr),
 
380
                    rbufp->dstadr->flags, restrict_mask);
359
381
#endif
360
382
        if (restrict_mask & RES_IGNORE) {
361
383
                sys_restricted++;
362
 
                return;                         /* no anything */
 
384
                return;                         /* ignore everything */
363
385
        }
364
386
        pkt = &rbufp->recv_pkt;
 
387
        hisversion = PKT_VERSION(pkt->li_vn_mode);
 
388
        hisleap = PKT_LEAP(pkt->li_vn_mode);
365
389
        hismode = (int)PKT_MODE(pkt->li_vn_mode);
 
390
        hisstratum = PKT_TO_STRATUM(pkt->stratum);
366
391
        if (hismode == MODE_PRIVATE) {
367
392
                if (restrict_mask & RES_NOQUERY) {
368
393
                        sys_restricted++;
393
418
         * Version check must be after the query packets, since they
394
419
         * intentionally use early version.
395
420
         */
396
 
        if (PKT_VERSION(pkt->li_vn_mode) == NTP_VERSION) {
 
421
        if (hisversion == NTP_VERSION) {
397
422
                sys_newversionpkt++;            /* new version */
398
 
        } else if (!(restrict_mask & RES_VERSION) &&
399
 
            PKT_VERSION(pkt->li_vn_mode) >= NTP_OLDVERSION) {
 
423
        } else if (!(restrict_mask & RES_VERSION) && hisversion >=
 
424
            NTP_OLDVERSION) {
400
425
                sys_oldversionpkt++;            /* previous version */
401
426
        } else {
402
427
                sys_unknownversion++;
410
435
         * would interpret as client mode.
411
436
         */
412
437
        if (hismode == MODE_UNSPEC) {
413
 
                if (PKT_VERSION(pkt->li_vn_mode) == NTP_OLDVERSION) {
 
438
                if (hisversion == NTP_OLDVERSION) {
414
439
                        hismode = MODE_CLIENT;
415
440
                } else {
416
441
                        sys_badlength++;
419
444
        }
420
445
 
421
446
        /*
422
 
         * Discard broadcast if not enabled as broadcast client. If
423
 
         * Autokey, the wildcard interface cannot be used, so dump
424
 
         * packets gettiing off the bus at that stop as well. This means
425
 
         * that some systems with broken interface code, specifically
426
 
         * Linux, will not work with Autokey.
427
 
         */
428
 
        if (hismode == MODE_BROADCAST) {
429
 
                if (!sys_bclient || restrict_mask & RES_NOPEER) {
430
 
                        sys_restricted++;
431
 
                        return;                 /* no client */
432
 
                }
433
 
#ifdef OPENSSL
434
 
                if (crypto_flags && rbufp->dstadr == any_interface) {
435
 
                        sys_restricted++;
436
 
                        return;                 /* no client */
437
 
                }
438
 
#endif /* OPENSSL */
439
 
        }
440
 
 
441
 
        /*
442
447
         * Parse the extension field if present. We figure out whether
443
448
         * an extension field is present by measuring the MAC size. If
444
 
         * the number of words following the packet header is 0 or 1, no
445
 
         * MAC is present and the packet is not authenticated. If 1, the
446
 
         * packet is a reply to a previous request that failed to
447
 
         * authenticate. If 3, the packet is authenticated with DES; if
448
 
         * 5, the packet is authenticated with MD5. If greater than 5,
449
 
         * an extension field is present. If 2 or 4, the packet is a
450
 
         * runt and goes poof! with a brilliant flash.
 
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.
451
456
         */
452
457
        authlen = LEN_PKT_NOMAC;
453
458
        has_mac = rbufp->recv_length - authlen;
497
502
         * address used to construct the autokey is the unicast address
498
503
         * of the interface. However, if the sender is a broadcaster,
499
504
         * the interface broadcast address is used instead.
500
 
         * Notwithstanding this technobabble, if the sender is a
 
505
         & Notwithstanding this technobabble, if the sender is a
501
506
         * multicaster, the broadcast address is null, so we use the
502
507
         * unicast address anyway. Don't ask.
503
508
         */
504
 
        peer = findpeer(&rbufp->recv_srcadr, rbufp->dstadr, rbufp->fd,
505
 
            hismode, &retcode);
506
 
        is_authentic = 0;
 
509
        peer = findpeer(&rbufp->recv_srcadr, rbufp->dstadr,  hismode,
 
510
            &retcode);
507
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);
 
515
 
 
516
        /*
 
517
         * Authentication is conditioned by three switches:
 
518
         *
 
519
         * NOPEER  (RES_NOPEER) do not mobilize an association unless
 
520
         *         authenticated
 
521
         * NOTRUST (RES_DONTTRUST) do not allow access unless
 
522
         *         authenticated (implies NOPEER)
 
523
         * enable  (sys_authenticate) master NOPEER switch, by default
 
524
         *         on
 
525
         *
 
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:
 
529
         *
 
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.
 
534
         *
 
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.
 
538
         */
508
539
        if (has_mac == 0) {
509
 
#ifdef DEBUG
510
 
                if (debug)
511
 
                        printf("receive: at %ld %s<-%s mode %d code %d\n",
512
 
                            current_time, stoa(&rbufp->dstadr->sin),
513
 
                            stoa(&rbufp->recv_srcadr), hismode,
514
 
                            retcode);
 
540
                is_authentic = AUTH_NONE; /* not required */
 
541
#ifdef DEBUG
 
542
                if (debug)
 
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,
 
546
                            is_authentic);
 
547
#endif
 
548
        } else if (has_mac == 4) {
 
549
                        is_authentic = AUTH_CRYPTO; /* crypto-NAK */
 
550
#ifdef DEBUG
 
551
                if (debug)
 
552
                        printf(
 
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);
515
557
#endif
516
558
        } else {
517
559
#ifdef OPENSSL
554
596
                                 * broadcast address when available;
555
597
                                 * otherwise, use the unicast address
556
598
                                 * found when the association was
557
 
                                 * mobilized.
 
599
                                 * mobilized. However, if this is from
 
600
                                 * the wildcard interface, game over.
558
601
                                 */
 
602
                                if (crypto_flags && rbufp->dstadr ==
 
603
                                    any_interface) {
 
604
                                        sys_restricted++;
 
605
                                        return;      /* no wildcard */
 
606
                                }
559
607
                                pkeyid = 0;
560
608
                                if (!SOCKNUL(&rbufp->dstadr->bcast))
561
609
                                        dstadr_sin =
594
642
                 * Compute the cryptosum. Note a clogging attack may
595
643
                 * succeed in bloating the key cache. If an autokey,
596
644
                 * purge it immediately, since we won't be needing it
597
 
                 * again. If the packet is authentic, it may mobilize an
598
 
                 * association.
 
645
                 * again. If the packet is authentic, it can mobilize an
 
646
                 * association. Note that there is no key zero.
599
647
                 */
600
 
                if (authdecrypt(skeyid, (u_int32 *)pkt, authlen,
 
648
                if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,
601
649
                    has_mac)) {
602
 
                        is_authentic = 1;
603
 
                        restrict_mask &= ~RES_DONTTRUST;
604
 
                } else {
 
650
                        is_authentic = AUTH_ERROR;
605
651
                        sys_badauth++;
 
652
                } else {
 
653
                        is_authentic = AUTH_OK;
606
654
                }
607
655
#ifdef OPENSSL
608
656
                if (skeyid > NTP_MAXKEY)
614
662
                            "receive: at %ld %s<-%s mode %d code %d keyid %08x len %d mac %d auth %d\n",
615
663
                            current_time, stoa(dstadr_sin),
616
664
                            stoa(&rbufp->recv_srcadr), hismode, retcode,
617
 
                            skeyid, authlen, has_mac,
618
 
                            is_authentic);
 
665
                            skeyid, authlen, has_mac, is_authentic);
619
666
#endif
620
667
        }
621
668
 
622
669
        /*
623
670
         * The association matching rules are implemented by a set of
624
 
         * routines and a table in ntp_peer.c. A packet matching an
625
 
         * association is processed by that association. If not and
626
 
         * certain conditions prevail, then an ephemeral association is
627
 
         * mobilized: a broadcast packet mobilizes a broadcast client
 
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
628
675
         * aassociation; a manycast server packet mobilizes a manycast
629
676
         * client association; a symmetric active packet mobilizes a
630
 
         * symmetric passive association. And, the adventure
631
 
         * continues...
 
677
         * symmetric passive association.
632
678
         */
633
679
        switch (retcode) {
 
680
 
 
681
        /*
 
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
 
685
         * little harder.
 
686
         */
634
687
        case AM_FXMIT:
635
688
 
636
689
                /*
637
 
                 * This is a client mode packet not matching a known
638
 
                 * association. If from a manycast client we run a few
639
 
                 * sanity checks before deciding to send a unicast
640
 
                 * server response. Otherwise, it must be a client
641
 
                 * request, so send a server response and go home.
642
 
                 */
643
 
                if (rbufp->dstadr->flags & INT_MULTICAST) {
644
 
 
645
 
                        /*
646
 
                         * Do not respond to multicast if not configured
647
 
                         * as a manycast server.
648
 
                         */
649
 
                        if (hismode == MODE_CLIENT &&
650
 
                            !sys_manycastserver)
651
 
                                return;
652
 
 
653
 
                        /*
654
 
                         * There is no reason to respond to a request if
655
 
                         * our time is worse than the manycaster or it
656
 
                         * has already synchronized to us.
657
 
                         */
658
 
                        if (sys_peer == NULL ||
659
 
                            PKT_TO_STRATUM(pkt->stratum) <
660
 
                            sys_stratum || (sys_cohort &&
661
 
                            PKT_TO_STRATUM(pkt->stratum) ==
662
 
                            sys_stratum) || rbufp->dstadr->addr_refid ==
663
 
                            pkt->refid)
664
 
                                return;         /* manycast dropped */
665
 
                }
666
 
 
667
 
                /*
668
 
                 * Note that we don't require an authentication check
669
 
                 * here, since we can't set the system clock; but, we do
670
 
                 * send a crypto-NAK to tell the caller about this.
671
 
                 */
672
 
                if (has_mac && !is_authentic)
673
 
                        fast_xmit(rbufp, MODE_SERVER, 0, restrict_mask);
674
 
                else
 
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.
 
694
                 */
 
695
                if (!(rbufp->dstadr->flags & INT_MCASTOPEN)) {
 
696
                        if (AUTH(restrict_mask & RES_DONTTRUST,
 
697
                           is_authentic))
 
698
                                fast_xmit(rbufp, MODE_SERVER, skeyid,
 
699
                                    restrict_mask);
 
700
                        else if (is_authentic == AUTH_ERROR)
 
701
                                fast_xmit(rbufp, MODE_SERVER, 0,
 
702
                                    restrict_mask);
 
703
                        return;                 /* hooray */
 
704
                }
 
705
 
 
706
                /*
 
707
                 * This must be manycast. Do not respond if not
 
708
                 * configured as a manycast server.
 
709
                 */
 
710
                if (!sys_manycastserver) {
 
711
                        sys_restricted++;
 
712
                        return;                 /* not enabled */
 
713
                }
 
714
 
 
715
                /*
 
716
                 * Do not respond if unsynchronized or stratum is below
 
717
                 * the floor or at or above the ceiling.
 
718
                 */
 
719
                if (sys_leap == LEAP_NOTINSYNC || sys_stratum <
 
720
                    sys_floor || sys_stratum >= sys_ceiling)
 
721
                        return;                 /* bad stratum */
 
722
 
 
723
                /*
 
724
                 * Do not respond if our stratum is greater than the
 
725
                 * manycaster or it has already synchronized to us.
 
726
                 */
 
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 */
 
731
 
 
732
                /*
 
733
                 * Respond only if authentication succeeds. Don't do a
 
734
                 * crypto-NAK, as that would not be useful.
 
735
                 */
 
736
                if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic))
675
737
                        fast_xmit(rbufp, MODE_SERVER, skeyid,
676
738
                            restrict_mask);
677
 
                return;
678
 
 
 
739
 
 
740
                return;                         /* hooray */
 
741
 
 
742
        /*
 
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
 
748
         * it.
 
749
         *
 
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.
 
754
         *
 
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.
 
758
         */
679
759
        case AM_MANYCAST:
 
760
                if (!AUTH(sys_authenticate | (restrict_mask &
 
761
                    (RES_NOPEER | RES_DONTTRUST)), is_authentic))
 
762
                        return;                 /* bad auth */
680
763
 
681
 
                /*
682
 
                 * This is a server mode packet returned in response to
683
 
                 * a client mode packet sent to a multicast group
684
 
                 * address. The originate timestamp is a good nonce to
685
 
                 * reliably associate the reply with what was sent. If
686
 
                 * there is no match, that's curious and could be an
687
 
                 * intruder attempting to clog, so we just ignore it.
688
 
                 *
689
 
                 * First, make sure the packet is authentic and not
690
 
                 * restricted. If so and the manycast association is
691
 
                 * found, we mobilize a client association and copy
692
 
                 * pertinent variables from the manycast association to
693
 
                 * the new client association.
694
 
                 *
695
 
                 * There is an implosion hazard at the manycast client,
696
 
                 * since the manycast servers send the server packet
697
 
                 * immediately. If the guy is already here, don't fire
698
 
                 * up a duplicate.
699
 
                 */
700
 
                if (restrict_mask & RES_DONTTRUST) {
 
764
                if ((peer2 = findmanycastpeer(rbufp)) == NULL) {
701
765
                        sys_restricted++;
702
 
                        return;                 /* no trust */
 
766
                        return;                 /* not enabled */
703
767
                }
704
 
                if (sys_authenticate && !is_authentic)
705
 
                        return;                 /* bad auth */
706
 
 
707
 
                if ((peer2 = findmanycastpeer(rbufp)) == NULL)
708
 
                        return;                 /* no assoc match */
709
 
 
710
 
                if ((peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
711
 
                    MODE_CLIENT, PKT_VERSION(pkt->li_vn_mode),
712
 
                    NTP_MINDPOLL, NTP_MAXDPOLL, FLAG_IBURST, MDF_UCAST |
713
 
                    MDF_ACLNT, 0, skeyid)) == NULL)
 
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,
 
772
                    0, skeyid)) == NULL)
714
773
                        return;                 /* system error */
715
774
 
716
775
                /*
719
778
                peer->ttl = peer2->ttl;
720
779
                break;
721
780
 
 
781
        /*
 
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.
 
786
         */
 
787
        case AM_NEWBCL:
 
788
                if (!AUTH(sys_authenticate | (restrict_mask &
 
789
                    (RES_NOPEER | RES_DONTTRUST)), is_authentic))
 
790
                        return;                 /* bad auth */
 
791
 
 
792
                /*
 
793
                 * Do not respond if unsynchronized or stratum is below
 
794
                 * the floor or at or above the ceiling.
 
795
                 */
 
796
                if (hisleap == LEAP_NOTINSYNC || hisstratum <
 
797
                    sys_floor || hisstratum >= sys_ceiling)
 
798
                        return;                 /* bad stratum */
 
799
 
 
800
                switch (sys_bclient) {
 
801
 
 
802
                /*
 
803
                 * If not enabled, just skedaddle.
 
804
                 */
 
805
                case 0:
 
806
                        sys_restricted++;
 
807
                        return;                 /* not enabled */
 
808
 
 
809
                /*
 
810
                 * Execute the initial volley in order to calibrate the
 
811
                 * propagation delay and run the Autokey protocol, if
 
812
                 * enabled.
 
813
                 */
 
814
                case 1:
 
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)) ==
 
819
                            NULL)
 
820
                                return;         /* system error */
 
821
#ifdef OPENSSL
 
822
                        if (skeyid > NTP_MAXKEY)
 
823
                                crypto_recv(peer, rbufp);
 
824
#endif /* OPENSSL */
 
825
                        return;                 /* hooray */
 
826
 
 
827
 
 
828
                /*
 
829
                 * Do not execute the initial volley.
 
830
                 */
 
831
                case 2:
 
832
#ifdef OPENSSL
 
833
                        /*
 
834
                         * If a two-way exchange is not possible,
 
835
                         * neither is Autokey.
 
836
                         */
 
837
                        if (skeyid > NTP_MAXKEY) {
 
838
                                msyslog(LOG_INFO,
 
839
                                    "receive: autokey requires two-way communication");
 
840
                                return;         /* no autokey */
 
841
                        }
 
842
#endif /* OPENSSL */
 
843
                        if ((peer = newpeer(&rbufp->recv_srcadr,
 
844
                            rbufp->dstadr, MODE_BCLIENT, hisversion,
 
845
                            NTP_MINDPOLL, NTP_MAXDPOLL, 0, MDF_BCLNT, 0,
 
846
                            skeyid)) == NULL)
 
847
                                return;         /* system error */
 
848
                }
 
849
                break;
 
850
 
 
851
        /*
 
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.
 
855
         */
722
856
        case AM_NEWPASS:
723
857
 
724
858
                /*
725
 
                 * This is the first packet received from a symmetric
726
 
                 * active peer. First, make sure it is authentic and not
727
 
                 * restricted. If so, mobilize a passive association.
728
 
                 * If authentication fails send a crypto-NAK; otherwise,
729
 
                 * 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. 
730
864
                 */
731
 
                if (restrict_mask & RES_DONTTRUST) {
732
 
                        sys_restricted++;
733
 
                        return;                 /* no trust */
 
865
                if (!AUTH(restrict_mask & RES_DONTTRUST, is_authentic))
 
866
                    {
 
867
                        if (is_authentic == AUTH_ERROR)
 
868
                                fast_xmit(rbufp, MODE_ACTIVE, 0,
 
869
                                    restrict_mask);
 
870
                        return;                 /* bad auth */
734
871
                }
735
 
                if (sys_authenticate && !is_authentic) {
736
 
                        fast_xmit(rbufp, MODE_PASSIVE, 0,
 
872
                if (!AUTH(sys_authenticate | (restrict_mask &
 
873
                    RES_NOPEER), is_authentic)) {
 
874
                        fast_xmit(rbufp, MODE_ACTIVE, skeyid,
737
875
                            restrict_mask);
738
 
                        return;                 /* bad auth */
 
876
                        return;                 /* hooray */
739
877
                }
740
 
                if ((peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
741
 
                    MODE_PASSIVE, PKT_VERSION(pkt->li_vn_mode),
 
878
 
 
879
                /*
 
880
                 * Do not respond if stratum is below the floor.
 
881
                 */
 
882
                if (hisstratum < sys_floor)
 
883
                        return;                 /* bad stratum */
 
884
 
 
885
                if ((peer = newpeer(&rbufp->recv_srcadr,
 
886
                    rbufp->dstadr, MODE_PASSIVE, hisversion,
742
887
                    NTP_MINDPOLL, NTP_MAXDPOLL, 0, MDF_UCAST, 0,
743
888
                    skeyid)) == NULL)
744
889
                        return;                 /* system error */
745
 
 
746
890
                break;
747
891
 
748
 
        case AM_NEWBCL:
749
 
 
750
 
                /*
751
 
                 * This is the first packet received from a broadcast
752
 
                 * server. First, make sure it is authentic and not
753
 
                 * restricted and that we are a broadcast client. If so,
754
 
                 * mobilize a broadcast client association. We don't
755
 
                 * kiss any frogs here.
756
 
                 */
757
 
                if (restrict_mask & RES_DONTTRUST) {
758
 
                        sys_restricted++;
759
 
                        return;                 /* no trust */
760
 
                }
761
 
                if (sys_authenticate && !is_authentic)
762
 
                        return;                 /* bad auth */
763
 
 
764
 
                if (sys_bclient == 0)
765
 
                        return;                 /* not a client */
766
 
 
767
 
                if (sys_bclient == 1)
768
 
                        peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
769
 
                            MODE_CLIENT, PKT_VERSION(pkt->li_vn_mode),
770
 
                            NTP_MINDPOLL, NTP_MAXDPOLL, FLAG_MCAST |
771
 
                            FLAG_IBURST, MDF_BCLNT, 0, skeyid);
772
 
                else
773
 
                        peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
774
 
                            MODE_BCLIENT, PKT_VERSION(pkt->li_vn_mode),
775
 
                            NTP_MINDPOLL, NTP_MAXDPOLL, 0, MDF_BCLNT, 0,
776
 
                            skeyid);
777
 
                if (peer == NULL)
778
 
                        return;                 /* system error */
779
 
#ifdef OPENSSL
780
 
                /*
781
 
                 * Danger looms. If this is autokey, go process the
782
 
                 * extension fields. If something goes wrong, abandon
783
 
                 * ship and don't trust subsequent packets.
784
 
                 */
785
 
                if (crypto_flags) {
786
 
                        if ((rval = crypto_recv(peer, rbufp)) !=
787
 
                            XEVNT_OK) {
788
 
                                struct sockaddr_storage mskadr_sin;
789
 
 
790
 
                                unpeer(peer);
791
 
                                sys_restricted++;
792
 
                                SET_HOSTMASK(&mskadr_sin,
793
 
                                    rbufp->recv_srcadr.ss_family);
794
 
                                hack_restrict(RESTRICT_FLAGS,
795
 
                                    &rbufp->recv_srcadr, &mskadr_sin,
796
 
                                    0, RES_DONTTRUST | RES_TIMEOUT);
797
 
#ifdef DEBUG
798
 
                                if (debug)
799
 
                                        printf(
800
 
                                            "packet: bad exten %x\n",
801
 
                                            rval);
802
 
#endif
803
 
                        }
804
 
                }
805
 
#endif /* OPENSSL */
806
 
                return;
807
 
 
808
 
        case AM_POSSBCL:
809
 
 
810
 
                /*
811
 
                 * This is a broadcast packet received in client mode.
812
 
                 * It could happen if the initial client/server volley
813
 
                 * is not complete before the next broadcast packet is
814
 
                 * received. Be liberal in what we accept.
815
 
                 */ 
 
892
        /*
 
893
         * Process regular packet. Nothing special.
 
894
         */
816
895
        case AM_PROCPKT:
817
 
 
818
 
                /*
819
 
                 * This is a symmetric mode packet received in symmetric
820
 
                 * mode, a server packet received in client mode or a
821
 
                 * broadcast packet received in broadcast client mode.
822
 
                 * If it is restricted, this is very strange because it
823
 
                 * is rude to send a packet to a restricted address. If
824
 
                 * anyway, flash a restrain kiss and skedaddle to
825
 
                 * Seattle. If not authentic, leave a light on and
826
 
                 * continue.
827
 
                 */
828
 
                if (restrict_mask & RES_DONTTRUST) {
829
 
                        sys_restricted++;
830
 
                        if (peer->flags & FLAG_CONFIG)
831
 
                                peer_clear(peer, "RSTR");
832
 
                        else
833
 
                                unpeer(peer);
834
 
                        return;                 /* no trust */
835
 
                }
836
896
                break;
837
897
 
 
898
        /*
 
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.
 
903
         */
 
904
        case AM_ERR:
 
905
                return;
 
906
 
 
907
        /*
 
908
         * For everything else there is the bit bucket.
 
909
         */
838
910
        default:
839
 
 
840
 
                /*
841
 
                 * Invalid mode combination. This happens when a passive
842
 
                 * mode packet arrives and matches another passive
843
 
                 * association or no association at all, or when a
844
 
                 * server mode packet arrives and matches a broadcast
845
 
                 * client association. This is usually the result of
846
 
                 * reconfiguring a client on-fly. If authenticated
847
 
                 * passive mode packet, send a crypto-NAK; otherwise,
848
 
                 * ignore it.
849
 
                 */
850
 
                if (has_mac && hismode == MODE_PASSIVE)
 
911
                return;
 
912
        }
 
913
        peer->flash &= ~PKT_TEST_MASK;
 
914
 
 
915
        /*
 
916
         * Next comes a rigorous schedule of timestamp checking. If the
 
917
         * transmit timestamp is zero, the server is horribly broken.
 
918
         */
 
919
        if (L_ISZERO(&p_xmt)) {
 
920
                return;                         /* read rfc1305 */
 
921
 
 
922
        /*
 
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.
 
926
         */
 
927
        } else if (L_ISEQU(&peer->org, &p_xmt)) {
 
928
                peer->flash |= TEST1;
 
929
                peer->oldpkt++;
 
930
                return;                         /* duplicate packet */
 
931
        
 
932
 
 
933
        /*
 
934
         * If this is a broadcast mode packet, skip further checking.
 
935
         */
 
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 */
 
941
        }
 
942
 
 
943
        /*
 
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.
 
947
         */
 
948
        peer->org = p_xmt;
 
949
        peer->rec = rbufp->recv_time;
 
950
        if (peer->flash & PKT_TEST_MASK) {
 
951
#ifdef OPENSSL
 
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 */
 
957
                        }
 
958
                }
 
959
#endif /* OPENSSL */
 
960
                return;                         /* unsynch */
 
961
        }
 
962
 
 
963
        /*
 
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.
 
968
         */
 
969
        if (is_authentic == AUTH_CRYPTO) {
 
970
                peer_clear(peer, "AUTH");
 
971
                return;                         /* crypto-NAK */
 
972
 
 
973
        /* 
 
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.
 
979
         */
 
980
        } else if (!AUTH(peer->keyid || (restrict_mask & RES_DONTTRUST),
 
981
            is_authentic)) {
 
982
                peer->flash |= TEST5;
 
983
                if (hismode == MODE_ACTIVE || hismode == MODE_PASSIVE)
851
984
                        fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
852
 
#ifdef DEBUG
853
 
                if (debug)
854
 
                        printf("receive: bad protocol %d\n", retcode);
855
 
#endif
856
 
                return;
 
985
                return;                         /* bad auth */
857
986
        }
858
987
 
859
988
        /*
860
 
         * We do a little homework. Note we can get here with an
861
 
         * authentication error. We need to do this in order to validate
862
 
         * a crypto-NAK later. Note the order of processing; it is very
863
 
         * important to avoid livelocks, deadlocks and lockpicks.
 
989
         * That was hard and I am sweaty, but the packet is squeaky
 
990
         * clean. Get on with real work.
864
991
         */
865
992
        peer->received++;
866
993
        peer->timereceived = current_time;
867
 
        peer->flash = 0;
868
 
        peer->flags &= ~FLAG_AUTHENTIC;
869
 
        if (has_mac) {
870
 
                if (is_authentic)
871
 
                        peer->flags |= FLAG_AUTHENTIC;
872
 
                else if (sys_authenticate)
873
 
                        peer->flash |= TEST5;   /* bad auth */
874
 
        }
875
 
        NTOHL_FP(&pkt->org, &p_org);
876
 
        NTOHL_FP(&pkt->xmt, &p_xmt);
877
 
 
878
 
        /*
879
 
         * If the packet is an old duplicate, drop it.
880
 
         */
881
 
        if (L_ISEQU(&peer->org, &p_xmt)) {      /* test 1 */
882
 
                peer->flash |= TEST1;           /* dupe */
883
 
                /* fall through */
884
 
 
885
 
        /*
886
 
         * For broadcast server mode, loopback checking is disabled. An
887
 
         * authentication error probably means the server restarted or
888
 
         * rolled a new private value. If so, dump the association
889
 
         * and wait for the next message.
890
 
         */
891
 
        } else if (hismode == MODE_BROADCAST) {
892
 
                if (peer->flash & TEST5) {
893
 
                        unpeer(peer);
894
 
                        return;
895
 
                }
896
 
                /* fall through */
897
 
 
898
 
        /*
899
 
         * For server and symmetric modes, if the association transmit
900
 
         * timestamp matches the packet originate timestamp, loopback is
901
 
         * confirmed. Note in symmetric modes this also happens when the
902
 
         * first packet from the active peer arrives at the newly
903
 
         * mobilized passive peer. An authentication error probably
904
 
         * means the server or peer restarted or rolled a new private
905
 
         * value, but could be an intruder trying to stir up trouble.
906
 
         * However, if this is a crypto-NAK, we know it is authentic. If
907
 
         * the server is reachable, restart the protocol; if not, ignore
908
 
         * it and wait for timeout.
909
 
         */
910
 
        } else if (L_ISEQU(&peer->xmt, &p_org)) {
911
 
                if (peer->flash & TEST5) {
912
 
                        if (has_mac == 4 && pkt->exten[0] == 0 &&
913
 
                                peer->reach) {
914
 
                                if (peer->flags & FLAG_CONFIG) {
915
 
                                        peer_clear(peer, "AUTH");
916
 
                                } else {
917
 
                                        unpeer(peer);
918
 
                                }
919
 
                        }
920
 
                        return;
921
 
                }
922
 
                /* fall through */
923
 
 
924
 
        /*
925
 
         * If the client or passive peer has never transmitted anything,
926
 
         * this is either the first message from a symmetric peer or
927
 
         * possibly a duplicate received before the transmit timeout.
928
 
         * Pass it on.
929
 
         */
930
 
        } else if (L_ISZERO(&peer->xmt)) {
931
 
                /* fall through */
932
 
 
933
 
        /*
934
 
         * Now it gets interesting. We have transmitted at least one
935
 
         * packet. If the packet originate timestamp is nonzero, it
936
 
         * does not match the association transmit timestamp, which is a
937
 
         * loopback error. This error might mean a manycast server has
938
 
         * answered a manycast honk from us and we already have an
939
 
         * association for him, in which case quietly drop the packet
940
 
         * here. It might mean an old duplicate, dropped packet or
941
 
         * intruder replay, in which case we drop it later after
942
 
         * extension field processing, but never let it touch the time
943
 
         * values.
944
 
         */
945
 
        } else if (!L_ISZERO(&p_org)) {
946
 
                if (peer->cast_flags & MDF_ACLNT)
947
 
                        return;                 /* not a client */
948
 
 
949
 
                peer->flash |= TEST2;
950
 
                /* fall through */
951
 
 
952
 
        /*
953
 
         * The packet originate timestamp is zero, meaning the other guy
954
 
         * either didn't receive the first packet or died and restarted.
955
 
         * If the association originate timestamp is zero, this is the
956
 
         * first packet received, so we pass it on.
957
 
         */
958
 
        } else if (L_ISZERO(&peer->org)) {
959
 
                /* fall through */
960
 
 
961
 
        /*
962
 
         * The other guy has restarted and we are still on the wire. We
963
 
         * should demobilize/clear and get out of Dodge. If this is
964
 
         * symmetric mode, we should also send a crypto-NAK.
965
 
         */
966
 
        } else {
967
 
                if (hismode == MODE_ACTIVE)
968
 
                        fast_xmit(rbufp, MODE_PASSIVE, 0,
969
 
                            restrict_mask);
970
 
                else if (hismode == MODE_PASSIVE)
971
 
                        fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
972
 
#if DEBUG
973
 
                if (debug)
974
 
                        printf("receive: dropped %03x\n", peer->flash);
975
 
#endif
976
 
                if (peer->flags & FLAG_CONFIG)
977
 
                        peer_clear(peer, "DROP");
978
 
                else
979
 
                        unpeer(peer);
980
 
                return;
981
 
        }
982
 
        if (peer->flash & ~TEST2) {
983
 
                return;
984
 
        }
985
 
 
 
994
        if (is_authentic == AUTH_OK)
 
995
                peer->flags |= FLAG_AUTHENTIC;
 
996
        else
 
997
                peer->flags &= ~FLAG_AUTHENTIC;
986
998
#ifdef OPENSSL
987
999
        /*
988
1000
         * More autokey dance. The rules of the cha-cha are as follows:
1005
1017
         *    match, sit the dance and wait for timeout.
1006
1018
         *
1007
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,
 
1022
         * scuttle the ship.
1008
1023
         */
1009
1024
        if (crypto_flags && (peer->flags & FLAG_SKEY)) {
1010
 
                peer->flash |= TEST10;
 
1025
                peer->flash |= TEST8;
1011
1026
                rval = crypto_recv(peer, rbufp);
1012
1027
                if (rval != XEVNT_OK) {
1013
1028
                        peer_clear(peer, "CRYP");
1014
 
                        peer->flash |= TEST4;   /* crypto error */
 
1029
                        peer->flash |= TEST9;   /* crypto error */
 
1030
                        if (peer->flags & FLAG_PREEMPT ||
 
1031
                            !(peer->flags & FLAG_CONFIG))
 
1032
                                unpeer(peer);
 
1033
                        return;
 
1034
 
1015
1035
                } else if (hismode == MODE_SERVER) {
1016
1036
                        if (skeyid == peer->keyid)
1017
 
                                peer->flash &= ~TEST10;
1018
 
                } else if (!peer->flash & TEST10) {
 
1037
                                peer->flash &= ~TEST8;
 
1038
                } else if (!(peer->flash & TEST8)) {
1019
1039
                        peer->pkeyid = skeyid;
1020
1040
                } else if ((ap = (struct autokey *)peer->recval.ptr) !=
1021
1041
                    NULL) {
1024
1044
                        for (i = 0; ; i++) {
1025
1045
                                if (tkeyid == peer->pkeyid ||
1026
1046
                                    tkeyid == ap->key) {
1027
 
                                        peer->flash &= ~TEST10;
 
1047
                                        peer->flash &= ~TEST8;
1028
1048
                                        peer->pkeyid = skeyid;
1029
1049
                                        break;
1030
1050
                                }
1035
1055
                                    tkeyid, pkeyid, 0);
1036
1056
                        }
1037
1057
                }
1038
 
                if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 11 */
1039
 
                        peer->flash |= TEST11;  /* not proventic */
 
1058
                if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */
 
1059
                        peer->flash |= TEST8;   /* not proventic */
1040
1060
 
1041
1061
                /*
1042
1062
                 * If the transmit queue is nonempty, clamp the host
1054
1074
         * the packet over the fence for processing, which may light up
1055
1075
         * more flashers.
1056
1076
         */
1057
 
        process_packet(peer, pkt, &rbufp->recv_time);
 
1077
        process_packet(peer, pkt);
1058
1078
 
1059
1079
        /*
1060
1080
         * Well, that was nice. If TEST4 is lit, either the crypto
1062
1082
         * which is fatal.
1063
1083
         */
1064
1084
        if (peer->flash & TEST4) {
1065
 
                msyslog(LOG_INFO, "receive: fatal error %03x for %s",
 
1085
                msyslog(LOG_INFO, "receive: fatal error %04x for %s",
1066
1086
                    peer->flash, stoa(&peer->srcadr));
1067
 
                if (!(peer->flags & FLAG_CONFIG))
1068
 
                        unpeer(peer);
1069
1087
                return;
1070
1088
        }
1071
 
 
1072
 
#ifdef OPENSSL
1073
 
        /*
1074
 
         * If TEST10 is lit, the autokey sequence has broken, which
1075
 
         * probably means the server has refreshed its private value.
1076
 
         * Not to worry, reset and wait for the next time.
1077
 
         */
1078
 
        if (peer->flash & TEST10 && peer->crypto & CRYPTO_FLAG_AUTO) {
1079
 
#ifdef DEBUG
1080
 
                if (debug)
1081
 
                        printf(
1082
 
                            "receive: bad auto %03x\n", peer->flash);
1083
 
#endif
1084
 
                if (peer->flags & FLAG_CONFIG)
1085
 
                        peer_clear(peer, "AUTO");
1086
 
                else
1087
 
                        unpeer(peer);
1088
 
        }
1089
 
#endif /* OPENSSL */
1090
1089
}
1091
1090
 
1092
1091
 
1099
1098
void
1100
1099
process_packet(
1101
1100
        register struct peer *peer,
1102
 
        register struct pkt *pkt,
1103
 
        l_fp    *recv_ts
 
1101
        register struct pkt *pkt
1104
1102
        )
1105
1103
{
1106
1104
        double  t34, t21;
1107
1105
        double  p_offset, p_del, p_disp;
1108
 
        double  dtemp;
1109
1106
        l_fp    p_rec, p_xmt, p_org, p_reftime;
1110
1107
        l_fp    ci;
1111
1108
        u_char  pmode, pleap, pstratum;
1112
1109
 
1113
 
        /*
1114
 
         * Swap header fields and keep the books. The books amount to
1115
 
         * the receive timestamp and poll interval in the header. We
1116
 
         * need these even if there are other problems in order to crank
1117
 
         * up the state machine.
1118
 
         */
1119
1110
        sys_processed++;
1120
1111
        peer->processed++;
1121
1112
        p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
1132
1123
        pstratum = PKT_TO_STRATUM(pkt->stratum);
1133
1124
 
1134
1125
        /*
1135
 
         * Test for kiss-o'death packet (DENY or CRYP)
 
1126
         * Test for kiss-o'death packet)
1136
1127
         */
1137
1128
        if (pleap == LEAP_NOTINSYNC && pstratum == STRATUM_UNSPEC) {
1138
1129
                if (memcmp(&pkt->refid, "DENY", 4) == 0) {
1139
1130
                        peer_clear(peer, "DENY");
1140
 
                        peer->flash |= TEST4;   /* access deny */
1141
 
                } else if (memcmp(&pkt->refid, "CRYP", 4) == 0) {
1142
 
                        peer_clear(peer, "CRYP");
1143
 
                        peer->flash |= TEST4;   /* crypto error */
 
1131
                        peer->flash |= TEST4;   /* access denied */
1144
1132
                }
1145
1133
        }
1146
1134
 
1147
1135
        /*
1148
 
         * Test for unsynchronized server.
1149
 
         */
1150
 
        if (L_ISHIS(&peer->org, &p_xmt))        /* count old packets */
1151
 
                peer->oldpkt++;
1152
 
        if (pmode != MODE_BROADCAST && (L_ISZERO(&p_rec) ||
1153
 
            L_ISZERO(&p_org)))                  /* test 3 */
1154
 
                peer->flash |= TEST3;           /* unsynch */
1155
 
        if (L_ISZERO(&p_xmt))                   /* test 3 */
1156
 
                peer->flash |= TEST3;           /* unsynch */
1157
 
 
1158
 
        /*
1159
 
         * If any tests fail, the packet is discarded leaving only the
1160
 
         * timestamps, which are enough to get the protocol started. The
1161
 
         * originate timestamp is copied from the packet transmit
1162
 
         * timestamp and the receive timestamp is copied from the
1163
 
         * packet receive timestamp. If okay so far, we save the leap,
1164
 
         * stratum and refid for billboards.
1165
 
         */
1166
 
        peer->org = p_xmt;
1167
 
        peer->rec = *recv_ts;
1168
 
        if (peer->flash) {
1169
 
#ifdef DEBUG
1170
 
                if (debug)
1171
 
                        printf("packet: bad data %03x from %s\n",
1172
 
                            peer->flash, stoa(&peer->srcadr));
1173
 
#endif
1174
 
                return;
1175
 
        }
 
1136
         * Capture the header values.
 
1137
         */
 
1138
        record_raw_stats(&peer->srcadr, peer->dstadr ? &peer->dstadr->sin : NULL, &p_org,
 
1139
            &p_rec, &p_xmt, &peer->rec);
1176
1140
        peer->leap = pleap;
1177
 
        peer->stratum = pstratum;
1178
 
        peer->refid = pkt->refid;
1179
 
 
1180
 
        /*
1181
 
         * Test for valid peer data (tests 6-8)
1182
 
         */
1183
 
        ci = p_xmt;
1184
 
        L_SUB(&ci, &p_reftime);
1185
 
        LFPTOD(&ci, dtemp);
1186
 
        if (pleap == LEAP_NOTINSYNC ||          /* test 6 */
1187
 
            pstratum >= STRATUM_UNSPEC || dtemp < 0)
1188
 
                peer->flash |= TEST6;           /* bad synch */
1189
 
        if (!(peer->flags & FLAG_CONFIG) && sys_peer != NULL) { /* test 7 */
1190
 
                if (pstratum > sys_stratum && pmode != MODE_ACTIVE)
1191
 
                        peer->flash |= TEST7;   /* bad stratum */
1192
 
        }
1193
 
        if (p_del < 0 || p_disp < 0 || p_del /  /* test 8 */
1194
 
            2 + p_disp >= MAXDISPERSE)
1195
 
                peer->flash |= TEST8;           /* bad peer values */
1196
 
 
1197
 
        /*
1198
 
         * If any tests fail at this point, the packet is discarded.
1199
 
         */
1200
 
        if (peer->flash) {
1201
 
#ifdef DEBUG
1202
 
                if (debug)
1203
 
                        printf("packet: bad header %03x\n",
1204
 
                            peer->flash);
1205
 
#endif
1206
 
                return;
1207
 
        }
1208
 
 
1209
 
        /*
1210
 
         * The header is valid. Capture the remaining header values and
1211
 
         * mark as reachable.
1212
 
         */
1213
 
        record_raw_stats(&peer->srcadr, &peer->dstadr->sin, &p_org,
1214
 
            &p_rec, &p_xmt, &peer->rec);
 
1141
        peer->stratum = min(pstratum, STRATUM_UNSPEC);
1215
1142
        peer->pmode = pmode;
1216
1143
        peer->ppoll = pkt->ppoll;
1217
1144
        peer->precision = pkt->precision;
1218
1145
        peer->rootdelay = p_del;
1219
1146
        peer->rootdispersion = p_disp;
 
1147
        peer->refid = pkt->refid;               /* network byte order */
1220
1148
        peer->reftime = p_reftime;
 
1149
 
 
1150
        /*
 
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.
 
1155
         */
 
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 */
 
1162
 
 
1163
        /*
 
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.
 
1167
         */
 
1168
        if (peer->flash & PKT_TEST_MASK) {
 
1169
#ifdef DEBUG
 
1170
                if (debug)
 
1171
                        printf("packet: flash header %04x\n",
 
1172
                            peer->flash);
 
1173
#endif
 
1174
                return;
 
1175
        }
1221
1176
        if (!(peer->reach)) {
1222
1177
                report_event(EVNT_REACH, peer);
1223
1178
                peer->timereachable = current_time;
1224
1179
        }
 
1180
        poll_update(peer, peer->hpoll);
1225
1181
        peer->reach |= 1;
1226
 
        poll_update(peer, peer->hpoll);
1227
1182
 
1228
1183
        /*
1229
1184
         * For a client/server association, calculate the clock offset,
1233
1188
         * computed delay during the client/server volley. Note that
1234
1189
         * org has been set to the time of last reception. Note the
1235
1190
         * computation of dispersion includes the system precision plus
1236
 
         * that due to the frequency error since the originate time.
 
1191
         * that due to the frequency error since the origin time.
1237
1192
         *
1238
1193
         * It is very important to respect the hazards of overflow. The
1239
1194
         * only permitted operation on raw timestamps is subtraction,
1244
1199
         * sums and differences of these first-order differences, which
1245
1200
         * if done using 64-bit integer arithmetic, would be valid over
1246
1201
         * only half that span. Since the typical first-order
1247
 
         * differences are usually very small, they are converted to 64-         * bit doubles and all remaining calculations done in floating-
 
1202
         * differences are usually very small, they are converted to 64-
 
1203
         * bit doubles and all remaining calculations done in floating-
1248
1204
         * point arithmetic. This preserves the accuracy while retaining
1249
1205
         * the 68-year span.
1250
1206
         *
1258
1214
        LFPTOD(&ci, t21);
1259
1215
        ci = peer->rec;                 /* t4 - t1 */
1260
1216
        L_SUB(&ci, &p_org);
1261
 
        LFPTOD(&ci, p_disp);
1262
 
        p_disp = clock_phi * max(p_disp, LOGTOD(sys_precision));
1263
1217
 
1264
1218
        /*
1265
1219
         * If running in a broadcast association, the clock offset is
1277
1231
                        if (peer->hmode == MODE_CLIENT)
1278
1232
                                return;
1279
1233
 
1280
 
                        peer->flags &= ~FLAG_MCAST;
 
1234
                        peer->flags &= ~(FLAG_MCAST | FLAG_BURST);
1281
1235
                }
1282
1236
                p_offset += peer->estbdelay;
1283
1237
                p_del = peer->delay;
 
1238
                p_disp = 0;
1284
1239
        } else {
1285
1240
                p_offset = (t21 + t34) / 2.;
1286
1241
                p_del = t21 - t34;
 
1242
                LFPTOD(&ci, p_disp);
 
1243
                p_disp = LOGTOD(sys_precision) +
 
1244
                    LOGTOD(peer->precision) + clock_phi * p_disp;
1287
1245
        }
1288
1246
        p_del = max(p_del, LOGTOD(sys_precision));
1289
 
        if ((peer->rootdelay + p_del) / 2. + peer->rootdispersion +
1290
 
            p_disp >= MAXDISPERSE)              /* test 9 */
1291
 
                peer->flash |= TEST9;           /* bad root distance */
1292
 
 
1293
 
        /*
1294
 
         * If any flasher bits remain set at this point, abandon ship.
1295
 
         * Otherwise, forward to the clock filter.
1296
 
         */
1297
 
        if (peer->flash) {
1298
 
#ifdef DEBUG
1299
 
                if (debug)
1300
 
                        printf("packet: bad packet data %03x\n",
1301
 
                            peer->flash);
1302
 
#endif
1303
 
                return;
1304
 
        }
1305
1247
        clock_filter(peer, p_offset, p_del, p_disp);
1306
1248
        record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
1307
 
            peer->offset, peer->delay, peer->disp,
1308
 
            SQRT(peer->jitter));
 
1249
            peer->offset, peer->delay, peer->disp, peer->jitter);
1309
1250
}
1310
1251
 
1311
1252
 
1315
1256
static void
1316
1257
clock_update(void)
1317
1258
{
1318
 
        u_char oleap;
1319
 
        u_char ostratum;
 
1259
        u_char  oleap;
 
1260
        u_char  ostratum;
 
1261
        double  dtemp;
1320
1262
 
1321
1263
        /*
1322
1264
         * There must be a system peer at this point. If we just changed
1331
1273
        if (sys_peer->epoch <= sys_clocktime)
1332
1274
                return;
1333
1275
 
1334
 
        sys_clocktime = sys_peer->epoch;
1335
1276
#ifdef DEBUG
1336
1277
        if (debug)
1337
1278
                printf("clock_update: at %ld assoc %d \n", current_time,
1342
1283
        switch (local_clock(sys_peer, sys_offset)) {
1343
1284
 
1344
1285
        /*
1345
 
         * Clock is too screwed up. Just exit for now.
 
1286
         * Clock exceeds panic threshold. Life as we know it ends.
1346
1287
         */
1347
1288
        case -1:
1348
1289
                report_event(EVNT_SYSFAULT, NULL);
1349
1290
                exit (-1);
1350
 
                /*NOTREACHED*/
 
1291
                /* not reached */
1351
1292
 
1352
1293
        /*
1353
1294
         * Clock was stepped. Flush all time values of all peers.
1354
1295
         */
1355
 
        case 1:
 
1296
        case 2:
1356
1297
                clear_all();
1357
 
                sys_peer = NULL;
 
1298
                sys_leap = LEAP_NOTINSYNC;
1358
1299
                sys_stratum = STRATUM_UNSPEC;
1359
 
                        memcpy(&sys_refid, "STEP", 4);
1360
 
                sys_poll = NTP_MINPOLL;
 
1300
                sys_peer = NULL;
 
1301
                sys_rootdelay = 0;
 
1302
                sys_rootdispersion = 0;
 
1303
                memcpy(&sys_refid, "STEP", 4);
1361
1304
                report_event(EVNT_CLOCKRESET, NULL);
1362
 
#ifdef OPENSSL
1363
 
                if (oleap != LEAP_NOTINSYNC)
1364
 
                        expire_all();
1365
 
#endif /* OPENSSL */
1366
1305
                break;
1367
1306
 
1368
1307
        /*
1369
 
         * Update the system stratum, leap bits, root delay, root
1370
 
         * dispersion, reference ID and reference time. We also update
1371
 
         * select dispersion and max frequency error. If the leap
1372
 
         * changes, we gotta reroll the keys.
 
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.
1373
1313
         */
1374
 
        default:
1375
 
                sys_stratum = (u_char) (sys_peer->stratum + 1);
1376
 
                if (sys_stratum == 1 || sys_stratum == STRATUM_UNSPEC)
1377
 
                        sys_refid = sys_peer->refid;
1378
 
                else
1379
 
                        sys_refid = sys_peer_refid;
 
1314
        case 1:
 
1315
                sys_leap = leap_next;
 
1316
                sys_stratum = min(sys_peer->stratum + 1,
 
1317
                    STRATUM_UNSPEC);
1380
1318
                sys_reftime = sys_peer->rec;
1381
 
                sys_rootdelay = sys_peer->rootdelay + sys_peer->delay;
1382
 
                sys_leap = leap_consensus;
 
1319
 
 
1320
                /*
 
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
 
1325
                 * ignored.
 
1326
                 */
 
1327
                dtemp = sys_peer->disp + clock_phi * (current_time -
 
1328
                    sys_peer->update) + sys_jitter +
 
1329
                    fabs(sys_peer->offset);
 
1330
#ifdef REFCLOCK
 
1331
                if (!(sys_peer->flags & FLAG_REFCLOCK) && dtemp <
 
1332
                    sys_mindisp)
 
1333
                        dtemp = sys_mindisp;
 
1334
#else
 
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;
 
1342
                } else {
 
1343
                        sys_rootdelay = sys_peer->delay +
 
1344
                            sys_peer->rootdelay;
 
1345
                        sys_rootdispersion = dtemp +
 
1346
                            sys_peer->rootdispersion;
 
1347
                }
1383
1348
                if (oleap == LEAP_NOTINSYNC) {
1384
1349
                        report_event(EVNT_SYNCCHG, NULL);
1385
1350
#ifdef OPENSSL
1386
1351
                        expire_all();
 
1352
                        crypto_update();
1387
1353
#endif /* OPENSSL */
1388
1354
                }
 
1355
                break;
 
1356
        /*
 
1357
         * Popcorn spike or step threshold exceeded. Pretend it never
 
1358
         * happened.
 
1359
         */
 
1360
        default:
 
1361
                break;
1389
1362
        }
1390
1363
        if (ostratum != sys_stratum)
1391
1364
                report_event(EVNT_PEERSTCHG, NULL);
1404
1377
        int     hpoll;
1405
1378
 
1406
1379
        /*
1407
 
         * This routine figures out when the next poll should set, and
1408
 
         * that turns out to be wickedly complicated. The big problem is
 
1380
         * This routine figures out when the next poll should be sent.
 
1381
         * That turns out to be wickedly complicated. The big problem is
1409
1382
         * that sometimes the time for the next poll is in the past.
1410
1383
         * Watch out for races here between the receive process and the
1411
 
         * poll process. The key assertion is that, if nextdate ==
 
1384
         * poll process. The key assertion is that, if nextdate equals
1412
1385
         * current_time, the call is from the poll process; otherwise,
1413
1386
         * it is from the receive process.
1414
 
         */
1415
 
        hpoll = mpoll;
1416
 
 
1417
 
        /*
1418
 
         * If during the crypto protocol and a message is pending, make
1419
 
         * it wait no more than two seconds.
 
1387
         *
 
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.
 
1392
         */
 
1393
        if (peer->flags & FLAG_FIXPOLL) {
 
1394
                hpoll = peer->minpoll;
 
1395
 
 
1396
        /*
 
1397
         * The ordinary case; clamp the poll interval between minpoll
 
1398
         * and maxpoll.
 
1399
         */
 
1400
        } else {
 
1401
                hpoll = max(min(peer->maxpoll, mpoll), peer->minpoll);
 
1402
        }
 
1403
#ifdef OPENSSL
 
1404
        /*
 
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.
 
1409
         */
 
1410
        if (hpoll != peer->hpoll)
 
1411
                key_expire(peer);
 
1412
#endif /* OPENSSL */
 
1413
        peer->hpoll = hpoll;
 
1414
 
 
1415
        /*
 
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.
1420
1419
         */
1421
1420
#ifdef OPENSSL
1422
1421
        if (peer->cmmd != NULL && (sys_leap != LEAP_NOTINSYNC ||
1439
1438
#ifdef REFCLOCK
1440
1439
                else if (peer->flags & FLAG_REFCLOCK)
1441
1440
                        peer->nextdate += RESP_DELAY;
1442
 
#endif
 
1441
#endif /* REFCLOCK */
1443
1442
                else if (peer->flags & (FLAG_IBURST | FLAG_BURST) &&
1444
1443
                    peer->burst == NTP_BURST)
1445
1444
                        peer->nextdate += sys_calldelay;
1446
1445
                else
1447
1446
                        peer->nextdate += BURST_DELAY;
1448
1447
        /*
1449
 
         * A manycast server beacons at the minimum poll interval times
1450
 
         * the ttl until a sufficient number of servers have been found,
1451
 
         * then beacons at the maximum poll interval.
1452
 
         */
1453
 
        } else if (peer->cast_flags & MDF_ACAST) {
1454
 
                if (sys_survivors >= sys_minclock || peer->ttl >=
1455
 
                    sys_ttlmax)
1456
 
                        hpoll = peer->maxpoll;
1457
 
                else
1458
 
                        hpoll = peer->minpoll + peer->ttl;
1459
 
                peer->nextdate = peer->outdate + RANDPOLL(hpoll);
1460
 
 
1461
 
        /*
1462
 
         * The normal case after all those pesky exceptions. Set the
1463
 
         * poll to the minimum of the host and peer values, but not
1464
 
         * below minpoll. That's max(min(ppoll, hpoll), minpoll).
 
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.
1465
1451
         */
1466
1452
        } else {
1467
 
                if (peer->ppoll < peer->minpoll)
1468
 
                        peer->nextdate = peer->outdate +
1469
 
                            RANDPOLL(peer->minpoll);
1470
 
                if (peer->ppoll < hpoll)
1471
 
                        peer->nextdate = peer->outdate +
1472
 
                            RANDPOLL(peer->ppoll);
1473
 
                else
1474
 
                        peer->nextdate = peer->outdate +
1475
 
                            RANDPOLL(hpoll);
 
1453
                peer->nextdate = peer->outdate +
 
1454
                    RANDPOLL(max(min(peer->ppoll, hpoll),
 
1455
                    peer->minpoll));
1476
1456
        }
1477
1457
 
1478
1458
        /*
1482
1462
         */
1483
1463
        if (peer->nextdate <= current_time)
1484
1464
                peer->nextdate = current_time + 1;
1485
 
#ifdef OPENSSL
1486
 
        /*
1487
 
         * Bit of crass arrogance at this point. If the poll interval
1488
 
         * has changed and we have a keylist, the lifetimes in the
1489
 
         * keylist are probably bogus. In this case purge the keylist
1490
 
         * and regenerate it later.
1491
 
         */
1492
 
        if (hpoll != peer->hpoll)
1493
 
                key_expire(peer);
1494
 
#endif /* OPENSSL */
1495
 
        peer->hpoll = hpoll;
1496
1465
#ifdef DEBUG
1497
1466
        if (debug > 1)
1498
1467
                printf("poll_update: at %lu %s flags %04x poll %d burst %d last %lu next %lu\n",
1502
1471
#endif
1503
1472
}
1504
1473
 
1505
 
 
1506
1474
/*
1507
 
 * peer_clear - clear peer filter registers.  See Section 3.4.8 of the spec.
 
1475
 * peer_crypto_clear - discard crypto information
1508
1476
 */
1509
1477
void
1510
 
peer_clear(
1511
 
        struct peer *peer,              /* peer structure */
1512
 
        char    *ident                  /* tally lights */
1513
 
        )
 
1478
peer_crypto_clear(
 
1479
                  struct peer *peer
 
1480
                  )
1514
1481
{
1515
 
        u_char  oreach, i;
1516
 
 
1517
1482
        /*
1518
1483
         * If cryptographic credentials have been acquired, toss them to
1519
1484
         * Valhalla. Note that autokeys are ephemeral, in that they are
1523
1488
         * purged, too. This makes it much harder to sneak in some
1524
1489
         * unauthenticated data in the clock filter.
1525
1490
         */
1526
 
        oreach = peer->reach;
 
1491
        DPRINTF(1, ("peer_crypto_clear: at %ld next %ld assoc ID %d\n",
 
1492
                    current_time, peer->nextdate, peer->associd));
 
1493
 
1527
1494
#ifdef OPENSSL
1528
 
        key_expire(peer);
 
1495
        peer->assoc = 0;
 
1496
        peer->crypto = 0;
 
1497
 
1529
1498
        if (peer->pkey != NULL)
1530
1499
                EVP_PKEY_free(peer->pkey);
1531
 
        if (peer->ident_pkey != NULL)
1532
 
                EVP_PKEY_free(peer->ident_pkey);
 
1500
        peer->pkey = NULL;
 
1501
 
 
1502
        peer->digest = NULL;    /* XXX MEMLEAK? check whether this needs to be freed in any way - never was freed */
 
1503
 
1533
1504
        if (peer->subject != NULL)
1534
1505
                free(peer->subject);
 
1506
        peer->subject = NULL;
 
1507
 
1535
1508
        if (peer->issuer != NULL)
1536
1509
                free(peer->issuer);
 
1510
        peer->issuer = NULL;
 
1511
 
 
1512
        peer->pkeyid = 0;
 
1513
 
 
1514
        peer->pcookie = 0;
 
1515
 
 
1516
        if (peer->ident_pkey != NULL)
 
1517
                EVP_PKEY_free(peer->ident_pkey);
 
1518
        peer->ident_pkey = NULL;
 
1519
        
 
1520
        memset(&peer->fstamp, 0, sizeof(peer->fstamp));
 
1521
 
1537
1522
        if (peer->iffval != NULL)
1538
1523
                BN_free(peer->iffval);
 
1524
        peer->iffval = NULL;
 
1525
 
1539
1526
        if (peer->grpkey != NULL)
1540
1527
                BN_free(peer->grpkey);
1541
 
        if (peer->cmmd != NULL)
1542
 
                free(peer->cmmd);
 
1528
        peer->grpkey = NULL;
 
1529
 
1543
1530
        value_free(&peer->cookval);
1544
1531
        value_free(&peer->recval);
1545
 
        value_free(&peer->tai_leap);
 
1532
 
 
1533
        if (peer->cmmd != NULL) {
 
1534
                free(peer->cmmd);
 
1535
                peer->cmmd = NULL;
 
1536
        }
 
1537
 
 
1538
        key_expire(peer);
 
1539
 
1546
1540
        value_free(&peer->encrypt);
1547
 
        value_free(&peer->sndval);
1548
1541
#endif /* OPENSSL */
 
1542
}
 
1543
 
 
1544
/*
 
1545
 * peer_clear - clear peer filter registers.  See Section 3.4.8 of the spec.
 
1546
 */
 
1547
void
 
1548
peer_clear(
 
1549
        struct peer *peer,              /* peer structure */
 
1550
        char    *ident                  /* tally lights */
 
1551
        )
 
1552
{
 
1553
        int     i;
 
1554
 
 
1555
        peer_crypto_clear(peer);
 
1556
        
 
1557
        if (peer == sys_peer)
 
1558
                sys_peer = NULL;
1549
1559
 
1550
1560
        /*
1551
1561
         * Wipe the association clean and initialize the nonzero values.
1552
1562
         */
1553
1563
        memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO);
1554
 
        if (peer == sys_peer)
1555
 
                sys_peer = NULL;
1556
1564
        peer->estbdelay = sys_bdelay;
 
1565
        peer->ppoll = peer->maxpoll;
1557
1566
        peer->hpoll = peer->minpoll;
1558
 
        peer->ppoll = peer->maxpoll;
1559
 
        peer->jitter = MAXDISPERSE;
1560
 
        peer->epoch = current_time;
 
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;
 
1572
        }
1561
1573
#ifdef REFCLOCK
1562
1574
        if (!(peer->flags & FLAG_REFCLOCK)) {
1563
1575
                peer->leap = LEAP_NOTINSYNC;
1568
1580
        peer->leap = LEAP_NOTINSYNC;
1569
1581
        peer->stratum = STRATUM_UNSPEC;
1570
1582
        memcpy(&peer->refid, ident, 4);
1571
 
#endif
1572
 
        for (i = 0; i < NTP_SHIFT; i++) {
1573
 
                peer->filter_order[i] = i;
1574
 
                peer->filter_disp[i] = MAXDISPERSE;
1575
 
                peer->filter_epoch[i] = current_time;
1576
 
        }
 
1583
#endif /* REFCLOCK */
1577
1584
 
1578
1585
        /*
1579
 
         * Randomize the first poll to avoid bunching, but only if the
1580
 
         * rascal has never been heard. During initialization use the
1581
 
         * association count to spread out the polls at one-second
1582
 
         * intervals.
 
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
 
1589
         * implosion.
1583
1590
         */
1584
1591
        peer->nextdate = peer->update = peer->outdate = current_time;
1585
 
        if (oreach)
1586
 
                poll_update(peer, peer->minpoll);
1587
 
        else if (initializing)
1588
 
                peer->nextdate = current_time + peer_associations;
 
1592
        if (initializing)
 
1593
                peer->nextdate += peer_associations;
 
1594
        else if (peer->hmode == MODE_PASSIVE)
 
1595
                peer->nextdate += RESP_DELAY;
1589
1596
        else
1590
 
                peer->nextdate = current_time + max((u_int)RANDOM %
1591
 
                    peer_associations, BURST_DELAY);
1592
 
#ifdef DEBUG
1593
 
        if (debug)
1594
 
                printf("peer_clear: at %ld assoc ID %d refid %s\n",
1595
 
                    current_time, peer->associd, ident);
1596
 
#endif
 
1597
                peer->nextdate += (ntp_random() & ((1 << NTP_MINDPOLL) -
 
1598
                    1));
 
1599
 
 
1600
        DPRINTF(1, ("peer_clear: at %ld next %ld assoc ID %d refid %s\n",
 
1601
                    current_time, peer->nextdate, peer->associd, ident));
1597
1602
}
1598
1603
 
1599
1604
 
1612
1617
        double  dst[NTP_SHIFT];         /* distance vector */
1613
1618
        int     ord[NTP_SHIFT];         /* index vector */
1614
1619
        int     i, j, k, m;
1615
 
        double  dsp, jit, dtemp, etemp;
 
1620
        double  dtemp, etemp;
1616
1621
 
1617
1622
        /*
1618
1623
         * Shift the new sample into the register and discard the oldest
1623
1628
         * precision. The delay can sometimes swing negative due to
1624
1629
         * frequency skew, so it is clamped non-negative.
1625
1630
         */
1626
 
        dsp = min(LOGTOD(peer->precision) + LOGTOD(sys_precision) +
1627
 
            sample_disp, MAXDISPERSE);
1628
1631
        j = peer->filter_nextpt;
1629
1632
        peer->filter_offset[j] = sample_offset;
1630
1633
        peer->filter_delay[j] = max(0, sample_delay);
1631
 
        peer->filter_disp[j] = dsp;
1632
 
        j++; j %= NTP_SHIFT;
1633
 
        peer->filter_nextpt = (u_short) j;
 
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;
1634
1638
 
1635
1639
        /*
1636
1640
         * Update dispersions since the last update and at the same
1650
1654
                        dst[i] = MAXDISPERSE;
1651
1655
                else if (peer->update - peer->filter_epoch[j] >
1652
1656
                    allan_xpt)
1653
 
                        dst[i] = MAXDISTANCE + peer->filter_disp[j];
 
1657
                        dst[i] = sys_maxdist + peer->filter_disp[j];
1654
1658
                else
1655
1659
                        dst[i] = peer->filter_delay[j];
1656
1660
                ord[i] = j;
1657
1661
                j++; j %= NTP_SHIFT;
1658
1662
        }
1659
 
        peer->filter_epoch[j] = current_time;
1660
1663
 
1661
1664
        /*
1662
 
         * Sort the samples in both lists by distance.
 
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.  
1663
1669
         */
1664
 
        for (i = 1; i < NTP_SHIFT; i++) {
1665
 
                for (j = 0; j < i; j++) {
1666
 
                        if (dst[j] > dst[i]) {
1667
 
                                k = ord[j];
1668
 
                                ord[j] = ord[i];
1669
 
                                ord[i] = k;
1670
 
                                etemp = dst[j];
1671
 
                                dst[j] = dst[i];
1672
 
                                dst[i] = etemp;
 
1670
        if (state == 4) {
 
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)) {
 
1675
                                        k = ord[j];
 
1676
                                        ord[j] = ord[i];
 
1677
                                        ord[i] = k;
 
1678
                                        etemp = dst[j];
 
1679
                                        dst[j] = dst[i];
 
1680
                                        dst[i] = etemp;
 
1681
                                }
1673
1682
                        }
1674
1683
                }
1675
1684
        }
1677
1686
        /*
1678
1687
         * Copy the index list to the association structure so ntpq
1679
1688
         * can see it later. Prune the distance list to samples less
1680
 
         * than MAXDISTANCE, but keep at least two valid samples for
 
1689
         * than max distance, but keep at least two valid samples for
1681
1690
         * jitter calculation.
1682
1691
         */
1683
1692
        m = 0;
1684
1693
        for (i = 0; i < NTP_SHIFT; i++) {
1685
1694
                peer->filter_order[i] = (u_char) ord[i];
1686
1695
                if (dst[i] >= MAXDISPERSE || (m >= 2 && dst[i] >=
1687
 
                    MAXDISTANCE))
 
1696
                    sys_maxdist))
1688
1697
                        continue;
1689
1698
                m++;
1690
1699
        }
1691
1700
        
1692
1701
        /*
1693
 
         * Compute the dispersion and jitter squares. The dispersion
1694
 
         * is weighted exponentially by NTP_FWEIGHT (0.5) so it is
1695
 
         * normalized close to 1.0. The jitter is the mean of the square
1696
 
         * differences relative to the lowest delay sample. If no
1697
 
         * acceptable samples remain in the shift register, quietly
1698
 
         * tiptoe home leaving only the dispersion.
 
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
 
1707
         * dispersion.
1699
1708
         */
1700
 
        jit = 0;
1701
 
        peer->disp = 0;
 
1709
        peer->disp = peer->jitter = 0;
1702
1710
        k = ord[0];
1703
1711
        for (i = NTP_SHIFT - 1; i >= 0; i--) {
1704
 
 
1705
1712
                j = ord[i];
1706
1713
                peer->disp = NTP_FWEIGHT * (peer->disp +
1707
1714
                    peer->filter_disp[j]);
1708
1715
                if (i < m)
1709
 
                        jit += DIFF(peer->filter_offset[j],
 
1716
                        peer->jitter += DIFF(peer->filter_offset[j],
1710
1717
                            peer->filter_offset[k]);
1711
1718
        }
1712
1719
 
1713
1720
        /*
1714
1721
         * If no acceptable samples remain in the shift register,
1715
1722
         * quietly tiptoe home leaving only the dispersion. Otherwise,
1716
 
         * save the offset, delay and jitter average. Note the jitter
1717
 
         * must not be less than the system precision.
 
1723
         * save the offset, delay and jitter. Note the jitter must not
 
1724
         * be less than the precision.
1718
1725
         */
1719
1726
        if (m == 0)
1720
1727
                return;
 
1728
 
1721
1729
        etemp = fabs(peer->offset - peer->filter_offset[k]);
1722
 
        dtemp = sqrt(peer->jitter);
1723
1730
        peer->offset = peer->filter_offset[k];
1724
1731
        peer->delay = peer->filter_delay[k];
1725
1732
        if (m > 1)
1726
 
                jit /= m - 1;
1727
 
        peer->jitter = max(jit, SQUARE(LOGTOD(sys_precision)));
 
1733
                peer->jitter /= m - 1;
 
1734
        peer->jitter = max(SQRT(peer->jitter), LOGTOD(sys_precision));
1728
1735
 
1729
1736
        /*
1730
1737
         * A new sample is useful only if it is younger than the last
1731
 
         * one used, but only if the sucker has been synchronized.
 
1738
         * one used. Note the order is FIFO if the clock discipline has
 
1739
         * not stabilized.
1732
1740
         */
1733
 
        if (peer->filter_epoch[k] <= peer->epoch && sys_leap !=
1734
 
            LEAP_NOTINSYNC) {
 
1741
        if (peer->filter_epoch[k] <= peer->epoch) {
1735
1742
#ifdef DEBUG
1736
1743
                if (debug)
1737
1744
                        printf("clock_filter: discard %lu\n",
1746
1753
         * last update is less than twice the system poll interval,
1747
1754
         * consider the update a popcorn spike and ignore it.
1748
1755
         */
1749
 
        if (m > 1 && etemp > CLOCK_SGATE * dtemp &&
1750
 
            (long)(peer->filter_epoch[k] - peer->epoch) < (1 <<
1751
 
            (sys_poll + 1))) {
 
1756
        if (etemp > CLOCK_SGATE * peer->jitter && m > 1 &&
 
1757
            peer->filter_epoch[k] - peer->epoch < 2. *
 
1758
            ULOGTOD(sys_poll)) {
1752
1759
#ifdef DEBUG
1753
1760
                if (debug)
1754
1761
                        printf("clock_filter: popcorn %.6f %.6f\n",
1762
1769
         * processing. If not in a burst, tickle the select.
1763
1770
         */
1764
1771
        peer->epoch = peer->filter_epoch[k];
 
1772
#ifdef DEBUG
 
1773
        if (debug)
 
1774
                printf(
 
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);
 
1778
#endif
1765
1779
        if (peer->burst == 0 || sys_leap == LEAP_NOTINSYNC)
1766
1780
                clock_select();
1767
 
#ifdef DEBUG
1768
 
        if (debug)
1769
 
                printf(
1770
 
                    "clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f, age %lu\n",
1771
 
                    m, peer->offset, peer->delay, peer->disp,
1772
 
                    SQRT(peer->jitter), peer->update - peer->epoch);
1773
 
#endif
1774
1781
}
1775
1782
 
1776
1783
 
1789
1796
        int     i, j, k, n;
1790
1797
        int     nlist, nl3;
1791
1798
 
1792
 
        double  d, e, f;
1793
 
        int     allow, sw, osurv;
 
1799
        int     allow, osurv;
 
1800
        double  d, e, f, g;
1794
1801
        double  high, low;
1795
 
        double  synch[NTP_MAXCLOCK], error[NTP_MAXCLOCK];
 
1802
        double  synch[NTP_MAXASSOC], error[NTP_MAXASSOC];
1796
1803
        struct peer *osys_peer;
1797
1804
        struct peer *typeacts = NULL;
1798
1805
        struct peer *typelocal = NULL;
1799
 
        struct peer *typepps = NULL;
1800
1806
        struct peer *typesystem = NULL;
1801
1807
 
1802
1808
        static int list_alloc = 0;
1813
1819
         */
1814
1820
        osys_peer = sys_peer;
1815
1821
        sys_peer = NULL;
 
1822
        sys_pps = NULL;
 
1823
        sys_prefer = NULL;
1816
1824
        osurv = sys_survivors;
1817
1825
        sys_survivors = 0;
1818
 
        sys_prefer = NULL;
1819
1826
#ifdef LOCKCLOCK
1820
1827
        sys_leap = LEAP_NOTINSYNC;
1821
1828
        sys_stratum = STRATUM_UNSPEC;
1836
1843
                        indx_size += 5 * 3 * sizeof(*indx);
1837
1844
                        peer_list_size += 5 * sizeof(*peer_list);
1838
1845
                }
1839
 
                endpoint = emalloc(endpoint_size);
1840
 
                indx = emalloc(indx_size);
1841
 
                peer_list = emalloc(peer_list_size);
 
1846
                endpoint = (struct endpoint *)emalloc(endpoint_size);
 
1847
                indx = (int *)emalloc(indx_size);
 
1848
                peer_list = (struct peer **)emalloc(peer_list_size);
1842
1849
        }
1843
1850
 
1844
1851
        /*
1862
1869
                         * Leave the island immediately if the peer is
1863
1870
                         * unfit to synchronize.
1864
1871
                         */
1865
 
                        if (peer_unfit(peer) || root_distance(peer) >=
1866
 
                            MAXDISTANCE + 2. * clock_phi *
1867
 
                            ULOGTOD(sys_poll))
 
1872
                        if (peer_unfit(peer))
1868
1873
                                continue;
1869
1874
 
1870
1875
                        /*
1874
1879
                         * nobody else is around. These guys are all
1875
1880
                         * configured, so we never throw them away.
1876
1881
                         */
 
1882
#ifdef REFCLOCK
1877
1883
                        if (peer->refclktype == REFCLK_LOCALCLOCK
1878
1884
#if defined(VMS) && defined(VMS_LOCALUNIT)
1879
1885
                        /* wjm: VMS_LOCALUNIT taken seriously */
1882
1888
#endif  /* VMS && VMS_LOCALUNIT */
1883
1889
                                ) {
1884
1890
                                typelocal = peer;
 
1891
#ifndef LOCKCLOCK
1885
1892
                                if (!(peer->flags & FLAG_PREFER))
1886
1893
                                        continue; /* no local clock */
1887
 
#ifdef LOCKCLOCK
1888
 
                                else
1889
 
                                        sys_prefer = peer;
1890
1894
#endif /* LOCKCLOCK */
1891
1895
                        }
1892
1896
                        if (peer->sstclktype == CTL_SST_TS_TELEPHONE) {
1894
1898
                                if (!(peer->flags & FLAG_PREFER))
1895
1899
                                        continue; /* no acts */
1896
1900
                        }
 
1901
#endif /* REFCLOCK */
1897
1902
 
1898
1903
                        /*
1899
1904
                         * If we get this far, the peer can stay on the
1913
1918
                        for (i = nl3 - 1; i >= 0; i--) {
1914
1919
                                if (e >= endpoint[indx[i]].val)
1915
1920
                                        break;
 
1921
 
1916
1922
                                indx[i + 3] = indx[i];
1917
1923
                        }
1918
1924
                        indx[i + 3] = nl3;
1923
1929
                        for (; i >= 0; i--) {
1924
1930
                                if (e >= endpoint[indx[i]].val)
1925
1931
                                        break;
 
1932
 
1926
1933
                                indx[i + 2] = indx[i];
1927
1934
                        }
1928
1935
                        indx[i + 2] = nl3;
1933
1940
                        for (; i >= 0; i--) {
1934
1941
                                if (e >= endpoint[indx[i]].val)
1935
1942
                                        break;
 
1943
 
1936
1944
                                indx[i + 1] = indx[i];
1937
1945
                        }
1938
1946
                        indx[i + 1] = nl3;
1965
1973
         * correct synchronization is not possible.
1966
1974
         *
1967
1975
         * Here, nlist is the number of candidates and allow is the
1968
 
         * number of falsetickers.
 
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.
1969
1979
         */
1970
1980
        low = 1e9;
1971
1981
        high = -1e9;
2016
2026
        }
2017
2027
 
2018
2028
        /*
 
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.
 
2036
         */
 
2037
        j = 0;
 
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 <
 
2043
                    sys_orphan))
 
2044
                        continue;
 
2045
 
 
2046
                peer->status = CTL_PST_SEL_DISTSYSPEER;
 
2047
 
 
2048
                /*
 
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.
 
2054
                 */
 
2055
                d = root_distance(peer) + peer->stratum * sys_maxdist;
 
2056
                if (j >= NTP_MAXASSOC) {
 
2057
                        if (d >= synch[j - 1])
 
2058
                                continue;
 
2059
                        else
 
2060
                                j--;
 
2061
                }
 
2062
                for (k = j; k > 0; k--) {
 
2063
                        if (d >= synch[k - 1])
 
2064
                                break;
 
2065
 
 
2066
                        peer_list[k] = peer_list[k - 1];
 
2067
                        error[k] = error[k - 1];
 
2068
                        synch[k] = synch[k - 1];
 
2069
                }
 
2070
                peer_list[k] = peer;
 
2071
                error[k] = peer->jitter;
 
2072
                synch[k] = d;
 
2073
                j++;
 
2074
        }
 
2075
        nlist = j;
 
2076
 
 
2077
        /*
2019
2078
         * If no survivors remain at this point, check if the local
2020
2079
         * clock or modem drivers have been found. If so, nominate one
2021
2080
         * of them as the only survivor. Otherwise, give up and leave
2022
2081
         * the island to the rats.
2023
2082
         */
2024
 
        if (high <= low) {
 
2083
        if (nlist == 0) {
2025
2084
                if (typeacts != 0) {
2026
 
                        typeacts->status = CTL_PST_SEL_SANE;
 
2085
                        typeacts->status = CTL_PST_SEL_DISTSYSPEER;
2027
2086
                        peer_list[0] = typeacts;
2028
2087
                        nlist = 1;
2029
2088
                } else if (typelocal != 0) {
2030
 
                        typelocal->status = CTL_PST_SEL_SANE;
 
2089
                        typelocal->status = CTL_PST_SEL_DISTSYSPEER;
2031
2090
                        peer_list[0] = typelocal;
2032
2091
                        nlist = 1;
2033
2092
                } else {
2034
2093
                        if (osys_peer != NULL) {
2035
 
                                sys_poll = NTP_MINPOLL;
2036
2094
                                NLOG(NLOG_SYNCSTATUS)
2037
2095
                                    msyslog(LOG_INFO,
2038
2096
                                    "no servers reachable");
2039
2097
                                report_event(EVNT_PEERSTCHG, NULL);
2040
2098
                        }
2041
 
                        if (osurv > 0)
2042
 
                                resetmanycast();
2043
 
                        return;
2044
2099
                }
2045
2100
        }
2046
2101
 
2050
2105
         * cast out one falsticker. For the Byzantine agreement
2051
2106
         * algorithm used here, that number is 4; however, the default
2052
2107
         * sys_minsane is 1 to speed initial synchronization. Careful
2053
 
         * operators will tinker the value to 4 and use at least that
 
2108
         * operators will tinker a higher value and use at least that
2054
2109
         * number of synchronization sources.
2055
2110
         */
2056
2111
        if (nlist < sys_minsane)
2057
2112
                return;
2058
2113
 
2059
 
        /*
2060
 
         * Clustering algorithm. Construct candidate list in order first
2061
 
         * by stratum then by root distance, but keep only the best
2062
 
         * NTP_MAXCLOCK of them. Scan the list to find falsetickers, who
2063
 
         * leave the island immediately. If a falseticker is not
2064
 
         * configured, his association raft is drowned as well, but only
2065
 
         * if at at least eight poll intervals have gone. We must leave
2066
 
         * at least one peer to collect the million bucks.
2067
 
         *
2068
 
         * Note the hysteresis gimmick that increases the effective
2069
 
         * distance for those rascals that have not made the final cut.
2070
 
         * This is to discourage clockhopping. Note also the prejudice
2071
 
         * against lower stratum peers if the floor is elevated.
2072
 
         */
2073
 
        j = 0;
2074
 
        for (i = 0; i < nlist; i++) {
2075
 
                peer = peer_list[i];
2076
 
                if (nlist > 1 && (peer->offset <= low || peer->offset >=
2077
 
                    high)) {
2078
 
                        if (!(peer->flags & FLAG_CONFIG))
2079
 
                                unpeer(peer);
2080
 
                        continue;
2081
 
                }
2082
 
                peer->status = CTL_PST_SEL_DISTSYSPEER;
2083
 
                d = peer->stratum;
2084
 
                if (d < sys_floor)
2085
 
                        d += sys_floor;
2086
 
                if (d > sys_ceiling)
2087
 
                        d = STRATUM_UNSPEC;
2088
 
                d = root_distance(peer) + d * MAXDISTANCE;
2089
 
                d *= 1. - peer->hyst;
2090
 
                if (j >= NTP_MAXCLOCK) {
2091
 
                        if (d >= synch[j - 1])
2092
 
                                continue;
2093
 
                        else
2094
 
                                j--;
2095
 
                }
2096
 
                for (k = j; k > 0; k--) {
2097
 
                        if (d >= synch[k - 1])
2098
 
                                break;
2099
 
                        peer_list[k] = peer_list[k - 1];
2100
 
                        error[k] = error[k - 1];
2101
 
                        synch[k] = synch[k - 1];
2102
 
                }
2103
 
                peer_list[k] = peer;
2104
 
                error[k] = peer->jitter;
2105
 
                synch[k] = d;
2106
 
                j++;
2107
 
        }
2108
 
        nlist = j;
2109
 
        if (nlist == 0) {
2110
 
#ifdef DEBUG
2111
 
                if (debug)
2112
 
                        printf("clock_select: empty intersection interval\n");
2113
 
#endif
2114
 
                return;
2115
 
        }
2116
 
        for (i = 0; i < nlist; i++) {
 
2114
        for (i = 0; i < nlist; i++)
2117
2115
                peer_list[i]->status = CTL_PST_SEL_SELCAND;
2118
2116
 
2119
 
#ifdef DEBUG
2120
 
                if (debug > 2)
2121
 
                        printf("select: %s distance %.6f jitter %.6f\n",
2122
 
                            ntoa(&peer_list[i]->srcadr), synch[i],
2123
 
                            SQRT(error[i]));
2124
 
#endif
2125
 
        }
2126
 
 
2127
2117
        /*
2128
2118
         * Now, vote outlyers off the island by select jitter weighted
2129
 
         * by root dispersion. Continue voting as long as there are more
2130
 
         * than sys_minclock survivors and the minimum select jitter
2131
 
         * squared is greater than the maximum peer jitter squared. Stop
2132
 
         * if we are about to discard a prefer peer, who of course has
2133
 
         * the immunity idol.
 
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
 
2123
         * immunity idol.
2134
2124
         */
2135
2125
        while (1) {
2136
2126
                d = 1e9;
2137
2127
                e = -1e9;
 
2128
                f = g = 0;
2138
2129
                k = 0;
2139
2130
                for (i = 0; i < nlist; i++) {
2140
2131
                        if (error[i] < d)
2144
2135
                                for (j = 0; j < nlist; j++)
2145
2136
                                        f += DIFF(peer_list[j]->offset,
2146
2137
                                            peer_list[i]->offset);
2147
 
                                f /= nlist - 1;
 
2138
                                f = SQRT(f / (nlist - 1));
2148
2139
                        }
2149
2140
                        if (f * synch[i] > e) {
2150
 
                                sys_selerr = f;
 
2141
                                g = f;
2151
2142
                                e = f * synch[i];
2152
2143
                                k = i;
2153
2144
                        }
2154
2145
                }
2155
 
                f = max(sys_selerr, SQUARE(LOGTOD(sys_precision))); 
 
2146
                f = max(f, LOGTOD(sys_precision));
2156
2147
                if (nlist <= sys_minclock || f <= d ||
2157
 
                    peer_list[k]->flags & FLAG_PREFER)
 
2148
                    peer_list[k]->flags & (FLAG_TRUE | FLAG_PREFER))
2158
2149
                        break;
2159
2150
#ifdef DEBUG
2160
2151
                if (debug > 2)
2161
2152
                        printf(
2162
2153
                            "select: drop %s select %.6f jitter %.6f\n",
2163
 
                            ntoa(&peer_list[k]->srcadr),
2164
 
                            SQRT(sys_selerr), SQRT(d));
 
2154
                            ntoa(&peer_list[k]->srcadr), g, d);
2165
2155
#endif
2166
 
                if (!(peer_list[k]->flags & FLAG_CONFIG) &&
2167
 
                    peer_list[k]->hmode == MODE_CLIENT)
2168
 
                        unpeer(peer_list[k]);
2169
2156
                for (j = k + 1; j < nlist; j++) {
2170
2157
                        peer_list[j - 1] = peer_list[j];
2171
2158
                        error[j - 1] = error[j];
2177
2164
         * What remains is a list usually not greater than sys_minclock
2178
2165
         * peers. We want only a peer at the lowest stratum to become
2179
2166
         * the system peer, although all survivors are eligible for the
2180
 
         * combining algorithm. First record their order, diddle the
2181
 
         * flags and clamp the poll intervals. Then, consider each peer
2182
 
         * in turn and OR the leap bits on the assumption that, if some
2183
 
         * of them honk nonzero bits, they must know what they are
2184
 
         * doing. Check for prefer and pps peers at any stratum. Check
2185
 
         * if the old system peer is among the peers at the lowest
2186
 
         * stratum. Note that the head of the list is at the lowest
2187
 
         * stratum and that unsynchronized peers cannot survive this
2188
 
         * far.
2189
 
         *
2190
 
         * Fiddle for hysteresis. Pump it up for a peer only if the peer
2191
 
         * stratum is at least the floor and there are enough survivors.
2192
 
         * This minimizes the pain when tossing out rascals beneath the
2193
 
         * floorboard. Don't count peers with stratum above the ceiling.
2194
 
         * Manycast is sooo complicated.
 
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.
2195
2173
         */
2196
 
        leap_consensus = 0;
2197
 
        for (i = nlist - 1; i >= 0; i--) {
 
2174
        leap_next = 0;
 
2175
        for (i = 0; i < nlist; i++) {
2198
2176
                peer = peer_list[i];
2199
 
                leap_consensus |= peer->leap;
 
2177
                sys_survivors++;
 
2178
                leap_next |= peer->leap;
2200
2179
                peer->status = CTL_PST_SEL_SYNCCAND;
2201
 
                peer->rank++;
2202
 
                peer->flags |= FLAG_SYSPEER;
2203
 
                if (peer->stratum >= sys_floor && osurv >= sys_minclock)
2204
 
                        peer->hyst = HYST;
2205
 
                else
2206
 
                        peer->hyst = 0;
2207
 
                if (peer->stratum <= sys_ceiling)
2208
 
                        sys_survivors++;
2209
2180
                if (peer->flags & FLAG_PREFER)
2210
2181
                        sys_prefer = peer;
2211
 
                if (peer->refclktype == REFCLK_ATOM_PPS &&
2212
 
                    peer->stratum < STRATUM_UNSPEC)
2213
 
                        typepps = peer;
2214
 
                if (peer->stratum == peer_list[0]->stratum && peer ==
2215
 
                    osys_peer)
 
2182
                if (peer == osys_peer)
2216
2183
                        typesystem = peer;
 
2184
#ifdef REFCLOCK
 
2185
                if (peer->refclktype == REFCLK_ATOM_PPS)
 
2186
                        sys_pps = peer;
 
2187
#endif /* REFCLOCK */
 
2188
#if DEBUG
 
2189
                if (debug > 1)
 
2190
                        printf("cluster: survivor %s metric %.6f\n",
 
2191
                            ntoa(&peer_list[i]->srcadr), synch[i]);
 
2192
#endif
2217
2193
        }
2218
2194
 
2219
2195
        /*
2220
 
         * In manycast client mode we may have spooked a sizeable number
2221
 
         * of peers that we don't need. If there are at least
2222
 
         * sys_minclock of them, the manycast message will be turned
2223
 
         * off. By the time we get here we nay be ready to prune some of
2224
 
         * them back, but we want to make sure all the candicates have
2225
 
         * had a chance. If they didn't pass the sanity and intersection
2226
 
         * tests, they have already been voted off the island.
 
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
 
2198
         * times.
2227
2199
         */
2228
 
        if (sys_survivors < sys_minclock && osurv >= sys_minclock)
2229
 
                resetmanycast();
 
2200
        if (osys_peer == NULL || typesystem == NULL || typesystem ==
 
2201
            peer_list[0] || sys_hopper > sys_maxhop) {
 
2202
                typesystem = peer_list[0];
 
2203
                sys_hopper = 0;
 
2204
        } else {
 
2205
                peer->selbroken++;
 
2206
        }
2230
2207
 
2231
2208
        /*
2232
2209
         * Mitigation rules of the game. There are several types of
2233
 
         * peers that make a difference here: (1) prefer local peers
2234
 
         * (type REFCLK_LOCALCLOCK with FLAG_PREFER) or prefer modem
2235
 
         * peers (type REFCLK_NIST_ATOM etc with FLAG_PREFER), (2) pps
2236
 
         * peers (type REFCLK_ATOM_PPS), (3) remaining prefer peers
2237
 
         * (flag FLAG_PREFER), (4) the existing system peer, if any, (5)
2238
 
         * the head of the survivor list. Note that only one peer can be
2239
 
         * declared prefer. The order of preference is in the order
2240
 
         * stated. Note that all of these must be at the lowest stratum,
2241
 
         * i.e., the stratum of the head of the survivor list.
 
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
 
2213
         * survivor list.
2242
2214
         */
2243
 
        if (sys_prefer)
2244
 
                sw = sys_prefer->refclktype == REFCLK_LOCALCLOCK ||
2245
 
                    sys_prefer->sstclktype == CTL_SST_TS_TELEPHONE ||
2246
 
                    !typepps;
2247
 
        else
2248
 
                sw = 0;
2249
 
        if (sw) {
2250
 
                sys_peer = sys_prefer;
 
2215
        if (typesystem->stratum >= sys_orphan) {
 
2216
 
 
2217
                /*
 
2218
                 * If in orphan mode, choose the system peer. If the
 
2219
                 * lowest distance, we are the orphan parent and the
 
2220
                 * offset is zero.
 
2221
                 */
 
2222
                sys_peer = typesystem;
2251
2223
                sys_peer->status = CTL_PST_SEL_SYSPEER;
2252
 
                sys_offset = sys_peer->offset;
2253
 
                sys_error = SQRT(sys_peer->jitter);
2254
 
#ifdef DEBUG
2255
 
                if (debug > 1)
2256
 
                        printf("select: prefer offset %.6f\n",
2257
 
                            sys_offset);
2258
 
#endif
2259
 
        }
2260
 
#ifndef LOCKCLOCK
2261
 
          else if (typepps) {
2262
 
                sys_peer = typepps;
2263
 
                sys_peer->status = CTL_PST_SEL_PPS;
2264
 
                sys_offset = sys_peer->offset;
2265
 
                sys_error = SQRT(sys_peer->jitter);
2266
 
                if (!pps_control)
2267
 
                        NLOG(NLOG_SYSEVENT)
2268
 
                            msyslog(LOG_INFO, "pps sync enabled");
2269
 
                pps_control = current_time;
2270
 
#ifdef DEBUG
2271
 
                if (debug > 1)
2272
 
                        printf("select: pps offset %.6f\n",
2273
 
                            sys_offset);
2274
 
#endif
 
2224
                if (sys_orphandelay < sys_peer->rootdelay) {
 
2225
                        sys_offset = 0;
 
2226
                        sys_refid = htonl(LOOPBACKADR);
 
2227
                } else {
 
2228
                        sys_offset = sys_peer->offset;
 
2229
                        sys_refid = addr2refid(&sys_peer->srcadr);
 
2230
                }
 
2231
                sys_jitter = LOGTOD(sys_precision);
 
2232
#ifdef DEBUG
 
2233
                if (debug > 1)
 
2234
                        printf("select: orphan offset %.6f\n",
 
2235
                            sys_offset);
 
2236
#endif
 
2237
        } else if (sys_prefer) {
 
2238
 
 
2239
                /*
 
2240
                 * If a pps peer is present, choose it; otherwise,
 
2241
                 * choose the prefer peer.
 
2242
                 */
 
2243
                if (sys_pps) {
 
2244
                        sys_peer = sys_pps;
 
2245
                        sys_peer->status = CTL_PST_SEL_PPS;
 
2246
                        sys_offset = sys_peer->offset;
 
2247
                        if (!pps_control)
 
2248
                                NLOG(NLOG_SYSEVENT)
 
2249
                                    msyslog(LOG_INFO,
 
2250
                                    "pps sync enabled");
 
2251
                        pps_control = current_time;
 
2252
#ifdef DEBUG
 
2253
                        if (debug > 1)
 
2254
                                printf("select: pps offset %.6f\n",
 
2255
                                    sys_offset);
 
2256
#endif
 
2257
                } else {
 
2258
                        sys_peer = sys_prefer;
 
2259
                        sys_peer->status = CTL_PST_SEL_SYSPEER;
 
2260
                        sys_offset = sys_peer->offset;
 
2261
#ifdef DEBUG
 
2262
                        if (debug > 1)
 
2263
                                printf("select: prefer offset %.6f\n",
 
2264
                                    sys_offset);
 
2265
#endif
 
2266
                }
 
2267
                if (sys_peer->stratum == STRATUM_REFCLOCK ||
 
2268
                    sys_peer->stratum == STRATUM_UNSPEC)
 
2269
                        sys_refid = sys_peer->refid;
 
2270
                else
 
2271
                        sys_refid = addr2refid(&sys_peer->srcadr);
 
2272
                sys_jitter = sys_peer->jitter;
2275
2273
        } else {
2276
 
                if (typesystem)
2277
 
                        sys_peer = osys_peer;
 
2274
 
 
2275
                /*
 
2276
                 * Otherwise, choose the anticlockhopper.
 
2277
                 */ 
 
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;
2278
2284
                else
2279
 
                        sys_peer = peer_list[0];
2280
 
                sys_peer->status = CTL_PST_SEL_SYSPEER;
2281
 
                sys_peer->rank++;
2282
 
                sys_offset = clock_combine(peer_list, nlist);
2283
 
                sys_error = SQRT(sys_peer->jitter + sys_selerr);
 
2285
                        sys_refid = addr2refid(&sys_peer->srcadr);
 
2286
                sys_jitter = SQRT(SQUARE(sys_peer->jitter) +
 
2287
                    SQUARE(sys_jitter));
2284
2288
#ifdef DEBUG
2285
2289
                if (debug > 1)
2286
2290
                        printf("select: combine offset %.6f\n",
2287
2291
                           sys_offset);
2288
2292
#endif
2289
2293
        }
2290
 
#endif /* LOCKCLOCK */
 
2294
 
 
2295
        /*
 
2296
         * We have found the alpha male.
 
2297
         */
 
2298
        sys_peer->flags |= FLAG_SYSPEER;
2291
2299
        if (osys_peer != sys_peer) {
2292
2300
                char *src;
2293
2301
 
2294
 
                if (sys_peer == NULL)
2295
 
                        sys_peer_refid = 0;
2296
 
                else
2297
 
                        sys_peer_refid = addr2refid(&sys_peer->srcadr);
2298
2302
                report_event(EVNT_PEERSTCHG, NULL);
2299
2303
 
2300
2304
#ifdef REFCLOCK
2301
 
                if (ISREFCLOCKADR(&sys_peer->srcadr))
 
2305
                if (sys_peer->flags & FLAG_REFCLOCK)
2302
2306
                        src = refnumtoa(&sys_peer->srcadr);
2303
2307
                else
2304
 
#endif
 
2308
#endif /* REFCLOCK */
2305
2309
                        src = ntoa(&sys_peer->srcadr);
2306
2310
                NLOG(NLOG_SYNCSTATUS)
2307
2311
                    msyslog(LOG_INFO, "synchronized to %s, stratum %d",
2310
2314
        clock_update();
2311
2315
}
2312
2316
 
 
2317
 
2313
2318
/*
2314
 
 * clock_combine - combine offsets from selected peers
 
2319
 * clock_combine - compute system offset and jitter from selected peers
2315
2320
 */
2316
 
static double
 
2321
static void
2317
2322
clock_combine(
2318
 
        struct peer **peers,
2319
 
        int     npeers
 
2323
        struct peer **peers,            /* survivor list */
 
2324
        int     npeers                  /* number of survivors */
2320
2325
        )
2321
2326
{
2322
2327
        int     i;
2323
 
        double  x, y, z;
 
2328
        double  x, y, z, w;
2324
2329
 
2325
 
        y = z = 0;
 
2330
        y = z = w = 0;
2326
2331
        for (i = 0; i < npeers; i++) {
2327
2332
                x = root_distance(peers[i]);
2328
2333
                y += 1. / x;
2329
2334
                z += peers[i]->offset / x;
 
2335
                w += SQUARE(peers[i]->offset - peers[0]->offset) / x;
2330
2336
        }
2331
 
        return (z / y);
 
2337
        sys_offset = z / y;
 
2338
        sys_jitter = SQRT(w / y);
2332
2339
}
2333
2340
 
2334
2341
/*
2339
2346
        struct peer *peer
2340
2347
        )
2341
2348
{
 
2349
        double  dist;
 
2350
 
2342
2351
        /*
2343
2352
         * Careful squeak here. The value returned must be greater than
2344
 
         * zero blamed on the peer jitter, which must be at least the
2345
 
         * square of sys_precision.
 
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.
2346
2356
         */
2347
 
        return ((peer->rootdelay + peer->delay) / 2 +
 
2357
        if (peer->stratum >= sys_orphan)
 
2358
                dist = 0;
 
2359
        else
 
2360
                dist = peer->rootdelay;
 
2361
        dist += max(sys_mindisp, dist + peer->delay) / 2 +
2348
2362
            peer->rootdispersion + peer->disp + clock_phi *
2349
 
            (current_time - peer->update) + SQRT(peer->jitter));
 
2363
            (current_time - peer->update) + peer->jitter;
 
2364
        return (dist);
2350
2365
}
2351
2366
 
2352
2367
/*
2359
2374
{
2360
2375
        struct pkt xpkt;        /* transmit packet */
2361
2376
        int     sendlen, authlen;
2362
 
        keyid_t xkeyid = 0;             /* transmit key ID */
 
2377
        keyid_t xkeyid = 0;     /* transmit key ID */
2363
2378
        l_fp    xmt_tx;
2364
2379
 
2365
 
        /*
2366
 
         * Initialize the transmit packet header fields.
2367
 
         */
2368
 
        xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
2369
 
            peer->hmode);
2370
 
        xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
 
2380
        if (!peer->dstadr)      /* don't bother with peers without interface */
 
2381
                return;
 
2382
 
 
2383
        /*
 
2384
         * This is deliciously complicated. There are three cases.
 
2385
         *
 
2386
         * case         leap    stratum refid   delay   dispersion
 
2387
         *
 
2388
         * normal       system  system  system  system  system
 
2389
         * orphan child 00      orphan  system  orphan  system
 
2390
         * orphan parent 00     orphan  loopbk  0       0
 
2391
         */
 
2392
        /*
 
2393
         * This is a normal packet. Use the system variables.
 
2394
         */
 
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));
 
2403
 
 
2404
        /*
 
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.
 
2408
         */
 
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));
 
2417
 
 
2418
        /*
 
2419
         * This is an orphan parent. Show leap synchronized, orphan
 
2420
         * stratum, loopack reference ID and zero root delay and root
 
2421
         * dispersion.
 
2422
         */
 
2423
        } else {
 
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;
 
2428
                xpkt.rootdelay = 0;
 
2429
                xpkt.rootdispersion = 0;
 
2430
        }
2371
2431
        xpkt.ppoll = peer->hpoll;
2372
2432
        xpkt.precision = sys_precision;
2373
 
        xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
2374
 
        xpkt.rootdispersion = HTONS_FP(DTOUFP(sys_rootdispersion));
2375
 
        xpkt.refid = sys_refid;
2376
2433
        HTONL_FP(&sys_reftime, &xpkt.reftime);
2377
2434
        HTONL_FP(&peer->org, &xpkt.org);
2378
2435
        HTONL_FP(&peer->rec, &xpkt.rec);
2382
2439
         * is authenticated and contains a MAC. If not, the transmitted
2383
2440
         * packet is not authenticated.
2384
2441
         *
2385
 
         * In the current I/O semantics the default interface is set
2386
 
         * until after receiving a packet and setting the right
2387
 
         * interface. So, the first packet goes out unauthenticated.
2388
 
         * That's why the really icky test next is here.
 
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.
2389
2448
         */
2390
2449
        sendlen = LEN_PKT_NOMAC;
2391
2450
        if (!(peer->flags & FLAG_AUTHENABLE)) {
2392
2451
                get_systime(&peer->xmt);
2393
2452
                HTONL_FP(&peer->xmt, &xpkt.xmt);
2394
2453
                sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl],
2395
 
                    &xpkt, sendlen);
 
2454
                        &xpkt, sendlen);
2396
2455
                peer->sent++;
2397
2456
#ifdef DEBUG
2398
2457
                if (debug)
2399
2458
                        printf("transmit: at %ld %s->%s mode %d\n",
2400
 
                            current_time, stoa(&peer->dstadr->sin),
2401
 
                            stoa(&peer->srcadr), peer->hmode);
 
2459
                               current_time, peer->dstadr ? stoa(&peer->dstadr->sin) : "-",
 
2460
                               stoa(&peer->srcadr), peer->hmode);
2402
2461
#endif
2403
2462
                return;
2404
2463
        }
2406
2465
        /*
2407
2466
         * The received packet contains a MAC, so the transmitted packet
2408
2467
         * must be authenticated. If autokey is enabled, fuss with the
2409
 
         * various modes; otherwise, private key cryptography is used.
 
2468
         * various modes; otherwise, symmetric key cryptography is used.
2410
2469
         */
2411
2470
#ifdef OPENSSL
2412
2471
        if (crypto_flags && (peer->flags & FLAG_SKEY)) {
2470
2529
                exten = NULL;
2471
2530
                switch (peer->hmode) {
2472
2531
 
2473
 
                /*
2474
 
                 * In broadcast server mode the autokey values are
2475
 
                 * required by the broadcast clients. Push them when a
2476
 
                 * new keylist is generated; otherwise, push the
2477
 
                 * association message so the client can request them at
2478
 
                 * other times.
2479
 
                 */
 
2532
                        /*
 
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
 
2537
                         * other times.
 
2538
                         */
2480
2539
                case MODE_BROADCAST:
2481
2540
                        if (peer->flags & FLAG_ASSOC)
2482
2541
                                exten = crypto_args(peer, CRYPTO_AUTO |
2483
 
                                    CRYPTO_RESP, NULL);
 
2542
                                                    CRYPTO_RESP, NULL);
2484
2543
                        else
2485
2544
                                exten = crypto_args(peer, CRYPTO_ASSOC |
2486
 
                                    CRYPTO_RESP, NULL);
 
2545
                                                    CRYPTO_RESP, NULL);
2487
2546
                        break;
2488
2547
 
2489
2548
                /*
2494
2553
                 * synchronized, so the agreement must be postponed
2495
2554
                 * until then. In any case, if a new keylist is
2496
2555
                 * generated, the autokey values are pushed.
 
2556
                 *
 
2557
                 * If the crypto bit is lit, don't send requests.
2497
2558
                 */
2498
2559
                case MODE_ACTIVE:
2499
2560
                case MODE_PASSIVE:
 
2561
                        if (peer->flash & TEST9)
 
2562
                                break;
 
2563
                        /*
 
2564
                         * Parameter and certificate.
 
2565
                         */
2500
2566
                        if (!peer->crypto)
2501
2567
                                exten = crypto_args(peer, CRYPTO_ASSOC,
2502
 
                                    sys_hostname);
 
2568
                                                    sys_hostname);
2503
2569
                        else if (!(peer->crypto & CRYPTO_FLAG_VALID))
2504
2570
                                exten = crypto_args(peer, CRYPTO_CERT,
2505
 
                                    peer->issuer);
 
2571
                                                    peer->issuer);
2506
2572
 
2507
2573
                        /*
2508
2574
                         * Identity. Note we have to sign the
2512
2578
                         */
2513
2579
                        else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
2514
2580
                                exten = crypto_args(peer,
2515
 
                                    crypto_ident(peer), NULL);
 
2581
                                                    crypto_ident(peer), NULL);
2516
2582
                        else if (sys_leap != LEAP_NOTINSYNC &&
2517
 
                           !(peer->crypto & CRYPTO_FLAG_SIGN))
 
2583
                                 !(peer->crypto & CRYPTO_FLAG_SIGN))
2518
2584
                                exten = crypto_args(peer, CRYPTO_SIGN,
2519
 
                                    sys_hostname);
 
2585
                                                    sys_hostname);
2520
2586
 
2521
2587
                        /*
2522
2588
                         * Autokey. We request the cookie only when the
2529
2595
                         * the autokey values without being asked.
2530
2596
                         */
2531
2597
                        else if (sys_leap != LEAP_NOTINSYNC &&
2532
 
                            peer->leap != LEAP_NOTINSYNC &&
2533
 
                            !(peer->crypto & CRYPTO_FLAG_AGREE))
 
2598
                                 peer->leap != LEAP_NOTINSYNC &&
 
2599
                                 !(peer->crypto & CRYPTO_FLAG_AGREE))
2534
2600
                                exten = crypto_args(peer, CRYPTO_COOK,
2535
 
                                    NULL);
 
2601
                                                    NULL);
2536
2602
                        else if (peer->flags & FLAG_ASSOC)
2537
2603
                                exten = crypto_args(peer, CRYPTO_AUTO |
2538
 
                                    CRYPTO_RESP, NULL);
 
2604
                                                    CRYPTO_RESP, NULL);
2539
2605
                        else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
2540
2606
                                exten = crypto_args(peer, CRYPTO_AUTO,
2541
 
                                    NULL);
 
2607
                                                    NULL);
2542
2608
 
2543
2609
                        /*
2544
2610
                         * Postamble. We trade leapseconds only when the
2545
2611
                         * server and client are synchronized.
2546
2612
                         */
2547
2613
                        else if (sys_leap != LEAP_NOTINSYNC &&
2548
 
                            peer->leap != LEAP_NOTINSYNC &&
2549
 
                            peer->crypto & CRYPTO_FLAG_TAI &&
2550
 
                            !(peer->crypto & CRYPTO_FLAG_LEAP))
 
2614
                                 peer->leap != LEAP_NOTINSYNC &&
 
2615
                                 peer->crypto & CRYPTO_FLAG_TAI &&
 
2616
                                 !(peer->crypto & CRYPTO_FLAG_LEAP))
2551
2617
                                exten = crypto_args(peer, CRYPTO_TAI,
2552
 
                                    NULL);
 
2618
                                                    NULL);
2553
2619
                        break;
2554
2620
 
2555
2621
                /*
2569
2635
                 * requests them and the protocol blinds it using the
2570
2636
                 * agreed key. It is a protocol error if the client has
2571
2637
                 * the parameters but the server does not.
 
2638
                 *
 
2639
                 * If the crypto bit is lit, don't send requests.
2572
2640
                 */
2573
2641
                case MODE_CLIENT:
 
2642
                        if (peer->flash & TEST9)
 
2643
                                break;
 
2644
                        /*
 
2645
                         * Parameter and certificate.
 
2646
                         */
2574
2647
                        if (!peer->crypto)
2575
2648
                                exten = crypto_args(peer, CRYPTO_ASSOC,
2576
 
                                    sys_hostname);
 
2649
                                                    sys_hostname);
2577
2650
                        else if (!(peer->crypto & CRYPTO_FLAG_VALID))
2578
2651
                                exten = crypto_args(peer, CRYPTO_CERT,
2579
 
                                    peer->issuer);
 
2652
                                                    peer->issuer);
2580
2653
 
2581
2654
                        /*
2582
2655
                         * Identity
2583
2656
                         */
2584
2657
                        else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
2585
2658
                                exten = crypto_args(peer,
2586
 
                                    crypto_ident(peer), NULL);
 
2659
                                                    crypto_ident(peer), NULL);
2587
2660
 
2588
2661
                        /*
2589
2662
                         * Autokey
2590
2663
                         */
2591
2664
                        else if (!(peer->crypto & CRYPTO_FLAG_AGREE))
2592
2665
                                exten = crypto_args(peer, CRYPTO_COOK,
2593
 
                                    NULL);
 
2666
                                                    NULL);
2594
2667
                        else if (!(peer->crypto & CRYPTO_FLAG_AUTO) &&
2595
 
                            (peer->cast_flags & MDF_BCLNT))
 
2668
                                 (peer->cast_flags & MDF_BCLNT))
2596
2669
                                exten = crypto_args(peer, CRYPTO_AUTO,
2597
 
                                    NULL);
 
2670
                                                    NULL);
2598
2671
 
2599
2672
                        /*
2600
2673
                         * Postamble. We can sign the certificate here,
2601
2674
                         * since there is no chance of deadlock.
2602
2675
                         */
2603
2676
                        else if (sys_leap != LEAP_NOTINSYNC &&
2604
 
                           !(peer->crypto & CRYPTO_FLAG_SIGN))
 
2677
                                 !(peer->crypto & CRYPTO_FLAG_SIGN))
2605
2678
                                exten = crypto_args(peer, CRYPTO_SIGN,
2606
 
                                    sys_hostname);
 
2679
                                                    sys_hostname);
2607
2680
                        else if (sys_leap != LEAP_NOTINSYNC &&
2608
 
                            peer->crypto & CRYPTO_FLAG_TAI &&
2609
 
                            !(peer->crypto & CRYPTO_FLAG_LEAP))
 
2681
                                 peer->crypto & CRYPTO_FLAG_TAI &&
 
2682
                                 !(peer->crypto & CRYPTO_FLAG_LEAP))
2610
2683
                                exten = crypto_args(peer, CRYPTO_TAI,
2611
 
                                    NULL);
 
2684
                                                    NULL);
2612
2685
                        break;
2613
2686
                }
2614
2687
 
2615
2688
                /*
2616
 
                 * Build the extension fields if available. If an error
2617
 
                 * occured, the crypto machinery broke or was
2618
 
                 * misconfigured, so plaint the log and douse the
2619
 
                 * boiler.
 
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.
2620
2694
                 */
2621
2695
                if (peer->cmmd != NULL) {
2622
2696
                        peer->cmmd->associd = htonl(peer->associd);
2623
2697
                        sendlen += crypto_xmit(&xpkt, &peer->srcadr,
2624
 
                            sendlen, peer->cmmd, 0);
 
2698
                                               sendlen, peer->cmmd, 0);
2625
2699
                        free(peer->cmmd);
2626
2700
                        peer->cmmd = NULL;
2627
2701
                }
2628
2702
                if (exten != NULL) {
 
2703
                        int ltemp = 0;
 
2704
 
2629
2705
                        if (exten->opcode != 0) {
2630
 
                                sendlen += crypto_xmit(&xpkt,
2631
 
                                    &peer->srcadr, sendlen, exten, 0);
2632
 
                        } else {
2633
 
                                peer_clear(peer, "CRYP");
2634
 
                                peer->flash |= TEST4; /* crypto error */
2635
 
                                msyslog(LOG_INFO,
2636
 
                                    "transmit: crypto error for %s",
2637
 
                                    stoa(&peer->srcadr));
 
2706
                                ltemp = crypto_xmit(&xpkt,
 
2707
                                                       &peer->srcadr, sendlen, exten, 0);
 
2708
                                if (ltemp == 0) {
 
2709
                                        peer->flash |= TEST9; /* crypto error */
 
2710
                                        free(exten);
 
2711
                                        return;
 
2712
                                }
2638
2713
                        }
 
2714
                        sendlen += ltemp;
2639
2715
                        free(exten);
2640
2716
                }
2641
2717
 
2642
2718
                /*
2643
2719
                 * If extension fields are present, we must use a
2644
 
                 * private cookie value of zero. Most intricate.
 
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.
2645
2723
                 */
2646
 
                if (sendlen > LEN_PKT_NOMAC)
 
2724
                if (sendlen > LEN_PKT_NOMAC) {
2647
2725
                        session_key(&peer->dstadr->sin, &peer->srcadr,
2648
2726
                            xkeyid, 0, 2);
 
2727
                } else if (peer->flash & TEST9) {
 
2728
                        authtrust(xkeyid, 0);
 
2729
                        return;
 
2730
                }
2649
2731
        } 
2650
2732
#endif /* OPENSSL */
2651
2733
 
2652
2734
        /*
2653
 
         * If something broke go directly to jail without sending the
2654
 
         * packet.
 
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,
 
2738
         * etc.
2655
2739
         */
2656
 
        if (peer->flash & TEST4)
2657
 
                return;
2658
 
 
2659
2740
        xkeyid = peer->keyid;
2660
2741
        get_systime(&peer->xmt);
2661
2742
        L_ADD(&peer->xmt, &sys_authdelay);
2662
2743
        HTONL_FP(&peer->xmt, &xpkt.xmt);
2663
2744
        authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2664
2745
        if (authlen == 0) {
2665
 
                peer_clear(peer, "NKEY");
2666
 
                peer->flash |= TEST4;           /* no key found */
2667
 
                msyslog(LOG_INFO, "transmit: key %u not found for %s",
2668
 
                    xkeyid, stoa(&peer->srcadr));
 
2746
                msyslog(LOG_INFO, "transmit: %s key %u not found",
 
2747
                    stoa(&peer->srcadr), xkeyid);
 
2748
                peer->flash |= TEST9;           /* no key found */
2669
2749
                return;
2670
2750
        }
2671
2751
        sendlen += authlen;
2679
2759
                exit (-1);
2680
2760
        }
2681
2761
        sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl], &xpkt,
2682
 
            sendlen);
 
2762
                sendlen);
2683
2763
 
2684
2764
        /*
2685
2765
         * Calculate the encryption delay. Keep the minimum over
2698
2778
#ifdef DEBUG
2699
2779
        if (debug)
2700
2780
                printf(
2701
 
                    "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d index %d\n",
2702
 
                    current_time, ntoa(&peer->dstadr->sin),
2703
 
                    ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen -
2704
 
                    authlen, authlen, peer->keynumber);
 
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);
2705
2785
#endif
2706
2786
#else
2707
2787
#ifdef DEBUG
2708
2788
        if (debug)
2709
2789
                printf(
2710
 
                    "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
2711
 
                    current_time, ntoa(&peer->dstadr->sin),
2712
 
                    ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen -
2713
 
                    authlen, authlen);
 
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 -
 
2793
                        authlen, authlen);
2714
2794
#endif
2715
2795
#endif /* OPENSSL */
2716
2796
}
2742
2822
         * buffer provided. We leave some fields intact as received. If
2743
2823
         * the gazinta was from a multicast address, the gazoutta must
2744
2824
         * go out another way.
 
2825
         *
 
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.
2745
2830
         */
2746
2831
        rpkt = &rbufp->recv_pkt;
2747
 
        if (rbufp->dstadr->flags & INT_MULTICAST)
 
2832
        if (rbufp->dstadr->flags & INT_MCASTOPEN)
2748
2833
                rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
2749
2834
 
2750
2835
        /*
2751
 
         * If the packet has picked up a restriction due to either
2752
 
         * access denied or rate exceeded, decide what to do with it.
2753
 
         */
2754
 
        if (mask & (RES_DONTTRUST | RES_LIMITED)) {
2755
 
                char    *code = "????";
2756
 
 
2757
 
                if (mask & RES_LIMITED) {
2758
 
                        sys_limitrejected++;
2759
 
                        code = "RATE";
2760
 
                } else if (mask & RES_DONTTRUST) {
2761
 
                        sys_restricted++;
2762
 
                        code = "DENY";
2763
 
                }
2764
 
 
2765
 
                /*
2766
 
                 * Here we light up a kiss-of-death (KoD) packet. KoD
2767
 
                 * packets have leap bits unsynchronized, stratum zero
2768
 
                 * and reference ID the four-character error code. Note
2769
 
                 * the rate limit on these packets. Once a second
2770
 
                 * initialize a bucket counter. Every packet sent
2771
 
                 * decrements the counter until reaching zero. If the
2772
 
                 * counter is zero, drop the kod.
2773
 
                 */
 
2836
         * This is deliciously complicated. There are four cases.
 
2837
         *
 
2838
         * case         leap    stratum refid   delay   dispersion
 
2839
         *
 
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
 
2844
         */
 
2845
        /*
 
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.
 
2852
         */
 
2853
        if (mask & RES_LIMITED) {
 
2854
                sys_limitrejected++;
2774
2855
                if (sys_kod == 0 || !(mask & RES_DEMOBILIZE))
2775
2856
                        return;
2776
2857
 
2777
2858
                sys_kod--;
2778
 
                memcpy(&xpkt.refid, code, 4);
2779
2859
                xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
2780
2860
                    PKT_VERSION(rpkt->li_vn_mode), xmode);
2781
2861
                xpkt.stratum = STRATUM_UNSPEC;
2782
 
        } else {
 
2862
                memcpy(&xpkt.refid, "RATE", 4);
 
2863
                xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
 
2864
                xpkt.rootdispersion =
 
2865
                    HTONS_FP(DTOUFP(sys_rootdispersion));
 
2866
 
 
2867
        /*
 
2868
         * This is a normal packet. Use the system variables.
 
2869
         */
 
2870
        } else if (sys_stratum < sys_orphan) {
2783
2871
                xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
2784
2872
                    PKT_VERSION(rpkt->li_vn_mode), xmode);
2785
2873
                xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
2786
2874
                xpkt.refid = sys_refid;
 
2875
                xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
 
2876
                xpkt.rootdispersion =
 
2877
                    HTONS_FP(DTOUFP(sys_rootdispersion));
 
2878
 
 
2879
        /*
 
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.
 
2883
         */
 
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));
 
2892
 
 
2893
        /*
 
2894
         * This is an orphan parent. Show leap synchronized, orphan
 
2895
         * stratum, loopack reference ID and zero root delay.
 
2896
         */
 
2897
        } else {
 
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));
2787
2904
        }
2788
2905
        xpkt.ppoll = rpkt->ppoll;
2789
2906
        xpkt.precision = sys_precision;
2790
 
        xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
2791
 
        xpkt.rootdispersion =
2792
 
            HTONS_FP(DTOUFP(sys_rootdispersion));
 
2907
        xpkt.rootdispersion = HTONS_FP(DTOUFP(sys_rootdispersion));
2793
2908
        HTONL_FP(&sys_reftime, &xpkt.reftime);
2794
2909
        xpkt.org = rpkt->xmt;
2795
2910
        HTONL_FP(&rbufp->recv_time, &xpkt.rec);
2816
2931
 
2817
2932
        /*
2818
2933
         * The received packet contains a MAC, so the transmitted packet
2819
 
         * must be authenticated. For private-key cryptography, use the
2820
 
         * predefined private keys to generate the cryptosum. For
2821
 
         * autokey cryptography, use the server private value to
2822
 
         * generate the cookie, which is unique for every source-
2823
 
         * destination-key ID combination.
 
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.
2824
2939
         */
2825
2940
#ifdef OPENSSL
2826
2941
        if (xkeyid > NTP_MAXKEY) {
2837
2952
                 */
2838
2953
                cookie = session_key(&rbufp->recv_srcadr,
2839
2954
                    &rbufp->dstadr->sin, 0, sys_private, 0);
2840
 
                if (rbufp->recv_length >= (int)(sendlen + MAX_MAC_LEN + 2 *
2841
 
                    sizeof(u_int32))) {
 
2955
                if (rbufp->recv_length >= (int)(sendlen + MAX_MAC_LEN +
 
2956
                    2 * sizeof(u_int32))) {
2842
2957
                        session_key(&rbufp->dstadr->sin,
2843
2958
                            &rbufp->recv_srcadr, xkeyid, 0, 2);
2844
2959
                        temp32 = CRYPTO_RESP;
2922
3037
 * Determine if the peer is unfit for synchronization
2923
3038
 *
2924
3039
 * A peer is unfit for synchronization if
2925
 
 * > not reachable
2926
 
 * > a synchronization loop would form
2927
 
 * > never been synchronized
2928
 
 * > stratum undefined or too high
2929
 
 * > too long without synchronization
2930
 
 * > designated noselect
 
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
2931
3044
 */
2932
 
static int                      /* 0 if no, 1 if yes */
 
3045
int                             /* FALSE if fit, TRUE if unfit */
2933
3046
peer_unfit(
2934
3047
        struct peer *peer       /* peer structure pointer */
2935
3048
        )
2936
3049
{
2937
 
        return (!peer->reach || (peer->stratum > 1 && peer->refid ==
2938
 
            peer->dstadr->addr_refid) || peer->leap == LEAP_NOTINSYNC ||
2939
 
            peer->stratum >= STRATUM_UNSPEC || peer->flags &
2940
 
            FLAG_NOSELECT);
 
3050
        int     rval = 0;
 
3051
 
 
3052
        /*
 
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.
 
3058
         */
 
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 */
 
3063
 
 
3064
        /*
 
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.
 
3068
         */
 
3069
        if (root_distance(peer) >= sys_maxdist + clock_phi *
 
3070
            ULOGTOD(sys_poll))
 
3071
                rval |= TEST11;         /* distance exceeded */
 
3072
 
 
3073
        /*
 
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.
 
3078
         */
 
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 */
 
3083
 
 
3084
        /*
 
3085
         * An unreachable error occurs if the server is unreachable or
 
3086
         * the noselect bit is set.
 
3087
         */
 
3088
        if (!peer->reach || peer->flags & FLAG_NOSELECT)
 
3089
                rval |= TEST13;         /* unreachable */
 
3090
 
 
3091
        peer->flash &= ~PEER_TEST_MASK;
 
3092
        peer->flash |= rval;
 
3093
        return (rval);
2941
3094
}
2942
3095
 
2943
3096
 
2950
3103
 
2951
3104
/*
2952
3105
 * This routine calculates the system precision, defined as the minimum
2953
 
 * of a sequency of differences between successive readings of the
 
3106
 * of a sequence of differences between successive readings of the
2954
3107
 * system clock. However, if the system clock can be read more than once
2955
3108
 * during a tick interval, the difference can be zero or one LSB unit,
2956
3109
 * where the LSB corresponds to one nanosecond or one microsecond.
3032
3185
        sys_stratum = STRATUM_UNSPEC;
3033
3186
        memcpy(&sys_refid, "INIT", 4);
3034
3187
        sys_precision = (s_char)default_get_precision();
3035
 
        sys_error = LOGTOD(sys_precision);
 
3188
        sys_jitter = LOGTOD(sys_precision);
3036
3189
        sys_rootdelay = 0;
 
3190
        sys_orphandelay = (double)(ntp_random() & 0xffff) / 65536. *
 
3191
            sys_maxdist;
3037
3192
        sys_rootdispersion = 0;
3038
3193
        L_CLR(&sys_reftime);
3039
3194
        sys_peer = NULL;
3116
3271
                break;
3117
3272
 
3118
3273
        /*
3119
 
         * Turn on/off facility to listen to broadcasts.
 
3274
         * Turn on/off enable broadcasts.
3120
3275
         */
3121
3276
        case PROTO_BROADCLIENT:
3122
3277
                sys_bclient = (int)value;
3127
3282
                break;
3128
3283
 
3129
3284
        /*
 
3285
         * Turn on/off PPS discipline.
 
3286
         */
 
3287
        case PROTO_PPS:
 
3288
                pps_enable = (int)value;
 
3289
                break;
 
3290
 
 
3291
        /*
3130
3292
         * Add muliticast group address.
3131
3293
         */
3132
3294
        case PROTO_MULTICAST_ADD:
3133
3295
                if (svalue)
3134
3296
                    io_multicast_add(*svalue);
 
3297
                sys_bclient = 1;
3135
3298
                break;
3136
3299
 
3137
3300
        /*
3157
3320
                break;
3158
3321
 
3159
3322
        /*
3160
 
         * Require authentication to mobilize ephemeral associations.
 
3323
         * Turn on/off authentication to mobilize ephemeral
 
3324
         * associations.
3161
3325
         */
3162
3326
        case PROTO_AUTHENTICATE:
3163
3327
                sys_authenticate = (int)value;
3164
3328
                break;
3165
3329
 
3166
3330
        /*
3167
 
         * Turn on/off PPS discipline.
3168
 
         */
3169
 
        case PROTO_PPS:
3170
 
                pps_enable = (int)value;
3171
 
                break;
3172
 
 
3173
 
        /*
3174
 
         * Set the minimum number of survivors.
 
3331
         * Set minimum number of survivors.
3175
3332
         */
3176
3333
        case PROTO_MINCLOCK:
3177
3334
                sys_minclock = (int)dvalue;
3178
3335
                break;
3179
3336
 
3180
3337
        /*
3181
 
         * Set the minimum number of candidates.
 
3338
         * Set maximum number of preemptable associations.
 
3339
         */
 
3340
        case PROTO_MAXCLOCK:
 
3341
                sys_maxclock = (int)dvalue;
 
3342
                break;
 
3343
 
 
3344
        /*
 
3345
         * Set minimum number of survivors.
3182
3346
         */
3183
3347
        case PROTO_MINSANE:
3184
3348
                sys_minsane = (int)dvalue;
3185
3349
                break;
3186
3350
 
3187
3351
        /*
3188
 
         * Set the stratum floor.
 
3352
         * Set stratum floor.
3189
3353
         */
3190
3354
        case PROTO_FLOOR:
3191
3355
                sys_floor = (int)dvalue;
3192
3356
                break;
3193
3357
 
3194
3358
        /*
3195
 
         * Set the stratum ceiling.
 
3359
         * Set stratum ceiling.
3196
3360
         */
3197
3361
        case PROTO_CEILING:
3198
3362
                sys_ceiling = (int)dvalue;
3199
3363
                break;
3200
3364
 
3201
3365
        /*
3202
 
         * Set the cohort switch.
 
3366
         * Set orphan stratum.
 
3367
         */
 
3368
        case PROTO_ORPHAN:
 
3369
                sys_orphan = (int)dvalue;
 
3370
                break;
 
3371
 
 
3372
        /*
 
3373
         * Set cohort switch.
3203
3374
         */
3204
3375
        case PROTO_COHORT:
3205
 
                sys_cohort= (int)dvalue;
3206
 
                break;
3207
 
        /*
3208
 
         * Set the adjtime() resolution (s).
 
3376
                sys_cohort = (int)dvalue;
 
3377
                break;
 
3378
 
 
3379
        /*
 
3380
         * Set minimum dispersion increment.
 
3381
         */
 
3382
        case PROTO_MINDISP:
 
3383
                sys_mindisp = dvalue;
 
3384
                break;
 
3385
 
 
3386
        /*
 
3387
         * Set maximum distance (select threshold).
 
3388
         */
 
3389
        case PROTO_MAXDIST:
 
3390
                sys_maxdist = dvalue;
 
3391
                break;
 
3392
 
 
3393
        /*
 
3394
         * Set anticlockhop threshold.
 
3395
         */
 
3396
        case PROTO_MAXHOP:
 
3397
                sys_maxhop = (int)dvalue;
 
3398
                break;
 
3399
 
 
3400
        /*
 
3401
         * Set adjtime() resolution (s).
3209
3402
         */
3210
3403
        case PROTO_ADJ:
3211
3404
                sys_tick = dvalue;
3212
3405
                break;
3213
3406
 
 
3407
        /*
 
3408
         * Set manycast beacon interval.
 
3409
         */
 
3410
        case PROTO_BEACON:
 
3411
                sys_beacon = (int)dvalue;
 
3412
                break;
 
3413
 
3214
3414
#ifdef REFCLOCK
3215
3415
        /*
3216
3416
         * Turn on/off refclock calibrate
3218
3418
        case PROTO_CAL:
3219
3419
                cal_enable = (int)value;
3220
3420
                break;
3221
 
#endif
 
3421
#endif /* REFCLOCK */
3222
3422
        default:
3223
3423
 
3224
3424
                /*