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: releng/10.3/sbin/routed/input.c 286348 2015-08-05 22:05:02Z delphij $
30 */
31
32#include "defs.h"
33
34#ifdef __NetBSD__
35__RCSID("$NetBSD$");
36#elif defined(__FreeBSD__)
37__RCSID("$FreeBSD: releng/10.3/sbin/routed/input.c 286348 2015-08-05 22:05:02Z delphij $");
38#else
39__RCSID("$Revision: 2.26 $");
40#ident "$Revision: 2.26 $"
41#endif
42
43static void input(struct sockaddr_in *, struct interface *, struct interface *,
44		  struct rip *, int);
45static void input_route(naddr, naddr, struct rt_spare *, struct netinfo *);
46static int ck_passwd(struct interface *, struct rip *, void *,
47		     naddr, struct msg_limit *);
48
49
50/* process RIP input
51 */
52void
53read_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 */
134static void
135input(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 (sifp == 0) {
164		trace_pkt("    discard a request from an indirect router"
165		    " (possibly an attack)");
166		return;
167	}
168
169	if (rip->rip_vers == 0) {
170		msglim(&bad_router, FROM_NADDR,
171		       "RIP version 0, cmd %d, packet received from %s",
172		       rip->rip_cmd, naddr_ntoa(FROM_NADDR));
173		return;
174	} else if (rip->rip_vers > RIPv2) {
175		rip->rip_vers = RIPv2;
176	}
177	if (cc > (int)OVER_MAXPACKETSIZE) {
178		msglim(&bad_router, FROM_NADDR,
179		       "packet at least %d bytes too long received from %s",
180		       cc-MAXPACKETSIZE, naddr_ntoa(FROM_NADDR));
181		return;
182	}
183
184	n = rip->rip_nets;
185	lim = (struct netinfo *)((char*)rip + cc);
186
187	/* Notice authentication.
188	 * As required by section 4.2 in RFC 1723, discard authenticated
189	 * RIPv2 messages, but only if configured for that silliness.
190	 *
191	 * RIPv2 authentication is lame.  Why authenticate queries?
192	 * Why should a RIPv2 implementation with authentication disabled
193	 * not be able to listen to RIPv2 packets with authentication, while
194	 * RIPv1 systems will listen?  Crazy!
195	 */
196	if (!auth_ok
197	    && rip->rip_vers == RIPv2
198	    && n < lim && n->n_family == RIP_AF_AUTH) {
199		msglim(&use_auth, FROM_NADDR,
200		       "RIPv2 message with authentication from %s discarded",
201		       naddr_ntoa(FROM_NADDR));
202		return;
203	}
204
205	switch (rip->rip_cmd) {
206	case RIPCMD_REQUEST:
207		/* For mere requests, be a little sloppy about the source
208		 */
209		if (aifp == 0)
210			aifp = sifp;
211
212		/* Are we talking to ourself or a remote gateway?
213		 */
214		ifp1 = ifwithaddr(FROM_NADDR, 0, 1);
215		if (ifp1) {
216			if (ifp1->int_state & IS_REMOTE) {
217				/* remote gateway */
218				aifp = ifp1;
219				if (check_remote(aifp)) {
220					aifp->int_act_time = now.tv_sec;
221					(void)if_ok(aifp, "remote ");
222				}
223			} else if (from->sin_port == htons(RIP_PORT)) {
224				trace_pkt("    discard our own RIP request");
225				return;
226			}
227		}
228
229		/* did the request come from a router?
230		 */
231		if (from->sin_port == htons(RIP_PORT)) {
232			/* yes, ignore the request if RIP is off so that
233			 * the router does not depend on us.
234			 */
235			if (rip_sock < 0
236			    || (aifp != 0
237				&& IS_RIP_OUT_OFF(aifp->int_state))) {
238				trace_pkt("    discard request while RIP off");
239				return;
240			}
241		}
242
243		/* According to RFC 1723, we should ignore unauthenticated
244		 * queries.  That is too silly to bother with.  Sheesh!
245		 * Are forwarding tables supposed to be secret, when
246		 * a bad guy can infer them with test traffic?  When RIP
247		 * is still the most common router-discovery protocol
248		 * and so hosts need to send queries that will be answered?
249		 * What about `rtquery`?
250		 * Maybe on firewalls you'd care, but not enough to
251		 * give up the diagnostic facilities of remote probing.
252		 */
253
254		if (n >= lim) {
255			msglim(&bad_len, FROM_NADDR, "empty request from %s",
256			       naddr_ntoa(FROM_NADDR));
257			return;
258		}
259		if (cc%sizeof(*n) != sizeof(struct rip)%sizeof(*n)) {
260			msglim(&bad_len, FROM_NADDR,
261			       "request of bad length (%d) from %s",
262			       cc, naddr_ntoa(FROM_NADDR));
263		}
264
265		if (rip->rip_vers == RIPv2
266		    && (aifp == 0 || (aifp->int_state & IS_NO_RIPV1_OUT))) {
267			v12buf.buf->rip_vers = RIPv2;
268			/* If we have a secret but it is a cleartext secret,
269			 * do not disclose our secret unless the other guy
270			 * already knows it.
271			 */
272			ap = find_auth(aifp);
273			if (ap != 0 && ap->type == RIP_AUTH_PW
274			    && n->n_family == RIP_AF_AUTH
275			    && !ck_passwd(aifp,rip,lim,FROM_NADDR,&use_auth))
276				ap = 0;
277		} else {
278			v12buf.buf->rip_vers = RIPv1;
279			ap = 0;
280		}
281		clr_ws_buf(&v12buf, ap);
282
283		do {
284			n->n_metric = ntohl(n->n_metric);
285
286			/* A single entry with family RIP_AF_UNSPEC and
287			 * metric HOPCNT_INFINITY means "all routes".
288			 * We respond to routers only if we are acting
289			 * as a supplier, or to anyone other than a router
290			 * (i.e. a query).
291			 */
292			if (n->n_family == RIP_AF_UNSPEC
293			    && n->n_metric == HOPCNT_INFINITY) {
294				/* Answer a query from a utility program
295				 * with all we know.
296				 */
297				if (from->sin_port != htons(RIP_PORT)) {
298					/*
299					 * insecure: query from non-router node
300					 *   > 1: allow from distant node
301					 *   > 0: allow from neighbor node
302					 *  == 0: deny
303					 */
304					if ((aifp != NULL && insecure > 0) ||
305					    (aifp == NULL && insecure > 1))
306						supply(from, aifp, OUT_QUERY, 0,
307						       rip->rip_vers, ap != 0);
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 == 0) {
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 (0 != (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 != 0);
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 == 0) {
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 != 0
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 != 0 && 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 == 0) {
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 == 0) {
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 == 0) {
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)) == 0
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 */
778static void
779input_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 != 0
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 == 0) {
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		    && 0 != ifwithaddr(n->n_nhop, 1, 0))
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		    && 0 != 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
937static int				/* 0 if bad */
938ck_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