xref: /titanic_44/usr/src/cmd/cmd-inet/usr.sbin/in.routed/input.c (revision 9dd0f810214fdc8e1af881a9a5c4b6927629ff9e)
1 /*
2  * Copyright 2006 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 			rtchange(rt, rt->rt_state | rt_state, new, 0);
1168 			/*
1169 			 * If the route got worse, check for something better.
1170 			 */
1171 			if (new->rts_metric != rts->rts_metric)
1172 				rtswitch(rt, 0);
1173 			return;
1174 		}
1175 
1176 		/*
1177 		 * This is an update for a spare route.
1178 		 * Finished if the route is unchanged.
1179 		 */
1180 		if (rts->rts_gate == new->rts_gate &&
1181 		    rts->rts_metric == new->rts_metric &&
1182 		    rts->rts_tag == new->rts_tag) {
1183 			if ((rt->rt_dst == RIP_DEFAULT) &&
1184 			    (rts->rts_ifp != new->rts_ifp))
1185 				trace_misc("input_route update for spare");
1186 			trace_upslot(rt, rts, new);
1187 			*rts = *new;
1188 			return;
1189 		}
1190 
1191 		/*
1192 		 * Forget it if it has gone bad.
1193 		 */
1194 		if (new->rts_metric == HOPCNT_INFINITY) {
1195 			rts_delete(rt, rts);
1196 			return;
1197 		}
1198 
1199 	} else {
1200 		/*
1201 		 * The update is for a route we know about,
1202 		 * but not from a familiar router.
1203 		 *
1204 		 * Ignore the route if it points to us.
1205 		 */
1206 		if (n != NULL && n->n_nhop != 0 &&
1207 		    NULL != ifwithaddr(n->n_nhop, _B_TRUE, _B_FALSE))
1208 			return;
1209 
1210 		/* the loop above set rts0=worst spare */
1211 		if (rts0->rts_metric < HOPCNT_INFINITY) {
1212 			ptrsize = (rt->rt_num_spares + SPARE_INC) *
1213 			    sizeof (struct rt_spare);
1214 			ptr = realloc(rt->rt_spares, ptrsize);
1215 			if (ptr != NULL) {
1216 
1217 				rt->rt_spares = ptr;
1218 				rts0 = &rt->rt_spares[rt->rt_num_spares];
1219 				(void) memset(rts0, 0,
1220 				    SPARE_INC * sizeof (struct rt_spare));
1221 				rt->rt_num_spares += SPARE_INC;
1222 				for (rts = rts0, i = SPARE_INC;
1223 				    i != 0; i--, rts++)
1224 					rts->rts_metric = HOPCNT_INFINITY;
1225 			}
1226 		}
1227 		rts = rts0;
1228 
1229 		/*
1230 		 * Save the route as a spare only if it has
1231 		 * a better metric than our worst spare.
1232 		 * This also ignores poisoned routes (those
1233 		 * received with metric HOPCNT_INFINITY).
1234 		 */
1235 		if (new->rts_metric >= rts->rts_metric)
1236 			return;
1237 	}
1238 	trace_upslot(rt, rts, new);
1239 	*rts = *new;
1240 
1241 	/* try to switch to a better route */
1242 	rtswitch(rt, rts);
1243 }
1244 
1245 /*
1246  * Recorded information about peer's MD5 sequence numbers.  This is
1247  * used to validate that received sequence numbers are in
1248  * non-decreasing order as per the RFC.
1249  */
1250 struct peer_hash {
1251 	struct peer_hash *ph_next;
1252 	in_addr_t ph_addr;
1253 	time_t ph_heard;
1254 	uint32_t ph_seqno;
1255 };
1256 
1257 static struct peer_hash **peer_hashes;
1258 static int ph_index;
1259 static int ph_num_peers;
1260 
1261 /*
1262  * Get a peer_hash structure from the hash of known peers.  Create a
1263  * new one if not found.  Returns NULL on unrecoverable allocation
1264  * failure.
1265  */
1266 static struct peer_hash *
1267 get_peer_info(in_addr_t from)
1268 {
1269 	struct peer_hash *php;
1270 	struct peer_hash *pnhp;
1271 	struct peer_hash **ph_pp;
1272 	struct peer_hash **ph2_pp;
1273 	struct peer_hash **ph3_pp;
1274 	int i;
1275 	static uint_t failed_count;
1276 
1277 	if (peer_hashes == NULL) {
1278 		peer_hashes = calloc(hash_table_sizes[0],
1279 		    sizeof (peer_hashes[0]));
1280 		if (peer_hashes == NULL) {
1281 			if (++failed_count % 100 == 1)
1282 				msglog("no memory for peer hash");
1283 			return (NULL);
1284 		}
1285 	}
1286 	/* Search for peer in existing hash table */
1287 	ph_pp = peer_hashes + (from % hash_table_sizes[ph_index]);
1288 	for (php = ph_pp[0]; php != NULL; php = php->ph_next) {
1289 		if (php->ph_addr == from)
1290 			return (php);
1291 	}
1292 	/*
1293 	 * Not found; we need to add this peer to the table.  If there
1294 	 * are already too many peers, then try to expand the table
1295 	 * first.  It's not a big deal if we can't expand the table
1296 	 * right now due to memory constraints.  We'll try again
1297 	 * later.
1298 	 */
1299 	if (ph_num_peers >= hash_table_sizes[ph_index] * 5 &&
1300 	    hash_table_sizes[ph_index + 1] != 0 &&
1301 	    (ph_pp = calloc(hash_table_sizes[ph_index + 1],
1302 		sizeof (peer_hashes[0]))) != NULL) {
1303 		ph2_pp = peer_hashes;
1304 		for (i = hash_table_sizes[ph_index] - 1; i >= 0; i--) {
1305 			for (php = ph2_pp[i]; php != NULL; php = pnhp) {
1306 				pnhp = php->ph_next;
1307 				ph3_pp = ph_pp + (php->ph_addr %
1308 				    hash_table_sizes[ph_index + 1]);
1309 				php->ph_next = ph3_pp[0];
1310 				ph3_pp[0] = php;
1311 			}
1312 		}
1313 		ph_index++;
1314 		free(peer_hashes);
1315 		peer_hashes = ph_pp;
1316 		ph_pp += from % hash_table_sizes[ph_index];
1317 	}
1318 	php = calloc(sizeof (*php), 1);
1319 	if (php == NULL) {
1320 		if (++failed_count % 100 == 1)
1321 			msglog("no memory for peer hash entry");
1322 	} else {
1323 		php->ph_addr = from;
1324 		php->ph_heard = now.tv_sec;
1325 		php->ph_next = ph_pp[0];
1326 		ph_pp[0] = php;
1327 		ph_num_peers++;
1328 	}
1329 	return (php);
1330 }
1331 
1332 /*
1333  * Age out entries in the peer table.  This is called every time we do
1334  * a normal 30 second broadcast.
1335  */
1336 void
1337 age_peer_info(void)
1338 {
1339 	struct peer_hash *php;
1340 	struct peer_hash *next_ph;
1341 	struct peer_hash *prev_ph;
1342 	struct peer_hash **ph_pp;
1343 	int i;
1344 
1345 	/*
1346 	 * Scan through the list and remove peers that should not
1347 	 * still have valid authenticated entries in the routing
1348 	 * table.
1349 	 */
1350 	if ((ph_pp = peer_hashes) == NULL || ph_num_peers == 0)
1351 		return;
1352 	for (i = hash_table_sizes[ph_index] - 1; i >= 0; i--) {
1353 		prev_ph = NULL;
1354 		for (php = ph_pp[i]; php != NULL; php = next_ph) {
1355 			next_ph = php->ph_next;
1356 			if (php->ph_heard <= now_expire) {
1357 				if (prev_ph == NULL)
1358 					ph_pp[i] = next_ph;
1359 				else
1360 					prev_ph->ph_next = next_ph;
1361 				free(php);
1362 				if (--ph_num_peers == 0)
1363 					return;
1364 			} else {
1365 				prev_ph = php;
1366 			}
1367 		}
1368 	}
1369 }
1370 
1371 static boolean_t		/* _B_FALSE if bad, _B_TRUE if good */
1372 ck_passwd(struct interface *aifp,
1373     struct rip *rip,
1374     uint8_t *lim,
1375     in_addr_t from,
1376     struct msg_limit *use_authp)
1377 {
1378 #define	NA (rip->rip_auths)
1379 	struct netauth *na2;
1380 	struct auth *ap;
1381 	MD5_CTX md5_ctx;
1382 	uchar_t hash[RIP_AUTH_PW_LEN];
1383 	int i, len;
1384 	struct peer_hash *php;
1385 	uint32_t seqno;
1386 
1387 	if ((uint8_t *)NA >= lim || NA->a_family != RIP_AF_AUTH) {
1388 		msglim(use_authp, from, "missing auth data from %s",
1389 		    naddr_ntoa(from));
1390 		return (_B_FALSE);
1391 	}
1392 
1393 	/*
1394 	 * Validate sequence number on RIPv2 responses using keyed MD5
1395 	 * authentication per RFC 2082 section 3.2.2.  Note that if we
1396 	 * can't locate the peer information (due to transient
1397 	 * allocation problems), then we don't do the test.  Also note
1398 	 * that we assume that all sequence numbers 0x80000000 or more
1399 	 * away are "less than."
1400 	 *
1401 	 * We intentionally violate RFC 2082 with respect to one case:
1402 	 * restablishing contact.  The RFC says that you should
1403 	 * continue to ignore old sequence numbers in this case but
1404 	 * make a special allowance for 0.  This is extremely foolish.
1405 	 * The problem is that if the router has crashed, it's
1406 	 * entirely possible that either we'll miss sequence zero (or
1407 	 * that it might not even send it!) or that the peer doesn't
1408 	 * remember what it last used for a sequence number.  In
1409 	 * either case, we'll create a failure state that persists
1410 	 * until the sequence number happens to advance past the last
1411 	 * one we saw.  This is bad because it means that we may have
1412 	 * to wait until the router has been up for at least as long
1413 	 * as it was last time before we even pay attention to it.
1414 	 * Meanwhile, other routers may listen to it if they hadn't
1415 	 * seen it before (i.e., if they crashed in the meantime).
1416 	 * This means -- perversely -- that stable systems that stay
1417 	 * "up" for a long time pay a penalty for doing so.
1418 	 */
1419 	if (rip->rip_cmd == RIPCMD_RESPONSE && NA->a_type == RIP_AUTH_MD5 &&
1420 	    (php = get_peer_info(from)) != NULL) {
1421 		/*
1422 		 * If the entry that we find has been updated
1423 		 * recently enough that the routes are known
1424 		 * to still be good, but the sequence number
1425 		 * looks bad, then discard the packet.
1426 		 */
1427 		seqno = ntohl(NA->au.a_md5.md5_seqno);
1428 		if (php->ph_heard > now_expire && php->ph_seqno != 0 &&
1429 		    (seqno == 0 || ((seqno - php->ph_seqno) & 0x80000000ul))) {
1430 			msglim(use_authp, from,
1431 			    "discarding sequence %x (older than %x)",
1432 			    (unsigned)seqno, (unsigned)php->ph_seqno);
1433 			return (_B_FALSE);
1434 		}
1435 		php->ph_heard = now.tv_sec;
1436 		php->ph_seqno = seqno;
1437 	}
1438 
1439 	/*
1440 	 * accept any current (+/- 24 hours) password
1441 	 */
1442 	for (ap = aifp->int_auth, i = 0; i < MAX_AUTH_KEYS; i++, ap++) {
1443 		if (ap->type != NA->a_type ||
1444 		    (ulong_t)ap->start > (ulong_t)clk.tv_sec+DAY ||
1445 		    (ulong_t)ap->end+DAY < (ulong_t)clk.tv_sec)
1446 			continue;
1447 
1448 		if (NA->a_type == RIP_AUTH_PW) {
1449 			if (0 == memcmp(NA->au.au_pw, ap->key, RIP_AUTH_PW_LEN))
1450 				return (_B_TRUE);
1451 
1452 		} else {
1453 			/*
1454 			 * accept MD5 secret with the right key ID
1455 			 */
1456 			if (NA->au.a_md5.md5_keyid != ap->keyid)
1457 				continue;
1458 
1459 			len = ntohs(NA->au.a_md5.md5_pkt_len);
1460 			if ((len - sizeof (*rip)) % sizeof (*NA) != 0 ||
1461 			    len > (lim - (uint8_t *)rip - sizeof (*NA))) {
1462 				msglim(use_authp, from,
1463 				    "wrong MD5 RIPv2 packet length of %d"
1464 				    " instead of %d from %s",
1465 				    len, lim - (uint8_t *)rip - sizeof (*NA),
1466 				    naddr_ntoa(from));
1467 				return (_B_FALSE);
1468 			}
1469 			na2 = (struct netauth *)(rip->rip_nets +
1470 			    (len - 4) / sizeof (struct netinfo));
1471 
1472 			/*
1473 			 * Given a good hash value, these are not security
1474 			 * problems so be generous and accept the routes,
1475 			 * after complaining.
1476 			 */
1477 			if (TRACEPACKETS) {
1478 				if (NA->au.a_md5.md5_auth_len !=
1479 				    RIP_AUTH_MD5_LEN)
1480 					msglim(use_authp, from,
1481 					    "unknown MD5 RIPv2 auth len %#x"
1482 					    " instead of %#x from %s",
1483 					    NA->au.a_md5.md5_auth_len,
1484 					    RIP_AUTH_MD5_LEN,
1485 					    naddr_ntoa(from));
1486 				if (na2->a_family != RIP_AF_AUTH)
1487 					msglim(use_authp, from,
1488 					    "unknown MD5 RIPv2 family %#x"
1489 					    " instead of %#x from %s",
1490 					    na2->a_family, RIP_AF_AUTH,
1491 					    naddr_ntoa(from));
1492 				if (na2->a_type != RIP_AUTH_TRAILER)
1493 					msglim(use_authp, from,
1494 					    "MD5 RIPv2 hash has %#x"
1495 					    " instead of %#x from %s",
1496 					    ntohs(na2->a_type),
1497 					    ntohs(RIP_AUTH_TRAILER),
1498 					    naddr_ntoa(from));
1499 			}
1500 
1501 			MD5Init(&md5_ctx);
1502 			/*
1503 			 * len+4 to include auth trailer's family/type in
1504 			 * MD5 sum
1505 			 */
1506 			MD5Update(&md5_ctx, (uchar_t *)rip, len + 4);
1507 			MD5Update(&md5_ctx, ap->key, RIP_AUTH_MD5_LEN);
1508 			MD5Final(hash, &md5_ctx);
1509 			if (0 == memcmp(hash, na2->au.au_pw, sizeof (hash)))
1510 				return (_B_TRUE);
1511 		}
1512 	}
1513 
1514 	msglim(use_authp, from, "bad auth data from %s",
1515 	    naddr_ntoa(from));
1516 	return (_B_FALSE);
1517 #undef NA
1518 }
1519