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