xref: /netbsd/external/bsd/ntp/dist/ntpd/ntp_peer.c (revision 9034ec65)
1 /*	$NetBSD: ntp_peer.c,v 1.13 2020/05/25 20:47:25 christos Exp $	*/
2 
3 /*
4  * ntp_peer.c - management of data maintained for peer associations
5  */
6 #ifdef HAVE_CONFIG_H
7 #include <config.h>
8 #endif
9 
10 #include <stdio.h>
11 #include <sys/types.h>
12 
13 #include "ntpd.h"
14 #include "ntp_lists.h"
15 #include "ntp_stdlib.h"
16 #include "ntp_control.h"
17 #include <ntp_random.h>
18 
19 /*
20  *		    Table of valid association combinations
21  *		    ---------------------------------------
22  *
23  *                             packet->mode
24  * peer->mode      | UNSPEC  ACTIVE PASSIVE  CLIENT  SERVER  BCAST
25  * ----------      | ---------------------------------------------
26  * NO_PEER         |   e       1       0       1       1       1
27  * ACTIVE          |   e       1       1       0       0       0
28  * PASSIVE         |   e       1       e       0       0       0
29  * CLIENT          |   e       0       0       0       1       0
30  * SERVER          |   e       0       0       0       0       0
31  * BCAST           |   e       0       0       0       0       0
32  * BCLIENT         |   e       0       0       0       e       1
33  *
34  * One point to note here: a packet in BCAST mode can potentially match
35  * a peer in CLIENT mode, but we that is a special case and we check for
36  * that early in the decision process.  This avoids having to keep track
37  * of what kind of associations are possible etc...  We actually
38  * circumvent that problem by requiring that the first b(m)roadcast
39  * received after the change back to BCLIENT mode sets the clock.
40  */
41 #define AM_MODES	7	/* number of rows and columns */
42 #define NO_PEER		0	/* action when no peer is found */
43 
44 int AM[AM_MODES][AM_MODES] = {
45 /*			packet->mode					    */
46 /* peer { UNSPEC,   ACTIVE,     PASSIVE,    CLIENT,     SERVER,     BCAST } */
47 /* mode */
48 /*NONE*/{ AM_ERR, AM_NEWPASS, AM_NOMATCH, AM_FXMIT,   AM_MANYCAST, AM_NEWBCL},
49 
50 /*A*/	{ AM_ERR, AM_PROCPKT, AM_PROCPKT, AM_NOMATCH, AM_NOMATCH,  AM_NOMATCH},
51 
52 /*P*/	{ AM_ERR, AM_PROCPKT, AM_ERR,     AM_NOMATCH, AM_NOMATCH,  AM_NOMATCH},
53 
54 /*C*/	{ AM_ERR, AM_NOMATCH, AM_NOMATCH, AM_NOMATCH, AM_PROCPKT,  AM_NOMATCH},
55 
56 /*S*/	{ AM_ERR, AM_NOMATCH, AM_NOMATCH, AM_NOMATCH, AM_NOMATCH,  AM_NOMATCH},
57 
58 /*BCST*/{ AM_ERR, AM_NOMATCH, AM_NOMATCH, AM_NOMATCH, AM_NOMATCH,  AM_NOMATCH},
59 
60 /*BCL*/ { AM_ERR, AM_NOMATCH, AM_NOMATCH, AM_NOMATCH, AM_NOMATCH,  AM_PROCPKT},
61 };
62 
63 #define MATCH_ASSOC(x, y)	AM[(x)][(y)]
64 
65 /*
66  * These routines manage the allocation of memory to peer structures
67  * and the maintenance of three data structures involving all peers:
68  *
69  * - peer_list is a single list with all peers, suitable for scanning
70  *   operations over all peers.
71  * - peer_adr_hash is an array of lists indexed by hashed peer address.
72  * - peer_aid_hash is an array of lists indexed by hashed associd.
73  *
74  * They also maintain a free list of peer structures, peer_free.
75  *
76  * The three main entry points are findpeer(), which looks for matching
77  * peer structures in the peer list, newpeer(), which allocates a new
78  * peer structure and adds it to the list, and unpeer(), which
79  * demobilizes the association and deallocates the structure.
80  */
81 /*
82  * Peer hash tables
83  */
84 struct peer *peer_hash[NTP_HASH_SIZE];	/* peer hash table */
85 int	peer_hash_count[NTP_HASH_SIZE];	/* peers in each bucket */
86 struct peer *assoc_hash[NTP_HASH_SIZE];	/* association ID hash table */
87 int	assoc_hash_count[NTP_HASH_SIZE];/* peers in each bucket */
88 struct peer *peer_list;			/* peer structures list */
89 static struct peer *peer_free;		/* peer structures free list */
90 int	peer_free_count;		/* count of free structures */
91 
92 /*
93  * Association ID.  We initialize this value randomly, then assign a new
94  * value every time an association is mobilized.
95  */
96 static associd_t current_association_ID; /* association ID */
97 static associd_t initial_association_ID; /* association ID */
98 
99 /*
100  * Memory allocation watermarks.
101  */
102 #define	INIT_PEER_ALLOC		8	/* static preallocation */
103 #define	INC_PEER_ALLOC		4	/* add N more when empty */
104 
105 /*
106  * Miscellaneous statistic counters which may be queried.
107  */
108 u_long	peer_timereset;			/* time stat counters zeroed */
109 u_long	findpeer_calls;			/* calls to findpeer */
110 u_long	assocpeer_calls;		/* calls to findpeerbyassoc */
111 u_long	peer_allocations;		/* allocations from free list */
112 u_long	peer_demobilizations;		/* structs freed to free list */
113 int	total_peer_structs;		/* peer structs */
114 int	peer_associations;		/* mobilized associations */
115 int	peer_preempt;			/* preemptable associations */
116 static struct peer init_peer_alloc[INIT_PEER_ALLOC]; /* init alloc */
117 
118 static struct peer *	findexistingpeer_name(const char *, u_short,
119 					      struct peer *, int);
120 static struct peer *	findexistingpeer_addr(sockaddr_u *,
121 					      struct peer *, int,
122 					      u_char, int *);
123 static void		free_peer(struct peer *, int);
124 static void		getmorepeermem(void);
125 static int		score(struct peer *);
126 
127 
128 /*
129  * init_peer - initialize peer data structures and counters
130  *
131  * N.B. We use the random number routine in here. It had better be
132  * initialized prior to getting here.
133  */
134 void
init_peer(void)135 init_peer(void)
136 {
137 	int i;
138 
139 	/*
140 	 * Initialize peer free list from static allocation.
141 	 */
142 	for (i = COUNTOF(init_peer_alloc) - 1; i >= 0; i--)
143 		LINK_SLIST(peer_free, &init_peer_alloc[i], p_link);
144 	total_peer_structs = COUNTOF(init_peer_alloc);
145 	peer_free_count = COUNTOF(init_peer_alloc);
146 
147 	/*
148 	 * Initialize our first association ID
149 	 */
150 	do
151 		current_association_ID = ntp_random() & ASSOCID_MAX;
152 	while (!current_association_ID);
153 	initial_association_ID = current_association_ID;
154 }
155 
156 
157 /*
158  * getmorepeermem - add more peer structures to the free list
159  */
160 static void
getmorepeermem(void)161 getmorepeermem(void)
162 {
163 	int i;
164 	struct peer *peers;
165 
166 	peers = eallocarray(INC_PEER_ALLOC, sizeof(*peers));
167 
168 	for (i = INC_PEER_ALLOC - 1; i >= 0; i--)
169 		LINK_SLIST(peer_free, &peers[i], p_link);
170 
171 	total_peer_structs += INC_PEER_ALLOC;
172 	peer_free_count += INC_PEER_ALLOC;
173 }
174 
175 
176 static struct peer *
findexistingpeer_name(const char * hostname,u_short hname_fam,struct peer * start_peer,int mode)177 findexistingpeer_name(
178 	const char *	hostname,
179 	u_short		hname_fam,
180 	struct peer *	start_peer,
181 	int		mode
182 	)
183 {
184 	struct peer *p;
185 
186 	if (NULL == start_peer)
187 		p = peer_list;
188 	else
189 		p = start_peer->p_link;
190 	for (; p != NULL; p = p->p_link)
191 		if (p->hostname != NULL
192 		    && (-1 == mode || p->hmode == mode)
193 		    && (AF_UNSPEC == hname_fam
194 			|| AF_UNSPEC == AF(&p->srcadr)
195 			|| hname_fam == AF(&p->srcadr))
196 		    && !strcasecmp(p->hostname, hostname))
197 			break;
198 	return p;
199 }
200 
201 
202 static
203 struct peer *
findexistingpeer_addr(sockaddr_u * addr,struct peer * start_peer,int mode,u_char cast_flags,int * ip_count)204 findexistingpeer_addr(
205 	sockaddr_u *	addr,
206 	struct peer *	start_peer,
207 	int		mode,
208 	u_char		cast_flags,
209 	int *		ip_count
210 	)
211 {
212 	struct peer *peer;
213 
214 	DPRINTF(2, ("findexistingpeer_addr(%s, %s, %d, 0x%x, %p)\n",
215 		sptoa(addr),
216 		(start_peer)
217 		    ? sptoa(&start_peer->srcadr)
218 		    : "NULL",
219 		mode, (u_int)cast_flags, ip_count));
220 
221 	/*
222 	 * start_peer is included so we can locate instances of the
223 	 * same peer through different interfaces in the hash table.
224 	 * Without MDF_BCLNT, a match requires the same mode and remote
225 	 * address.  MDF_BCLNT associations start out as MODE_CLIENT
226 	 * if broadcastdelay is not specified, and switch to
227 	 * MODE_BCLIENT after estimating the one-way delay.  Duplicate
228 	 * associations are expanded in definition to match any other
229 	 * MDF_BCLNT with the same srcadr (remote, unicast address).
230 	 */
231 	if (NULL == start_peer)
232 		peer = peer_hash[NTP_HASH_ADDR(addr)];
233 	else
234 		peer = start_peer->adr_link;
235 
236 	while (peer != NULL) {
237 		DPRINTF(3, ("%s %s %d %d 0x%x 0x%x ", sptoa(addr),
238 			sptoa(&peer->srcadr), mode, peer->hmode,
239 			(u_int)cast_flags, (u_int)peer->cast_flags));
240 		if (ip_count) {
241 			if (SOCK_EQ(addr, &peer->srcadr)) {
242 				(*ip_count)++;
243 			}
244 		}
245  		if ((-1 == mode || peer->hmode == mode ||
246 		     ((MDF_BCLNT & peer->cast_flags) &&
247 		      (MDF_BCLNT & cast_flags))) &&
248 		    ADDR_PORT_EQ(addr, &peer->srcadr)) {
249 			DPRINTF(3, ("found.\n"));
250 			break;
251 		}
252 		DPRINTF(3, ("\n"));
253 		peer = peer->adr_link;
254 	}
255 
256 	return peer;
257 }
258 
259 
260 /*
261  * findexistingpeer - search by address and return a pointer to a peer.
262  */
263 struct peer *
findexistingpeer(sockaddr_u * addr,const char * hostname,struct peer * start_peer,int mode,u_char cast_flags,int * ip_count)264 findexistingpeer(
265 	sockaddr_u *	addr,
266 	const char *	hostname,
267 	struct peer *	start_peer,
268 	int		mode,
269 	u_char		cast_flags,
270 	int *		ip_count
271 	)
272 {
273 	if (hostname != NULL)
274 		return findexistingpeer_name(hostname, AF(addr),
275 					     start_peer, mode);
276 	else
277 		return findexistingpeer_addr(addr, start_peer, mode,
278 					     cast_flags, ip_count);
279 }
280 
281 
282 /*
283  * findpeer - find and return a peer match for a received datagram in
284  *	      the peer_hash table.
285  *
286  * [Bug 3072] To faciliate a faster reorganisation after routing changes
287  * the original code re-assigned the peer address to be the destination
288  * of the received packet and initiated another round on a mismatch.
289  * Unfortunately this leaves us wide open for a DoS attack where the
290  * attacker directs a packet with forged destination address to us --
291  * this results in a wrong interface assignment, actually creating a DoS
292  * situation.
293  *
294  * This condition would persist until the next update of the interface
295  * list, but a continued attack would put us out of business again soon
296  * enough. Authentication alone does not help here, since it does not
297  * protect the UDP layer and leaves us open for a replay attack.
298  *
299  * So we do not update the adresses and wait until the next interface
300  * list update does the right thing for us.
301  */
302 struct peer *
findpeer(struct recvbuf * rbufp,int pkt_mode,int * action)303 findpeer(
304 	struct recvbuf *rbufp,
305 	int		pkt_mode,
306 	int *		action
307 	)
308 {
309 	struct peer *	p;
310 	sockaddr_u *	srcadr;
311 	u_int		hash;
312 	struct pkt *	pkt;
313 	l_fp		pkt_org;
314 
315 	findpeer_calls++;
316 	srcadr = &rbufp->recv_srcadr;
317 	hash = NTP_HASH_ADDR(srcadr);
318 	for (p = peer_hash[hash]; p != NULL; p = p->adr_link) {
319 
320 		/* [Bug 3072] ensure interface of peer matches */
321 		/* [Bug 3356] ... if NOT a broadcast peer!     */
322 		if (p->hmode != MODE_BCLIENT && p->dstadr != rbufp->dstadr)
323 			continue;
324 
325 		/* ensure peer source address matches */
326 		if ( ! ADDR_PORT_EQ(srcadr, &p->srcadr))
327 			continue;
328 
329 		/* If the association matching rules determine that this
330 		 * is not a valid combination, then look for the next
331 		 * valid peer association.
332 		 */
333 		*action = MATCH_ASSOC(p->hmode, pkt_mode);
334 
335 		/* A response to our manycastclient solicitation might
336 		 * be misassociated with an ephemeral peer already spun
337 		 * for the server.  If the packet's org timestamp
338 		 * doesn't match the peer's, check if it matches the
339 		 * ACST prototype peer's.  If so it is a redundant
340 		 * solicitation response, return AM_ERR to discard it.
341 		 * [Bug 1762]
342 		 */
343 		if (MODE_SERVER == pkt_mode && AM_PROCPKT == *action) {
344 			pkt = &rbufp->recv_pkt;
345 			NTOHL_FP(&pkt->org, &pkt_org);
346 			if (!L_ISEQU(&p->aorg, &pkt_org) &&
347 			    findmanycastpeer(rbufp))
348 				*action = AM_ERR;
349 		}
350 
351 		/* if an error was returned, exit back right here. */
352 		if (*action == AM_ERR)
353 			return NULL;
354 
355 		/* if a match is found, we stop our search. */
356 		if (*action != AM_NOMATCH)
357 			break;
358 	}
359 
360 	/* If no matching association is found... */
361 	if (NULL == p)
362 		*action = MATCH_ASSOC(NO_PEER, pkt_mode);
363 
364 	return p;
365 }
366 
367 /*
368  * findpeerbyassoc - find and return a peer using his association ID
369  */
370 struct peer *
findpeerbyassoc(associd_t assoc)371 findpeerbyassoc(
372 	associd_t assoc
373 	)
374 {
375 	struct peer *p;
376 	u_int hash;
377 
378 	assocpeer_calls++;
379 	hash = assoc & NTP_HASH_MASK;
380 	for (p = assoc_hash[hash]; p != NULL; p = p->aid_link)
381 		if (assoc == p->associd)
382 			break;
383 	return p;
384 }
385 
386 
387 /*
388  * clear_all - flush all time values for all associations
389  */
390 void
clear_all(void)391 clear_all(void)
392 {
393 	struct peer *p;
394 
395 	/*
396 	 * This routine is called when the clock is stepped, and so all
397 	 * previously saved time values are untrusted.
398 	 */
399 	for (p = peer_list; p != NULL; p = p->p_link)
400 		if (!(MDF_TXONLY_MASK & p->cast_flags))
401 			peer_clear(p, "STEP");
402 
403 	DPRINTF(1, ("clear_all: at %lu\n", current_time));
404 }
405 
406 
407 /*
408  * score_all() - determine if an association can be demobilized
409  */
410 int
score_all(struct peer * peer)411 score_all(
412 	struct peer *peer	/* peer structure pointer */
413 	)
414 {
415 	struct peer *speer;
416 	int	temp, tamp;
417 	int	x;
418 
419 	/*
420 	 * This routine finds the minimum score for all preemptible
421 	 * associations and returns > 0 if the association can be
422 	 * demobilized.
423 	 */
424 	tamp = score(peer);
425 	temp = 100;
426 	for (speer = peer_list; speer != NULL; speer = speer->p_link)
427 		if (speer->flags & FLAG_PREEMPT) {
428 			x = score(speer);
429 			if (x < temp)
430 				temp = x;
431 		}
432 	DPRINTF(1, ("score_all: at %lu score %d min %d\n",
433 		    current_time, tamp, temp));
434 
435 	if (tamp != temp)
436 		temp = 0;
437 
438 	return temp;
439 }
440 
441 
442 /*
443  * score() - calculate preemption score
444  */
445 static int
score(struct peer * peer)446 score(
447 	struct peer *peer	/* peer structure pointer */
448 	)
449 {
450 	int	temp;
451 
452 	/*
453 	 * This routine calculates the premption score from the peer
454 	 * error bits and status. Increasing values are more cherished.
455 	 */
456 	temp = 0;
457 	if (!(peer->flash & TEST10))
458 		temp++;			/* 1 good synch and stratum */
459 	if (!(peer->flash & TEST13))
460 		temp++;			/* 2 reachable */
461 	if (!(peer->flash & TEST12))
462 		temp++;			/* 3 no loop */
463 	if (!(peer->flash & TEST11))
464 		temp++;			/* 4 good distance */
465 	if (peer->status >= CTL_PST_SEL_SELCAND)
466 		temp++;			/* 5 in the hunt */
467 	if (peer->status != CTL_PST_SEL_EXCESS)
468 		temp++;			/* 6 not spare tire */
469 	return (temp);			/* selection status */
470 }
471 
472 
473 /*
474  * free_peer - internal routine to free memory referred to by a struct
475  *	       peer and return it to the peer free list.  If unlink is
476  *	       nonzero, unlink from the various lists.
477  */
478 static void
free_peer(struct peer * p,int unlink_peer)479 free_peer(
480 	struct peer *	p,
481 	int		unlink_peer
482 	)
483 {
484 	struct peer *	unlinked;
485 	int		hash;
486 
487 	if (unlink_peer) {
488 		hash = NTP_HASH_ADDR(&p->srcadr);
489 		peer_hash_count[hash]--;
490 
491 		UNLINK_SLIST(unlinked, peer_hash[hash], p, adr_link,
492 			     struct peer);
493 		if (NULL == unlinked) {
494 			peer_hash_count[hash]++;
495 			msyslog(LOG_ERR, "peer %s not in address table!",
496 				stoa(&p->srcadr));
497 		}
498 
499 		/*
500 		 * Remove him from the association hash as well.
501 		 */
502 		hash = p->associd & NTP_HASH_MASK;
503 		assoc_hash_count[hash]--;
504 
505 		UNLINK_SLIST(unlinked, assoc_hash[hash], p, aid_link,
506 			     struct peer);
507 		if (NULL == unlinked) {
508 			assoc_hash_count[hash]++;
509 			msyslog(LOG_ERR,
510 				"peer %s not in association ID table!",
511 				stoa(&p->srcadr));
512 		}
513 
514 		/* Remove him from the overall list. */
515 		UNLINK_SLIST(unlinked, peer_list, p, p_link,
516 			     struct peer);
517 		if (NULL == unlinked)
518 			msyslog(LOG_ERR, "%s not in peer list!",
519 				stoa(&p->srcadr));
520 	}
521 
522 	if (p->hostname != NULL)
523 		free(p->hostname);
524 
525 	if (p->ident != NULL)
526 		free(p->ident);
527 
528 	if (p->addrs != NULL)
529 		free(p->addrs);		/* from copy_addrinfo_list() */
530 
531 	/* Add his corporeal form to peer free list */
532 	ZERO(*p);
533 	LINK_SLIST(peer_free, p, p_link);
534 	peer_free_count++;
535 }
536 
537 
538 /*
539  * unpeer - remove peer structure from hash table and free structure
540  */
541 void
unpeer(struct peer * peer)542 unpeer(
543 	struct peer *peer
544 	)
545 {
546 	mprintf_event(PEVNT_DEMOBIL, peer, "assoc %u", peer->associd);
547 	restrict_source(&peer->srcadr, 1, 0);
548 	set_peerdstadr(peer, NULL);
549 	peer_demobilizations++;
550 	peer_associations--;
551 	if (FLAG_PREEMPT & peer->flags)
552 		peer_preempt--;
553 #ifdef REFCLOCK
554 	/*
555 	 * If this peer is actually a clock, shut it down first
556 	 */
557 	if (FLAG_REFCLOCK & peer->flags)
558 		refclock_unpeer(peer);
559 #endif
560 
561 	free_peer(peer, TRUE);
562 }
563 
564 
565 /*
566  * peer_config - configure a new association
567  */
568 struct peer *
peer_config(sockaddr_u * srcadr,const char * hostname,endpt * dstadr,int ippeerlimit,u_char hmode,u_char version,u_char minpoll,u_char maxpoll,u_int flags,u_int32 ttl,keyid_t key,const char * ident)569 peer_config(
570 	sockaddr_u *	srcadr,
571 	const char *	hostname,
572 	endpt *		dstadr,
573 	int		ippeerlimit,
574 	u_char		hmode,
575 	u_char		version,
576 	u_char		minpoll,
577 	u_char		maxpoll,
578 	u_int		flags,
579 	u_int32		ttl,
580 	keyid_t		key,
581 	const char *	ident		/* autokey group */
582 	)
583 {
584 	u_char cast_flags;
585 
586 	/*
587 	 * We do a dirty little jig to figure the cast flags. This is
588 	 * probably not the best place to do this, at least until the
589 	 * configure code is rebuilt. Note only one flag can be set.
590 	 */
591 	switch (hmode) {
592 	case MODE_BROADCAST:
593 		if (IS_MCAST(srcadr))
594 			cast_flags = MDF_MCAST;
595 		else
596 			cast_flags = MDF_BCAST;
597 		break;
598 
599 	case MODE_CLIENT:
600 		if (hostname != NULL && SOCK_UNSPEC(srcadr))
601 			cast_flags = MDF_POOL;
602 		else if (IS_MCAST(srcadr))
603 			cast_flags = MDF_ACAST;
604 		else
605 			cast_flags = MDF_UCAST;
606 		break;
607 
608 	default:
609 		cast_flags = MDF_UCAST;
610 	}
611 
612 	/*
613 	 * Mobilize the association and initialize its variables. If
614 	 * emulating ntpdate, force iburst.  For pool and manycastclient
615 	 * strip FLAG_PREEMPT as the prototype associations are not
616 	 * themselves preemptible, though the resulting associations
617 	 * are.
618 	 */
619 	flags |= FLAG_CONFIG;
620 	if (mode_ntpdate)
621 		flags |= FLAG_IBURST;
622 	if ((MDF_ACAST | MDF_POOL) & cast_flags)
623 		flags &= ~FLAG_PREEMPT;
624 	return newpeer(srcadr, hostname, dstadr, ippeerlimit, hmode, version,
625 	    minpoll, maxpoll, flags, cast_flags, ttl, key, ident);
626 }
627 
628 /*
629  * setup peer dstadr field keeping it in sync with the interface
630  * structures
631  */
632 void
set_peerdstadr(struct peer * p,endpt * dstadr)633 set_peerdstadr(
634 	struct peer *	p,
635 	endpt *		dstadr
636 	)
637 {
638 	struct peer *	unlinked;
639 
640 	DEBUG_INSIST(p != NULL);
641 
642 	if (p == NULL)
643 		return;
644 
645 	/* check for impossible or identical assignment */
646 	if (p->dstadr == dstadr)
647 		return;
648 
649 	/*
650 	 * Don't accept updates to a separate multicast receive-only
651 	 * endpt while a BCLNT peer is running its unicast protocol.
652 	 */
653 	if (dstadr != NULL && (FLAG_BC_VOL & p->flags) &&
654 	    (INT_MCASTIF & dstadr->flags) && MODE_CLIENT == p->hmode) {
655 		return;
656 	}
657 
658 	/* unlink from list if we have an address prior to assignment */
659 	if (p->dstadr != NULL) {
660 		p->dstadr->peercnt--;
661 		UNLINK_SLIST(unlinked, p->dstadr->peers, p, ilink,
662 			     struct peer);
663 		msyslog(LOG_INFO, "%s local addr %s -> %s",
664 			stoa(&p->srcadr), latoa(p->dstadr),
665 			latoa(dstadr));
666 	}
667 
668 	p->dstadr = dstadr;
669 
670 	/* link to list if we have an address after assignment */
671 	if (p->dstadr != NULL) {
672 		LINK_SLIST(dstadr->peers, p, ilink);
673 		dstadr->peercnt++;
674 	}
675 }
676 
677 /*
678  * attempt to re-rebind interface if necessary
679  */
680 static void
peer_refresh_interface(struct peer * p)681 peer_refresh_interface(
682 	struct peer *p
683 	)
684 {
685 	endpt *	niface;
686 	endpt *	piface;
687 
688 	niface = select_peerinterface(p, &p->srcadr, NULL);
689 
690 	DPRINTF(4, (
691 	    "peer_refresh_interface: %s->%s mode %d vers %d poll %d %d flags 0x%x 0x%x ttl %u key %08x: new interface: ",
692 	    p->dstadr == NULL ? "<null>" :
693 	    stoa(&p->dstadr->sin), stoa(&p->srcadr), p->hmode,
694 	    p->version, p->minpoll, p->maxpoll, p->flags, p->cast_flags,
695 	    p->ttl, p->keyid));
696 	if (niface != NULL) {
697 		DPRINTF(4, (
698 		    "fd=%d, bfd=%d, name=%.16s, flags=0x%x, ifindex=%u, sin=%s",
699 		    niface->fd,  niface->bfd, niface->name,
700 		    niface->flags, niface->ifindex,
701 		    stoa(&niface->sin)));
702 		if (niface->flags & INT_BROADCAST)
703 			DPRINTF(4, (", bcast=%s",
704 				stoa(&niface->bcast)));
705 		DPRINTF(4, (", mask=%s\n", stoa(&niface->mask)));
706 	} else {
707 		DPRINTF(4, ("<NONE>\n"));
708 	}
709 
710 	piface = p->dstadr;
711 	set_peerdstadr(p, niface);
712 	if (p->dstadr != NULL) {
713 		/*
714 		 * clear crypto if we change the local address
715 		 */
716 		if (p->dstadr != piface && !(MDF_ACAST & p->cast_flags)
717 		    && MODE_BROADCAST != p->pmode)
718 			peer_clear(p, "XFAC");
719 
720 		/*
721 	 	 * Broadcast needs the socket enabled for broadcast
722 	 	 */
723 		if (MDF_BCAST & p->cast_flags)
724 			enable_broadcast(p->dstadr, &p->srcadr);
725 
726 		/*
727 	 	 * Multicast needs the socket interface enabled for
728 		 * multicast
729 	 	 */
730 		if (MDF_MCAST & p->cast_flags)
731 			enable_multicast_if(p->dstadr, &p->srcadr);
732 	}
733 }
734 
735 
736 /*
737  * refresh_all_peerinterfaces - see that all interface bindings are up
738  * to date
739  */
740 void
refresh_all_peerinterfaces(void)741 refresh_all_peerinterfaces(void)
742 {
743 	struct peer *p;
744 
745 	/*
746 	 * this is called when the interface list has changed
747 	 * give all peers a chance to find a better interface
748 	 * but only if either they don't have an address already
749 	 * or if the one they have hasn't worked for a while.
750 	 */
751 	for (p = peer_list; p != NULL; p = p->p_link) {
752 		if (!(p->dstadr && (p->reach & 0x3)))	// Bug 2849 XOR 2043
753 			peer_refresh_interface(p);
754 	}
755 }
756 
757 
758 /*
759  * newpeer - initialize a new peer association
760  */
761 struct peer *
newpeer(sockaddr_u * srcadr,const char * hostname,endpt * dstadr,int ippeerlimit,u_char hmode,u_char version,u_char minpoll,u_char maxpoll,u_int flags,u_char cast_flags,u_int32 ttl,keyid_t key,const char * ident)762 newpeer(
763 	sockaddr_u *	srcadr,
764 	const char *	hostname,
765 	endpt *		dstadr,
766 	int		ippeerlimit,
767 	u_char		hmode,
768 	u_char		version,
769 	u_char		minpoll,
770 	u_char		maxpoll,
771 	u_int		flags,
772 	u_char		cast_flags,
773 	u_int32		ttl,
774 	keyid_t		key,
775 	const char *	ident
776 	)
777 {
778 	struct peer *	peer;
779 	u_int		hash;
780 	int		ip_count = 0;
781 
782 
783 	DEBUG_REQUIRE(srcadr);
784 
785 #ifdef AUTOKEY
786 	/*
787 	 * If Autokey is requested but not configured, complain loudly.
788 	 */
789 	if (!crypto_flags) {
790 		if (key > NTP_MAXKEY) {
791 			return (NULL);
792 
793 		} else if (flags & FLAG_SKEY) {
794 			msyslog(LOG_ERR, "Autokey not configured");
795 			return (NULL);
796 		}
797 	}
798 #endif	/* AUTOKEY */
799 
800 	/*
801 	 * For now only pool associations have a hostname.
802 	 */
803 	INSIST(NULL == hostname || (MDF_POOL & cast_flags));
804 
805 	/*
806 	 * First search from the beginning for an association with given
807 	 * remote address and mode. If an interface is given, search
808 	 * from there to find the association which matches that
809 	 * destination. If the given interface is "any", track down the
810 	 * actual interface, because that's what gets put into the peer
811 	 * structure.
812 	 */
813 	if (dstadr != NULL) {
814 		peer = findexistingpeer(srcadr, hostname, NULL, hmode,
815 					cast_flags, &ip_count);
816 		while (peer != NULL) {
817 			if (   peer->dstadr == dstadr
818 			    || (   (MDF_BCLNT & cast_flags)
819 				&& (MDF_BCLNT & peer->cast_flags)))
820 				break;
821 
822 			if (dstadr == ANY_INTERFACE_CHOOSE(srcadr) &&
823 			    peer->dstadr == findinterface(srcadr))
824 				break;
825 
826 			peer = findexistingpeer(srcadr, hostname, peer,
827 						hmode, cast_flags, &ip_count);
828 		}
829 	} else {
830 		/* no endpt address given */
831 		peer = findexistingpeer(srcadr, hostname, NULL, hmode,
832 					cast_flags, &ip_count);
833 	}
834 
835 	/*
836 	 * If a peer is found, this would be a duplicate and we don't
837 	 * allow that. This avoids duplicate ephemeral (broadcast/
838 	 * multicast) and preemptible (manycast and pool) client
839 	 * associations.
840 	 */
841 	if (peer != NULL) {
842 		DPRINTF(2, ("newpeer(%s) found existing association\n",
843 			(hostname)
844 			    ? hostname
845 			    : stoa(srcadr)));
846 		return NULL;
847 	}
848 
849 #if 0
850 DPRINTF(1, ("newpeer(%s) found no existing and %d other associations\n",
851 		(hostname)
852 		    ? hostname
853 		    : stoa(srcadr),
854 		ip_count));
855 #endif
856 
857 	/* Check ippeerlimit wrt ip_count */
858 	if (ippeerlimit > -1) {
859 		if (ip_count + 1 > ippeerlimit) {
860 			DPRINTF(2, ("newpeer(%s) denied - ippeerlimit %d\n",
861 				(hostname)
862 				    ? hostname
863 				    : stoa(srcadr),
864 				ippeerlimit));
865 			return NULL;
866 		}
867 	} else {
868 		DPRINTF(1, ("newpeer(%s) - ippeerlimit %d ignored\n",
869 			(hostname)
870 			    ? hostname
871 			    : stoa(srcadr),
872 			ippeerlimit));
873 	}
874 
875 	/*
876 	 * Allocate a new peer structure. Some dirt here, since some of
877 	 * the initialization requires knowlege of our system state.
878 	 */
879 	if (peer_free_count == 0)
880 		getmorepeermem();
881 	UNLINK_HEAD_SLIST(peer, peer_free, p_link);
882 	INSIST(peer != NULL);
883 	peer_free_count--;
884 	peer_associations++;
885 	if (FLAG_PREEMPT & flags)
886 		peer_preempt++;
887 
888 	/*
889 	 * Assign an association ID and increment the system variable.
890 	 */
891 	peer->associd = current_association_ID;
892 	if (++current_association_ID == 0)
893 		++current_association_ID;
894 
895 	peer->srcadr = *srcadr;
896 	if (hostname != NULL)
897 		peer->hostname = estrdup(hostname);
898 	peer->hmode = hmode;
899 	peer->version = version;
900 	peer->flags = flags;
901 	peer->cast_flags = cast_flags;
902 	set_peerdstadr(peer,
903 		       select_peerinterface(peer, srcadr, dstadr));
904 
905 	/*
906 	 * It is an error to set minpoll less than NTP_MINPOLL or to
907 	 * set maxpoll greater than NTP_MAXPOLL. However, minpoll is
908 	 * clamped not greater than NTP_MAXPOLL and maxpoll is clamped
909 	 * not less than NTP_MINPOLL without complaint. Finally,
910 	 * minpoll is clamped not greater than maxpoll.
911 	 */
912 	if (minpoll == 0)
913 		peer->minpoll = NTP_MINDPOLL;
914 	else
915 		peer->minpoll = min(minpoll, NTP_MAXPOLL);
916 	if (maxpoll == 0)
917 		peer->maxpoll = NTP_MAXDPOLL;
918 	else
919 		peer->maxpoll = max(maxpoll, NTP_MINPOLL);
920 	if (peer->minpoll > peer->maxpoll)
921 		peer->minpoll = peer->maxpoll;
922 
923 	if (peer->dstadr != NULL)
924 		DPRINTF(3, ("newpeer(%s): using fd %d and our addr %s\n",
925 			stoa(srcadr), peer->dstadr->fd,
926 			stoa(&peer->dstadr->sin)));
927 	else
928 		DPRINTF(3, ("newpeer(%s): local interface currently not bound\n",
929 			stoa(srcadr)));
930 
931 	/*
932 	 * Broadcast needs the socket enabled for broadcast
933 	 */
934 	if ((MDF_BCAST & cast_flags) && peer->dstadr != NULL)
935 		enable_broadcast(peer->dstadr, srcadr);
936 
937 	/*
938 	 * Multicast needs the socket interface enabled for multicast
939 	 */
940 	if ((MDF_MCAST & cast_flags) && peer->dstadr != NULL)
941 		enable_multicast_if(peer->dstadr, srcadr);
942 
943 #ifdef AUTOKEY
944 	if (key > NTP_MAXKEY)
945 		peer->flags |= FLAG_SKEY;
946 #endif	/* AUTOKEY */
947 	peer->ttl = ttl;
948 	peer->keyid = key;
949 	if (ident != NULL)
950 		peer->ident = estrdup(ident);
951 	peer->precision = sys_precision;
952 	peer->hpoll = peer->minpoll;
953 	if (cast_flags & MDF_ACAST)
954 		peer_clear(peer, "ACST");
955 	else if (cast_flags & MDF_POOL)
956 		peer_clear(peer, "POOL");
957 	else if (cast_flags & MDF_MCAST)
958 		peer_clear(peer, "MCST");
959 	else if (cast_flags & MDF_BCAST)
960 		peer_clear(peer, "BCST");
961 	else
962 		peer_clear(peer, "INIT");
963 	if (mode_ntpdate)
964 		peer_ntpdate++;
965 
966 	/*
967 	 * Note time on statistics timers.
968 	 */
969 	peer->timereset = current_time;
970 	peer->timereachable = current_time;
971 	peer->timereceived = current_time;
972 
973 	if (ISREFCLOCKADR(&peer->srcadr)) {
974 #ifdef REFCLOCK
975 		/*
976 		 * We let the reference clock support do clock
977 		 * dependent initialization.  This includes setting
978 		 * the peer timer, since the clock may have requirements
979 		 * for this.
980 		 */
981 		if (maxpoll == 0)
982 			peer->maxpoll = peer->minpoll;
983 		if (!refclock_newpeer(peer)) {
984 			/*
985 			 * Dump it, something screwed up
986 			 */
987 			set_peerdstadr(peer, NULL);
988 			free_peer(peer, 0);
989 			return NULL;
990 		}
991 #else /* REFCLOCK */
992 		msyslog(LOG_ERR, "refclock %s isn't supported. ntpd was compiled without refclock support.",
993 			stoa(&peer->srcadr));
994 		set_peerdstadr(peer, NULL);
995 		free_peer(peer, 0);
996 		return NULL;
997 #endif /* REFCLOCK */
998 	}
999 
1000 	/*
1001 	 * Put the new peer in the hash tables.
1002 	 */
1003 	hash = NTP_HASH_ADDR(&peer->srcadr);
1004 	LINK_SLIST(peer_hash[hash], peer, adr_link);
1005 	peer_hash_count[hash]++;
1006 	hash = peer->associd & NTP_HASH_MASK;
1007 	LINK_SLIST(assoc_hash[hash], peer, aid_link);
1008 	assoc_hash_count[hash]++;
1009 	LINK_SLIST(peer_list, peer, p_link);
1010 
1011 	restrict_source(&peer->srcadr, 0, 0);
1012 	mprintf_event(PEVNT_MOBIL, peer, "assoc %d", peer->associd);
1013 	DPRINTF(1, ("newpeer: %s->%s mode %u vers %u poll %u %u flags 0x%x 0x%x ttl %u key %08x\n",
1014 	    latoa(peer->dstadr), stoa(&peer->srcadr), peer->hmode,
1015 	    peer->version, peer->minpoll, peer->maxpoll, peer->flags,
1016 	    peer->cast_flags, peer->ttl, peer->keyid));
1017 	return peer;
1018 }
1019 
1020 
1021 /*
1022  * peer_clr_stats - clear peer module statistics counters
1023  */
1024 void
peer_clr_stats(void)1025 peer_clr_stats(void)
1026 {
1027 	findpeer_calls = 0;
1028 	assocpeer_calls = 0;
1029 	peer_allocations = 0;
1030 	peer_demobilizations = 0;
1031 	peer_timereset = current_time;
1032 }
1033 
1034 
1035 /*
1036  * peer_reset - reset statistics counters
1037  */
1038 void
peer_reset(struct peer * peer)1039 peer_reset(
1040 	struct peer *peer
1041 	)
1042 {
1043 	if (peer == NULL)
1044 		return;
1045 
1046 	peer->timereset = current_time;
1047 	peer->sent = 0;
1048 	peer->received = 0;
1049 	peer->processed = 0;
1050 	peer->badauth = 0;
1051 	peer->bogusorg = 0;
1052 	peer->oldpkt = 0;
1053 	peer->seldisptoolarge = 0;
1054 	peer->selbroken = 0;
1055 }
1056 
1057 
1058 /*
1059  * peer_all_reset - reset all peer statistics counters
1060  */
1061 void
peer_all_reset(void)1062 peer_all_reset(void)
1063 {
1064 	struct peer *peer;
1065 
1066 	for (peer = peer_list; peer != NULL; peer = peer->p_link)
1067 		peer_reset(peer);
1068 }
1069 
1070 
1071 /*
1072  * findmanycastpeer - find and return a manycastclient or pool
1073  *		      association matching a received response.
1074  */
1075 struct peer *
findmanycastpeer(struct recvbuf * rbufp)1076 findmanycastpeer(
1077 	struct recvbuf *rbufp	/* receive buffer pointer */
1078 	)
1079 {
1080 	struct peer *peer;
1081 	struct pkt *pkt;
1082 	l_fp p_org;
1083 
1084  	/*
1085  	 * This routine is called upon arrival of a server-mode response
1086 	 * to a manycastclient multicast solicitation, or to a pool
1087 	 * server unicast solicitation.  Search the peer list for a
1088 	 * manycastclient association where the last transmit timestamp
1089 	 * matches the response packet's originate timestamp.  There can
1090 	 * be multiple manycastclient associations, or multiple pool
1091 	 * solicitation assocations, so this assumes the transmit
1092 	 * timestamps are unique for such.
1093 	 */
1094 	pkt = &rbufp->recv_pkt;
1095 	for (peer = peer_list; peer != NULL; peer = peer->p_link)
1096 		if (MDF_SOLICIT_MASK & peer->cast_flags) {
1097 			NTOHL_FP(&pkt->org, &p_org);
1098 			if (L_ISEQU(&p_org, &peer->aorg))
1099 				break;
1100 		}
1101 
1102 	return peer;
1103 }
1104 
1105 /* peer_cleanup - clean peer list prior to shutdown */
peer_cleanup(void)1106 void peer_cleanup(void)
1107 {
1108         struct peer *peer;
1109         associd_t assoc;
1110 
1111         for (assoc = initial_association_ID; assoc != current_association_ID; assoc++) {
1112             if (assoc != 0U) {
1113                 peer = findpeerbyassoc(assoc);
1114                 if (peer != NULL)
1115                     unpeer(peer);
1116             }
1117         }
1118         peer = findpeerbyassoc(current_association_ID);
1119         if (peer != NULL)
1120             unpeer(peer);
1121 }
1122