xref: /titanic_51/usr/src/cmd/cmd-inet/usr.sbin/in.routed/input.c (revision 9e86db79b7d1bbc5f2f04e99954cbd5eae0e22bb)
1 /*
2  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  *
5  * Copyright (c) 1983, 1988, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgment:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * $FreeBSD: src/sbin/routed/input.c,v 1.9 2001/06/06 20:52:30 phk Exp $
37  */
38 
39 #include "defs.h"
40 #include <md5.h>
41 
42 /*
43  * The size of the control buffer passed to recvmsg() used to receive
44  * ancillary data.
45  */
46 #define	CONTROL_BUFSIZE	1024
47 
48 static void input(struct sockaddr_in *, struct interface *, struct rip *, int);
49 static boolean_t ck_passwd(struct interface *, struct rip *, uint8_t *,
50     in_addr_t, struct msg_limit *);
51 
52 
53 /*
54  * Find the interface which received the given message.
55  */
56 struct interface *
57 receiving_interface(struct msghdr *msg, boolean_t findremote)
58 {
59 	struct interface *ifp, *ifp1, *ifp2;
60 	struct sockaddr_in *from;
61 	void *opt;
62 	uint_t ifindex;
63 
64 	from = (struct sockaddr_in *)msg->msg_name;
65 
66 	/* First see if this packet came from a remote gateway. */
67 	if (findremote && ((ifp = findremoteif(from->sin_addr.s_addr)) != NULL))
68 		return (ifp);
69 
70 	/*
71 	 * It did not come from a remote gateway.  Determine which
72 	 * physical interface this packet was received on by
73 	 * processing the message's ancillary data to find the
74 	 * IP_RECVIF option we requested.
75 	 */
76 	if ((opt = find_ancillary(msg, IP_RECVIF)) == NULL) {
77 		msglog("unable to retrieve IP_RECVIF");
78 	} else {
79 		ifindex = *(uint_t *)opt;
80 		if ((ifp = ifwithindex(ifindex, _B_TRUE)) != NULL) {
81 			/* Find the best match of the aliases */
82 			ifp2 = NULL;
83 			for (ifp1 = ifp; ifp1 != NULL;
84 			    ifp1 = ifp1->int_ilist.hl_next) {
85 				if (ifp1->int_addr == from->sin_addr.s_addr)
86 					return (ifp1);
87 				if ((ifp2 == NULL ||
88 				    (ifp2->int_state & IS_ALIAS)) &&
89 				    on_net(from->sin_addr.s_addr, ifp1->int_net,
90 				    ifp1->int_mask)) {
91 					ifp2 = ifp1;
92 				}
93 			}
94 			if (ifp2 != NULL)
95 				ifp = ifp2;
96 			return (ifp);
97 		}
98 	}
99 
100 	/*
101 	 * As a last resort (for some reason, ip didn't give us the
102 	 * IP_RECVIF index we requested), try to deduce the receiving
103 	 * interface based on the source address of the packet.
104 	 */
105 	return (iflookup(from->sin_addr.s_addr));
106 }
107 
108 /*
109  * Process RIP input on rip_sock.  Returns 0 for success, -1 for failure.
110  */
111 int
112 read_rip()
113 {
114 	struct sockaddr_in from;
115 	struct interface *ifp;
116 	int cc;
117 	union pkt_buf inbuf;
118 	struct msghdr msg;
119 	struct iovec iov;
120 	uint8_t ancillary_data[CONTROL_BUFSIZE];
121 
122 	iov.iov_base = &inbuf;
123 	iov.iov_len = sizeof (inbuf);
124 	msg.msg_iov = &iov;
125 	msg.msg_iovlen = 1;
126 	msg.msg_name = &from;
127 	msg.msg_control = &ancillary_data;
128 
129 	for (;;) {
130 		msg.msg_namelen = sizeof (from);
131 		msg.msg_controllen = sizeof (ancillary_data);
132 		cc = recvmsg(rip_sock, &msg, 0);
133 		if (cc == 0)
134 			return (-1);
135 		if (cc < 0) {
136 			if (errno == EWOULDBLOCK || errno == EINTR)
137 				return (0);
138 			LOGERR("recvmsg(rip_sock)");
139 			return (-1);
140 		}
141 
142 		/*
143 		 * ifp is the interface via which the packet arrived.
144 		 */
145 		ifp = receiving_interface(&msg, _B_TRUE);
146 
147 		input(&from, ifp, &inbuf.rip, cc);
148 	}
149 }
150 
151 
152 /* Process a RIP packet */
153 static void
154 input(struct sockaddr_in *from,		/* received from this IP address */
155     struct interface *ifp,		/* interface of incoming socket */
156     struct rip *rip,
157     int cc)
158 {
159 #define	FROM_NADDR from->sin_addr.s_addr
160 	static struct msg_limit use_auth, bad_len, bad_mask;
161 	static struct msg_limit unk_router, bad_router, bad_nhop;
162 
163 	struct rt_entry *rt;
164 	struct rt_spare new;
165 	struct netinfo *n, *lim;
166 	struct interface *ifp1;
167 	in_addr_t gate, mask, v1_mask, dst, ddst_h = 0;
168 	struct auth *ap;
169 	struct tgate *tg = NULL;
170 	struct tgate_net *tn;
171 	int i, j;
172 	boolean_t poll_answer = _B_FALSE; /* Set to _B_TRUE if RIPCMD_POLL */
173 	uint16_t rt_state = 0;	/* Extra route state to pass to input_route() */
174 	uint8_t metric;
175 
176 	(void) memset(&new, 0, sizeof (new));
177 	/* Notice when we hear from a remote gateway */
178 	if (ifp != NULL && (ifp->int_state & IS_REMOTE))
179 		ifp->int_act_time = now.tv_sec;
180 
181 	trace_rip("Recv", "from", from, ifp, rip, cc);
182 
183 	if (ifp != NULL && (ifp->int_if_flags & IFF_NORTEXCH)) {
184 		trace_misc("discard RIP packet received over %s (IFF_NORTEXCH)",
185 		    ifp->int_name);
186 		return;
187 	}
188 
189 	gate = ntohl(FROM_NADDR);
190 	if (IN_CLASSD(gate) || (gate >> IN_CLASSA_NSHIFT) == 0) {
191 		msglim(&bad_router, FROM_NADDR, "source address %s unusable",
192 		    naddr_ntoa(FROM_NADDR));
193 		return;
194 	}
195 
196 	if (rip->rip_vers == 0) {
197 		msglim(&bad_router, FROM_NADDR,
198 		    "RIP version 0, cmd %d, packet received from %s",
199 		    rip->rip_cmd, naddr_ntoa(FROM_NADDR));
200 		return;
201 	}
202 
203 	if (rip->rip_vers > RIPv2) {
204 		msglim(&bad_router, FROM_NADDR,
205 		    "Treating RIP version %d packet received from %s as "
206 		    "version %d", rip->rip_vers, naddr_ntoa(FROM_NADDR),
207 		    RIPv2);
208 		rip->rip_vers = RIPv2;
209 	}
210 
211 	if (cc > (int)OVER_MAXPACKETSIZE) {
212 		msglim(&bad_router, FROM_NADDR,
213 		    "packet at least %d bytes too long received from %s",
214 		    cc-MAXPACKETSIZE, naddr_ntoa(FROM_NADDR));
215 	}
216 
217 	n = rip->rip_nets;
218 	lim = n + (cc - 4) / sizeof (struct netinfo);
219 
220 	/*
221 	 * Notice authentication.
222 	 * As required by section 5.2 of RFC 2453, discard authenticated
223 	 * RIPv2 messages, but only if configured for that silliness.
224 	 *
225 	 * RIPv2 authentication is lame.  Why authenticate queries?
226 	 * Why should a RIPv2 implementation with authentication disabled
227 	 * not be able to listen to RIPv2 packets with authentication, while
228 	 * RIPv1 systems will listen?  Crazy!
229 	 */
230 	if (!auth_ok && rip->rip_vers == RIPv2 && n < lim &&
231 	    n->n_family == RIP_AF_AUTH) {
232 		msglim(&use_auth, FROM_NADDR,
233 		    "RIPv2 message with authentication from %s discarded",
234 		    naddr_ntoa(FROM_NADDR));
235 		return;
236 	}
237 
238 	switch (rip->rip_cmd) {
239 	case RIPCMD_POLL:
240 		/*
241 		 * Similar to RIPCMD_REQUEST, this command is used to
242 		 * request either a full-table or a set of entries.  Both
243 		 * silent processes and routers can respond to this
244 		 * command.
245 		 */
246 		poll_answer = _B_TRUE;
247 		/* FALLTHRU */
248 	case RIPCMD_REQUEST:
249 		/* Are we talking to ourself or a remote gateway? */
250 		ifp1 = ifwithaddr(FROM_NADDR, _B_FALSE, _B_TRUE);
251 		if (ifp1 != NULL) {
252 			if (ifp1->int_state & IS_REMOTE) {
253 				/* remote gateway */
254 				ifp = ifp1;
255 				if (check_remote(ifp)) {
256 					ifp->int_act_time = now.tv_sec;
257 					if_ok(ifp, "remote ", _B_FALSE);
258 				}
259 			} else if (from->sin_port == htons(RIP_PORT)) {
260 				trace_pkt("    discard our own RIP request");
261 				return;
262 			}
263 		}
264 
265 		/* did the request come from a router? */
266 		if (!poll_answer && (from->sin_port == htons(RIP_PORT))) {
267 			/*
268 			 * yes, ignore the request if RIP is off so that
269 			 * the router does not depend on us.
270 			 */
271 			if (ripout_interfaces == 0 ||
272 			    (ifp != NULL && (IS_RIP_OUT_OFF(ifp->int_state) ||
273 			    !IS_IFF_ROUTING(ifp->int_if_flags)))) {
274 				trace_pkt("    discard request while RIP off");
275 				return;
276 			}
277 		}
278 
279 		/*
280 		 * According to RFC 2453 section 5.2, we should ignore
281 		 * unauthenticated queries when authentication is
282 		 * configured.  That is too silly to bother with.  Sheesh!
283 		 * Are forwarding tables supposed to be secret even though
284 		 * a bad guy can infer them with test traffic?  RIP is
285 		 * still the most common router-discovery protocol, so
286 		 * hosts need to send queries that will be answered.  What
287 		 * about `rtquery`?  Maybe on firewalls you'd care, but not
288 		 * enough to give up the diagnostic facilities of remote
289 		 * probing.
290 		 */
291 
292 		if (n >= lim) {
293 			msglim(&bad_len, FROM_NADDR, "empty request from %s",
294 			    naddr_ntoa(FROM_NADDR));
295 			return;
296 		}
297 		if (cc%sizeof (*n) != sizeof (struct rip)%sizeof (*n)) {
298 			msglim(&bad_len, FROM_NADDR,
299 			    "request of bad length (%d) from %s",
300 			    cc, naddr_ntoa(FROM_NADDR));
301 		}
302 
303 		if (rip->rip_vers == RIPv2 && (ifp == NULL ||
304 		    (ifp->int_state & IS_NO_RIPV1_OUT))) {
305 			v12buf.buf->rip_vers = RIPv2;
306 			/*
307 			 * If we have a secret but it is a cleartext secret,
308 			 * do not disclose our secret unless the other guy
309 			 * already knows it.
310 			 */
311 			ap = find_auth(ifp);
312 			if (ap != NULL &&
313 			    (ulong_t)ap->end < (ulong_t)clk.tv_sec) {
314 				/*
315 				 * Don't authenticate incoming packets
316 				 * using an expired key.
317 				 */
318 				msglim(&use_auth, FROM_NADDR,
319 				    "%s attempting to authenticate using "
320 				    "an expired password.",
321 				    naddr_ntoa(FROM_NADDR));
322 				ap = NULL;
323 			}
324 			if (ap != NULL && ap->type == RIP_AUTH_PW &&
325 			    (n->n_family != RIP_AF_AUTH ||
326 			    !ck_passwd(ifp, rip, (uint8_t *)lim, FROM_NADDR,
327 			    &use_auth)))
328 				ap = NULL;
329 		} else {
330 			v12buf.buf->rip_vers = RIPv1;
331 			ap = NULL;
332 		}
333 		clr_ws_buf(&v12buf, ap);
334 
335 		do {
336 			n->n_metric = ntohl(n->n_metric);
337 
338 			/*
339 			 * A single entry with family RIP_AF_UNSPEC and
340 			 * metric HOPCNT_INFINITY means "all routes".
341 			 * We respond to routers only if we are acting
342 			 * as a supplier, or to anyone other than a router
343 			 * (i.e. a query).
344 			 */
345 			if (n->n_family == RIP_AF_UNSPEC &&
346 			    n->n_metric == HOPCNT_INFINITY) {
347 				/*
348 				 * Answer a full-table query from a utility
349 				 * program with all we know.
350 				 */
351 				if (poll_answer ||
352 				    (from->sin_port != htons(RIP_PORT))) {
353 					supply(from, ifp, OUT_QUERY, 0,
354 					    rip->rip_vers, ap != NULL);
355 					return;
356 				}
357 
358 				/*
359 				 * A router is trying to prime its tables.
360 				 * Filter the answer in the same way
361 				 * broadcasts are filtered.
362 				 *
363 				 * Only answer a router if we are a supplier
364 				 * to keep an unwary host that is just starting
365 				 * from picking us as a router.
366 				 */
367 				if (ifp == NULL) {
368 					trace_pkt("ignore distant router");
369 					return;
370 				}
371 				if (IS_RIP_OFF(ifp->int_state) ||
372 				    !should_supply(ifp)) {
373 					trace_pkt("ignore; not supplying");
374 					return;
375 				}
376 
377 				/*
378 				 * Do not answer a RIPv1 router if
379 				 * we are sending RIPv2.  But do offer
380 				 * poor man's router discovery.
381 				 */
382 				if ((ifp->int_state & IS_NO_RIPV1_OUT) &&
383 				    rip->rip_vers == RIPv1) {
384 					if (!(ifp->int_state & IS_PM_RDISC)) {
385 						trace_pkt("ignore; sending "
386 						    "RIPv2");
387 						return;
388 					}
389 
390 					v12buf.n->n_family = RIP_AF_INET;
391 					v12buf.n->n_dst = RIP_DEFAULT;
392 					metric = ifp->int_d_metric;
393 					if (NULL !=
394 					    (rt = rtget(RIP_DEFAULT, 0)))
395 						metric = MIN(metric,
396 						    (rt->rt_metric + 1));
397 					v12buf.n->n_metric = htonl(metric);
398 					v12buf.n++;
399 					break;
400 				}
401 
402 				/*
403 				 * Respond with RIPv1 instead of RIPv2 if
404 				 * that is what we are broadcasting on the
405 				 * interface to keep the remote router from
406 				 * getting the wrong initial idea of the
407 				 * routes we send.
408 				 */
409 				supply(from, ifp, OUT_UNICAST, 0,
410 				    (ifp->int_state & IS_NO_RIPV1_OUT)
411 				    ? RIPv2 : RIPv1,
412 				    ap != NULL);
413 				return;
414 			}
415 
416 			/* Ignore authentication */
417 			if (n->n_family == RIP_AF_AUTH)
418 				continue;
419 
420 			if (n->n_family != RIP_AF_INET) {
421 				msglim(&bad_router, FROM_NADDR,
422 				    "request from %s for unsupported"
423 				    " (af %d) %s",
424 				    naddr_ntoa(FROM_NADDR),
425 				    ntohs(n->n_family),
426 				    naddr_ntoa(n->n_dst));
427 				return;
428 			}
429 
430 			/* We are being asked about a specific destination. */
431 			v12buf.n->n_dst = dst = n->n_dst;
432 			v12buf.n->n_family = RIP_AF_INET;
433 			if (!check_dst(dst)) {
434 				msglim(&bad_router, FROM_NADDR,
435 				    "bad queried destination %s from %s",
436 				    naddr_ntoa(dst),
437 				    naddr_ntoa(FROM_NADDR));
438 				v12buf.n->n_metric = HOPCNT_INFINITY;
439 				goto rte_done;
440 			}
441 
442 			/* decide what mask was intended */
443 			if (rip->rip_vers == RIPv1 ||
444 			    0 == (mask = ntohl(n->n_mask)) ||
445 			    0 != (ntohl(dst) & ~mask))
446 				mask = ripv1_mask_host(dst, ifp);
447 
448 			/*
449 			 * Try to find the answer.  If we don't have an
450 			 * explicit route for the destination, use the best
451 			 * route to the destination.
452 			 */
453 			rt = rtget(dst, mask);
454 			if (rt == NULL && dst != RIP_DEFAULT)
455 				rt = rtfind(n->n_dst);
456 
457 			if (v12buf.buf->rip_vers != RIPv1)
458 				v12buf.n->n_mask = htonl(mask);
459 			if (rt == NULL) {
460 				/* we do not have the answer */
461 				v12buf.n->n_metric = HOPCNT_INFINITY;
462 				goto rte_done;
463 			}
464 
465 			/*
466 			 * we have the answer, so compute the right metric
467 			 * and next hop.
468 			 */
469 			v12buf.n->n_metric = rt->rt_metric + 1;
470 			if (v12buf.n->n_metric > HOPCNT_INFINITY)
471 				v12buf.n->n_metric = HOPCNT_INFINITY;
472 			if (v12buf.buf->rip_vers != RIPv1) {
473 				v12buf.n->n_tag = rt->rt_tag;
474 				if (ifp != NULL &&
475 				    on_net(rt->rt_gate, ifp->int_net,
476 				    ifp->int_mask) &&
477 				    rt->rt_gate != ifp->int_addr)
478 					v12buf.n->n_nhop = rt->rt_gate;
479 			}
480 rte_done:
481 			v12buf.n->n_metric = htonl(v12buf.n->n_metric);
482 
483 			/*
484 			 * Stop paying attention if we fill the output buffer.
485 			 */
486 			if (++v12buf.n >= v12buf.lim)
487 				break;
488 		} while (++n < lim);
489 
490 		/*
491 		 * If our response is authenticated with md5, complete the
492 		 * md5 computation.
493 		 */
494 		if (ap != NULL && ap->type == RIP_AUTH_MD5)
495 			end_md5_auth(&v12buf, ap);
496 
497 		/*
498 		 * Diagnostic programs make specific requests
499 		 * from ports other than 520.  Log other types
500 		 * of specific requests as suspicious.
501 		 */
502 		if (!poll_answer && (from->sin_port == htons(RIP_PORT))) {
503 			writelog(LOG_WARNING,
504 			    "Received suspicious request from %s port %d",
505 			    naddr_ntoa(FROM_NADDR), RIP_PORT);
506 		}
507 		if (poll_answer || (from->sin_port != htons(RIP_PORT))) {
508 			/* query */
509 			(void) output(OUT_QUERY, from, ifp, v12buf.buf,
510 			    ((char *)v12buf.n - (char *)v12buf.buf));
511 		} else {
512 			(void) output(OUT_UNICAST, from, ifp,
513 			    v12buf.buf, ((char *)v12buf.n -
514 			    (char *)v12buf.buf));
515 		}
516 		return;
517 
518 	case RIPCMD_TRACEON:
519 	case RIPCMD_TRACEOFF:
520 		/*
521 		 * Notice that trace messages are turned off for all possible
522 		 * abuse if PATH_TRACE is undefined in pathnames.h.
523 		 * Notice also that because of the way the trace file is
524 		 * handled in trace.c, no abuse is plausible even if
525 		 * PATH_TRACE is defined.
526 		 *
527 		 * First verify message came from a privileged port.
528 		 */
529 		if (ntohs(from->sin_port) > IPPORT_RESERVED) {
530 			trace_pkt("trace command from untrusted port %d on %s",
531 			    ntohs(from->sin_port), naddr_ntoa(FROM_NADDR));
532 			return;
533 		}
534 		if (ifp == NULL || !remote_address_ok(ifp, FROM_NADDR)) {
535 			/*
536 			 * Use a message here to warn about strange
537 			 * messages from remote systems.
538 			 */
539 			msglim(&bad_router, FROM_NADDR,
540 			    "trace command from non-local host %s",
541 			    naddr_ntoa(FROM_NADDR));
542 			return;
543 		}
544 		if (ifp->int_state & IS_DISTRUST) {
545 			tg = tgates;
546 			while (tg->tgate_addr != FROM_NADDR) {
547 				tg = tg->tgate_next;
548 				if (tg == NULL) {
549 					trace_pkt("trace command from "
550 					    "untrusted host %s",
551 					    naddr_ntoa(FROM_NADDR));
552 					return;
553 				}
554 			}
555 		}
556 		if (ifp->int_auth[0].type != RIP_AUTH_NONE) {
557 			/*
558 			 * Technically, it would be fairly easy to add
559 			 * standard authentication to the existing
560 			 * trace commands -- just bracket the payload
561 			 * with the authentication information.
562 			 * However, the tracing message behavior
563 			 * itself is marginal enough that we don't
564 			 * actually care.  Just discard if
565 			 * authentication is needed.
566 			 */
567 			trace_pkt("trace command unauthenticated from %s",
568 			    naddr_ntoa(FROM_NADDR));
569 			return;
570 		}
571 		if (rip->rip_cmd == RIPCMD_TRACEON) {
572 			rip->rip_tracefile[cc-4] = '\0';
573 			set_tracefile(rip->rip_tracefile,
574 			    "trace command: %s\n", 0);
575 		} else {
576 			trace_off("tracing turned off by %s",
577 			    naddr_ntoa(FROM_NADDR));
578 		}
579 		return;
580 
581 	case RIPCMD_RESPONSE:
582 		if (ifp != NULL && (ifp->int_if_flags & IFF_NOXMIT)) {
583 			trace_misc("discard RIP response received over %s "
584 			    "(IFF_NOXMIT)", ifp->int_name);
585 			return;
586 		}
587 
588 		if (cc%sizeof (*n) != sizeof (struct rip)%sizeof (*n)) {
589 			msglim(&bad_len, FROM_NADDR,
590 			    "response of bad length (%d) from %s",
591 			    cc, naddr_ntoa(FROM_NADDR));
592 		}
593 
594 		if ((gate >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
595 		    IN_LINKLOCAL(gate)) {
596 			msglim(&bad_router, FROM_NADDR,
597 			    "discard RIP response from bad source address %s",
598 			    naddr_ntoa(FROM_NADDR));
599 			return;
600 		}
601 
602 		/* verify message came from a router */
603 		if (from->sin_port != htons(RIP_PORT)) {
604 			msglim(&bad_router, FROM_NADDR,
605 			    "    discard RIP response from unknown port"
606 			    " %d on host %s", ntohs(from->sin_port),
607 			    naddr_ntoa(FROM_NADDR));
608 			return;
609 		}
610 
611 		if (!rip_enabled) {
612 			trace_pkt("    discard response while RIP off");
613 			return;
614 		}
615 
616 		/* Are we talking to ourself or a remote gateway? */
617 		ifp1 = ifwithaddr(FROM_NADDR, _B_FALSE, _B_TRUE);
618 		if (ifp1 != NULL) {
619 			if (ifp1->int_state & IS_REMOTE) {
620 				/* remote gateway */
621 				ifp = ifp1;
622 				if (check_remote(ifp)) {
623 					ifp->int_act_time = now.tv_sec;
624 					if_ok(ifp, "remote ", _B_FALSE);
625 				}
626 			} else {
627 				trace_pkt("    discard our own RIP response");
628 				return;
629 			}
630 		} else {
631 			/*
632 			 * If it's not a remote gateway, then the
633 			 * remote address *must* be directly
634 			 * connected.  Make sure that it is.
635 			 */
636 			if (ifp != NULL &&
637 			    !remote_address_ok(ifp, FROM_NADDR)) {
638 				msglim(&bad_router, FROM_NADDR,
639 				    "discard RIP response; source %s not on "
640 				    "interface %s", naddr_ntoa(FROM_NADDR),
641 				    ifp->int_name);
642 				return;
643 			}
644 		}
645 
646 		/*
647 		 * Accept routing packets from routers directly connected
648 		 * via broadcast or point-to-point networks, and from
649 		 * those listed in /etc/gateways.
650 		 */
651 		if (ifp == NULL) {
652 			msglim(&unk_router, FROM_NADDR,
653 			    "   discard response from %s"
654 			    " via unexpected interface",
655 			    naddr_ntoa(FROM_NADDR));
656 			return;
657 		}
658 
659 		if (IS_RIP_IN_OFF(ifp->int_state)) {
660 			trace_pkt("    discard RIPv%d response"
661 			    " via disabled interface %s",
662 			    rip->rip_vers, ifp->int_name);
663 			return;
664 		}
665 
666 		if (n >= lim) {
667 			msglim(&bad_len, FROM_NADDR, "empty response from %s",
668 			    naddr_ntoa(FROM_NADDR));
669 			return;
670 		}
671 
672 		if (((ifp->int_state & IS_NO_RIPV1_IN) &&
673 		    rip->rip_vers == RIPv1) ||
674 		    ((ifp->int_state & IS_NO_RIPV2_IN) &&
675 		    rip->rip_vers != RIPv1)) {
676 			trace_pkt("    discard RIPv%d response",
677 			    rip->rip_vers);
678 			return;
679 		}
680 
681 		/*
682 		 * Continue to listen to routes via broken interfaces
683 		 * which might be declared IS_BROKE because of
684 		 * device-driver idiosyncracies, but might otherwise
685 		 * be perfectly healthy.
686 		 */
687 		if (ifp->int_state & IS_BROKE) {
688 			trace_pkt("response via broken interface %s",
689 			    ifp->int_name);
690 		}
691 
692 		/*
693 		 * If the interface cares, ignore bad routers.
694 		 * Trace but do not log this problem, because where it
695 		 * happens, it happens frequently.
696 		 */
697 		if (ifp->int_state & IS_DISTRUST) {
698 			tg = tgates;
699 			while (tg->tgate_addr != FROM_NADDR) {
700 				tg = tg->tgate_next;
701 				if (tg == NULL) {
702 					trace_pkt("    discard RIP response"
703 					    " from untrusted router %s",
704 					    naddr_ntoa(FROM_NADDR));
705 					return;
706 				}
707 			}
708 		}
709 
710 		/*
711 		 * Authenticate the packet if we have a secret.
712 		 * If we do not have any secrets, ignore the error in
713 		 * RFC 1723 and accept it regardless.
714 		 */
715 		if (ifp->int_auth[0].type != RIP_AUTH_NONE &&
716 		    rip->rip_vers != RIPv1 &&
717 		    !ck_passwd(ifp, rip, (uint8_t *)lim, FROM_NADDR, &use_auth))
718 			return;
719 
720 		/*
721 		 * Do this only if we're supplying routes to *nobody*.
722 		 */
723 		if (!should_supply(NULL) && save_space) {
724 			/*
725 			 * "-S" option.  Instead of entering all routes,
726 			 * only enter a default route for the sender of
727 			 * this RESPONSE message
728 			 */
729 
730 			/* Should we trust this route from this router? */
731 			if (tg != NULL && tg->tgate_nets->mask != 0) {
732 				trace_pkt("   ignored unauthorized %s",
733 				    addrname(RIP_DEFAULT, 0, 0));
734 				break;
735 			}
736 
737 			new.rts_gate = FROM_NADDR;
738 			new.rts_router = FROM_NADDR;
739 			new.rts_metric = HOPCNT_INFINITY-1;
740 			new.rts_tag = n->n_tag;
741 			new.rts_time = now.tv_sec;
742 			new.rts_ifp = ifp;
743 			new.rts_de_ag = 0;
744 			new.rts_origin = RO_RIP;
745 			/*
746 			 * Add the newly generated default route, but don't
747 			 * propagate the madness.  Treat it the same way as
748 			 * default routes learned from Router Discovery.
749 			 */
750 			input_route(RIP_DEFAULT, 0, &new, n, RS_NOPROPAGATE);
751 			return;
752 		}
753 
754 		if (!IS_IFF_ROUTING(ifp->int_if_flags)) {
755 			/*
756 			 * We don't want to propagate routes which would
757 			 * result in a black-hole.
758 			 */
759 			rt_state = RS_NOPROPAGATE;
760 		}
761 
762 		do {
763 			if (n->n_family == RIP_AF_AUTH)
764 				continue;
765 
766 			n->n_metric = ntohl(n->n_metric);
767 			dst = n->n_dst;
768 			if (n->n_family != RIP_AF_INET &&
769 			    (n->n_family != RIP_AF_UNSPEC ||
770 			    dst != RIP_DEFAULT)) {
771 				msglim(&bad_router, FROM_NADDR,
772 				    "route from %s to unsupported"
773 				    " address family=%d destination=%s",
774 				    naddr_ntoa(FROM_NADDR), n->n_family,
775 				    naddr_ntoa(dst));
776 				continue;
777 			}
778 			if (!check_dst(dst)) {
779 				msglim(&bad_router, FROM_NADDR,
780 				    "bad destination %s from %s",
781 				    naddr_ntoa(dst),
782 				    naddr_ntoa(FROM_NADDR));
783 				continue;
784 			}
785 			if (n->n_metric == 0 || n->n_metric > HOPCNT_INFINITY) {
786 				msglim(&bad_router, FROM_NADDR,
787 				    "bad metric %d from %s"
788 				    " for destination %s",
789 				    n->n_metric, naddr_ntoa(FROM_NADDR),
790 				    naddr_ntoa(dst));
791 				continue;
792 			}
793 
794 			/*
795 			 * Notice the next-hop.
796 			 */
797 			gate = FROM_NADDR;
798 			if (n->n_nhop != 0) {
799 				if (rip->rip_vers == RIPv1) {
800 					n->n_nhop = 0;
801 				} else {
802 					/* Use it only if it is valid. */
803 					if (on_net(n->n_nhop,
804 					    ifp->int_net, ifp->int_mask) &&
805 					    check_dst(n->n_nhop)) {
806 						gate = n->n_nhop;
807 					} else {
808 						msglim(&bad_nhop,
809 						    FROM_NADDR,
810 						    "router %s to %s"
811 						    " has bad next hop %s",
812 						    naddr_ntoa(FROM_NADDR),
813 						    naddr_ntoa(dst),
814 						    naddr_ntoa(n->n_nhop));
815 						n->n_nhop = 0;
816 					}
817 				}
818 			}
819 
820 			if (rip->rip_vers == RIPv1 ||
821 			    0 == (mask = ntohl(n->n_mask))) {
822 				mask = ripv1_mask_host(dst, ifp);
823 			} else if ((ntohl(dst) & ~mask) != 0) {
824 				msglim(&bad_mask, FROM_NADDR,
825 				    "router %s sent bad netmask %s with %s",
826 				    naddr_ntoa(FROM_NADDR),
827 				    naddr_ntoa(htonl(mask)),
828 				    naddr_ntoa(dst));
829 				continue;
830 			}
831 
832 			if (mask == HOST_MASK &&
833 			    (ifp->int_state & IS_NO_HOST)) {
834 				trace_pkt("   ignored host route %s",
835 				    addrname(dst, mask, 0));
836 				continue;
837 			}
838 
839 			if (rip->rip_vers == RIPv1)
840 				n->n_tag = 0;
841 
842 			/*
843 			 * Adjust metric according to incoming interface cost.
844 			 * We intentionally don't drop incoming routes with
845 			 * metric 15 on the floor even though they will
846 			 * not be advertised to other routers.  We can use
847 			 * such routes locally, resulting in a network with
848 			 * a maximum width of 15 hops rather than 14.
849 			 */
850 			n->n_metric += ifp->int_metric;
851 			if (n->n_metric > HOPCNT_INFINITY)
852 				n->n_metric = HOPCNT_INFINITY;
853 
854 			/*
855 			 * Should we trust this route from this router?
856 			 */
857 			if (tg != NULL && (tn = tg->tgate_nets)->mask != 0) {
858 				for (i = 0; i < MAX_TGATE_NETS; i++, tn++) {
859 					if (on_net(dst, tn->net, tn->mask) &&
860 					    tn->mask <= mask)
861 						break;
862 				}
863 				if (i >= MAX_TGATE_NETS || tn->mask == 0) {
864 					trace_pkt("   ignored unauthorized %s",
865 					    addrname(dst, mask, 0));
866 					continue;
867 				}
868 			}
869 
870 			/*
871 			 * Recognize and ignore a default route we faked
872 			 * which is being sent back to us by a machine with
873 			 * broken split-horizon. Be a little more paranoid
874 			 * than that, and reject default routes with the
875 			 * same metric we advertised.
876 			 */
877 			if (ifp->int_d_metric != 0 && dst == RIP_DEFAULT &&
878 			    n->n_metric >= ifp->int_d_metric)
879 				continue;
880 
881 			/*
882 			 * We can receive aggregated RIPv2 routes that must
883 			 * be broken down before they are transmitted by
884 			 * RIPv1 via an interface on a subnet. We might
885 			 * also receive the same routes aggregated via
886 			 * other RIPv2 interfaces.  This could cause
887 			 * duplicate routes to be sent on the RIPv1
888 			 * interfaces. "Longest matching variable length
889 			 * netmasks" lets RIPv2 listeners understand, but
890 			 * breaking down the aggregated routes for RIPv1
891 			 * listeners can produce duplicate routes.
892 			 *
893 			 * Breaking down aggregated routes here bloats the
894 			 * daemon table, but does not hurt the kernel
895 			 * table, since routes are always aggregated for
896 			 * the kernel.
897 			 *
898 			 * Notice that this does not break down network
899 			 * routes corresponding to subnets. This is part of
900 			 * the defense against RS_NET_SYN.
901 			 */
902 			if (have_ripv1_out &&
903 			    (((rt = rtget(dst, mask)) == NULL ||
904 			    !(rt->rt_state & RS_NET_SYN))) &&
905 			    (v1_mask = ripv1_mask_net(dst, 0)) > mask) {
906 				/* Get least significant set bit */
907 				ddst_h = v1_mask & -v1_mask;
908 				i = (v1_mask & ~mask)/ddst_h;
909 				/*
910 				 * If you're going to make 512 or more
911 				 * routes, then that's just too many.  The
912 				 * reason here is that breaking an old
913 				 * class B into /24 allocations is common
914 				 * enough that allowing for the creation of
915 				 * at least 256 deaggregated routes is
916 				 * good.  The next power of 2 is 512.
917 				 */
918 				if (i >= 511) {
919 					/*
920 					 * Punt if we would have to
921 					 * generate an unreasonable number
922 					 * of routes.
923 					 */
924 					if (TRACECONTENTS)
925 						trace_misc("accept %s-->%s as 1"
926 						    " instead of %d routes",
927 						    addrname(dst, mask, 0),
928 						    naddr_ntoa(FROM_NADDR),
929 						    i + 1);
930 					i = 0;
931 				} else {
932 					mask = v1_mask;
933 				}
934 			} else {
935 				i = 0;
936 			}
937 
938 			new.rts_gate = gate;
939 			new.rts_router = FROM_NADDR;
940 			new.rts_metric = n->n_metric;
941 			new.rts_tag = n->n_tag;
942 			new.rts_time = now.tv_sec;
943 			new.rts_ifp = ifp;
944 			new.rts_de_ag = i;
945 			new.rts_origin = RO_RIP;
946 			j = 0;
947 			for (;;) {
948 				input_route(dst, mask, &new, n, rt_state);
949 				if (++j > i)
950 					break;
951 				dst = htonl(ntohl(dst) + ddst_h);
952 			}
953 		} while (++n < lim);
954 		return;
955 	case RIPCMD_POLLENTRY:
956 		/*
957 		 * With this command one can request a single entry.
958 		 * Both silent processes and routers can respond to this
959 		 * command
960 		 */
961 
962 		if (n >= lim) {
963 			msglim(&bad_len, FROM_NADDR, "empty request from %s",
964 			    naddr_ntoa(FROM_NADDR));
965 			return;
966 		}
967 		if (cc%sizeof (*n) != sizeof (struct rip)%sizeof (*n)) {
968 			msglim(&bad_len, FROM_NADDR,
969 			    "request of bad length (%d) from %s",
970 			    cc, naddr_ntoa(FROM_NADDR));
971 		}
972 
973 		if (rip->rip_vers == RIPv2 && (ifp == NULL ||
974 		    (ifp->int_state & IS_NO_RIPV1_OUT))) {
975 			v12buf.buf->rip_vers = RIPv2;
976 		} else {
977 			v12buf.buf->rip_vers = RIPv1;
978 		}
979 		/* Dont bother with md5 authentication with POLLENTRY */
980 		ap = NULL;
981 		clr_ws_buf(&v12buf, ap);
982 
983 		n->n_metric = ntohl(n->n_metric);
984 
985 		if (n->n_family != RIP_AF_INET) {
986 			msglim(&bad_router, FROM_NADDR,
987 			    "POLLENTRY request from %s for unsupported"
988 			    " (af %d) %s",
989 			    naddr_ntoa(FROM_NADDR),
990 			    ntohs(n->n_family),
991 			    naddr_ntoa(n->n_dst));
992 			return;
993 		}
994 
995 		/* We are being asked about a specific destination. */
996 		v12buf.n->n_dst = dst = n->n_dst;
997 		v12buf.n->n_family = RIP_AF_INET;
998 		if (!check_dst(dst)) {
999 			msglim(&bad_router, FROM_NADDR,
1000 			    "bad queried destination %s from %s",
1001 			    naddr_ntoa(dst),
1002 			    naddr_ntoa(FROM_NADDR));
1003 			v12buf.n->n_metric = HOPCNT_INFINITY;
1004 			goto pollentry_done;
1005 		}
1006 
1007 		/* decide what mask was intended */
1008 		if (rip->rip_vers == RIPv1 ||
1009 		    0 == (mask = ntohl(n->n_mask)) ||
1010 		    0 != (ntohl(dst) & ~mask))
1011 			mask = ripv1_mask_host(dst, ifp);
1012 
1013 		/* try to find the answer */
1014 		rt = rtget(dst, mask);
1015 		if (rt == NULL && dst != RIP_DEFAULT)
1016 			rt = rtfind(n->n_dst);
1017 
1018 		if (v12buf.buf->rip_vers != RIPv1)
1019 			v12buf.n->n_mask = htonl(mask);
1020 		if (rt == NULL) {
1021 			/* we do not have the answer */
1022 			v12buf.n->n_metric = HOPCNT_INFINITY;
1023 			goto pollentry_done;
1024 		}
1025 
1026 
1027 		/*
1028 		 * we have the answer, so compute the right metric and next
1029 		 * hop.
1030 		 */
1031 		v12buf.n->n_metric = rt->rt_metric + 1;
1032 		if (v12buf.n->n_metric > HOPCNT_INFINITY)
1033 			v12buf.n->n_metric = HOPCNT_INFINITY;
1034 		if (v12buf.buf->rip_vers != RIPv1) {
1035 			v12buf.n->n_tag = rt->rt_tag;
1036 			if (ifp != NULL &&
1037 			    on_net(rt->rt_gate, ifp->int_net, ifp->int_mask) &&
1038 			    rt->rt_gate != ifp->int_addr)
1039 				v12buf.n->n_nhop = rt->rt_gate;
1040 		}
1041 pollentry_done:
1042 		v12buf.n->n_metric = htonl(v12buf.n->n_metric);
1043 
1044 		/*
1045 		 * Send the answer about specific routes.
1046 		 */
1047 		(void) output(OUT_QUERY, from, ifp, v12buf.buf,
1048 		    ((char *)v12buf.n - (char *)v12buf.buf));
1049 		break;
1050 	}
1051 #undef FROM_NADDR
1052 }
1053 
1054 
1055 /*
1056  * Process a single input route.
1057  */
1058 void
1059 input_route(in_addr_t dst,			/* network order */
1060     in_addr_t mask,
1061     struct rt_spare *new,
1062     struct netinfo *n,
1063     uint16_t rt_state)
1064 {
1065 	int i;
1066 	struct rt_entry *rt;
1067 	struct rt_spare *rts, *rts0;
1068 	struct interface *ifp1;
1069 	struct rt_spare *ptr;
1070 	size_t ptrsize;
1071 
1072 	/*
1073 	 * See if we can already get there by a working interface.  Ignore
1074 	 * if so.
1075 	 */
1076 	ifp1 = ifwithaddr(dst, _B_TRUE, _B_FALSE);
1077 	if (ifp1 != NULL && (ifp1->int_state & IS_PASSIVE))
1078 		return;
1079 
1080 	/*
1081 	 * Look for the route in our table.
1082 	 */
1083 	rt = rtget(dst, mask);
1084 
1085 	/* Consider adding the route if we do not already have it. */
1086 	if (rt == NULL) {
1087 		/* Ignore unknown routes being poisoned. */
1088 		if (new->rts_metric == HOPCNT_INFINITY)
1089 			return;
1090 
1091 		/* Ignore the route if it points to us */
1092 		if (n != NULL && n->n_nhop != 0 &&
1093 		    NULL != ifwithaddr(n->n_nhop, _B_TRUE, _B_FALSE))
1094 			return;
1095 
1096 		/*
1097 		 * If something has not gone crazy and tried to fill
1098 		 * our memory, accept the new route.
1099 		 */
1100 		rtadd(dst, mask, rt_state, new);
1101 		return;
1102 	}
1103 
1104 	/*
1105 	 * We already know about the route.  Consider this update.
1106 	 *
1107 	 * If (rt->rt_state & RS_NET_SYN), then this route
1108 	 * is the same as a network route we have inferred
1109 	 * for subnets we know, in order to tell RIPv1 routers
1110 	 * about the subnets.
1111 	 *
1112 	 * It is impossible to tell if the route is coming
1113 	 * from a distant RIPv2 router with the standard
1114 	 * netmask because that router knows about the entire
1115 	 * network, or if it is a round-about echo of a
1116 	 * synthetic, RIPv1 network route of our own.
1117 	 * The worst is that both kinds of routes might be
1118 	 * received, and the bad one might have the smaller
1119 	 * metric.  Partly solve this problem by never
1120 	 * aggregating into such a route.  Also keep it
1121 	 * around as long as the interface exists.
1122 	 */
1123 
1124 	rts0 = rt->rt_spares;
1125 	for (rts = rts0, i = rt->rt_num_spares; i != 0; i--, rts++) {
1126 		if (rts->rts_router == new->rts_router)
1127 			break;
1128 		/*
1129 		 * Note the worst slot to reuse,
1130 		 * other than the current slot.
1131 		 */
1132 		if (BETTER_LINK(rt, rts0, rts))
1133 			rts0 = rts;
1134 	}
1135 	if (i != 0) {
1136 		/*
1137 		 * Found a route from the router already in the table.
1138 		 */
1139 
1140 		/*
1141 		 * If the new route is a route broken down from an
1142 		 * aggregated route, and if the previous route is either
1143 		 * not a broken down route or was broken down from a finer
1144 		 * netmask, and if the previous route is current,
1145 		 * then forget this one.
1146 		 */
1147 		if (new->rts_de_ag > rts->rts_de_ag &&
1148 		    now_stale <= rts->rts_time)
1149 			return;
1150 
1151 		/*
1152 		 * Keep poisoned routes around only long enough to pass
1153 		 * the poison on.  Use a new timestamp for good routes.
1154 		 */
1155 		if (rts->rts_metric == HOPCNT_INFINITY &&
1156 		    new->rts_metric == HOPCNT_INFINITY)
1157 			new->rts_time = rts->rts_time;
1158 
1159 		/*
1160 		 * If this is an update for the router we currently prefer,
1161 		 * then note it.
1162 		 */
1163 		if (i == rt->rt_num_spares) {
1164 			uint8_t old_metric = rts->rts_metric;
1165 
1166 			rtchange(rt, rt->rt_state | rt_state, new, 0);
1167 			/*
1168 			 * If the route got worse, check for something better.
1169 			 */
1170 			if (new->rts_metric != old_metric)
1171 				rtswitch(rt, 0);
1172 			return;
1173 		}
1174 
1175 		/*
1176 		 * This is an update for a spare route.
1177 		 * Finished if the route is unchanged.
1178 		 */
1179 		if (rts->rts_gate == new->rts_gate &&
1180 		    rts->rts_metric == new->rts_metric &&
1181 		    rts->rts_tag == new->rts_tag) {
1182 			if ((rt->rt_dst == RIP_DEFAULT) &&
1183 			    (rts->rts_ifp != new->rts_ifp))
1184 				trace_misc("input_route update for spare");
1185 			trace_upslot(rt, rts, new);
1186 			*rts = *new;
1187 			return;
1188 		}
1189 
1190 		/*
1191 		 * Forget it if it has gone bad.
1192 		 */
1193 		if (new->rts_metric == HOPCNT_INFINITY) {
1194 			rts_delete(rt, rts);
1195 			return;
1196 		}
1197 
1198 	} else {
1199 		/*
1200 		 * The update is for a route we know about,
1201 		 * but not from a familiar router.
1202 		 *
1203 		 * Ignore the route if it points to us.
1204 		 */
1205 		if (n != NULL && n->n_nhop != 0 &&
1206 		    NULL != ifwithaddr(n->n_nhop, _B_TRUE, _B_FALSE))
1207 			return;
1208 
1209 		/* the loop above set rts0=worst spare */
1210 		if (rts0->rts_metric < HOPCNT_INFINITY) {
1211 			ptrsize = (rt->rt_num_spares + SPARE_INC) *
1212 			    sizeof (struct rt_spare);
1213 			ptr = realloc(rt->rt_spares, ptrsize);
1214 			if (ptr != NULL) {
1215 
1216 				rt->rt_spares = ptr;
1217 				rts0 = &rt->rt_spares[rt->rt_num_spares];
1218 				(void) memset(rts0, 0,
1219 				    SPARE_INC * sizeof (struct rt_spare));
1220 				rt->rt_num_spares += SPARE_INC;
1221 				for (rts = rts0, i = SPARE_INC;
1222 				    i != 0; i--, rts++)
1223 					rts->rts_metric = HOPCNT_INFINITY;
1224 			}
1225 		}
1226 		rts = rts0;
1227 
1228 		/*
1229 		 * Save the route as a spare only if it has
1230 		 * a better metric than our worst spare.
1231 		 * This also ignores poisoned routes (those
1232 		 * received with metric HOPCNT_INFINITY).
1233 		 */
1234 		if (new->rts_metric >= rts->rts_metric)
1235 			return;
1236 	}
1237 	trace_upslot(rt, rts, new);
1238 	*rts = *new;
1239 
1240 	/* try to switch to a better route */
1241 	rtswitch(rt, rts);
1242 }
1243 
1244 /*
1245  * Recorded information about peer's MD5 sequence numbers.  This is
1246  * used to validate that received sequence numbers are in
1247  * non-decreasing order as per the RFC.
1248  */
1249 struct peer_hash {
1250 	struct peer_hash *ph_next;
1251 	in_addr_t ph_addr;
1252 	time_t ph_heard;
1253 	uint32_t ph_seqno;
1254 };
1255 
1256 static struct peer_hash **peer_hashes;
1257 static int ph_index;
1258 static int ph_num_peers;
1259 
1260 /*
1261  * Get a peer_hash structure from the hash of known peers.  Create a
1262  * new one if not found.  Returns NULL on unrecoverable allocation
1263  * failure.
1264  */
1265 static struct peer_hash *
1266 get_peer_info(in_addr_t from)
1267 {
1268 	struct peer_hash *php;
1269 	struct peer_hash *pnhp;
1270 	struct peer_hash **ph_pp;
1271 	struct peer_hash **ph2_pp;
1272 	struct peer_hash **ph3_pp;
1273 	int i;
1274 	static uint_t failed_count;
1275 
1276 	if (peer_hashes == NULL) {
1277 		peer_hashes = calloc(hash_table_sizes[0],
1278 		    sizeof (peer_hashes[0]));
1279 		if (peer_hashes == NULL) {
1280 			if (++failed_count % 100 == 1)
1281 				msglog("no memory for peer hash");
1282 			return (NULL);
1283 		}
1284 	}
1285 	/* Search for peer in existing hash table */
1286 	ph_pp = peer_hashes + (from % hash_table_sizes[ph_index]);
1287 	for (php = ph_pp[0]; php != NULL; php = php->ph_next) {
1288 		if (php->ph_addr == from)
1289 			return (php);
1290 	}
1291 	/*
1292 	 * Not found; we need to add this peer to the table.  If there
1293 	 * are already too many peers, then try to expand the table
1294 	 * first.  It's not a big deal if we can't expand the table
1295 	 * right now due to memory constraints.  We'll try again
1296 	 * later.
1297 	 */
1298 	if (ph_num_peers >= hash_table_sizes[ph_index] * 5 &&
1299 	    hash_table_sizes[ph_index + 1] != 0 &&
1300 	    (ph_pp = calloc(hash_table_sizes[ph_index + 1],
1301 	    sizeof (peer_hashes[0]))) != NULL) {
1302 		ph2_pp = peer_hashes;
1303 		for (i = hash_table_sizes[ph_index] - 1; i >= 0; i--) {
1304 			for (php = ph2_pp[i]; php != NULL; php = pnhp) {
1305 				pnhp = php->ph_next;
1306 				ph3_pp = ph_pp + (php->ph_addr %
1307 				    hash_table_sizes[ph_index + 1]);
1308 				php->ph_next = ph3_pp[0];
1309 				ph3_pp[0] = php;
1310 			}
1311 		}
1312 		ph_index++;
1313 		free(peer_hashes);
1314 		peer_hashes = ph_pp;
1315 		ph_pp += from % hash_table_sizes[ph_index];
1316 	}
1317 	php = calloc(sizeof (*php), 1);
1318 	if (php == NULL) {
1319 		if (++failed_count % 100 == 1)
1320 			msglog("no memory for peer hash entry");
1321 	} else {
1322 		php->ph_addr = from;
1323 		php->ph_heard = now.tv_sec;
1324 		php->ph_next = ph_pp[0];
1325 		ph_pp[0] = php;
1326 		ph_num_peers++;
1327 	}
1328 	return (php);
1329 }
1330 
1331 /*
1332  * Age out entries in the peer table.  This is called every time we do
1333  * a normal 30 second broadcast.
1334  */
1335 void
1336 age_peer_info(void)
1337 {
1338 	struct peer_hash *php;
1339 	struct peer_hash *next_ph;
1340 	struct peer_hash *prev_ph;
1341 	struct peer_hash **ph_pp;
1342 	int i;
1343 
1344 	/*
1345 	 * Scan through the list and remove peers that should not
1346 	 * still have valid authenticated entries in the routing
1347 	 * table.
1348 	 */
1349 	if ((ph_pp = peer_hashes) == NULL || ph_num_peers == 0)
1350 		return;
1351 	for (i = hash_table_sizes[ph_index] - 1; i >= 0; i--) {
1352 		prev_ph = NULL;
1353 		for (php = ph_pp[i]; php != NULL; php = next_ph) {
1354 			next_ph = php->ph_next;
1355 			if (php->ph_heard <= now_expire) {
1356 				if (prev_ph == NULL)
1357 					ph_pp[i] = next_ph;
1358 				else
1359 					prev_ph->ph_next = next_ph;
1360 				free(php);
1361 				if (--ph_num_peers == 0)
1362 					return;
1363 			} else {
1364 				prev_ph = php;
1365 			}
1366 		}
1367 	}
1368 }
1369 
1370 static boolean_t		/* _B_FALSE if bad, _B_TRUE if good */
1371 ck_passwd(struct interface *aifp,
1372     struct rip *rip,
1373     uint8_t *lim,
1374     in_addr_t from,
1375     struct msg_limit *use_authp)
1376 {
1377 #define	NA (rip->rip_auths)
1378 	struct netauth *na2;
1379 	struct auth *ap;
1380 	MD5_CTX md5_ctx;
1381 	uchar_t hash[RIP_AUTH_PW_LEN];
1382 	int i, len;
1383 	struct peer_hash *php;
1384 	uint32_t seqno;
1385 
1386 	if ((uint8_t *)NA >= lim || NA->a_family != RIP_AF_AUTH) {
1387 		msglim(use_authp, from, "missing auth data from %s",
1388 		    naddr_ntoa(from));
1389 		return (_B_FALSE);
1390 	}
1391 
1392 	/*
1393 	 * Validate sequence number on RIPv2 responses using keyed MD5
1394 	 * authentication per RFC 2082 section 3.2.2.  Note that if we
1395 	 * can't locate the peer information (due to transient
1396 	 * allocation problems), then we don't do the test.  Also note
1397 	 * that we assume that all sequence numbers 0x80000000 or more
1398 	 * away are "less than."
1399 	 *
1400 	 * We intentionally violate RFC 2082 with respect to one case:
1401 	 * restablishing contact.  The RFC says that you should
1402 	 * continue to ignore old sequence numbers in this case but
1403 	 * make a special allowance for 0.  This is extremely foolish.
1404 	 * The problem is that if the router has crashed, it's
1405 	 * entirely possible that either we'll miss sequence zero (or
1406 	 * that it might not even send it!) or that the peer doesn't
1407 	 * remember what it last used for a sequence number.  In
1408 	 * either case, we'll create a failure state that persists
1409 	 * until the sequence number happens to advance past the last
1410 	 * one we saw.  This is bad because it means that we may have
1411 	 * to wait until the router has been up for at least as long
1412 	 * as it was last time before we even pay attention to it.
1413 	 * Meanwhile, other routers may listen to it if they hadn't
1414 	 * seen it before (i.e., if they crashed in the meantime).
1415 	 * This means -- perversely -- that stable systems that stay
1416 	 * "up" for a long time pay a penalty for doing so.
1417 	 */
1418 	if (rip->rip_cmd == RIPCMD_RESPONSE && NA->a_type == RIP_AUTH_MD5 &&
1419 	    (php = get_peer_info(from)) != NULL) {
1420 		/*
1421 		 * If the entry that we find has been updated
1422 		 * recently enough that the routes are known
1423 		 * to still be good, but the sequence number
1424 		 * looks bad, then discard the packet.
1425 		 */
1426 		seqno = ntohl(NA->au.a_md5.md5_seqno);
1427 		if (php->ph_heard > now_expire && php->ph_seqno != 0 &&
1428 		    (seqno == 0 || ((seqno - php->ph_seqno) & 0x80000000ul))) {
1429 			msglim(use_authp, from,
1430 			    "discarding sequence %x (older than %x)",
1431 			    (unsigned)seqno, (unsigned)php->ph_seqno);
1432 			return (_B_FALSE);
1433 		}
1434 		php->ph_heard = now.tv_sec;
1435 		php->ph_seqno = seqno;
1436 	}
1437 
1438 	/*
1439 	 * accept any current (+/- 24 hours) password
1440 	 */
1441 	for (ap = aifp->int_auth, i = 0; i < MAX_AUTH_KEYS; i++, ap++) {
1442 		if (ap->type != NA->a_type ||
1443 		    (ulong_t)ap->start > (ulong_t)clk.tv_sec+DAY ||
1444 		    (ulong_t)ap->end+DAY < (ulong_t)clk.tv_sec)
1445 			continue;
1446 
1447 		if (NA->a_type == RIP_AUTH_PW) {
1448 			if (0 == memcmp(NA->au.au_pw, ap->key, RIP_AUTH_PW_LEN))
1449 				return (_B_TRUE);
1450 
1451 		} else {
1452 			/*
1453 			 * accept MD5 secret with the right key ID
1454 			 */
1455 			if (NA->au.a_md5.md5_keyid != ap->keyid)
1456 				continue;
1457 
1458 			len = ntohs(NA->au.a_md5.md5_pkt_len);
1459 			if ((len - sizeof (*rip)) % sizeof (*NA) != 0 ||
1460 			    len > (lim - (uint8_t *)rip - sizeof (*NA))) {
1461 				msglim(use_authp, from,
1462 				    "wrong MD5 RIPv2 packet length of %d"
1463 				    " instead of %d from %s",
1464 				    len, lim - (uint8_t *)rip - sizeof (*NA),
1465 				    naddr_ntoa(from));
1466 				return (_B_FALSE);
1467 			}
1468 			na2 = (struct netauth *)(rip->rip_nets +
1469 			    (len - 4) / sizeof (struct netinfo));
1470 
1471 			/*
1472 			 * Given a good hash value, these are not security
1473 			 * problems so be generous and accept the routes,
1474 			 * after complaining.
1475 			 */
1476 			if (TRACEPACKETS) {
1477 				if (NA->au.a_md5.md5_auth_len !=
1478 				    RIP_AUTH_MD5_LEN)
1479 					msglim(use_authp, from,
1480 					    "unknown MD5 RIPv2 auth len %#x"
1481 					    " instead of %#x from %s",
1482 					    NA->au.a_md5.md5_auth_len,
1483 					    RIP_AUTH_MD5_LEN,
1484 					    naddr_ntoa(from));
1485 				if (na2->a_family != RIP_AF_AUTH)
1486 					msglim(use_authp, from,
1487 					    "unknown MD5 RIPv2 family %#x"
1488 					    " instead of %#x from %s",
1489 					    na2->a_family, RIP_AF_AUTH,
1490 					    naddr_ntoa(from));
1491 				if (na2->a_type != RIP_AUTH_TRAILER)
1492 					msglim(use_authp, from,
1493 					    "MD5 RIPv2 hash has %#x"
1494 					    " instead of %#x from %s",
1495 					    ntohs(na2->a_type),
1496 					    ntohs(RIP_AUTH_TRAILER),
1497 					    naddr_ntoa(from));
1498 			}
1499 
1500 			MD5Init(&md5_ctx);
1501 			/*
1502 			 * len+4 to include auth trailer's family/type in
1503 			 * MD5 sum
1504 			 */
1505 			MD5Update(&md5_ctx, (uchar_t *)rip, len + 4);
1506 			MD5Update(&md5_ctx, ap->key, RIP_AUTH_MD5_LEN);
1507 			MD5Final(hash, &md5_ctx);
1508 			if (0 == memcmp(hash, na2->au.au_pw, sizeof (hash)))
1509 				return (_B_TRUE);
1510 		}
1511 	}
1512 
1513 	msglim(use_authp, from, "bad auth data from %s",
1514 	    naddr_ntoa(from));
1515 	return (_B_FALSE);
1516 #undef NA
1517 }
1518