xref: /freebsd/sys/netinet/ip_fastfwd.c (revision 942815c54820783d3d4f7f6faa71ab7919b5f0e5)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2003 Andre Oppermann, Internet Business Solutions AG
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote
16  *    products derived from this software without specific prior written
17  *    permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
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 
65 /*
66  * Many thanks to Matt Thomas of NetBSD for basic structure of ip_flow.c which
67  * is being followed here.
68  */
69 
70 #include <sys/cdefs.h>
71 __FBSDID("$FreeBSD$");
72 
73 #include "opt_ipstealth.h"
74 
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/kernel.h>
78 #include <sys/malloc.h>
79 #include <sys/mbuf.h>
80 #include <sys/protosw.h>
81 #include <sys/sdt.h>
82 #include <sys/socket.h>
83 #include <sys/sysctl.h>
84 
85 #include <net/if.h>
86 #include <net/if_types.h>
87 #include <net/if_var.h>
88 #include <net/if_dl.h>
89 #include <net/if_private.h>
90 #include <net/pfil.h>
91 #include <net/route.h>
92 #include <net/route/nhop.h>
93 #include <net/vnet.h>
94 
95 #include <netinet/in.h>
96 #include <netinet/in_fib.h>
97 #include <netinet/in_kdtrace.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 #include <netinet/ip_options.h>
104 
105 #include <machine/in_cksum.h>
106 
107 #define	V_ipsendredirects	VNET(ipsendredirects)
108 
109 static struct mbuf *
110 ip_redir_alloc(struct mbuf *m, struct nhop_object *nh, u_short ip_len,
111     struct in_addr *osrc, struct in_addr *newgw)
112 {
113 	struct in_ifaddr *nh_ia;
114 	struct mbuf *mcopy;
115 
116 	KASSERT(nh != NULL, ("%s: m %p nh is NULL\n", __func__, m));
117 
118 	/*
119 	 * Only send a redirect if:
120 	 * - Redirects are not disabled (must be checked by caller),
121 	 * - We have not applied NAT (must be checked by caller as possible),
122 	 * - Neither a MCAST or BCAST packet (must be checked by caller)
123 	 *   [RFC1009 Appendix A.2].
124 	 * - The packet does not do IP source routing or having any other
125 	 *   IP options (this case was handled already by ip_input() calling
126 	 *   ip_dooptions() [RFC792, p13],
127 	 * - The packet is being forwarded out the same physical interface
128 	 *   that it was received from [RFC1812, 5.2.7.2].
129 	 */
130 
131 	/*
132 	 * - The forwarding route was not created by a redirect
133 	 *   [RFC1812, 5.2.7.2], or
134 	 *   if it was to follow a default route (see below).
135 	 * - The next-hop is reachable by us [RFC1009 Appendix A.2].
136 	 */
137 	if ((nh->nh_flags & (NHF_DEFAULT | NHF_REDIRECT |
138 	    NHF_BLACKHOLE | NHF_REJECT)) != 0)
139 		return (NULL);
140 
141 	/* Get the new gateway. */
142 	if ((nh->nh_flags & NHF_GATEWAY) == 0 || nh->gw_sa.sa_family != AF_INET)
143 		return (NULL);
144 	newgw->s_addr = nh->gw4_sa.sin_addr.s_addr;
145 
146 	/*
147 	 * - The resulting forwarding destination is not "This host on this
148 	 *   network" [RFC1122, Section 3.2.1.3] (default route check above).
149 	 */
150 	if (newgw->s_addr == 0)
151 		return (NULL);
152 
153 	/*
154 	 * - We know how to reach the sender and the source address is
155 	 *   directly connected to us [RFC792, p13].
156 	 * + The new gateway address and the source address are on the same
157 	 *   subnet [RFC1009 Appendix A.2, RFC1122 3.2.2.2, RFC1812, 5.2.7.2].
158 	 * NB: if you think multiple logical subnets on the same wire should
159 	 *     receive redirects read [RFC1812, APPENDIX C (14->15)].
160 	 */
161 	nh_ia = (struct in_ifaddr *)nh->nh_ifa;
162 	if ((ntohl(osrc->s_addr) & nh_ia->ia_subnetmask) != nh_ia->ia_subnet)
163 		return (NULL);
164 
165 	/* Prepare for sending the redirect. */
166 
167 	/*
168 	 * Make a copy of as much as we need of the packet as the original
169 	 * one will be forwarded but we need (a portion) for icmp_error().
170 	 */
171 	mcopy = m_gethdr(M_NOWAIT, m->m_type);
172 	if (mcopy == NULL)
173 		return (NULL);
174 
175 	if (m_dup_pkthdr(mcopy, m, M_NOWAIT) == 0) {
176 		/*
177 		 * It's probably ok if the pkthdr dup fails (because
178 		 * the deep copy of the tag chain failed), but for now
179 		 * be conservative and just discard the copy since
180 		 * code below may some day want the tags.
181 		 */
182 		m_free(mcopy);
183 		return (NULL);
184 	}
185 	mcopy->m_len = min(ip_len, M_TRAILINGSPACE(mcopy));
186 	mcopy->m_pkthdr.len = mcopy->m_len;
187 	m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
188 
189 	return (mcopy);
190 }
191 
192 
193 static int
194 ip_findroute(struct nhop_object **pnh, struct in_addr dest, struct mbuf *m)
195 {
196 	struct nhop_object *nh;
197 
198 	nh = fib4_lookup(M_GETFIB(m), dest, 0, NHR_NONE,
199 	    m->m_pkthdr.flowid);
200 	if (nh == NULL) {
201 		IPSTAT_INC(ips_noroute);
202 		IPSTAT_INC(ips_cantforward);
203 		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
204 		return (EHOSTUNREACH);
205 	}
206 	/*
207 	 * Drop blackholed traffic and directed broadcasts.
208 	 */
209 	if ((nh->nh_flags & (NHF_BLACKHOLE | NHF_BROADCAST)) != 0) {
210 		IPSTAT_INC(ips_cantforward);
211 		m_freem(m);
212 		return (EHOSTUNREACH);
213 	}
214 
215 	if (nh->nh_flags & NHF_REJECT) {
216 		IPSTAT_INC(ips_cantforward);
217 		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
218 		return (EHOSTUNREACH);
219 	}
220 
221 	*pnh = nh;
222 
223 	return (0);
224 }
225 
226 /*
227  * Try to forward a packet based on the destination address.
228  * This is a fast path optimized for the plain forwarding case.
229  * If the packet is handled (and consumed) here then we return NULL;
230  * otherwise mbuf is returned and the packet should be delivered
231  * to ip_input for full processing.
232  */
233 struct mbuf *
234 ip_tryforward(struct mbuf *m)
235 {
236 	struct ip *ip;
237 	struct mbuf *m0 = NULL;
238 	struct nhop_object *nh = NULL;
239 	struct route ro;
240 	struct sockaddr_in *dst;
241 	const struct sockaddr *gw;
242 	struct in_addr dest, odest, rtdest, osrc;
243 	uint16_t ip_len, ip_off;
244 	int error = 0;
245 	struct m_tag *fwd_tag = NULL;
246 	struct mbuf *mcopy = NULL;
247 	struct in_addr redest;
248 	/*
249 	 * Are we active and forwarding packets?
250 	 */
251 
252 	M_ASSERTVALID(m);
253 	M_ASSERTPKTHDR(m);
254 
255 	/*
256 	 * Only IP packets without options
257 	 */
258 	ip = mtod(m, struct ip *);
259 
260 	if (ip->ip_hl != (sizeof(struct ip) >> 2)) {
261 		if (V_ip_doopts == 1)
262 			return m;
263 		else if (V_ip_doopts == 2) {
264 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_FILTER_PROHIB,
265 				0, 0);
266 			return NULL;	/* mbuf already free'd */
267 		}
268 		/* else ignore IP options and continue */
269 	}
270 
271 	/*
272 	 * Only unicast IP, not from loopback, no L2 or IP broadcast,
273 	 * no multicast, no INADDR_ANY
274 	 *
275 	 * XXX: Probably some of these checks could be direct drop
276 	 * conditions.  However it is not clear whether there are some
277 	 * hacks or obscure behaviours which make it necessary to
278 	 * let ip_input handle it.  We play safe here and let ip_input
279 	 * deal with it until it is proven that we can directly drop it.
280 	 */
281 	if ((m->m_flags & (M_BCAST|M_MCAST)) ||
282 	    (m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) ||
283 	    ntohl(ip->ip_src.s_addr) == (u_long)INADDR_BROADCAST ||
284 	    ntohl(ip->ip_dst.s_addr) == (u_long)INADDR_BROADCAST ||
285 	    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
286 	    IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
287 	    IN_LINKLOCAL(ntohl(ip->ip_src.s_addr)) ||
288 	    IN_LINKLOCAL(ntohl(ip->ip_dst.s_addr)) ||
289 	    ip->ip_src.s_addr == INADDR_ANY ||
290 	    ip->ip_dst.s_addr == INADDR_ANY )
291 		return m;
292 
293 	/*
294 	 * Is it for a local address on this host?
295 	 */
296 	if (in_localip(ip->ip_dst))
297 		return m;
298 
299 	IPSTAT_INC(ips_total);
300 
301 	/*
302 	 * Step 3: incoming packet firewall processing
303 	 */
304 
305 	odest.s_addr = dest.s_addr = ip->ip_dst.s_addr;
306 	osrc.s_addr = ip->ip_src.s_addr;
307 
308 	/*
309 	 * Run through list of ipfilter hooks for input packets
310 	 */
311 	if (!PFIL_HOOKED_IN(V_inet_pfil_head))
312 		goto passin;
313 
314 	if (pfil_mbuf_in(V_inet_pfil_head, &m, m->m_pkthdr.rcvif,
315 	    NULL) != PFIL_PASS)
316 		goto drop;
317 
318 	M_ASSERTVALID(m);
319 	M_ASSERTPKTHDR(m);
320 
321 	ip = mtod(m, struct ip *);	/* m may have changed by pfil hook */
322 	dest.s_addr = ip->ip_dst.s_addr;
323 
324 	/*
325 	 * Destination address changed?
326 	 */
327 	if (odest.s_addr != dest.s_addr) {
328 		/*
329 		 * Is it now for a local address on this host?
330 		 */
331 		if (in_localip(dest))
332 			goto forwardlocal;
333 		/*
334 		 * Go on with new destination address
335 		 */
336 	}
337 
338 	if (m->m_flags & M_FASTFWD_OURS) {
339 		/*
340 		 * ipfw changed it for a local address on this host.
341 		 */
342 		goto forwardlocal;
343 	}
344 
345 passin:
346 	/*
347 	 * Step 4: decrement TTL and look up route
348 	 */
349 
350 	/*
351 	 * Check TTL
352 	 */
353 #ifdef IPSTEALTH
354 	if (!V_ipstealth) {
355 #endif
356 	if (ip->ip_ttl <= IPTTLDEC) {
357 		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, 0, 0);
358 		return NULL;	/* mbuf already free'd */
359 	}
360 
361 	/*
362 	 * Decrement the TTL and incrementally change the IP header checksum.
363 	 * Don't bother doing this with hw checksum offloading, it's faster
364 	 * doing it right here.
365 	 */
366 	ip->ip_ttl -= IPTTLDEC;
367 	if (ip->ip_sum >= (u_int16_t) ~htons(IPTTLDEC << 8))
368 		ip->ip_sum -= ~htons(IPTTLDEC << 8);
369 	else
370 		ip->ip_sum += htons(IPTTLDEC << 8);
371 #ifdef IPSTEALTH
372 	}
373 #endif
374 
375 	/*
376 	 * Next hop forced by pfil(9) hook?
377 	 */
378 	if ((m->m_flags & M_IP_NEXTHOP) &&
379 	    ((fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL)) != NULL)) {
380 		/*
381 		 * Now we will find route to forced destination.
382 		 */
383 		dest.s_addr = ((struct sockaddr_in *)
384 			    (fwd_tag + 1))->sin_addr.s_addr;
385 		m_tag_delete(m, fwd_tag);
386 		m->m_flags &= ~M_IP_NEXTHOP;
387 	}
388 
389 	/*
390 	 * Find route to destination.
391 	 */
392 	if (ip_findroute(&nh, dest, m) != 0)
393 		return (NULL);	/* icmp unreach already sent */
394 
395 	/*
396 	 * Avoid second route lookup by caching destination.
397 	 */
398 	rtdest.s_addr = dest.s_addr;
399 
400 	/*
401 	 * Step 5: outgoing firewall packet processing
402 	 */
403 	if (!PFIL_HOOKED_OUT(V_inet_pfil_head))
404 		goto passout;
405 
406 	if (pfil_mbuf_out(V_inet_pfil_head, &m, nh->nh_ifp,
407 	    NULL) != PFIL_PASS)
408 		goto drop;
409 
410 	M_ASSERTVALID(m);
411 	M_ASSERTPKTHDR(m);
412 
413 	ip = mtod(m, struct ip *);
414 	dest.s_addr = ip->ip_dst.s_addr;
415 
416 	/*
417 	 * Destination address changed?
418 	 */
419 	if (m->m_flags & M_IP_NEXTHOP)
420 		fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
421 	else
422 		fwd_tag = NULL;
423 	if (odest.s_addr != dest.s_addr || fwd_tag != NULL) {
424 		/*
425 		 * Is it now for a local address on this host?
426 		 */
427 		if (m->m_flags & M_FASTFWD_OURS || in_localip(dest)) {
428 forwardlocal:
429 			/*
430 			 * Return packet for processing by ip_input().
431 			 */
432 			m->m_flags |= M_FASTFWD_OURS;
433 			return (m);
434 		}
435 		/*
436 		 * Redo route lookup with new destination address
437 		 */
438 		if (fwd_tag) {
439 			dest.s_addr = ((struct sockaddr_in *)
440 				    (fwd_tag + 1))->sin_addr.s_addr;
441 			m_tag_delete(m, fwd_tag);
442 			m->m_flags &= ~M_IP_NEXTHOP;
443 		}
444 		if (dest.s_addr != rtdest.s_addr &&
445 		    ip_findroute(&nh, dest, m) != 0)
446 			return (NULL);	/* icmp unreach already sent */
447 	}
448 
449 passout:
450 	/*
451 	 * Step 6: send off the packet
452 	 */
453 	ip_len = ntohs(ip->ip_len);
454 	ip_off = ntohs(ip->ip_off);
455 
456 	bzero(&ro, sizeof(ro));
457 	dst = (struct sockaddr_in *)&ro.ro_dst;
458 	dst->sin_family = AF_INET;
459 	dst->sin_len = sizeof(*dst);
460 	dst->sin_addr = dest;
461 	if (nh->nh_flags & NHF_GATEWAY) {
462 		gw = &nh->gw_sa;
463 		ro.ro_flags |= RT_HAS_GW;
464 	} else
465 		gw = (const struct sockaddr *)dst;
466 
467 	/* Handle redirect case. */
468 	redest.s_addr = 0;
469 	if (V_ipsendredirects && osrc.s_addr == ip->ip_src.s_addr &&
470 	    nh->nh_ifp == m->m_pkthdr.rcvif)
471 		mcopy = ip_redir_alloc(m, nh, ip_len, &osrc, &redest);
472 
473 	/*
474 	 * Check if packet fits MTU or if hardware will fragment for us
475 	 */
476 	if (ip_len <= nh->nh_mtu) {
477 		/*
478 		 * Avoid confusing lower layers.
479 		 */
480 		m_clrprotoflags(m);
481 		/*
482 		 * Send off the packet via outgoing interface
483 		 */
484 		IP_PROBE(send, NULL, NULL, ip, nh->nh_ifp, ip, NULL);
485 		error = (*nh->nh_ifp->if_output)(nh->nh_ifp, m, gw, &ro);
486 	} else {
487 		/*
488 		 * Handle EMSGSIZE with icmp reply needfrag for TCP MTU discovery
489 		 */
490 		if (ip_off & IP_DF) {
491 			IPSTAT_INC(ips_cantfrag);
492 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG,
493 				0, nh->nh_mtu);
494 			goto consumed;
495 		} else {
496 			/*
497 			 * We have to fragment the packet
498 			 */
499 			m->m_pkthdr.csum_flags |= CSUM_IP;
500 			if (ip_fragment(ip, &m, nh->nh_mtu,
501 			    nh->nh_ifp->if_hwassist) != 0)
502 				goto drop;
503 			KASSERT(m != NULL, ("null mbuf and no error"));
504 			/*
505 			 * Send off the fragments via outgoing interface
506 			 */
507 			error = 0;
508 			do {
509 				m0 = m->m_nextpkt;
510 				m->m_nextpkt = NULL;
511 				/*
512 				 * Avoid confusing lower layers.
513 				 */
514 				m_clrprotoflags(m);
515 
516 				IP_PROBE(send, NULL, NULL,
517 				    mtod(m, struct ip *), nh->nh_ifp,
518 				    mtod(m, struct ip *), NULL);
519 				error = (*nh->nh_ifp->if_output)(nh->nh_ifp, m,
520 				    gw, &ro);
521 				if (error)
522 					break;
523 			} while ((m = m0) != NULL);
524 			if (error) {
525 				/* Reclaim remaining fragments */
526 				for (m = m0; m; m = m0) {
527 					m0 = m->m_nextpkt;
528 					m_freem(m);
529 				}
530 			} else
531 				IPSTAT_INC(ips_fragmented);
532 		}
533 	}
534 
535 	if (error != 0)
536 		IPSTAT_INC(ips_odropped);
537 	else {
538 		IPSTAT_INC(ips_forward);
539 		IPSTAT_INC(ips_fastforward);
540 	}
541 
542 	/* Send required redirect */
543 	if (mcopy != NULL) {
544 		icmp_error(mcopy, ICMP_REDIRECT, ICMP_REDIRECT_HOST, redest.s_addr, 0);
545 		mcopy = NULL; /* Was consumed by callee. */
546 	}
547 
548 consumed:
549 	if (mcopy != NULL)
550 		m_freem(mcopy);
551 	return NULL;
552 drop:
553 	if (m)
554 		m_freem(m);
555 	return NULL;
556 }
557