xref: /freebsd/sbin/routed/input.c (revision 09a53ad8f1318c5daae6cfb19d97f4f6459f0013)
1 /*
2  * Copyright (c) 1983, 1988, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31 
32 #include "defs.h"
33 
34 #ifdef __NetBSD__
35 __RCSID("$NetBSD$");
36 #elif defined(__FreeBSD__)
37 __RCSID("$FreeBSD$");
38 #else
39 __RCSID("$Revision: 2.26 $");
40 #ident "$Revision: 2.26 $"
41 #endif
42 
43 static void input(struct sockaddr_in *, struct interface *, struct interface *,
44 		  struct rip *, int);
45 static void input_route(naddr, naddr, struct rt_spare *, struct netinfo *);
46 static int ck_passwd(struct interface *, struct rip *, void *,
47 		     naddr, struct msg_limit *);
48 
49 
50 /* process RIP input
51  */
52 void
53 read_rip(int sock,
54 	 struct interface *sifp)
55 {
56 	struct sockaddr_in from;
57 	struct interface *aifp;
58 	socklen_t fromlen;
59 	int cc;
60 #ifdef USE_PASSIFNAME
61 	static struct msg_limit  bad_name;
62 	struct {
63 		char	ifname[IFNAMSIZ];
64 		union pkt_buf pbuf;
65 	} inbuf;
66 #else
67 	struct {
68 		union pkt_buf pbuf;
69 	} inbuf;
70 #endif
71 
72 
73 	for (;;) {
74 		fromlen = sizeof(from);
75 		cc = recvfrom(sock, &inbuf, sizeof(inbuf), 0,
76 			      (struct sockaddr*)&from, &fromlen);
77 		if (cc <= 0) {
78 			if (cc < 0 && errno != EWOULDBLOCK)
79 				LOGERR("recvfrom(rip)");
80 			break;
81 		}
82 		if (fromlen != sizeof(struct sockaddr_in))
83 			logbad(1,"impossible recvfrom(rip) fromlen=%d",
84 			       (int)fromlen);
85 
86 		/* aifp is the "authenticated" interface via which the packet
87 		 *	arrived.  In fact, it is only the interface on which
88 		 *	the packet should have arrived based on is source
89 		 *	address.
90 		 * sifp is interface associated with the socket through which
91 		 *	the packet was received.
92 		 */
93 #ifdef USE_PASSIFNAME
94 		if ((cc -= sizeof(inbuf.ifname)) < 0)
95 			logbad(0,"missing USE_PASSIFNAME; only %d bytes",
96 			       cc+sizeof(inbuf.ifname));
97 
98 		/* check the remote interfaces first */
99 		LIST_FOREACH(aifp, &remote_if, remote_list) {
100 			if (aifp->int_addr == from.sin_addr.s_addr)
101 				break;
102 		}
103 		if (aifp == NULL) {
104 			aifp = ifwithname(inbuf.ifname, 0);
105 			if (aifp == NULL) {
106 				msglim(&bad_name, from.sin_addr.s_addr,
107 				       "impossible interface name %.*s",
108 				       IFNAMSIZ, inbuf.ifname);
109 			} else if (((aifp->int_if_flags & IFF_POINTOPOINT)
110 				    && aifp->int_dstaddr!=from.sin_addr.s_addr)
111 				   || (!(aifp->int_if_flags & IFF_POINTOPOINT)
112 				       && !on_net(from.sin_addr.s_addr,
113 						  aifp->int_net,
114 						  aifp->int_mask))) {
115 				/* If it came via the wrong interface, do not
116 				 * trust it.
117 				 */
118 				aifp = NULL;
119 			}
120 		}
121 #else
122 		aifp = iflookup(from.sin_addr.s_addr);
123 #endif
124 		if (sifp == NULL)
125 			sifp = aifp;
126 
127 		input(&from, sifp, aifp, &inbuf.pbuf.rip, cc);
128 	}
129 }
130 
131 
132 /* Process a RIP packet
133  */
134 static void
135 input(struct sockaddr_in *from,		/* received from this IP address */
136       struct interface *sifp,		/* interface of incoming socket */
137       struct interface *aifp,		/* "authenticated" interface */
138       struct rip *rip,
139       int cc)
140 {
141 #	define FROM_NADDR from->sin_addr.s_addr
142 	static struct msg_limit use_auth, bad_len, bad_mask;
143 	static struct msg_limit unk_router, bad_router, bad_nhop;
144 
145 	struct rt_entry *rt;
146 	struct rt_spare new;
147 	struct netinfo *n, *lim;
148 	struct interface *ifp1;
149 	naddr gate, mask, v1_mask, dst, ddst_h = 0;
150 	struct auth *ap;
151 	struct tgate *tg = NULL;
152 	struct tgate_net *tn;
153 	int i, j;
154 
155 	/* Notice when we hear from a remote gateway
156 	 */
157 	if (aifp != NULL
158 	    && (aifp->int_state & IS_REMOTE))
159 		aifp->int_act_time = now.tv_sec;
160 
161 	trace_rip("Recv", "from", from, sifp, rip, cc);
162 
163 	if (sifp == NULL) {
164 		trace_pkt("    discard a request from an indirect router"
165 		    " (possibly an attack)");
166 		return;
167 	}
168 
169 	if (rip->rip_vers == 0) {
170 		msglim(&bad_router, FROM_NADDR,
171 		       "RIP version 0, cmd %d, packet received from %s",
172 		       rip->rip_cmd, naddr_ntoa(FROM_NADDR));
173 		return;
174 	} else if (rip->rip_vers > RIPv2) {
175 		rip->rip_vers = RIPv2;
176 	}
177 	if (cc > (int)OVER_MAXPACKETSIZE) {
178 		msglim(&bad_router, FROM_NADDR,
179 		       "packet at least %d bytes too long received from %s",
180 		       cc-MAXPACKETSIZE, naddr_ntoa(FROM_NADDR));
181 		return;
182 	}
183 
184 	n = rip->rip_nets;
185 	lim = (struct netinfo *)((char*)rip + cc);
186 
187 	/* Notice authentication.
188 	 * As required by section 4.2 in RFC 1723, discard authenticated
189 	 * RIPv2 messages, but only if configured for that silliness.
190 	 *
191 	 * RIPv2 authentication is lame.  Why authenticate queries?
192 	 * Why should a RIPv2 implementation with authentication disabled
193 	 * not be able to listen to RIPv2 packets with authentication, while
194 	 * RIPv1 systems will listen?  Crazy!
195 	 */
196 	if (!auth_ok
197 	    && rip->rip_vers == RIPv2
198 	    && n < lim && n->n_family == RIP_AF_AUTH) {
199 		msglim(&use_auth, FROM_NADDR,
200 		       "RIPv2 message with authentication from %s discarded",
201 		       naddr_ntoa(FROM_NADDR));
202 		return;
203 	}
204 
205 	switch (rip->rip_cmd) {
206 	case RIPCMD_REQUEST:
207 		/* For mere requests, be a little sloppy about the source
208 		 */
209 		if (aifp == NULL)
210 			aifp = sifp;
211 
212 		/* Are we talking to ourself or a remote gateway?
213 		 */
214 		ifp1 = ifwithaddr(FROM_NADDR, 0, 1);
215 		if (ifp1) {
216 			if (ifp1->int_state & IS_REMOTE) {
217 				/* remote gateway */
218 				aifp = ifp1;
219 				if (check_remote(aifp)) {
220 					aifp->int_act_time = now.tv_sec;
221 					(void)if_ok(aifp, "remote ");
222 				}
223 			} else if (from->sin_port == htons(RIP_PORT)) {
224 				trace_pkt("    discard our own RIP request");
225 				return;
226 			}
227 		}
228 
229 		/* did the request come from a router?
230 		 */
231 		if (from->sin_port == htons(RIP_PORT)) {
232 			/* yes, ignore the request if RIP is off so that
233 			 * the router does not depend on us.
234 			 */
235 			if (rip_sock < 0
236 			    || (aifp != NULL
237 				&& IS_RIP_OUT_OFF(aifp->int_state))) {
238 				trace_pkt("    discard request while RIP off");
239 				return;
240 			}
241 		}
242 
243 		/* According to RFC 1723, we should ignore unauthenticated
244 		 * queries.  That is too silly to bother with.  Sheesh!
245 		 * Are forwarding tables supposed to be secret, when
246 		 * a bad guy can infer them with test traffic?  When RIP
247 		 * is still the most common router-discovery protocol
248 		 * and so hosts need to send queries that will be answered?
249 		 * What about `rtquery`?
250 		 * Maybe on firewalls you'd care, but not enough to
251 		 * give up the diagnostic facilities of remote probing.
252 		 */
253 
254 		if (n >= lim) {
255 			msglim(&bad_len, FROM_NADDR, "empty request from %s",
256 			       naddr_ntoa(FROM_NADDR));
257 			return;
258 		}
259 		if (cc%sizeof(*n) != sizeof(struct rip)%sizeof(*n)) {
260 			msglim(&bad_len, FROM_NADDR,
261 			       "request of bad length (%d) from %s",
262 			       cc, naddr_ntoa(FROM_NADDR));
263 		}
264 
265 		if (rip->rip_vers == RIPv2
266 		    && (aifp == NULL || (aifp->int_state & IS_NO_RIPV1_OUT))) {
267 			v12buf.buf->rip_vers = RIPv2;
268 			/* If we have a secret but it is a cleartext secret,
269 			 * do not disclose our secret unless the other guy
270 			 * already knows it.
271 			 */
272 			ap = find_auth(aifp);
273 			if (ap != NULL && ap->type == RIP_AUTH_PW
274 			    && n->n_family == RIP_AF_AUTH
275 			    && !ck_passwd(aifp,rip,lim,FROM_NADDR,&use_auth))
276 				ap = NULL;
277 		} else {
278 			v12buf.buf->rip_vers = RIPv1;
279 			ap = NULL;
280 		}
281 		clr_ws_buf(&v12buf, ap);
282 
283 		do {
284 			n->n_metric = ntohl(n->n_metric);
285 
286 			/* A single entry with family RIP_AF_UNSPEC and
287 			 * metric HOPCNT_INFINITY means "all routes".
288 			 * We respond to routers only if we are acting
289 			 * as a supplier, or to anyone other than a router
290 			 * (i.e. a query).
291 			 */
292 			if (n->n_family == RIP_AF_UNSPEC
293 			    && n->n_metric == HOPCNT_INFINITY) {
294 				/* Answer a query from a utility program
295 				 * with all we know.
296 				 */
297 				if (aifp == NULL) {
298 					trace_pkt("ignore remote query");
299 					return;
300 				}
301 				if (from->sin_port != htons(RIP_PORT)) {
302 					/*
303 					 * insecure: query from non-router node
304 					 *   > 1: allow from distant node
305 					 *   > 0: allow from neighbor node
306 					 *  == 0: deny
307 					 */
308 					if ((aifp != NULL && insecure > 0) ||
309 					    (aifp == NULL && insecure > 1))
310 						supply(from, aifp, OUT_QUERY, 0,
311 						       rip->rip_vers,
312 						       ap != NULL);
313 					else
314 						trace_pkt("Warning: "
315 						    "possible attack detected");
316 					return;
317 				}
318 
319 				/* A router trying to prime its tables.
320 				 * Filter the answer in the about same way
321 				 * broadcasts are filtered.
322 				 *
323 				 * Only answer a router if we are a supplier
324 				 * to keep an unwary host that is just starting
325 				 * from picking us as a router.
326 				 */
327 				if (aifp == NULL) {
328 					trace_pkt("ignore distant router");
329 					return;
330 				}
331 				if (!supplier
332 				    || IS_RIP_OFF(aifp->int_state)) {
333 					trace_pkt("ignore; not supplying");
334 					return;
335 				}
336 
337 				/* Do not answer a RIPv1 router if
338 				 * we are sending RIPv2.  But do offer
339 				 * poor man's router discovery.
340 				 */
341 				if ((aifp->int_state & IS_NO_RIPV1_OUT)
342 				    && rip->rip_vers == RIPv1) {
343 					if (!(aifp->int_state & IS_PM_RDISC)) {
344 					    trace_pkt("ignore; sending RIPv2");
345 					    return;
346 					}
347 
348 					v12buf.n->n_family = RIP_AF_INET;
349 					v12buf.n->n_dst = RIP_DEFAULT;
350 					i = aifp->int_d_metric;
351 					if (NULL != (rt = rtget(RIP_DEFAULT, 0))) {
352 					    j = (rt->rt_metric
353 						 +aifp->int_metric
354 						 +aifp->int_adj_outmetric
355 						 +1);
356 					    if (i > j)
357 						i = j;
358 					}
359 					v12buf.n->n_metric = htonl(i);
360 					v12buf.n++;
361 					break;
362 				}
363 
364 				/* Respond with RIPv1 instead of RIPv2 if
365 				 * that is what we are broadcasting on the
366 				 * interface to keep the remote router from
367 				 * getting the wrong initial idea of the
368 				 * routes we send.
369 				 */
370 				supply(from, aifp, OUT_UNICAST, 0,
371 				       (aifp->int_state & IS_NO_RIPV1_OUT)
372 				       ? RIPv2 : RIPv1,
373 				       ap != NULL);
374 				return;
375 			}
376 
377 			/* Ignore authentication */
378 			if (n->n_family == RIP_AF_AUTH)
379 				continue;
380 
381 			if (n->n_family != RIP_AF_INET) {
382 				msglim(&bad_router, FROM_NADDR,
383 				       "request from %s for unsupported"
384 				       " (af %d) %s",
385 				       naddr_ntoa(FROM_NADDR),
386 				       ntohs(n->n_family),
387 				       naddr_ntoa(n->n_dst));
388 				return;
389 			}
390 
391 			/* We are being asked about a specific destination.
392 			 */
393 			dst = n->n_dst;
394 			if (!check_dst(dst)) {
395 				msglim(&bad_router, FROM_NADDR,
396 				       "bad queried destination %s from %s",
397 				       naddr_ntoa(dst),
398 				       naddr_ntoa(FROM_NADDR));
399 				return;
400 			}
401 
402 			/* decide what mask was intended */
403 			if (rip->rip_vers == RIPv1
404 			    || 0 == (mask = ntohl(n->n_mask))
405 			    || 0 != (ntohl(dst) & ~mask))
406 				mask = ripv1_mask_host(dst, aifp);
407 
408 			/* try to find the answer */
409 			rt = rtget(dst, mask);
410 			if (!rt && dst != RIP_DEFAULT)
411 				rt = rtfind(n->n_dst);
412 
413 			if (v12buf.buf->rip_vers != RIPv1)
414 				v12buf.n->n_mask = mask;
415 			if (rt == NULL) {
416 				/* we do not have the answer */
417 				v12buf.n->n_metric = HOPCNT_INFINITY;
418 			} else {
419 				/* we have the answer, so compute the
420 				 * right metric and next hop.
421 				 */
422 				v12buf.n->n_family = RIP_AF_INET;
423 				v12buf.n->n_dst = dst;
424 				j = rt->rt_metric+1;
425 				if (!aifp)
426 					++j;
427 				else
428 					j += (aifp->int_metric
429 					      + aifp->int_adj_outmetric);
430 				if (j < HOPCNT_INFINITY)
431 					v12buf.n->n_metric = j;
432 				else
433 					v12buf.n->n_metric = HOPCNT_INFINITY;
434 				if (v12buf.buf->rip_vers != RIPv1) {
435 					v12buf.n->n_tag = rt->rt_tag;
436 					v12buf.n->n_mask = mask;
437 					if (aifp != NULL
438 					    && on_net(rt->rt_gate,
439 						      aifp->int_net,
440 						      aifp->int_mask)
441 					    && rt->rt_gate != aifp->int_addr)
442 					    v12buf.n->n_nhop = rt->rt_gate;
443 				}
444 			}
445 			v12buf.n->n_metric = htonl(v12buf.n->n_metric);
446 
447 			/* Stop paying attention if we fill the output buffer.
448 			 */
449 			if (++v12buf.n >= v12buf.lim)
450 				break;
451 		} while (++n < lim);
452 
453 		/* Send the answer about specific routes.
454 		 */
455 		if (ap != NULL && ap->type == RIP_AUTH_MD5)
456 			end_md5_auth(&v12buf, ap);
457 
458 		if (from->sin_port != htons(RIP_PORT)) {
459 			/* query */
460 			(void)output(OUT_QUERY, from, aifp,
461 				     v12buf.buf,
462 				     ((char *)v12buf.n - (char*)v12buf.buf));
463 		} else if (supplier) {
464 			(void)output(OUT_UNICAST, from, aifp,
465 				     v12buf.buf,
466 				     ((char *)v12buf.n - (char*)v12buf.buf));
467 		} else {
468 			/* Only answer a router if we are a supplier
469 			 * to keep an unwary host that is just starting
470 			 * from picking us an a router.
471 			 */
472 			;
473 		}
474 		return;
475 
476 	case RIPCMD_TRACEON:
477 	case RIPCMD_TRACEOFF:
478 		/* Notice that trace messages are turned off for all possible
479 		 * abuse if _PATH_TRACE is undefined in pathnames.h.
480 		 * Notice also that because of the way the trace file is
481 		 * handled in trace.c, no abuse is plausible even if
482 		 * _PATH_TRACE_ is defined.
483 		 *
484 		 * First verify message came from a privileged port. */
485 		if (ntohs(from->sin_port) > IPPORT_RESERVED) {
486 			msglog("trace command from untrusted port on %s",
487 			       naddr_ntoa(FROM_NADDR));
488 			return;
489 		}
490 		if (aifp == NULL) {
491 			msglog("trace command from unknown router %s",
492 			       naddr_ntoa(FROM_NADDR));
493 			return;
494 		}
495 		if (rip->rip_cmd == RIPCMD_TRACEON) {
496 			rip->rip_tracefile[cc-4] = '\0';
497 			set_tracefile((char*)rip->rip_tracefile,
498 				      "trace command: %s\n", 0);
499 		} else {
500 			trace_off("tracing turned off by %s",
501 				  naddr_ntoa(FROM_NADDR));
502 		}
503 		return;
504 
505 	case RIPCMD_RESPONSE:
506 		if (cc%sizeof(*n) != sizeof(struct rip)%sizeof(*n)) {
507 			msglim(&bad_len, FROM_NADDR,
508 			       "response of bad length (%d) from %s",
509 			       cc, naddr_ntoa(FROM_NADDR));
510 		}
511 
512 		/* verify message came from a router */
513 		if (from->sin_port != ntohs(RIP_PORT)) {
514 			msglim(&bad_router, FROM_NADDR,
515 			       "    discard RIP response from unknown port"
516 			       " %d on %s",
517 			       ntohs(from->sin_port), naddr_ntoa(FROM_NADDR));
518 			return;
519 		}
520 
521 		if (rip_sock < 0) {
522 			trace_pkt("    discard response while RIP off");
523 			return;
524 		}
525 
526 		/* Are we talking to ourself or a remote gateway?
527 		 */
528 		ifp1 = ifwithaddr(FROM_NADDR, 0, 1);
529 		if (ifp1) {
530 			if (ifp1->int_state & IS_REMOTE) {
531 				/* remote gateway */
532 				aifp = ifp1;
533 				if (check_remote(aifp)) {
534 					aifp->int_act_time = now.tv_sec;
535 					(void)if_ok(aifp, "remote ");
536 				}
537 			} else {
538 				trace_pkt("    discard our own RIP response");
539 				return;
540 			}
541 		}
542 
543 		/* Accept routing packets from routers directly connected
544 		 * via broadcast or point-to-point networks, and from
545 		 * those listed in /etc/gateways.
546 		 */
547 		if (aifp == NULL) {
548 			msglim(&unk_router, FROM_NADDR,
549 			       "   discard response from %s"
550 			       " via unexpected interface",
551 			       naddr_ntoa(FROM_NADDR));
552 			return;
553 		}
554 		if (IS_RIP_IN_OFF(aifp->int_state)) {
555 			trace_pkt("    discard RIPv%d response"
556 				  " via disabled interface %s",
557 				  rip->rip_vers, aifp->int_name);
558 			return;
559 		}
560 
561 		if (n >= lim) {
562 			msglim(&bad_len, FROM_NADDR, "empty response from %s",
563 			       naddr_ntoa(FROM_NADDR));
564 			return;
565 		}
566 
567 		if (((aifp->int_state & IS_NO_RIPV1_IN)
568 		     && rip->rip_vers == RIPv1)
569 		    || ((aifp->int_state & IS_NO_RIPV2_IN)
570 			&& rip->rip_vers != RIPv1)) {
571 			trace_pkt("    discard RIPv%d response",
572 				  rip->rip_vers);
573 			return;
574 		}
575 
576 		/* Ignore routes via dead interface.
577 		 */
578 		if (aifp->int_state & IS_BROKE) {
579 			trace_pkt("discard response via broken interface %s",
580 				  aifp->int_name);
581 			return;
582 		}
583 
584 		/* If the interface cares, ignore bad routers.
585 		 * Trace but do not log this problem, because where it
586 		 * happens, it happens frequently.
587 		 */
588 		if (aifp->int_state & IS_DISTRUST) {
589 			tg = tgates;
590 			while (tg->tgate_addr != FROM_NADDR) {
591 				tg = tg->tgate_next;
592 				if (tg == NULL) {
593 					trace_pkt("    discard RIP response"
594 						  " from untrusted router %s",
595 						  naddr_ntoa(FROM_NADDR));
596 					return;
597 				}
598 			}
599 		}
600 
601 		/* Authenticate the packet if we have a secret.
602 		 * If we do not have any secrets, ignore the error in
603 		 * RFC 1723 and accept it regardless.
604 		 */
605 		if (aifp->int_auth[0].type != RIP_AUTH_NONE
606 		    && rip->rip_vers != RIPv1
607 		    && !ck_passwd(aifp,rip,lim,FROM_NADDR,&use_auth))
608 			return;
609 
610 		do {
611 			if (n->n_family == RIP_AF_AUTH)
612 				continue;
613 
614 			n->n_metric = ntohl(n->n_metric);
615 			dst = n->n_dst;
616 			if (n->n_family != RIP_AF_INET
617 			    && (n->n_family != RIP_AF_UNSPEC
618 				|| dst != RIP_DEFAULT)) {
619 				msglim(&bad_router, FROM_NADDR,
620 				       "route from %s to unsupported"
621 				       " address family=%d destination=%s",
622 				       naddr_ntoa(FROM_NADDR),
623 				       n->n_family,
624 				       naddr_ntoa(dst));
625 				continue;
626 			}
627 			if (!check_dst(dst)) {
628 				msglim(&bad_router, FROM_NADDR,
629 				       "bad destination %s from %s",
630 				       naddr_ntoa(dst),
631 				       naddr_ntoa(FROM_NADDR));
632 				return;
633 			}
634 			if (n->n_metric == 0
635 			    || n->n_metric > HOPCNT_INFINITY) {
636 				msglim(&bad_router, FROM_NADDR,
637 				       "bad metric %d from %s"
638 				       " for destination %s",
639 				       n->n_metric,
640 				       naddr_ntoa(FROM_NADDR),
641 				       naddr_ntoa(dst));
642 				return;
643 			}
644 
645 			/* Notice the next-hop.
646 			 */
647 			gate = FROM_NADDR;
648 			if (n->n_nhop != 0) {
649 				if (rip->rip_vers == RIPv1) {
650 					n->n_nhop = 0;
651 				} else {
652 				    /* Use it only if it is valid. */
653 				    if (on_net(n->n_nhop,
654 					       aifp->int_net, aifp->int_mask)
655 					&& check_dst(n->n_nhop)) {
656 					    gate = n->n_nhop;
657 				    } else {
658 					    msglim(&bad_nhop, FROM_NADDR,
659 						   "router %s to %s"
660 						   " has bad next hop %s",
661 						   naddr_ntoa(FROM_NADDR),
662 						   naddr_ntoa(dst),
663 						   naddr_ntoa(n->n_nhop));
664 					    n->n_nhop = 0;
665 				    }
666 				}
667 			}
668 
669 			if (rip->rip_vers == RIPv1
670 			    || 0 == (mask = ntohl(n->n_mask))) {
671 				mask = ripv1_mask_host(dst,aifp);
672 			} else if ((ntohl(dst) & ~mask) != 0) {
673 				msglim(&bad_mask, FROM_NADDR,
674 				       "router %s sent bad netmask"
675 				       " %#lx with %s",
676 				       naddr_ntoa(FROM_NADDR),
677 				       (u_long)mask,
678 				       naddr_ntoa(dst));
679 				continue;
680 			}
681 			if (rip->rip_vers == RIPv1)
682 				n->n_tag = 0;
683 
684 			/* Adjust metric according to incoming interface..
685 			 */
686 			n->n_metric += (aifp->int_metric
687 					+ aifp->int_adj_inmetric);
688 			if (n->n_metric > HOPCNT_INFINITY)
689 				n->n_metric = HOPCNT_INFINITY;
690 
691 			/* Should we trust this route from this router? */
692 			if (tg && (tn = tg->tgate_nets)->mask != 0) {
693 				for (i = 0; i < MAX_TGATE_NETS; i++, tn++) {
694 					if (on_net(dst, tn->net, tn->mask)
695 					    && tn->mask <= mask)
696 					    break;
697 				}
698 				if (i >= MAX_TGATE_NETS || tn->mask == 0) {
699 					trace_pkt("   ignored unauthorized %s",
700 						  addrname(dst,mask,0));
701 					continue;
702 				}
703 			}
704 
705 			/* Recognize and ignore a default route we faked
706 			 * which is being sent back to us by a machine with
707 			 * broken split-horizon.
708 			 * Be a little more paranoid than that, and reject
709 			 * default routes with the same metric we advertised.
710 			 */
711 			if (aifp->int_d_metric != 0
712 			    && dst == RIP_DEFAULT
713 			    && (int)n->n_metric >= aifp->int_d_metric)
714 				continue;
715 
716 			/* We can receive aggregated RIPv2 routes that must
717 			 * be broken down before they are transmitted by
718 			 * RIPv1 via an interface on a subnet.
719 			 * We might also receive the same routes aggregated
720 			 * via other RIPv2 interfaces.
721 			 * This could cause duplicate routes to be sent on
722 			 * the RIPv1 interfaces.  "Longest matching variable
723 			 * length netmasks" lets RIPv2 listeners understand,
724 			 * but breaking down the aggregated routes for RIPv1
725 			 * listeners can produce duplicate routes.
726 			 *
727 			 * Breaking down aggregated routes here bloats
728 			 * the daemon table, but does not hurt the kernel
729 			 * table, since routes are always aggregated for
730 			 * the kernel.
731 			 *
732 			 * Notice that this does not break down network
733 			 * routes corresponding to subnets.  This is part
734 			 * of the defense against RS_NET_SYN.
735 			 */
736 			if (have_ripv1_out
737 			    && (((rt = rtget(dst,mask)) == NULL
738 				 || !(rt->rt_state & RS_NET_SYN)))
739 			    && (v1_mask = ripv1_mask_net(dst,0)) > mask) {
740 				ddst_h = v1_mask & -v1_mask;
741 				i = (v1_mask & ~mask)/ddst_h;
742 				if (i >= 511) {
743 					/* Punt if we would have to generate
744 					 * an unreasonable number of routes.
745 					 */
746 					if (TRACECONTENTS)
747 					    trace_misc("accept %s-->%s as 1"
748 						       " instead of %d routes",
749 						       addrname(dst,mask,0),
750 						       naddr_ntoa(FROM_NADDR),
751 						       i+1);
752 					i = 0;
753 				} else {
754 					mask = v1_mask;
755 				}
756 			} else {
757 				i = 0;
758 			}
759 
760 			new.rts_gate = gate;
761 			new.rts_router = FROM_NADDR;
762 			new.rts_metric = n->n_metric;
763 			new.rts_tag = n->n_tag;
764 			new.rts_time = now.tv_sec;
765 			new.rts_ifp = aifp;
766 			new.rts_de_ag = i;
767 			j = 0;
768 			for (;;) {
769 				input_route(dst, mask, &new, n);
770 				if (++j > i)
771 					break;
772 				dst = htonl(ntohl(dst) + ddst_h);
773 			}
774 		} while (++n < lim);
775 		break;
776 	}
777 #undef FROM_NADDR
778 }
779 
780 
781 /* Process a single input route.
782  */
783 static void
784 input_route(naddr dst,			/* network order */
785 	    naddr mask,
786 	    struct rt_spare *new,
787 	    struct netinfo *n)
788 {
789 	int i;
790 	struct rt_entry *rt;
791 	struct rt_spare *rts, *rts0;
792 	struct interface *ifp1;
793 
794 
795 	/* See if the other guy is telling us to send our packets to him.
796 	 * Sometimes network routes arrive over a point-to-point link for
797 	 * the network containing the address(es) of the link.
798 	 *
799 	 * If our interface is broken, switch to using the other guy.
800 	 */
801 	ifp1 = ifwithaddr(dst, 1, 1);
802 	if (ifp1 != NULL
803 	    && (!(ifp1->int_state & IS_BROKE)
804 		|| (ifp1->int_state & IS_PASSIVE)))
805 		return;
806 
807 	/* Look for the route in our table.
808 	 */
809 	rt = rtget(dst, mask);
810 
811 	/* Consider adding the route if we do not already have it.
812 	 */
813 	if (rt == NULL) {
814 		/* Ignore unknown routes being poisoned.
815 		 */
816 		if (new->rts_metric == HOPCNT_INFINITY)
817 			return;
818 
819 		/* Ignore the route if it points to us */
820 		if (n->n_nhop != 0
821 		    && ifwithaddr(n->n_nhop, 1, 0) != NULL)
822 			return;
823 
824 		/* If something has not gone crazy and tried to fill
825 		 * our memory, accept the new route.
826 		 */
827 		if (total_routes < MAX_ROUTES)
828 			rtadd(dst, mask, 0, new);
829 		return;
830 	}
831 
832 	/* We already know about the route.  Consider this update.
833 	 *
834 	 * If (rt->rt_state & RS_NET_SYN), then this route
835 	 * is the same as a network route we have inferred
836 	 * for subnets we know, in order to tell RIPv1 routers
837 	 * about the subnets.
838 	 *
839 	 * It is impossible to tell if the route is coming
840 	 * from a distant RIPv2 router with the standard
841 	 * netmask because that router knows about the entire
842 	 * network, or if it is a round-about echo of a
843 	 * synthetic, RIPv1 network route of our own.
844 	 * The worst is that both kinds of routes might be
845 	 * received, and the bad one might have the smaller
846 	 * metric.  Partly solve this problem by never
847 	 * aggregating into such a route.  Also keep it
848 	 * around as long as the interface exists.
849 	 */
850 
851 	rts0 = rt->rt_spares;
852 	for (rts = rts0, i = NUM_SPARES; i != 0; i--, rts++) {
853 		if (rts->rts_router == new->rts_router)
854 			break;
855 		/* Note the worst slot to reuse,
856 		 * other than the current slot.
857 		 */
858 		if (rts0 == rt->rt_spares
859 		    || BETTER_LINK(rt, rts0, rts))
860 			rts0 = rts;
861 	}
862 	if (i != 0) {
863 		/* Found a route from the router already in the table.
864 		 */
865 
866 		/* If the new route is a route broken down from an
867 		 * aggregated route, and if the previous route is either
868 		 * not a broken down route or was broken down from a finer
869 		 * netmask, and if the previous route is current,
870 		 * then forget this one.
871 		 */
872 		if (new->rts_de_ag > rts->rts_de_ag
873 		    && now_stale <= rts->rts_time)
874 			return;
875 
876 		/* Keep poisoned routes around only long enough to pass
877 		 * the poison on.  Use a new timestamp for good routes.
878 		 */
879 		if (rts->rts_metric == HOPCNT_INFINITY
880 		    && new->rts_metric == HOPCNT_INFINITY)
881 			new->rts_time = rts->rts_time;
882 
883 		/* If this is an update for the router we currently prefer,
884 		 * then note it.
885 		 */
886 		if (i == NUM_SPARES) {
887 			rtchange(rt, rt->rt_state, new, 0);
888 			/* If the route got worse, check for something better.
889 			 */
890 			if (new->rts_metric > rts->rts_metric)
891 				rtswitch(rt, 0);
892 			return;
893 		}
894 
895 		/* This is an update for a spare route.
896 		 * Finished if the route is unchanged.
897 		 */
898 		if (rts->rts_gate == new->rts_gate
899 		    && rts->rts_metric == new->rts_metric
900 		    && rts->rts_tag == new->rts_tag) {
901 			trace_upslot(rt, rts, new);
902 			*rts = *new;
903 			return;
904 		}
905 		/* Forget it if it has gone bad.
906 		 */
907 		if (new->rts_metric == HOPCNT_INFINITY) {
908 			rts_delete(rt, rts);
909 			return;
910 		}
911 
912 	} else {
913 		/* The update is for a route we know about,
914 		 * but not from a familiar router.
915 		 *
916 		 * Ignore the route if it points to us.
917 		 */
918 		if (n->n_nhop != 0
919 		    && NULL != ifwithaddr(n->n_nhop, 1, 0))
920 			return;
921 
922 		/* the loop above set rts0=worst spare */
923 		rts = rts0;
924 
925 		/* Save the route as a spare only if it has
926 		 * a better metric than our worst spare.
927 		 * This also ignores poisoned routes (those
928 		 * received with metric HOPCNT_INFINITY).
929 		 */
930 		if (new->rts_metric >= rts->rts_metric)
931 			return;
932 	}
933 
934 	trace_upslot(rt, rts, new);
935 	*rts = *new;
936 
937 	/* try to switch to a better route */
938 	rtswitch(rt, rts);
939 }
940 
941 
942 static int				/* 0 if bad */
943 ck_passwd(struct interface *aifp,
944 	  struct rip *rip,
945 	  void *lim,
946 	  naddr from,
947 	  struct msg_limit *use_authp)
948 {
949 #	define NA (rip->rip_auths)
950 	struct netauth *na2;
951 	struct auth *ap;
952 	MD5_CTX md5_ctx;
953 	u_char hash[RIP_AUTH_PW_LEN];
954 	int i, len;
955 
956 	assert(aifp != NULL);
957 	if ((void *)NA >= lim || NA->a_family != RIP_AF_AUTH) {
958 		msglim(use_authp, from, "missing password from %s",
959 		       naddr_ntoa(from));
960 		return 0;
961 	}
962 
963 	/* accept any current (+/- 24 hours) password
964 	 */
965 	for (ap = aifp->int_auth, i = 0; i < MAX_AUTH_KEYS; i++, ap++) {
966 		if (ap->type != NA->a_type
967 		    || (u_long)ap->start > (u_long)clk.tv_sec+DAY
968 		    || (u_long)ap->end+DAY < (u_long)clk.tv_sec)
969 			continue;
970 
971 		if (NA->a_type == RIP_AUTH_PW) {
972 			if (!memcmp(NA->au.au_pw, ap->key, RIP_AUTH_PW_LEN))
973 				return 1;
974 
975 		} else {
976 			/* accept MD5 secret with the right key ID
977 			 */
978 			if (NA->au.a_md5.md5_keyid != ap->keyid)
979 				continue;
980 
981 			len = ntohs(NA->au.a_md5.md5_pkt_len);
982 			if ((len-sizeof(*rip)) % sizeof(*NA) != 0
983 			    || len != (char *)lim-(char*)rip-(int)sizeof(*NA)) {
984 				msglim(use_authp, from,
985 				       "wrong MD5 RIPv2 packet length of %d"
986 				       " instead of %d from %s",
987 				       len, (int)((char *)lim-(char *)rip
988 						  -sizeof(*NA)),
989 				       naddr_ntoa(from));
990 				return 0;
991 			}
992 			na2 = (struct netauth *)((char *)rip+len);
993 
994 			/* Given a good hash value, these are not security
995 			 * problems so be generous and accept the routes,
996 			 * after complaining.
997 			 */
998 			if (TRACEPACKETS) {
999 				if (NA->au.a_md5.md5_auth_len
1000 				    != RIP_AUTH_MD5_HASH_LEN)
1001 					msglim(use_authp, from,
1002 					       "unknown MD5 RIPv2 auth len %#x"
1003 					       " instead of %#x from %s",
1004 					       NA->au.a_md5.md5_auth_len,
1005 					       (unsigned)RIP_AUTH_MD5_HASH_LEN,
1006 					       naddr_ntoa(from));
1007 				if (na2->a_family != RIP_AF_AUTH)
1008 					msglim(use_authp, from,
1009 					       "unknown MD5 RIPv2 family %#x"
1010 					       " instead of %#x from %s",
1011 					       na2->a_family, RIP_AF_AUTH,
1012 					       naddr_ntoa(from));
1013 				if (na2->a_type != ntohs(1))
1014 					msglim(use_authp, from,
1015 					       "MD5 RIPv2 hash has %#x"
1016 					       " instead of %#x from %s",
1017 					       na2->a_type, ntohs(1),
1018 					       naddr_ntoa(from));
1019 			}
1020 
1021 			MD5Init(&md5_ctx);
1022 			MD5Update(&md5_ctx, (u_char *)rip,
1023 				  len + RIP_AUTH_MD5_HASH_XTRA);
1024 			MD5Update(&md5_ctx, ap->key, RIP_AUTH_MD5_KEY_LEN);
1025 			MD5Final(hash, &md5_ctx);
1026 			if (!memcmp(hash, na2->au.au_pw, sizeof(hash)))
1027 				return 1;
1028 		}
1029 	}
1030 
1031 	msglim(use_authp, from, "bad password from %s",
1032 	       naddr_ntoa(from));
1033 	return 0;
1034 #undef NA
1035 }
1036