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