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