xref: /freebsd/sys/netinet6/frag6.c (revision 9af6c78cd43b18e169f10802142c61638bd62bed)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  * Copyright (c) 2019 Netflix, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	$KAME: frag6.c,v 1.33 2002/01/07 11:34:48 kjc Exp $
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include "opt_rss.h"
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/domain.h>
43 #include <sys/eventhandler.h>
44 #include <sys/hash.h>
45 #include <sys/kernel.h>
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/protosw.h>
49 #include <sys/queue.h>
50 #include <sys/socket.h>
51 #include <sys/sysctl.h>
52 #include <sys/syslog.h>
53 
54 #include <net/if.h>
55 #include <net/if_var.h>
56 #include <net/netisr.h>
57 #include <net/route.h>
58 #include <net/vnet.h>
59 
60 #include <netinet/in.h>
61 #include <netinet/in_var.h>
62 #include <netinet/ip6.h>
63 #include <netinet6/ip6_var.h>
64 #include <netinet/icmp6.h>
65 #include <netinet/in_systm.h>	/* For ECN definitions. */
66 #include <netinet/ip.h>		/* For ECN definitions. */
67 
68 #ifdef MAC
69 #include <security/mac/mac_framework.h>
70 #endif
71 
72 /*
73  * A "big picture" of how IPv6 fragment queues are all linked together.
74  *
75  * struct ip6qbucket ip6qb[...];			hashed buckets
76  * ||||||||
77  * |
78  * +--- TAILQ(struct ip6q, packets) *q6;		tailq entries holding
79  *      ||||||||					fragmented packets
80  *      |						(1 per original packet)
81  *      |
82  *      +--- TAILQ(struct ip6asfrag, ip6q_frags) *af6;	tailq entries of IPv6
83  *           |                                   *ip6af;fragment packets
84  *           |						for one original packet
85  *           + *mbuf
86  */
87 
88 /* Reassembly headers are stored in hash buckets. */
89 #define	IP6REASS_NHASH_LOG2	10
90 #define	IP6REASS_NHASH		(1 << IP6REASS_NHASH_LOG2)
91 #define	IP6REASS_HMASK		(IP6REASS_NHASH - 1)
92 
93 TAILQ_HEAD(ip6qhead, ip6q);
94 struct ip6qbucket {
95 	struct ip6qhead	packets;
96 	struct mtx	lock;
97 	int		count;
98 };
99 
100 struct ip6asfrag {
101 	TAILQ_ENTRY(ip6asfrag) ip6af_tq;
102 	struct mbuf	*ip6af_m;
103 	int		ip6af_offset;	/* Offset in ip6af_m to next header. */
104 	int		ip6af_frglen;	/* Fragmentable part length. */
105 	int		ip6af_off;	/* Fragment offset. */
106 	bool		ip6af_mff;	/* More fragment bit in frag off. */
107 };
108 
109 static MALLOC_DEFINE(M_FRAG6, "frag6", "IPv6 fragment reassembly header");
110 
111 #ifdef VIMAGE
112 /* A flag to indicate if IPv6 fragmentation is initialized. */
113 VNET_DEFINE_STATIC(bool,		frag6_on);
114 #define	V_frag6_on			VNET(frag6_on)
115 #endif
116 
117 /* System wide (global) maximum and count of packets in reassembly queues. */
118 static int ip6_maxfrags;
119 static volatile u_int frag6_nfrags = 0;
120 
121 /* Maximum and current packets in per-VNET reassembly queue. */
122 VNET_DEFINE_STATIC(int,			ip6_maxfragpackets);
123 VNET_DEFINE_STATIC(volatile u_int,	frag6_nfragpackets);
124 #define	V_ip6_maxfragpackets		VNET(ip6_maxfragpackets)
125 #define	V_frag6_nfragpackets		VNET(frag6_nfragpackets)
126 
127 /* Maximum per-VNET reassembly queues per bucket and fragments per packet. */
128 VNET_DEFINE_STATIC(int,			ip6_maxfragbucketsize);
129 VNET_DEFINE_STATIC(int,			ip6_maxfragsperpacket);
130 #define	V_ip6_maxfragbucketsize		VNET(ip6_maxfragbucketsize)
131 #define	V_ip6_maxfragsperpacket		VNET(ip6_maxfragsperpacket)
132 
133 /* Per-VNET reassembly queue buckets. */
134 VNET_DEFINE_STATIC(struct ip6qbucket,	ip6qb[IP6REASS_NHASH]);
135 VNET_DEFINE_STATIC(uint32_t,		ip6qb_hashseed);
136 #define	V_ip6qb				VNET(ip6qb)
137 #define	V_ip6qb_hashseed		VNET(ip6qb_hashseed)
138 
139 #define	IP6QB_LOCK(_b)		mtx_lock(&V_ip6qb[(_b)].lock)
140 #define	IP6QB_TRYLOCK(_b)	mtx_trylock(&V_ip6qb[(_b)].lock)
141 #define	IP6QB_LOCK_ASSERT(_b)	mtx_assert(&V_ip6qb[(_b)].lock, MA_OWNED)
142 #define	IP6QB_UNLOCK(_b)	mtx_unlock(&V_ip6qb[(_b)].lock)
143 #define	IP6QB_HEAD(_b)		(&V_ip6qb[(_b)].packets)
144 
145 /*
146  * By default, limit the number of IP6 fragments across all reassembly
147  * queues to  1/32 of the total number of mbuf clusters.
148  *
149  * Limit the total number of reassembly queues per VNET to the
150  * IP6 fragment limit, but ensure the limit will not allow any bucket
151  * to grow above 100 items. (The bucket limit is
152  * IP_MAXFRAGPACKETS / (IPREASS_NHASH / 2), so the 50 is the correct
153  * multiplier to reach a 100-item limit.)
154  * The 100-item limit was chosen as brief testing seems to show that
155  * this produces "reasonable" performance on some subset of systems
156  * under DoS attack.
157  */
158 #define	IP6_MAXFRAGS		(nmbclusters / 32)
159 #define	IP6_MAXFRAGPACKETS	(imin(IP6_MAXFRAGS, IP6REASS_NHASH * 50))
160 
161 
162 /*
163  * Sysctls and helper function.
164  */
165 SYSCTL_DECL(_net_inet6_ip6);
166 
167 SYSCTL_UINT(_net_inet6_ip6, OID_AUTO, frag6_nfrags,
168 	CTLFLAG_RD, __DEVOLATILE(u_int *, &frag6_nfrags), 0,
169 	"Global number of IPv6 fragments across all reassembly queues.");
170 
171 static void
172 frag6_set_bucketsize(void)
173 {
174 	int i;
175 
176 	if ((i = V_ip6_maxfragpackets) > 0)
177 		V_ip6_maxfragbucketsize = imax(i / (IP6REASS_NHASH / 2), 1);
178 }
179 
180 SYSCTL_INT(_net_inet6_ip6, IPV6CTL_MAXFRAGS, maxfrags,
181 	CTLFLAG_RW, &ip6_maxfrags, 0,
182 	"Maximum allowed number of outstanding IPv6 packet fragments. "
183 	"A value of 0 means no fragmented packets will be accepted, while a "
184 	"a value of -1 means no limit");
185 
186 static int
187 sysctl_ip6_maxfragpackets(SYSCTL_HANDLER_ARGS)
188 {
189 	int error, val;
190 
191 	val = V_ip6_maxfragpackets;
192 	error = sysctl_handle_int(oidp, &val, 0, req);
193 	if (error != 0 || !req->newptr)
194 		return (error);
195 	V_ip6_maxfragpackets = val;
196 	frag6_set_bucketsize();
197 	return (0);
198 }
199 SYSCTL_PROC(_net_inet6_ip6, IPV6CTL_MAXFRAGPACKETS, maxfragpackets,
200 	CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW, NULL, 0,
201 	sysctl_ip6_maxfragpackets, "I",
202 	"Default maximum number of outstanding fragmented IPv6 packets. "
203 	"A value of 0 means no fragmented packets will be accepted, while a "
204 	"a value of -1 means no limit");
205 SYSCTL_UINT(_net_inet6_ip6, OID_AUTO, frag6_nfragpackets,
206 	CTLFLAG_VNET | CTLFLAG_RD,
207 	__DEVOLATILE(u_int *, &VNET_NAME(frag6_nfragpackets)), 0,
208 	"Per-VNET number of IPv6 fragments across all reassembly queues.");
209 SYSCTL_INT(_net_inet6_ip6, IPV6CTL_MAXFRAGSPERPACKET, maxfragsperpacket,
210 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_maxfragsperpacket), 0,
211 	"Maximum allowed number of fragments per packet");
212 SYSCTL_INT(_net_inet6_ip6, IPV6CTL_MAXFRAGBUCKETSIZE, maxfragbucketsize,
213 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_maxfragbucketsize), 0,
214 	"Maximum number of reassembly queues per hash bucket");
215 
216 
217 /*
218  * Remove the IPv6 fragmentation header from the mbuf.
219  */
220 int
221 ip6_deletefraghdr(struct mbuf *m, int offset, int wait __unused)
222 {
223 	struct ip6_hdr *ip6;
224 
225 	KASSERT(m->m_len >= offset + sizeof(struct ip6_frag),
226 	    ("%s: ext headers not contigous in mbuf %p m_len %d >= "
227 	    "offset %d + %zu\n", __func__, m, m->m_len, offset,
228 	    sizeof(struct ip6_frag)));
229 
230 	/* Delete frag6 header. */
231 	ip6 = mtod(m, struct ip6_hdr *);
232 	bcopy(ip6, (char *)ip6 + sizeof(struct ip6_frag), offset);
233 	m->m_data += sizeof(struct ip6_frag);
234 	m->m_len -= sizeof(struct ip6_frag);
235 	m->m_flags |= M_FRAGMENTED;
236 
237 	return (0);
238 }
239 
240 /*
241  * Free a fragment reassembly header and all associated datagrams.
242  */
243 static void
244 frag6_freef(struct ip6q *q6, uint32_t bucket)
245 {
246 	struct ip6_hdr *ip6;
247 	struct ip6asfrag *af6;
248 	struct mbuf *m;
249 
250 	IP6QB_LOCK_ASSERT(bucket);
251 
252 	while ((af6 = TAILQ_FIRST(&q6->ip6q_frags)) != NULL) {
253 
254 		m = af6->ip6af_m;
255 		TAILQ_REMOVE(&q6->ip6q_frags, af6, ip6af_tq);
256 
257 		/*
258 		 * Return ICMP time exceeded error for the 1st fragment.
259 		 * Just free other fragments.
260 		 */
261 		if (af6->ip6af_off == 0 && m->m_pkthdr.rcvif != NULL) {
262 
263 			/* Adjust pointer. */
264 			ip6 = mtod(m, struct ip6_hdr *);
265 
266 			/* Restore source and destination addresses. */
267 			ip6->ip6_src = q6->ip6q_src;
268 			ip6->ip6_dst = q6->ip6q_dst;
269 
270 			icmp6_error(m, ICMP6_TIME_EXCEEDED,
271 			    ICMP6_TIME_EXCEED_REASSEMBLY, 0);
272 		} else
273 			m_freem(m);
274 
275 		free(af6, M_FRAG6);
276 	}
277 
278 	TAILQ_REMOVE(IP6QB_HEAD(bucket), q6, ip6q_tq);
279 	V_ip6qb[bucket].count--;
280 	atomic_subtract_int(&frag6_nfrags, q6->ip6q_nfrag);
281 #ifdef MAC
282 	mac_ip6q_destroy(q6);
283 #endif
284 	free(q6, M_FRAG6);
285 	atomic_subtract_int(&V_frag6_nfragpackets, 1);
286 }
287 
288 /*
289  * Drain off all datagram fragments belonging to
290  * the given network interface.
291  */
292 static void
293 frag6_cleanup(void *arg __unused, struct ifnet *ifp)
294 {
295 	struct ip6qhead *head;
296 	struct ip6q *q6;
297 	struct ip6asfrag *af6;
298 	uint32_t bucket;
299 
300 	KASSERT(ifp != NULL, ("%s: ifp is NULL", __func__));
301 
302 	CURVNET_SET_QUIET(ifp->if_vnet);
303 #ifdef VIMAGE
304 	/*
305 	 * Skip processing if IPv6 reassembly is not initialised or
306 	 * torn down by frag6_destroy().
307 	 */
308 	if (!V_frag6_on) {
309 		CURVNET_RESTORE();
310 		return;
311 	}
312 #endif
313 
314 	for (bucket = 0; bucket < IP6REASS_NHASH; bucket++) {
315 		IP6QB_LOCK(bucket);
316 		head = IP6QB_HEAD(bucket);
317 		/* Scan fragment list. */
318 		TAILQ_FOREACH(q6, head, ip6q_tq) {
319 			TAILQ_FOREACH(af6, &q6->ip6q_frags, ip6af_tq) {
320 
321 				/* Clear no longer valid rcvif pointer. */
322 				if (af6->ip6af_m->m_pkthdr.rcvif == ifp)
323 					af6->ip6af_m->m_pkthdr.rcvif = NULL;
324 			}
325 		}
326 		IP6QB_UNLOCK(bucket);
327 	}
328 	CURVNET_RESTORE();
329 }
330 EVENTHANDLER_DEFINE(ifnet_departure_event, frag6_cleanup, NULL, 0);
331 
332 /*
333  * Like in RFC2460, in RFC8200, fragment and reassembly rules do not agree with
334  * each other, in terms of next header field handling in fragment header.
335  * While the sender will use the same value for all of the fragmented packets,
336  * receiver is suggested not to check for consistency.
337  *
338  * Fragment rules (p18,p19):
339  *	(2)  A Fragment header containing:
340  *	The Next Header value that identifies the first header
341  *	after the Per-Fragment headers of the original packet.
342  *		-> next header field is same for all fragments
343  *
344  * Reassembly rule (p20):
345  *	The Next Header field of the last header of the Per-Fragment
346  *	headers is obtained from the Next Header field of the first
347  *	fragment's Fragment header.
348  *		-> should grab it from the first fragment only
349  *
350  * The following note also contradicts with fragment rule - no one is going to
351  * send different fragment with different next header field.
352  *
353  * Additional note (p22) [not an error]:
354  *	The Next Header values in the Fragment headers of different
355  *	fragments of the same original packet may differ.  Only the value
356  *	from the Offset zero fragment packet is used for reassembly.
357  *		-> should grab it from the first fragment only
358  *
359  * There is no explicit reason given in the RFC.  Historical reason maybe?
360  */
361 /*
362  * Fragment input.
363  */
364 int
365 frag6_input(struct mbuf **mp, int *offp, int proto)
366 {
367 	struct mbuf *m, *t;
368 	struct ip6_hdr *ip6;
369 	struct ip6_frag *ip6f;
370 	struct ip6qhead *head;
371 	struct ip6q *q6;
372 	struct ip6asfrag *af6, *ip6af, *af6tmp;
373 	struct in6_ifaddr *ia6;
374 	struct ifnet *dstifp, *srcifp;
375 	uint32_t hashkey[(sizeof(struct in6_addr) * 2 +
376 		    sizeof(ip6f->ip6f_ident)) / sizeof(uint32_t)];
377 	uint32_t bucket, *hashkeyp;
378 	int fragoff, frgpartlen;	/* Must be larger than uint16_t. */
379 	int nxt, offset, plen;
380 	uint8_t ecn, ecn0;
381 	bool only_frag;
382 #ifdef RSS
383 	struct ip6_direct_ctx *ip6dc;
384 	struct m_tag *mtag;
385 #endif
386 
387 	m = *mp;
388 	offset = *offp;
389 
390 	M_ASSERTPKTHDR(m);
391 
392 	m = m_pullup(m, offset + sizeof(struct ip6_frag));
393 	if (m == NULL) {
394 		IP6STAT_INC(ip6s_exthdrtoolong);
395 		*mp = NULL;
396 		return (IPPROTO_DONE);
397 	}
398 	ip6 = mtod(m, struct ip6_hdr *);
399 
400 	dstifp = NULL;
401 	/* Find the destination interface of the packet. */
402 	ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
403 	if (ia6 != NULL) {
404 		dstifp = ia6->ia_ifp;
405 		ifa_free(&ia6->ia_ifa);
406 	}
407 
408 	/* Jumbo payload cannot contain a fragment header. */
409 	if (ip6->ip6_plen == 0) {
410 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER, offset);
411 		in6_ifstat_inc(dstifp, ifs6_reass_fail);
412 		*mp = NULL;
413 		return (IPPROTO_DONE);
414 	}
415 
416 	/*
417 	 * Check whether fragment packet's fragment length is a
418 	 * multiple of 8 octets (unless it is the last one).
419 	 * sizeof(struct ip6_frag) == 8
420 	 * sizeof(struct ip6_hdr) = 40
421 	 */
422 	ip6f = (struct ip6_frag *)((caddr_t)ip6 + offset);
423 	if ((ip6f->ip6f_offlg & IP6F_MORE_FRAG) &&
424 	    (((ntohs(ip6->ip6_plen) - offset) & 0x7) != 0)) {
425 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER,
426 		    offsetof(struct ip6_hdr, ip6_plen));
427 		in6_ifstat_inc(dstifp, ifs6_reass_fail);
428 		*mp = NULL;
429 		return (IPPROTO_DONE);
430 	}
431 
432 	IP6STAT_INC(ip6s_fragments);
433 	in6_ifstat_inc(dstifp, ifs6_reass_reqd);
434 
435 	/*
436 	 * Handle "atomic" fragments (offset and m bit set to 0) upfront,
437 	 * unrelated to any reassembly.  We need to remove the frag hdr
438 	 * which is ugly.
439 	 * See RFC 6946 and section 4.5 of RFC 8200.
440 	 */
441 	if ((ip6f->ip6f_offlg & ~IP6F_RESERVED_MASK) == 0) {
442 		IP6STAT_INC(ip6s_atomicfrags);
443 		nxt = ip6f->ip6f_nxt;
444 		/*
445 		 * Set nxt(-hdr field value) to the original value.
446 		 * We cannot just set ip6->ip6_nxt as there might be
447 		 * an unfragmentable part with extension headers and
448 		 * we must update the last one.
449 		 */
450 		m_copyback(m, ip6_get_prevhdr(m, offset), sizeof(uint8_t),
451 		    (caddr_t)&nxt);
452 		ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) -
453 		    sizeof(struct ip6_frag));
454 		if (ip6_deletefraghdr(m, offset, M_NOWAIT) != 0)
455 			goto dropfrag2;
456 		m->m_pkthdr.len -= sizeof(struct ip6_frag);
457 		in6_ifstat_inc(dstifp, ifs6_reass_ok);
458 		*mp = m;
459 		return (nxt);
460 	}
461 
462 	/* Offset now points to data portion. */
463 	offset += sizeof(struct ip6_frag);
464 
465 	/* Get fragment length and discard 0-byte fragments. */
466 	frgpartlen = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen) - offset;
467 	if (frgpartlen == 0) {
468 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER,
469 		    offsetof(struct ip6_hdr, ip6_plen));
470 		in6_ifstat_inc(dstifp, ifs6_reass_fail);
471 		IP6STAT_INC(ip6s_fragdropped);
472 		*mp = NULL;
473 		return (IPPROTO_DONE);
474 	}
475 
476 	/*
477 	 * Enforce upper bound on number of fragments for the entire system.
478 	 * If maxfrag is 0, never accept fragments.
479 	 * If maxfrag is -1, accept all fragments without limitation.
480 	 */
481 	if (ip6_maxfrags < 0)
482 		;
483 	else if (atomic_load_int(&frag6_nfrags) >= (u_int)ip6_maxfrags)
484 		goto dropfrag2;
485 
486 	/*
487 	 * Validate that a full header chain to the ULP is present in the
488 	 * packet containing the first fragment as per RFC RFC7112 and
489 	 * RFC 8200 pages 18,19:
490 	 * The first fragment packet is composed of:
491 	 * (3)  Extension headers, if any, and the Upper-Layer header.  These
492 	 *      headers must be in the first fragment.  ...
493 	 */
494 	fragoff = ntohs(ip6f->ip6f_offlg & IP6F_OFF_MASK);
495 	/* XXX TODO.  thj has D16851 open for this. */
496 	/* Send ICMPv6 4,3 in case of violation. */
497 
498 	/* Store receive network interface pointer for later. */
499 	srcifp = m->m_pkthdr.rcvif;
500 
501 	/* Generate a hash value for fragment bucket selection. */
502 	hashkeyp = hashkey;
503 	memcpy(hashkeyp, &ip6->ip6_src, sizeof(struct in6_addr));
504 	hashkeyp += sizeof(struct in6_addr) / sizeof(*hashkeyp);
505 	memcpy(hashkeyp, &ip6->ip6_dst, sizeof(struct in6_addr));
506 	hashkeyp += sizeof(struct in6_addr) / sizeof(*hashkeyp);
507 	*hashkeyp = ip6f->ip6f_ident;
508 	bucket = jenkins_hash32(hashkey, nitems(hashkey), V_ip6qb_hashseed);
509 	bucket &= IP6REASS_HMASK;
510 	IP6QB_LOCK(bucket);
511 	head = IP6QB_HEAD(bucket);
512 
513 	TAILQ_FOREACH(q6, head, ip6q_tq)
514 		if (ip6f->ip6f_ident == q6->ip6q_ident &&
515 		    IN6_ARE_ADDR_EQUAL(&ip6->ip6_src, &q6->ip6q_src) &&
516 		    IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &q6->ip6q_dst)
517 #ifdef MAC
518 		    && mac_ip6q_match(m, q6)
519 #endif
520 		    )
521 			break;
522 
523 	only_frag = false;
524 	if (q6 == NULL) {
525 
526 		/* A first fragment to arrive creates a reassembly queue. */
527 		only_frag = true;
528 
529 		/*
530 		 * Enforce upper bound on number of fragmented packets
531 		 * for which we attempt reassembly;
532 		 * If maxfragpackets is 0, never accept fragments.
533 		 * If maxfragpackets is -1, accept all fragments without
534 		 * limitation.
535 		 */
536 		if (V_ip6_maxfragpackets < 0)
537 			;
538 		else if (V_ip6qb[bucket].count >= V_ip6_maxfragbucketsize ||
539 		    atomic_load_int(&V_frag6_nfragpackets) >=
540 		    (u_int)V_ip6_maxfragpackets)
541 			goto dropfrag;
542 
543 		/* Allocate IPv6 fragement packet queue entry. */
544 		q6 = (struct ip6q *)malloc(sizeof(struct ip6q), M_FRAG6,
545 		    M_NOWAIT | M_ZERO);
546 		if (q6 == NULL)
547 			goto dropfrag;
548 #ifdef MAC
549 		if (mac_ip6q_init(q6, M_NOWAIT) != 0) {
550 			free(q6, M_FRAG6);
551 			goto dropfrag;
552 		}
553 		mac_ip6q_create(m, q6);
554 #endif
555 		atomic_add_int(&V_frag6_nfragpackets, 1);
556 
557 		/* ip6q_nxt will be filled afterwards, from 1st fragment. */
558 		TAILQ_INIT(&q6->ip6q_frags);
559 		q6->ip6q_ident	= ip6f->ip6f_ident;
560 		q6->ip6q_ttl	= IPV6_FRAGTTL;
561 		q6->ip6q_src	= ip6->ip6_src;
562 		q6->ip6q_dst	= ip6->ip6_dst;
563 		q6->ip6q_ecn	=
564 		    (ntohl(ip6->ip6_flow) >> 20) & IPTOS_ECN_MASK;
565 		q6->ip6q_unfrglen = -1;	/* The 1st fragment has not arrived. */
566 
567 		/* Add the fragemented packet to the bucket. */
568 		TAILQ_INSERT_HEAD(head, q6, ip6q_tq);
569 		V_ip6qb[bucket].count++;
570 	}
571 
572 	/*
573 	 * If it is the 1st fragment, record the length of the
574 	 * unfragmentable part and the next header of the fragment header.
575 	 * Assume the first 1st fragement to arrive will be correct.
576 	 * We do not have any duplicate checks here yet so another packet
577 	 * with fragoff == 0 could come and overwrite the ip6q_unfrglen
578 	 * and worse, the next header, at any time.
579 	 */
580 	if (fragoff == 0 && q6->ip6q_unfrglen == -1) {
581 		q6->ip6q_unfrglen = offset - sizeof(struct ip6_hdr) -
582 		    sizeof(struct ip6_frag);
583 		q6->ip6q_nxt = ip6f->ip6f_nxt;
584 		/* XXX ECN? */
585 	}
586 
587 	/*
588 	 * Check that the reassembled packet would not exceed 65535 bytes
589 	 * in size.
590 	 * If it would exceed, discard the fragment and return an ICMP error.
591 	 */
592 	if (q6->ip6q_unfrglen >= 0) {
593 		/* The 1st fragment has already arrived. */
594 		if (q6->ip6q_unfrglen + fragoff + frgpartlen > IPV6_MAXPACKET) {
595 			if (only_frag) {
596 				TAILQ_REMOVE(head, q6, ip6q_tq);
597 				V_ip6qb[bucket].count--;
598 				atomic_subtract_int(&V_frag6_nfragpackets, 1);
599 #ifdef MAC
600 				mac_ip6q_destroy(q6);
601 #endif
602 				free(q6, M_FRAG6);
603 			}
604 			IP6QB_UNLOCK(bucket);
605 			icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER,
606 			    offset - sizeof(struct ip6_frag) +
607 			    offsetof(struct ip6_frag, ip6f_offlg));
608 			*mp = NULL;
609 			return (IPPROTO_DONE);
610 		}
611 	} else if (fragoff + frgpartlen > IPV6_MAXPACKET) {
612 		if (only_frag) {
613 			TAILQ_REMOVE(head, q6, ip6q_tq);
614 			V_ip6qb[bucket].count--;
615 			atomic_subtract_int(&V_frag6_nfragpackets, 1);
616 #ifdef MAC
617 			mac_ip6q_destroy(q6);
618 #endif
619 			free(q6, M_FRAG6);
620 		}
621 		IP6QB_UNLOCK(bucket);
622 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER,
623 		    offset - sizeof(struct ip6_frag) +
624 		    offsetof(struct ip6_frag, ip6f_offlg));
625 		*mp = NULL;
626 		return (IPPROTO_DONE);
627 	}
628 
629 	/*
630 	 * If it is the first fragment, do the above check for each
631 	 * fragment already stored in the reassembly queue.
632 	 */
633 	if (fragoff == 0 && !only_frag) {
634 		TAILQ_FOREACH_SAFE(af6, &q6->ip6q_frags, ip6af_tq, af6tmp) {
635 
636 			if (q6->ip6q_unfrglen + af6->ip6af_off +
637 			    af6->ip6af_frglen > IPV6_MAXPACKET) {
638 				struct ip6_hdr *ip6err;
639 				struct mbuf *merr;
640 				int erroff;
641 
642 				merr = af6->ip6af_m;
643 				erroff = af6->ip6af_offset;
644 
645 				/* Dequeue the fragment. */
646 				TAILQ_REMOVE(&q6->ip6q_frags, af6, ip6af_tq);
647 				q6->ip6q_nfrag--;
648 				atomic_subtract_int(&frag6_nfrags, 1);
649 				free(af6, M_FRAG6);
650 
651 				/* Set a valid receive interface pointer. */
652 				merr->m_pkthdr.rcvif = srcifp;
653 
654 				/* Adjust pointer. */
655 				ip6err = mtod(merr, struct ip6_hdr *);
656 
657 				/*
658 				 * Restore source and destination addresses
659 				 * in the erroneous IPv6 header.
660 				 */
661 				ip6err->ip6_src = q6->ip6q_src;
662 				ip6err->ip6_dst = q6->ip6q_dst;
663 
664 				icmp6_error(merr, ICMP6_PARAM_PROB,
665 				    ICMP6_PARAMPROB_HEADER,
666 				    erroff - sizeof(struct ip6_frag) +
667 				    offsetof(struct ip6_frag, ip6f_offlg));
668 			}
669 		}
670 	}
671 
672 	/* Allocate an IPv6 fragement queue entry for this fragmented part. */
673 	ip6af = (struct ip6asfrag *)malloc(sizeof(struct ip6asfrag), M_FRAG6,
674 	    M_NOWAIT | M_ZERO);
675 	if (ip6af == NULL)
676 		goto dropfrag;
677 	ip6af->ip6af_mff = (ip6f->ip6f_offlg & IP6F_MORE_FRAG) ? true : false;
678 	ip6af->ip6af_off = fragoff;
679 	ip6af->ip6af_frglen = frgpartlen;
680 	ip6af->ip6af_offset = offset;
681 	ip6af->ip6af_m = m;
682 
683 	if (only_frag) {
684 		/*
685 		 * Do a manual insert rather than a hard-to-understand cast
686 		 * to a different type relying on data structure order to work.
687 		 */
688 		TAILQ_INSERT_HEAD(&q6->ip6q_frags, ip6af, ip6af_tq);
689 		goto postinsert;
690 	}
691 
692 	/* Do duplicate, condition, and boundry checks. */
693 	/*
694 	 * Handle ECN by comparing this segment with the first one;
695 	 * if CE is set, do not lose CE.
696 	 * Drop if CE and not-ECT are mixed for the same packet.
697 	 */
698 	ecn = (ntohl(ip6->ip6_flow) >> 20) & IPTOS_ECN_MASK;
699 	ecn0 = q6->ip6q_ecn;
700 	if (ecn == IPTOS_ECN_CE) {
701 		if (ecn0 == IPTOS_ECN_NOTECT) {
702 			free(ip6af, M_FRAG6);
703 			goto dropfrag;
704 		}
705 		if (ecn0 != IPTOS_ECN_CE)
706 			q6->ip6q_ecn = IPTOS_ECN_CE;
707 	}
708 	if (ecn == IPTOS_ECN_NOTECT && ecn0 != IPTOS_ECN_NOTECT) {
709 		free(ip6af, M_FRAG6);
710 		goto dropfrag;
711 	}
712 
713 	/* Find a fragmented part which begins after this one does. */
714 	TAILQ_FOREACH(af6, &q6->ip6q_frags, ip6af_tq)
715 		if (af6->ip6af_off > ip6af->ip6af_off)
716 			break;
717 
718 	/*
719 	 * If the incoming framgent overlaps some existing fragments in
720 	 * the reassembly queue, drop both the new fragment and the
721 	 * entire reassembly queue.  However, if the new fragment
722 	 * is an exact duplicate of an existing fragment, only silently
723 	 * drop the existing fragment and leave the fragmentation queue
724 	 * unchanged, as allowed by the RFC.  (RFC 8200, 4.5)
725 	 */
726 	if (af6 != NULL)
727 		af6tmp = TAILQ_PREV(af6, ip6fraghead, ip6af_tq);
728 	else
729 		af6tmp = TAILQ_LAST(&q6->ip6q_frags, ip6fraghead);
730 	if (af6tmp != NULL) {
731 		if (af6tmp->ip6af_off + af6tmp->ip6af_frglen -
732 		    ip6af->ip6af_off > 0) {
733 			if (af6tmp->ip6af_off != ip6af->ip6af_off ||
734 			    af6tmp->ip6af_frglen != ip6af->ip6af_frglen)
735 				frag6_freef(q6, bucket);
736 			free(ip6af, M_FRAG6);
737 			goto dropfrag;
738 		}
739 	}
740 	if (af6 != NULL) {
741 		if (ip6af->ip6af_off + ip6af->ip6af_frglen -
742 		    af6->ip6af_off > 0) {
743 			if (af6->ip6af_off != ip6af->ip6af_off ||
744 			    af6->ip6af_frglen != ip6af->ip6af_frglen)
745 				frag6_freef(q6, bucket);
746 			free(ip6af, M_FRAG6);
747 			goto dropfrag;
748 		}
749 	}
750 
751 #ifdef MAC
752 	mac_ip6q_update(m, q6);
753 #endif
754 
755 	/*
756 	 * Stick new segment in its place; check for complete reassembly.
757 	 * If not complete, check fragment limit.  Move to front of packet
758 	 * queue, as we are the most recently active fragmented packet.
759 	 */
760 	if (af6 != NULL)
761 		TAILQ_INSERT_BEFORE(af6, ip6af, ip6af_tq);
762 	else
763 		TAILQ_INSERT_TAIL(&q6->ip6q_frags, ip6af, ip6af_tq);
764 postinsert:
765 	atomic_add_int(&frag6_nfrags, 1);
766 	q6->ip6q_nfrag++;
767 
768 	plen = 0;
769 	TAILQ_FOREACH(af6, &q6->ip6q_frags, ip6af_tq) {
770 		if (af6->ip6af_off != plen) {
771 			if (q6->ip6q_nfrag > V_ip6_maxfragsperpacket) {
772 				IP6STAT_ADD(ip6s_fragdropped, q6->ip6q_nfrag);
773 				frag6_freef(q6, bucket);
774 			}
775 			IP6QB_UNLOCK(bucket);
776 			*mp = NULL;
777 			return (IPPROTO_DONE);
778 		}
779 		plen += af6->ip6af_frglen;
780 	}
781 	af6 = TAILQ_LAST(&q6->ip6q_frags, ip6fraghead);
782 	if (af6->ip6af_mff) {
783 		if (q6->ip6q_nfrag > V_ip6_maxfragsperpacket) {
784 			IP6STAT_ADD(ip6s_fragdropped, q6->ip6q_nfrag);
785 			frag6_freef(q6, bucket);
786 		}
787 		IP6QB_UNLOCK(bucket);
788 		*mp = NULL;
789 		return (IPPROTO_DONE);
790 	}
791 
792 	/* Reassembly is complete; concatenate fragments. */
793 	ip6af = TAILQ_FIRST(&q6->ip6q_frags);
794 	t = m = ip6af->ip6af_m;
795 	TAILQ_REMOVE(&q6->ip6q_frags, ip6af, ip6af_tq);
796 	while ((af6 = TAILQ_FIRST(&q6->ip6q_frags)) != NULL) {
797 		m->m_pkthdr.csum_flags &=
798 		    af6->ip6af_m->m_pkthdr.csum_flags;
799 		m->m_pkthdr.csum_data +=
800 		    af6->ip6af_m->m_pkthdr.csum_data;
801 
802 		TAILQ_REMOVE(&q6->ip6q_frags, af6, ip6af_tq);
803 		t = m_last(t);
804 		m_adj(af6->ip6af_m, af6->ip6af_offset);
805 		m_demote_pkthdr(af6->ip6af_m);
806 		m_cat(t, af6->ip6af_m);
807 		free(af6, M_FRAG6);
808 	}
809 
810 	while (m->m_pkthdr.csum_data & 0xffff0000)
811 		m->m_pkthdr.csum_data = (m->m_pkthdr.csum_data & 0xffff) +
812 		    (m->m_pkthdr.csum_data >> 16);
813 
814 	/* Adjust offset to point where the original next header starts. */
815 	offset = ip6af->ip6af_offset - sizeof(struct ip6_frag);
816 	free(ip6af, M_FRAG6);
817 	ip6 = mtod(m, struct ip6_hdr *);
818 	ip6->ip6_plen = htons((u_short)plen + offset - sizeof(struct ip6_hdr));
819 	if (q6->ip6q_ecn == IPTOS_ECN_CE)
820 		ip6->ip6_flow |= htonl(IPTOS_ECN_CE << 20);
821 	nxt = q6->ip6q_nxt;
822 
823 	TAILQ_REMOVE(head, q6, ip6q_tq);
824 	V_ip6qb[bucket].count--;
825 	atomic_subtract_int(&frag6_nfrags, q6->ip6q_nfrag);
826 
827 	ip6_deletefraghdr(m, offset, M_NOWAIT);
828 
829 	/* Set nxt(-hdr field value) to the original value. */
830 	m_copyback(m, ip6_get_prevhdr(m, offset), sizeof(uint8_t),
831 	    (caddr_t)&nxt);
832 
833 #ifdef MAC
834 	mac_ip6q_reassemble(q6, m);
835 	mac_ip6q_destroy(q6);
836 #endif
837 	free(q6, M_FRAG6);
838 	atomic_subtract_int(&V_frag6_nfragpackets, 1);
839 
840 	if (m->m_flags & M_PKTHDR) { /* Isn't it always true? */
841 
842 		plen = 0;
843 		for (t = m; t; t = t->m_next)
844 			plen += t->m_len;
845 		m->m_pkthdr.len = plen;
846 		/* Set a valid receive interface pointer. */
847 		m->m_pkthdr.rcvif = srcifp;
848 	}
849 
850 #ifdef RSS
851 	mtag = m_tag_alloc(MTAG_ABI_IPV6, IPV6_TAG_DIRECT, sizeof(*ip6dc),
852 	    M_NOWAIT);
853 	if (mtag == NULL)
854 		goto dropfrag;
855 
856 	ip6dc = (struct ip6_direct_ctx *)(mtag + 1);
857 	ip6dc->ip6dc_nxt = nxt;
858 	ip6dc->ip6dc_off = offset;
859 
860 	m_tag_prepend(m, mtag);
861 #endif
862 
863 	IP6QB_UNLOCK(bucket);
864 	IP6STAT_INC(ip6s_reassembled);
865 	in6_ifstat_inc(dstifp, ifs6_reass_ok);
866 
867 #ifdef RSS
868 	/* Queue/dispatch for reprocessing. */
869 	netisr_dispatch(NETISR_IPV6_DIRECT, m);
870 	*mp = NULL;
871 	return (IPPROTO_DONE);
872 #endif
873 
874 	/* Tell launch routine the next header. */
875 	*mp = m;
876 	*offp = offset;
877 
878 	return (nxt);
879 
880 dropfrag:
881 	IP6QB_UNLOCK(bucket);
882 dropfrag2:
883 	in6_ifstat_inc(dstifp, ifs6_reass_fail);
884 	IP6STAT_INC(ip6s_fragdropped);
885 	m_freem(m);
886 	*mp = NULL;
887 	return (IPPROTO_DONE);
888 }
889 
890 /*
891  * IPv6 reassembling timer processing;
892  * if a timer expires on a reassembly queue, discard it.
893  */
894 void
895 frag6_slowtimo(void)
896 {
897 	VNET_ITERATOR_DECL(vnet_iter);
898 	struct ip6qhead *head;
899 	struct ip6q *q6, *q6tmp;
900 	uint32_t bucket;
901 
902 	VNET_LIST_RLOCK_NOSLEEP();
903 	VNET_FOREACH(vnet_iter) {
904 		CURVNET_SET(vnet_iter);
905 		for (bucket = 0; bucket < IP6REASS_NHASH; bucket++) {
906 			IP6QB_LOCK(bucket);
907 			head = IP6QB_HEAD(bucket);
908 			TAILQ_FOREACH_SAFE(q6, head, ip6q_tq, q6tmp)
909 				if (--q6->ip6q_ttl == 0) {
910 					IP6STAT_ADD(ip6s_fragtimeout,
911 						q6->ip6q_nfrag);
912 					/* XXX in6_ifstat_inc(ifp, ifs6_reass_fail) */
913 					frag6_freef(q6, bucket);
914 				}
915 			/*
916 			 * If we are over the maximum number of fragments
917 			 * (due to the limit being lowered), drain off
918 			 * enough to get down to the new limit.
919 			 * Note that we drain all reassembly queues if
920 			 * maxfragpackets is 0 (fragmentation is disabled),
921 			 * and do not enforce a limit when maxfragpackets
922 			 * is negative.
923 			 */
924 			while ((V_ip6_maxfragpackets == 0 ||
925 			    (V_ip6_maxfragpackets > 0 &&
926 			    V_ip6qb[bucket].count > V_ip6_maxfragbucketsize)) &&
927 			    (q6 = TAILQ_LAST(head, ip6qhead)) != NULL) {
928 				IP6STAT_ADD(ip6s_fragoverflow, q6->ip6q_nfrag);
929 				/* XXX in6_ifstat_inc(ifp, ifs6_reass_fail) */
930 				frag6_freef(q6, bucket);
931 			}
932 			IP6QB_UNLOCK(bucket);
933 		}
934 		/*
935 		 * If we are still over the maximum number of fragmented
936 		 * packets, drain off enough to get down to the new limit.
937 		 */
938 		bucket = 0;
939 		while (V_ip6_maxfragpackets >= 0 &&
940 		    atomic_load_int(&V_frag6_nfragpackets) >
941 		    (u_int)V_ip6_maxfragpackets) {
942 			IP6QB_LOCK(bucket);
943 			q6 = TAILQ_LAST(IP6QB_HEAD(bucket), ip6qhead);
944 			if (q6 != NULL) {
945 				IP6STAT_ADD(ip6s_fragoverflow, q6->ip6q_nfrag);
946 				/* XXX in6_ifstat_inc(ifp, ifs6_reass_fail) */
947 				frag6_freef(q6, bucket);
948 			}
949 			IP6QB_UNLOCK(bucket);
950 			bucket = (bucket + 1) % IP6REASS_NHASH;
951 		}
952 		CURVNET_RESTORE();
953 	}
954 	VNET_LIST_RUNLOCK_NOSLEEP();
955 }
956 
957 /*
958  * Eventhandler to adjust limits in case nmbclusters change.
959  */
960 static void
961 frag6_change(void *tag)
962 {
963 	VNET_ITERATOR_DECL(vnet_iter);
964 
965 	ip6_maxfrags = IP6_MAXFRAGS;
966 	VNET_LIST_RLOCK_NOSLEEP();
967 	VNET_FOREACH(vnet_iter) {
968 		CURVNET_SET(vnet_iter);
969 		V_ip6_maxfragpackets = IP6_MAXFRAGPACKETS;
970 		frag6_set_bucketsize();
971 		CURVNET_RESTORE();
972 	}
973 	VNET_LIST_RUNLOCK_NOSLEEP();
974 }
975 
976 /*
977  * Initialise reassembly queue and fragment identifier.
978  */
979 void
980 frag6_init(void)
981 {
982 	uint32_t bucket;
983 
984 	V_ip6_maxfragpackets = IP6_MAXFRAGPACKETS;
985 	frag6_set_bucketsize();
986 	for (bucket = 0; bucket < IP6REASS_NHASH; bucket++) {
987 		TAILQ_INIT(IP6QB_HEAD(bucket));
988 		mtx_init(&V_ip6qb[bucket].lock, "ip6qb", NULL, MTX_DEF);
989 		V_ip6qb[bucket].count = 0;
990 	}
991 	V_ip6qb_hashseed = arc4random();
992 	V_ip6_maxfragsperpacket = 64;
993 #ifdef VIMAGE
994 	V_frag6_on = true;
995 #endif
996 	if (!IS_DEFAULT_VNET(curvnet))
997 		return;
998 
999 	ip6_maxfrags = IP6_MAXFRAGS;
1000 	EVENTHANDLER_REGISTER(nmbclusters_change,
1001 	    frag6_change, NULL, EVENTHANDLER_PRI_ANY);
1002 }
1003 
1004 /*
1005  * Drain off all datagram fragments.
1006  */
1007 static void
1008 frag6_drain_one(void)
1009 {
1010 	struct ip6q *q6;
1011 	uint32_t bucket;
1012 
1013 	for (bucket = 0; bucket < IP6REASS_NHASH; bucket++) {
1014 		IP6QB_LOCK(bucket);
1015 		while ((q6 = TAILQ_FIRST(IP6QB_HEAD(bucket))) != NULL) {
1016 			IP6STAT_INC(ip6s_fragdropped);
1017 			/* XXX in6_ifstat_inc(ifp, ifs6_reass_fail) */
1018 			frag6_freef(q6, bucket);
1019 		}
1020 		IP6QB_UNLOCK(bucket);
1021 	}
1022 }
1023 
1024 void
1025 frag6_drain(void)
1026 {
1027 	VNET_ITERATOR_DECL(vnet_iter);
1028 
1029 	VNET_LIST_RLOCK_NOSLEEP();
1030 	VNET_FOREACH(vnet_iter) {
1031 		CURVNET_SET(vnet_iter);
1032 		frag6_drain_one();
1033 		CURVNET_RESTORE();
1034 	}
1035 	VNET_LIST_RUNLOCK_NOSLEEP();
1036 }
1037 
1038 #ifdef VIMAGE
1039 /*
1040  * Clear up IPv6 reassembly structures.
1041  */
1042 void
1043 frag6_destroy(void)
1044 {
1045 	uint32_t bucket;
1046 
1047 	frag6_drain_one();
1048 	V_frag6_on = false;
1049 	for (bucket = 0; bucket < IP6REASS_NHASH; bucket++) {
1050 		KASSERT(V_ip6qb[bucket].count == 0,
1051 		    ("%s: V_ip6qb[%d] (%p) count not 0 (%d)", __func__,
1052 		    bucket, &V_ip6qb[bucket], V_ip6qb[bucket].count));
1053 		mtx_destroy(&V_ip6qb[bucket].lock);
1054 	}
1055 }
1056 #endif
1057