xref: /freebsd/sys/netinet/ip_fastfwd.c (revision 6af83ee0d2941d18880b6aaa2b4facd1d30c6106)
1 /*-
2  * Copyright (c) 2003 Andre Oppermann, Internet Business Solutions AG
3  * 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  * 3. The name of the author may not be used to endorse or promote
14  *    products derived from this software without specific prior written
15  *    permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 /*
33  * ip_fastforward gets its speed from processing the forwarded packet to
34  * completion (if_output on the other side) without any queues or netisr's.
35  * The receiving interface DMAs the packet into memory, the upper half of
36  * driver calls ip_fastforward, we do our routing table lookup and directly
37  * send it off to the outgoing interface which DMAs the packet to the
38  * network card. The only part of the packet we touch with the CPU is the
39  * IP header (unless there are complex firewall rules touching other parts
40  * of the packet, but that is up to you). We are essentially limited by bus
41  * bandwidth and how fast the network card/driver can set up receives and
42  * transmits.
43  *
44  * We handle basic errors, ip header errors, checksum errors,
45  * destination unreachable, fragmentation and fragmentation needed and
46  * report them via icmp to the sender.
47  *
48  * Else if something is not pure IPv4 unicast forwarding we fall back to
49  * the normal ip_input processing path. We should only be called from
50  * interfaces connected to the outside world.
51  *
52  * Firewalling is fully supported including divert, ipfw fwd and ipfilter
53  * ipnat and address rewrite.
54  *
55  * IPSEC is not supported if this host is a tunnel broker. IPSEC is
56  * supported for connections to/from local host.
57  *
58  * We try to do the least expensive (in CPU ops) checks and operations
59  * first to catch junk with as little overhead as possible.
60  *
61  * We take full advantage of hardware support for ip checksum and
62  * fragmentation offloading.
63  *
64  * We don't do ICMP redirect in the fast forwarding path. I have had my own
65  * cases where two core routers with Zebra routing suite would send millions
66  * ICMP redirects to connected hosts if the router to dest was not the default
67  * gateway. In one case it was filling the routing table of a host with close
68  * 300'000 cloned redirect entries until it ran out of kernel memory. However
69  * the networking code proved very robust and it didn't crash or went ill
70  * otherwise.
71  */
72 
73 /*
74  * Many thanks to Matt Thomas of NetBSD for basic structure of ip_flow.c which
75  * is being followed here.
76  */
77 
78 #include "opt_ipfw.h"
79 #include "opt_ipstealth.h"
80 
81 #include <sys/param.h>
82 #include <sys/systm.h>
83 #include <sys/kernel.h>
84 #include <sys/malloc.h>
85 #include <sys/mbuf.h>
86 #include <sys/protosw.h>
87 #include <sys/socket.h>
88 #include <sys/sysctl.h>
89 
90 #include <net/pfil.h>
91 #include <net/if.h>
92 #include <net/if_types.h>
93 #include <net/if_var.h>
94 #include <net/if_dl.h>
95 #include <net/route.h>
96 
97 #include <netinet/in.h>
98 #include <netinet/in_systm.h>
99 #include <netinet/in_var.h>
100 #include <netinet/ip.h>
101 #include <netinet/ip_var.h>
102 #include <netinet/ip_icmp.h>
103 
104 #include <machine/in_cksum.h>
105 
106 static int ipfastforward_active = 0;
107 SYSCTL_INT(_net_inet_ip, OID_AUTO, fastforwarding, CTLFLAG_RW,
108     &ipfastforward_active, 0, "Enable fast IP forwarding");
109 
110 static struct sockaddr_in *
111 ip_findroute(struct route *ro, struct in_addr dest, struct mbuf *m)
112 {
113 	struct sockaddr_in *dst;
114 	struct rtentry *rt;
115 
116 	/*
117 	 * Find route to destination.
118 	 */
119 	bzero(ro, sizeof(*ro));
120 	dst = (struct sockaddr_in *)&ro->ro_dst;
121 	dst->sin_family = AF_INET;
122 	dst->sin_len = sizeof(*dst);
123 	dst->sin_addr.s_addr = dest.s_addr;
124 	rtalloc_ign(ro, RTF_CLONING);
125 
126 	/*
127 	 * Route there and interface still up?
128 	 */
129 	rt = ro->ro_rt;
130 	if (rt && (rt->rt_flags & RTF_UP) &&
131 	    (rt->rt_ifp->if_flags & IFF_UP) &&
132 	    (rt->rt_ifp->if_flags & IFF_RUNNING)) {
133 		if (rt->rt_flags & RTF_GATEWAY)
134 			dst = (struct sockaddr_in *)rt->rt_gateway;
135 	} else {
136 		ipstat.ips_noroute++;
137 		ipstat.ips_cantforward++;
138 		if (rt)
139 			RTFREE(rt);
140 		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, NULL);
141 		return NULL;
142 	}
143 	return dst;
144 }
145 
146 /*
147  * Try to forward a packet based on the destination address.
148  * This is a fast path optimized for the plain forwarding case.
149  * If the packet is handled (and consumed) here then we return 1;
150  * otherwise 0 is returned and the packet should be delivered
151  * to ip_input for full processing.
152  */
153 int
154 ip_fastforward(struct mbuf *m)
155 {
156 	struct ip *ip;
157 	struct mbuf *m0 = NULL;
158 	struct route ro;
159 	struct sockaddr_in *dst = NULL;
160 	struct in_ifaddr *ia = NULL;
161 	struct ifaddr *ifa = NULL;
162 	struct ifnet *ifp;
163 	struct in_addr odest, dest;
164 	u_short sum, ip_len;
165 	int error = 0;
166 	int hlen, mtu;
167 #ifdef IPFIREWALL_FORWARD
168 	struct m_tag *fwd_tag;
169 #endif
170 
171 	/*
172 	 * Are we active and forwarding packets?
173 	 */
174 	if (!ipfastforward_active || !ipforwarding)
175 		return 0;
176 
177 	M_ASSERTVALID(m);
178 	M_ASSERTPKTHDR(m);
179 
180 	ro.ro_rt = NULL;
181 
182 	/*
183 	 * Step 1: check for packet drop conditions (and sanity checks)
184 	 */
185 
186 	/*
187 	 * Is entire packet big enough?
188 	 */
189 	if (m->m_pkthdr.len < sizeof(struct ip)) {
190 		ipstat.ips_tooshort++;
191 		goto drop;
192 	}
193 
194 	/*
195 	 * Is first mbuf large enough for ip header and is header present?
196 	 */
197 	if (m->m_len < sizeof (struct ip) &&
198 	   (m = m_pullup(m, sizeof (struct ip))) == NULL) {
199 		ipstat.ips_toosmall++;
200 		return 1;	/* mbuf already free'd */
201 	}
202 
203 	ip = mtod(m, struct ip *);
204 
205 	/*
206 	 * Is it IPv4?
207 	 */
208 	if (ip->ip_v != IPVERSION) {
209 		ipstat.ips_badvers++;
210 		goto drop;
211 	}
212 
213 	/*
214 	 * Is IP header length correct and is it in first mbuf?
215 	 */
216 	hlen = ip->ip_hl << 2;
217 	if (hlen < sizeof(struct ip)) {	/* minimum header length */
218 		ipstat.ips_badlen++;
219 		goto drop;
220 	}
221 	if (hlen > m->m_len) {
222 		if ((m = m_pullup(m, hlen)) == 0) {
223 			ipstat.ips_badhlen++;
224 			return 1;
225 		}
226 		ip = mtod(m, struct ip *);
227 	}
228 
229 	/*
230 	 * Checksum correct?
231 	 */
232 	if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED)
233 		sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
234 	else {
235 		if (hlen == sizeof(struct ip))
236 			sum = in_cksum_hdr(ip);
237 		else
238 			sum = in_cksum(m, hlen);
239 	}
240 	if (sum) {
241 		ipstat.ips_badsum++;
242 		goto drop;
243 	}
244 
245 	/*
246 	 * Remeber that we have checked the IP header and found it valid.
247 	 */
248 	m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED | CSUM_IP_VALID);
249 
250 	ip_len = ntohs(ip->ip_len);
251 
252 	/*
253 	 * Is IP length longer than packet we have got?
254 	 */
255 	if (m->m_pkthdr.len < ip_len) {
256 		ipstat.ips_tooshort++;
257 		goto drop;
258 	}
259 
260 	/*
261 	 * Is packet longer than IP header tells us? If yes, truncate packet.
262 	 */
263 	if (m->m_pkthdr.len > ip_len) {
264 		if (m->m_len == m->m_pkthdr.len) {
265 			m->m_len = ip_len;
266 			m->m_pkthdr.len = ip_len;
267 		} else
268 			m_adj(m, ip_len - m->m_pkthdr.len);
269 	}
270 
271 	/*
272 	 * Is packet from or to 127/8?
273 	 */
274 	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
275 	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
276 		ipstat.ips_badaddr++;
277 		goto drop;
278 	}
279 
280 #ifdef ALTQ
281 	/*
282 	 * Is packet dropped by traffic conditioner?
283 	 */
284 	if (altq_input != NULL && (*altq_input)(m, AF_INET) == 0)
285 		return 1;
286 #endif
287 
288 	/*
289 	 * Step 2: fallback conditions to normal ip_input path processing
290 	 */
291 
292 	/*
293 	 * Only IP packets without options
294 	 */
295 	if (ip->ip_hl != (sizeof(struct ip) >> 2)) {
296 		if (ip_doopts == 1)
297 			return 0;
298 		else if (ip_doopts == 2) {
299 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_FILTER_PROHIB,
300 				0, NULL);
301 			return 1;
302 		}
303 		/* else ignore IP options and continue */
304 	}
305 
306 	/*
307 	 * Only unicast IP, not from loopback, no L2 or IP broadcast,
308 	 * no multicast, no INADDR_ANY
309 	 *
310 	 * XXX: Probably some of these checks could be direct drop
311 	 * conditions.  However it is not clear whether there are some
312 	 * hacks or obscure behaviours which make it neccessary to
313 	 * let ip_input handle it.  We play safe here and let ip_input
314 	 * deal with it until it is proven that we can directly drop it.
315 	 */
316 	if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) ||
317 	    ntohl(ip->ip_src.s_addr) == (u_long)INADDR_BROADCAST ||
318 	    ntohl(ip->ip_dst.s_addr) == (u_long)INADDR_BROADCAST ||
319 	    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
320 	    IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
321 	    ip->ip_dst.s_addr == INADDR_ANY )
322 		return 0;
323 
324 	/*
325 	 * Is it for a local address on this host?
326 	 */
327 	if (in_localip(ip->ip_dst))
328 		return 0;
329 
330 	/*
331 	 * Or is it for a local IP broadcast address on this host?
332 	 */
333 	if ((m->m_flags & M_BCAST) &&
334 	    (m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST)) {
335 	        TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
336 			if (ifa->ifa_addr->sa_family != AF_INET)
337 				continue;
338 			ia = ifatoia(ifa);
339 			if (ia->ia_netbroadcast.s_addr == ip->ip_dst.s_addr)
340 				return 0;
341 			if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
342 			    ip->ip_dst.s_addr)
343 				return 0;
344 		}
345 	}
346 	ipstat.ips_total++;
347 
348 	/*
349 	 * Step 3: incoming packet firewall processing
350 	 */
351 
352 	/*
353 	 * Convert to host representation
354 	 */
355 	ip->ip_len = ntohs(ip->ip_len);
356 	ip->ip_off = ntohs(ip->ip_off);
357 
358 	odest.s_addr = dest.s_addr = ip->ip_dst.s_addr;
359 
360 	/*
361 	 * Run through list of ipfilter hooks for input packets
362 	 */
363 	if (inet_pfil_hook.ph_busy_count == -1)
364 		goto passin;
365 
366 	if (pfil_run_hooks(&inet_pfil_hook, &m, m->m_pkthdr.rcvif, PFIL_IN, NULL) ||
367 	    m == NULL)
368 		return 1;
369 
370 	M_ASSERTVALID(m);
371 	M_ASSERTPKTHDR(m);
372 
373 	ip = mtod(m, struct ip *);	/* m may have changed by pfil hook */
374 	dest.s_addr = ip->ip_dst.s_addr;
375 
376 	/*
377 	 * Destination address changed?
378 	 */
379 	if (odest.s_addr != dest.s_addr) {
380 		/*
381 		 * Is it now for a local address on this host?
382 		 */
383 		if (in_localip(dest))
384 			goto forwardlocal;
385 		/*
386 		 * Go on with new destination address
387 		 */
388 	}
389 #ifdef IPFIREWALL_FORWARD
390 	if (m->m_flags & M_FASTFWD_OURS) {
391 		/*
392 		 * ipfw changed it for a local address on this host.
393 		 */
394 		goto forwardlocal;
395 	}
396 #endif /* IPFIREWALL_FORWARD */
397 
398 passin:
399 	/*
400 	 * Step 4: decrement TTL and look up route
401 	 */
402 
403 	/*
404 	 * Check TTL
405 	 */
406 #ifdef IPSTEALTH
407 	if (!ipstealth) {
408 #endif
409 	if (ip->ip_ttl <= IPTTLDEC) {
410 		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, 0, NULL);
411 		return 1;
412 	}
413 
414 	/*
415 	 * Decrement the TTL and incrementally change the IP header checksum.
416 	 * Don't bother doing this with hw checksum offloading, it's faster
417 	 * doing it right here.
418 	 */
419 	ip->ip_ttl -= IPTTLDEC;
420 	if (ip->ip_sum >= (u_int16_t) ~htons(IPTTLDEC << 8))
421 		ip->ip_sum -= ~htons(IPTTLDEC << 8);
422 	else
423 		ip->ip_sum += htons(IPTTLDEC << 8);
424 #ifdef IPSTEALTH
425 	}
426 #endif
427 
428 	/*
429 	 * Find route to destination.
430 	 */
431 	if ((dst = ip_findroute(&ro, dest, m)) == NULL)
432 		return 1;	/* icmp unreach already sent */
433 	ifp = ro.ro_rt->rt_ifp;
434 
435 	/*
436 	 * Immediately drop blackholed traffic.
437 	 */
438 	if (ro.ro_rt->rt_flags & RTF_BLACKHOLE)
439 		goto drop;
440 
441 	/*
442 	 * Step 5: outgoing firewall packet processing
443 	 */
444 
445 	/*
446 	 * Run through list of hooks for output packets.
447 	 */
448 	if (inet_pfil_hook.ph_busy_count == -1)
449 		goto passout;
450 
451 	if (pfil_run_hooks(&inet_pfil_hook, &m, ifp, PFIL_OUT, NULL) || m == NULL) {
452 		goto consumed;
453 	}
454 
455 	M_ASSERTVALID(m);
456 	M_ASSERTPKTHDR(m);
457 
458 	ip = mtod(m, struct ip *);
459 	dest.s_addr = ip->ip_dst.s_addr;
460 
461 	/*
462 	 * Destination address changed?
463 	 */
464 #ifndef IPFIREWALL_FORWARD
465 	if (odest.s_addr != dest.s_addr) {
466 #else
467 	fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
468 	if (odest.s_addr != dest.s_addr || fwd_tag != NULL) {
469 #endif /* IPFIREWALL_FORWARD */
470 		/*
471 		 * Is it now for a local address on this host?
472 		 */
473 #ifndef IPFIREWALL_FORWARD
474 		if (in_localip(dest)) {
475 #else
476 		if (m->m_flags & M_FASTFWD_OURS || in_localip(dest)) {
477 #endif /* IPFIREWALL_FORWARD */
478 forwardlocal:
479 			/*
480 			 * Return packet for processing by ip_input().
481 			 * Keep host byte order as expected at ip_input's
482 			 * "ours"-label.
483 			 */
484 			m->m_flags |= M_FASTFWD_OURS;
485 			if (ro.ro_rt)
486 				RTFREE(ro.ro_rt);
487 			return 0;
488 		}
489 		/*
490 		 * Redo route lookup with new destination address
491 		 */
492 #ifdef IPFIREWALL_FORWARD
493 		if (fwd_tag) {
494 			if (!in_localip(ip->ip_src) && !in_localaddr(ip->ip_dst))
495 				dest.s_addr = ((struct sockaddr_in *)(fwd_tag+1))->sin_addr.s_addr;
496 			m_tag_delete(m, fwd_tag);
497 		}
498 #endif /* IPFIREWALL_FORWARD */
499 		RTFREE(ro.ro_rt);
500 		if ((dst = ip_findroute(&ro, dest, m)) == NULL)
501 			return 1;	/* icmp unreach already sent */
502 		ifp = ro.ro_rt->rt_ifp;
503 	}
504 
505 passout:
506 	/*
507 	 * Step 6: send off the packet
508 	 */
509 
510 	/*
511 	 * Check if route is dampned (when ARP is unable to resolve)
512 	 */
513 	if ((ro.ro_rt->rt_flags & RTF_REJECT) &&
514 	    ro.ro_rt->rt_rmx.rmx_expire >= time_second) {
515 		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, NULL);
516 		goto consumed;
517 	}
518 
519 #ifndef ALTQ
520 	/*
521 	 * Check if there is enough space in the interface queue
522 	 */
523 	if ((ifp->if_snd.ifq_len + ip->ip_len / ifp->if_mtu + 1) >=
524 	    ifp->if_snd.ifq_maxlen) {
525 		ipstat.ips_odropped++;
526 		/* would send source quench here but that is depreciated */
527 		goto drop;
528 	}
529 #endif
530 
531 	/*
532 	 * Check if media link state of interface is not down
533 	 */
534 	if (ifp->if_link_state == LINK_STATE_DOWN) {
535 		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, NULL);
536 		goto consumed;
537 	}
538 
539 	/*
540 	 * Check if packet fits MTU or if hardware will fragement for us
541 	 */
542 	if (ro.ro_rt->rt_rmx.rmx_mtu)
543 		mtu = min(ro.ro_rt->rt_rmx.rmx_mtu, ifp->if_mtu);
544 	else
545 		mtu = ifp->if_mtu;
546 
547 	if (ip->ip_len <= mtu ||
548 	    (ifp->if_hwassist & CSUM_FRAGMENT && (ip->ip_off & IP_DF) == 0)) {
549 		/*
550 		 * Restore packet header fields to original values
551 		 */
552 		ip->ip_len = htons(ip->ip_len);
553 		ip->ip_off = htons(ip->ip_off);
554 		/*
555 		 * Send off the packet via outgoing interface
556 		 */
557 		error = (*ifp->if_output)(ifp, m,
558 				(struct sockaddr *)dst, ro.ro_rt);
559 	} else {
560 		/*
561 		 * Handle EMSGSIZE with icmp reply needfrag for TCP MTU discovery
562 		 */
563 		if (ip->ip_off & IP_DF) {
564 			ipstat.ips_cantfrag++;
565 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG,
566 				0, ifp);
567 			goto consumed;
568 		} else {
569 			/*
570 			 * We have to fragement the packet
571 			 */
572 			m->m_pkthdr.csum_flags |= CSUM_IP;
573 			/*
574 			 * ip_fragment expects ip_len and ip_off in host byte
575 			 * order but returns all packets in network byte order
576 			 */
577 			if (ip_fragment(ip, &m, mtu, ifp->if_hwassist,
578 					(~ifp->if_hwassist & CSUM_DELAY_IP))) {
579 				goto drop;
580 			}
581 			KASSERT(m != NULL, ("null mbuf and no error"));
582 			/*
583 			 * Send off the fragments via outgoing interface
584 			 */
585 			error = 0;
586 			do {
587 				m0 = m->m_nextpkt;
588 				m->m_nextpkt = NULL;
589 
590 				error = (*ifp->if_output)(ifp, m,
591 					(struct sockaddr *)dst, ro.ro_rt);
592 				if (error)
593 					break;
594 			} while ((m = m0) != NULL);
595 			if (error) {
596 				/* Reclaim remaining fragments */
597 				for (; m; m = m0) {
598 					m0 = m->m_nextpkt;
599 					m->m_nextpkt = NULL;
600 					m_freem(m);
601 				}
602 			} else
603 				ipstat.ips_fragmented++;
604 		}
605 	}
606 
607 	if (error != 0)
608 		ipstat.ips_odropped++;
609 	else {
610 		ro.ro_rt->rt_rmx.rmx_pksent++;
611 		ipstat.ips_forward++;
612 		ipstat.ips_fastforward++;
613 	}
614 consumed:
615 	RTFREE(ro.ro_rt);
616 	return 1;
617 drop:
618 	if (m)
619 		m_freem(m);
620 	if (ro.ro_rt)
621 		RTFREE(ro.ro_rt);
622 	return 1;
623 }
624