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