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