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