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