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