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