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