xref: /freebsd/sys/netpfil/pf/pf_norm.c (revision 850041b025486614243fb2d481b3adb0382b02e7)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright 2001 Niels Provos <provos@citi.umich.edu>
5  * Copyright 2011-2018 Alexander Bluhm <bluhm@openbsd.org>
6  * All rights reserved.
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  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  *	$OpenBSD: pf_norm.c,v 1.114 2009/01/29 14:11:45 henning Exp $
29  */
30 
31 #include <sys/cdefs.h>
32 #include "opt_inet.h"
33 #include "opt_inet6.h"
34 #include "opt_pf.h"
35 
36 #include <sys/param.h>
37 #include <sys/kernel.h>
38 #include <sys/lock.h>
39 #include <sys/mbuf.h>
40 #include <sys/mutex.h>
41 #include <sys/refcount.h>
42 #include <sys/socket.h>
43 
44 #include <net/if.h>
45 #include <net/if_var.h>
46 #include <net/if_private.h>
47 #include <net/vnet.h>
48 #include <net/pfvar.h>
49 #include <net/if_pflog.h>
50 
51 #include <netinet/in.h>
52 #include <netinet/ip.h>
53 #include <netinet/ip_var.h>
54 #include <netinet6/in6_var.h>
55 #include <netinet6/nd6.h>
56 #include <netinet6/ip6_var.h>
57 #include <netinet6/scope6_var.h>
58 #include <netinet/tcp.h>
59 #include <netinet/tcp_fsm.h>
60 #include <netinet/tcp_seq.h>
61 #include <netinet/sctp_constants.h>
62 #include <netinet/sctp_header.h>
63 
64 #ifdef INET6
65 #include <netinet/ip6.h>
66 #endif /* INET6 */
67 
68 struct pf_frent {
69 	TAILQ_ENTRY(pf_frent)	fr_next;
70 	struct mbuf	*fe_m;
71 	uint16_t	fe_hdrlen;	/* ipv4 header length with ip options
72 					   ipv6, extension, fragment header */
73 	uint16_t	fe_extoff;	/* last extension header offset or 0 */
74 	uint16_t	fe_len;		/* fragment length */
75 	uint16_t	fe_off;		/* fragment offset */
76 	uint16_t	fe_mff;		/* more fragment flag */
77 };
78 
79 RB_HEAD(pf_frag_tree, pf_fragment);
80 struct pf_frnode {
81 	struct pf_addr		fn_src;		/* ip source address */
82 	struct pf_addr		fn_dst;		/* ip destination address */
83 	sa_family_t		fn_af;		/* address family */
84 	u_int8_t		fn_proto;	/* protocol for fragments in fn_tree */
85 	u_int8_t		fn_direction;	/* pf packet direction */
86 	u_int32_t		fn_fragments;	/* number of entries in fn_tree */
87 
88 	RB_ENTRY(pf_frnode)	fn_entry;
89 	struct pf_frag_tree	fn_tree;	/* matching fragments, lookup by id */
90 };
91 
92 struct pf_fragment {
93 	uint32_t	fr_id;	/* fragment id for reassemble */
94 
95 	/* pointers to queue element */
96 	struct pf_frent	*fr_firstoff[PF_FRAG_ENTRY_POINTS];
97 	/* count entries between pointers */
98 	uint8_t	fr_entries[PF_FRAG_ENTRY_POINTS];
99 	RB_ENTRY(pf_fragment) fr_entry;
100 	TAILQ_ENTRY(pf_fragment) frag_next;
101 	uint32_t	fr_timeout;
102 	TAILQ_HEAD(pf_fragq, pf_frent) fr_queue;
103 	uint16_t	fr_maxlen;	/* maximum length of single fragment */
104 	u_int16_t	fr_holes;	/* number of holes in the queue */
105 	struct pf_frnode *fr_node;	/* ip src/dst/proto/af for fragments */
106 };
107 
108 VNET_DEFINE_STATIC(struct mtx, pf_frag_mtx);
109 #define V_pf_frag_mtx		VNET(pf_frag_mtx)
110 #define PF_FRAG_LOCK()		mtx_lock(&V_pf_frag_mtx)
111 #define PF_FRAG_UNLOCK()	mtx_unlock(&V_pf_frag_mtx)
112 #define PF_FRAG_ASSERT()	mtx_assert(&V_pf_frag_mtx, MA_OWNED)
113 
114 VNET_DEFINE(uma_zone_t, pf_state_scrub_z);	/* XXX: shared with pfsync */
115 
116 VNET_DEFINE_STATIC(uma_zone_t, pf_frent_z);
117 #define	V_pf_frent_z	VNET(pf_frent_z)
118 VNET_DEFINE_STATIC(uma_zone_t, pf_frnode_z);
119 #define	V_pf_frnode_z	VNET(pf_frnode_z)
120 VNET_DEFINE_STATIC(uma_zone_t, pf_frag_z);
121 #define	V_pf_frag_z	VNET(pf_frag_z)
122 VNET_DEFINE(uma_zone_t, pf_anchor_z);
123 VNET_DEFINE(uma_zone_t, pf_eth_anchor_z);
124 
125 TAILQ_HEAD(pf_fragqueue, pf_fragment);
126 TAILQ_HEAD(pf_cachequeue, pf_fragment);
127 RB_HEAD(pf_frnode_tree, pf_frnode);
128 VNET_DEFINE_STATIC(struct pf_fragqueue,	pf_fragqueue);
129 #define	V_pf_fragqueue			VNET(pf_fragqueue)
130 static __inline int	pf_frnode_compare(struct pf_frnode *,
131 			    struct pf_frnode *);
132 VNET_DEFINE_STATIC(struct pf_frnode_tree, pf_frnode_tree);
133 #define	V_pf_frnode_tree		VNET(pf_frnode_tree)
134 RB_PROTOTYPE(pf_frnode_tree, pf_frnode, fn_entry, pf_frnode_compare);
135 RB_GENERATE(pf_frnode_tree, pf_frnode, fn_entry, pf_frnode_compare);
136 
137 static int		 pf_frag_compare(struct pf_fragment *,
138 			    struct pf_fragment *);
139 static RB_PROTOTYPE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
140 static RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
141 
142 static void	pf_flush_fragments(void);
143 static void	pf_free_fragment(struct pf_fragment *);
144 
145 static struct pf_frent *pf_create_fragment(u_short *);
146 static int	pf_frent_holes(struct pf_frent *frent);
147 static struct pf_fragment	*pf_find_fragment(struct pf_frnode *, u_int32_t);
148 static inline int	pf_frent_index(struct pf_frent *);
149 static int	pf_frent_insert(struct pf_fragment *,
150 			    struct pf_frent *, struct pf_frent *);
151 void			pf_frent_remove(struct pf_fragment *,
152 			    struct pf_frent *);
153 struct pf_frent		*pf_frent_previous(struct pf_fragment *,
154 			    struct pf_frent *);
155 static struct pf_fragment *pf_fillup_fragment(struct pf_frnode *, u_int32_t,
156 		    struct pf_frent *, u_short *);
157 static struct mbuf *pf_join_fragment(struct pf_fragment *);
158 #ifdef INET
159 static int	pf_reassemble(struct mbuf **, uint8_t, u_short *);
160 #endif	/* INET */
161 #ifdef INET6
162 static int	pf_reassemble6(struct mbuf **,
163 		    struct ip6_frag *, uint16_t, uint16_t, uint8_t, u_short *);
164 #endif	/* INET6 */
165 
166 #ifdef INET
167 static void
pf_ip2key(struct ip * ip,struct pf_frnode * key,uint8_t dir)168 pf_ip2key(struct ip *ip, struct pf_frnode *key, uint8_t dir)
169 {
170 
171 	key->fn_src.v4 = ip->ip_src;
172 	key->fn_dst.v4 = ip->ip_dst;
173 	key->fn_af = AF_INET;
174 	key->fn_proto = ip->ip_p;
175 	key->fn_direction = dir;
176 }
177 #endif	/* INET */
178 
179 void
pf_normalize_init(void)180 pf_normalize_init(void)
181 {
182 
183 	V_pf_frag_z = uma_zcreate("pf frags", sizeof(struct pf_fragment),
184 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
185 	V_pf_frnode_z = uma_zcreate("pf fragment node",
186 	    sizeof(struct pf_frnode), NULL, NULL, NULL, NULL,
187 	    UMA_ALIGN_PTR, 0);
188 	V_pf_frent_z = uma_zcreate("pf frag entries", sizeof(struct pf_frent),
189 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
190 	V_pf_state_scrub_z = uma_zcreate("pf state scrubs",
191 	    sizeof(struct pf_state_scrub),  NULL, NULL, NULL, NULL,
192 	    UMA_ALIGN_PTR, 0);
193 
194 	mtx_init(&V_pf_frag_mtx, "pf fragments", NULL, MTX_DEF);
195 
196 	V_pf_limits[PF_LIMIT_FRAGS].zone = V_pf_frent_z;
197 	V_pf_limits[PF_LIMIT_FRAGS].limit = PFFRAG_FRENT_HIWAT;
198 	uma_zone_set_max(V_pf_frent_z, PFFRAG_FRENT_HIWAT);
199 	uma_zone_set_warning(V_pf_frent_z, "PF frag entries limit reached");
200 
201 	TAILQ_INIT(&V_pf_fragqueue);
202 }
203 
204 void
pf_normalize_cleanup(void)205 pf_normalize_cleanup(void)
206 {
207 
208 	uma_zdestroy(V_pf_state_scrub_z);
209 	uma_zdestroy(V_pf_frent_z);
210 	uma_zdestroy(V_pf_frnode_z);
211 	uma_zdestroy(V_pf_frag_z);
212 
213 	mtx_destroy(&V_pf_frag_mtx);
214 }
215 
216 uint64_t
pf_normalize_get_frag_count(void)217 pf_normalize_get_frag_count(void)
218 {
219 	return (uma_zone_get_cur(V_pf_frent_z));
220 }
221 
222 static int
pf_frnode_compare(struct pf_frnode * a,struct pf_frnode * b)223 pf_frnode_compare(struct pf_frnode *a, struct pf_frnode *b)
224 {
225 	int	diff;
226 
227 	if ((diff = a->fn_proto - b->fn_proto) != 0)
228 		return (diff);
229 	if ((diff = a->fn_af - b->fn_af) != 0)
230 		return (diff);
231 	if ((diff = a->fn_direction - b->fn_direction) != 0)
232 		return (diff);
233 	if ((diff = pf_addr_cmp(&a->fn_src, &b->fn_src, a->fn_af)) != 0)
234 		return (diff);
235 	if ((diff = pf_addr_cmp(&a->fn_dst, &b->fn_dst, a->fn_af)) != 0)
236 		return (diff);
237 	return (0);
238 }
239 
240 static __inline int
pf_frag_compare(struct pf_fragment * a,struct pf_fragment * b)241 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b)
242 {
243 	if (a->fr_id > b->fr_id)
244 		return (1);
245 	if (a->fr_id < b->fr_id)
246 		return (-1);
247 
248 	return (0);
249 }
250 
251 void
pf_purge_expired_fragments(void)252 pf_purge_expired_fragments(void)
253 {
254 	u_int32_t	expire = time_uptime -
255 			    V_pf_default_rule.timeout[PFTM_FRAG];
256 
257 	pf_purge_fragments(expire);
258 }
259 
260 void
pf_purge_fragments(uint32_t expire)261 pf_purge_fragments(uint32_t expire)
262 {
263 	struct pf_fragment	*frag;
264 
265 	PF_FRAG_LOCK();
266 	while ((frag = TAILQ_LAST(&V_pf_fragqueue, pf_fragqueue)) != NULL) {
267 		if (frag->fr_timeout > expire)
268 			break;
269 
270 		DPFPRINTF(PF_DEBUG_MISC, "expiring %d(%p)",
271 		    frag->fr_id, frag);
272 		pf_free_fragment(frag);
273 	}
274 
275 	PF_FRAG_UNLOCK();
276 }
277 
278 /*
279  * Try to flush old fragments to make space for new ones
280  */
281 static void
pf_flush_fragments(void)282 pf_flush_fragments(void)
283 {
284 	struct pf_fragment	*frag;
285 	int			 goal;
286 
287 	PF_FRAG_ASSERT();
288 
289 	goal = uma_zone_get_cur(V_pf_frent_z) * 9 / 10;
290 	DPFPRINTF(PF_DEBUG_MISC, "trying to free %d frag entriess", goal);
291 	while (goal < uma_zone_get_cur(V_pf_frent_z)) {
292 		frag = TAILQ_LAST(&V_pf_fragqueue, pf_fragqueue);
293 		if (frag)
294 			pf_free_fragment(frag);
295 		else
296 			break;
297 	}
298 }
299 
300 /*
301  * Remove a fragment from the fragment queue, free its fragment entries,
302  * and free the fragment itself.
303  */
304 static void
pf_free_fragment(struct pf_fragment * frag)305 pf_free_fragment(struct pf_fragment *frag)
306 {
307 	struct pf_frent		*frent;
308 	struct pf_frnode	*frnode;
309 
310 	PF_FRAG_ASSERT();
311 
312 	frnode = frag->fr_node;
313 	RB_REMOVE(pf_frag_tree, &frnode->fn_tree, frag);
314 	MPASS(frnode->fn_fragments >= 1);
315 	frnode->fn_fragments--;
316 	if (frnode->fn_fragments == 0) {
317 		MPASS(RB_EMPTY(&frnode->fn_tree));
318 		RB_REMOVE(pf_frnode_tree, &V_pf_frnode_tree, frnode);
319 		uma_zfree(V_pf_frnode_z, frnode);
320 	}
321 
322 	TAILQ_REMOVE(&V_pf_fragqueue, frag, frag_next);
323 
324 	/* Free all fragment entries */
325 	while ((frent = TAILQ_FIRST(&frag->fr_queue)) != NULL) {
326 		TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
327 		counter_u64_add(V_pf_status.ncounters[NCNT_FRAG_REMOVALS], 1);
328 
329 		m_freem(frent->fe_m);
330 		uma_zfree(V_pf_frent_z, frent);
331 	}
332 
333 	uma_zfree(V_pf_frag_z, frag);
334 }
335 
336 static struct pf_fragment *
pf_find_fragment(struct pf_frnode * key,uint32_t id)337 pf_find_fragment(struct pf_frnode *key, uint32_t id)
338 {
339 	struct pf_fragment	*frag, idkey;
340 	struct pf_frnode	*frnode;
341 
342 	PF_FRAG_ASSERT();
343 
344 	frnode = RB_FIND(pf_frnode_tree, &V_pf_frnode_tree, key);
345 	counter_u64_add(V_pf_status.ncounters[NCNT_FRAG_SEARCH], 1);
346 	if (frnode == NULL)
347 		return (NULL);
348 	MPASS(frnode->fn_fragments >= 1);
349 	idkey.fr_id = id;
350 	frag = RB_FIND(pf_frag_tree, &frnode->fn_tree, &idkey);
351 	if (frag == NULL)
352 		return (NULL);
353 	TAILQ_REMOVE(&V_pf_fragqueue, frag, frag_next);
354 	TAILQ_INSERT_HEAD(&V_pf_fragqueue, frag, frag_next);
355 
356 	return (frag);
357 }
358 
359 static struct pf_frent *
pf_create_fragment(u_short * reason)360 pf_create_fragment(u_short *reason)
361 {
362 	struct pf_frent *frent;
363 
364 	PF_FRAG_ASSERT();
365 
366 	frent = uma_zalloc(V_pf_frent_z, M_NOWAIT);
367 	if (frent == NULL) {
368 		pf_flush_fragments();
369 		frent = uma_zalloc(V_pf_frent_z, M_NOWAIT);
370 		if (frent == NULL) {
371 			REASON_SET(reason, PFRES_MEMORY);
372 			return (NULL);
373 		}
374 	}
375 
376 	return (frent);
377 }
378 
379 /*
380  * Calculate the additional holes that were created in the fragment
381  * queue by inserting this fragment.  A fragment in the middle
382  * creates one more hole by splitting.  For each connected side,
383  * it loses one hole.
384  * Fragment entry must be in the queue when calling this function.
385  */
386 static int
pf_frent_holes(struct pf_frent * frent)387 pf_frent_holes(struct pf_frent *frent)
388 {
389 	struct pf_frent *prev = TAILQ_PREV(frent, pf_fragq, fr_next);
390 	struct pf_frent *next = TAILQ_NEXT(frent, fr_next);
391 	int holes = 1;
392 
393 	if (prev == NULL) {
394 		if (frent->fe_off == 0)
395 			holes--;
396 	} else {
397 		KASSERT(frent->fe_off != 0, ("frent->fe_off != 0"));
398 		if (frent->fe_off == prev->fe_off + prev->fe_len)
399 			holes--;
400 	}
401 	if (next == NULL) {
402 		if (!frent->fe_mff)
403 			holes--;
404 	} else {
405 		KASSERT(frent->fe_mff, ("frent->fe_mff"));
406 		if (next->fe_off == frent->fe_off + frent->fe_len)
407 			holes--;
408 	}
409 	return holes;
410 }
411 
412 static inline int
pf_frent_index(struct pf_frent * frent)413 pf_frent_index(struct pf_frent *frent)
414 {
415 	/*
416 	 * We have an array of 16 entry points to the queue.  A full size
417 	 * 65535 octet IP packet can have 8192 fragments.  So the queue
418 	 * traversal length is at most 512 and at most 16 entry points are
419 	 * checked.  We need 128 additional bytes on a 64 bit architecture.
420 	 */
421 	CTASSERT(((u_int16_t)0xffff &~ 7) / (0x10000 / PF_FRAG_ENTRY_POINTS) ==
422 	    16 - 1);
423 	CTASSERT(((u_int16_t)0xffff >> 3) / PF_FRAG_ENTRY_POINTS == 512 - 1);
424 
425 	return frent->fe_off / (0x10000 / PF_FRAG_ENTRY_POINTS);
426 }
427 
428 static int
pf_frent_insert(struct pf_fragment * frag,struct pf_frent * frent,struct pf_frent * prev)429 pf_frent_insert(struct pf_fragment *frag, struct pf_frent *frent,
430     struct pf_frent *prev)
431 {
432 	int index;
433 
434 	CTASSERT(PF_FRAG_ENTRY_LIMIT <= 0xff);
435 
436 	/*
437 	 * A packet has at most 65536 octets.  With 16 entry points, each one
438 	 * spawns 4096 octets.  We limit these to 64 fragments each, which
439 	 * means on average every fragment must have at least 64 octets.
440 	 */
441 	index = pf_frent_index(frent);
442 	if (frag->fr_entries[index] >= PF_FRAG_ENTRY_LIMIT)
443 		return ENOBUFS;
444 	frag->fr_entries[index]++;
445 
446 	if (prev == NULL) {
447 		TAILQ_INSERT_HEAD(&frag->fr_queue, frent, fr_next);
448 	} else {
449 		KASSERT(prev->fe_off + prev->fe_len <= frent->fe_off,
450 		    ("overlapping fragment"));
451 		TAILQ_INSERT_AFTER(&frag->fr_queue, prev, frent, fr_next);
452 	}
453 	counter_u64_add(V_pf_status.ncounters[NCNT_FRAG_INSERT], 1);
454 
455 	if (frag->fr_firstoff[index] == NULL) {
456 		KASSERT(prev == NULL || pf_frent_index(prev) < index,
457 		    ("prev == NULL || pf_frent_index(pref) < index"));
458 		frag->fr_firstoff[index] = frent;
459 	} else {
460 		if (frent->fe_off < frag->fr_firstoff[index]->fe_off) {
461 			KASSERT(prev == NULL || pf_frent_index(prev) < index,
462 			    ("prev == NULL || pf_frent_index(pref) < index"));
463 			frag->fr_firstoff[index] = frent;
464 		} else {
465 			KASSERT(prev != NULL, ("prev != NULL"));
466 			KASSERT(pf_frent_index(prev) == index,
467 			    ("pf_frent_index(prev) == index"));
468 		}
469 	}
470 
471 	frag->fr_holes += pf_frent_holes(frent);
472 
473 	return 0;
474 }
475 
476 void
pf_frent_remove(struct pf_fragment * frag,struct pf_frent * frent)477 pf_frent_remove(struct pf_fragment *frag, struct pf_frent *frent)
478 {
479 #ifdef INVARIANTS
480 	struct pf_frent *prev = TAILQ_PREV(frent, pf_fragq, fr_next);
481 #endif /* INVARIANTS */
482 	struct pf_frent *next = TAILQ_NEXT(frent, fr_next);
483 	int index;
484 
485 	frag->fr_holes -= pf_frent_holes(frent);
486 
487 	index = pf_frent_index(frent);
488 	KASSERT(frag->fr_firstoff[index] != NULL, ("frent not found"));
489 	if (frag->fr_firstoff[index]->fe_off == frent->fe_off) {
490 		if (next == NULL) {
491 			frag->fr_firstoff[index] = NULL;
492 		} else {
493 			KASSERT(frent->fe_off + frent->fe_len <= next->fe_off,
494 			    ("overlapping fragment"));
495 			if (pf_frent_index(next) == index) {
496 				frag->fr_firstoff[index] = next;
497 			} else {
498 				frag->fr_firstoff[index] = NULL;
499 			}
500 		}
501 	} else {
502 		KASSERT(frag->fr_firstoff[index]->fe_off < frent->fe_off,
503 		    ("frag->fr_firstoff[index]->fe_off < frent->fe_off"));
504 		KASSERT(prev != NULL, ("prev != NULL"));
505 		KASSERT(prev->fe_off + prev->fe_len <= frent->fe_off,
506 		    ("overlapping fragment"));
507 		KASSERT(pf_frent_index(prev) == index,
508 		    ("pf_frent_index(prev) == index"));
509 	}
510 
511 	TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
512 	counter_u64_add(V_pf_status.ncounters[NCNT_FRAG_REMOVALS], 1);
513 
514 	KASSERT(frag->fr_entries[index] > 0, ("No fragments remaining"));
515 	frag->fr_entries[index]--;
516 }
517 
518 struct pf_frent *
pf_frent_previous(struct pf_fragment * frag,struct pf_frent * frent)519 pf_frent_previous(struct pf_fragment *frag, struct pf_frent *frent)
520 {
521 	struct pf_frent *prev, *next;
522 	int index;
523 
524 	/*
525 	 * If there are no fragments after frag, take the final one.  Assume
526 	 * that the global queue is not empty.
527 	 */
528 	prev = TAILQ_LAST(&frag->fr_queue, pf_fragq);
529 	KASSERT(prev != NULL, ("prev != NULL"));
530 	if (prev->fe_off <= frent->fe_off)
531 		return prev;
532 	/*
533 	 * We want to find a fragment entry that is before frag, but still
534 	 * close to it.  Find the first fragment entry that is in the same
535 	 * entry point or in the first entry point after that.  As we have
536 	 * already checked that there are entries behind frag, this will
537 	 * succeed.
538 	 */
539 	for (index = pf_frent_index(frent); index < PF_FRAG_ENTRY_POINTS;
540 	    index++) {
541 		prev = frag->fr_firstoff[index];
542 		if (prev != NULL)
543 			break;
544 	}
545 	KASSERT(prev != NULL, ("prev != NULL"));
546 	/*
547 	 * In prev we may have a fragment from the same entry point that is
548 	 * before frent, or one that is just one position behind frent.
549 	 * In the latter case, we go back one step and have the predecessor.
550 	 * There may be none if the new fragment will be the first one.
551 	 */
552 	if (prev->fe_off > frent->fe_off) {
553 		prev = TAILQ_PREV(prev, pf_fragq, fr_next);
554 		if (prev == NULL)
555 			return NULL;
556 		KASSERT(prev->fe_off <= frent->fe_off,
557 		    ("prev->fe_off <= frent->fe_off"));
558 		return prev;
559 	}
560 	/*
561 	 * In prev is the first fragment of the entry point.  The offset
562 	 * of frag is behind it.  Find the closest previous fragment.
563 	 */
564 	for (next = TAILQ_NEXT(prev, fr_next); next != NULL;
565 	    next = TAILQ_NEXT(next, fr_next)) {
566 		if (next->fe_off > frent->fe_off)
567 			break;
568 		prev = next;
569 	}
570 	return prev;
571 }
572 
573 static struct pf_fragment *
pf_fillup_fragment(struct pf_frnode * key,uint32_t id,struct pf_frent * frent,u_short * reason)574 pf_fillup_fragment(struct pf_frnode *key, uint32_t id,
575     struct pf_frent *frent, u_short *reason)
576 {
577 	struct pf_frent		*after, *next, *prev;
578 	struct pf_fragment	*frag;
579 	struct pf_frnode	*frnode;
580 	uint16_t		total;
581 
582 	PF_FRAG_ASSERT();
583 
584 	/* No empty fragments. */
585 	if (frent->fe_len == 0) {
586 		DPFPRINTF(PF_DEBUG_MISC, "bad fragment: len 0");
587 		goto bad_fragment;
588 	}
589 
590 	/* All fragments are 8 byte aligned. */
591 	if (frent->fe_mff && (frent->fe_len & 0x7)) {
592 		DPFPRINTF(PF_DEBUG_MISC, "bad fragment: mff and len %d",
593 		    frent->fe_len);
594 		goto bad_fragment;
595 	}
596 
597 	/* Respect maximum length, IP_MAXPACKET == IPV6_MAXPACKET. */
598 	if (frent->fe_off + frent->fe_len > IP_MAXPACKET) {
599 		DPFPRINTF(PF_DEBUG_MISC, "bad fragment: max packet %d",
600 		    frent->fe_off + frent->fe_len);
601 		goto bad_fragment;
602 	}
603 
604 	if (key->fn_af == AF_INET)
605 		DPFPRINTF(PF_DEBUG_MISC, "reass frag %d @ %d-%d\n",
606 		    id, frent->fe_off, frent->fe_off + frent->fe_len);
607 	else
608 		DPFPRINTF(PF_DEBUG_MISC, "reass frag %#08x @ %d-%d",
609 		    id, frent->fe_off, frent->fe_off + frent->fe_len);
610 
611 	/* Fully buffer all of the fragments in this fragment queue. */
612 	frag = pf_find_fragment(key, id);
613 
614 	/* Create a new reassembly queue for this packet. */
615 	if (frag == NULL) {
616 		frag = uma_zalloc(V_pf_frag_z, M_NOWAIT);
617 		if (frag == NULL) {
618 			pf_flush_fragments();
619 			frag = uma_zalloc(V_pf_frag_z, M_NOWAIT);
620 			if (frag == NULL) {
621 				REASON_SET(reason, PFRES_MEMORY);
622 				goto drop_fragment;
623 			}
624 		}
625 
626 		frnode = RB_FIND(pf_frnode_tree, &V_pf_frnode_tree, key);
627 		if (frnode == NULL) {
628 			frnode = uma_zalloc(V_pf_frnode_z, M_NOWAIT);
629 			if (frnode == NULL) {
630 				pf_flush_fragments();
631 				frnode = uma_zalloc(V_pf_frnode_z, M_NOWAIT);
632 				if (frnode == NULL) {
633 					REASON_SET(reason, PFRES_MEMORY);
634 					uma_zfree(V_pf_frag_z, frag);
635 					goto drop_fragment;
636 				}
637 			}
638 			*frnode = *key;
639 			RB_INIT(&frnode->fn_tree);
640 			frnode->fn_fragments = 0;
641 		}
642 		memset(frag->fr_firstoff, 0, sizeof(frag->fr_firstoff));
643 		memset(frag->fr_entries, 0, sizeof(frag->fr_entries));
644 		frag->fr_timeout = time_uptime;
645 		TAILQ_INIT(&frag->fr_queue);
646 		frag->fr_maxlen = frent->fe_len;
647 		frag->fr_holes = 1;
648 
649 		frag->fr_id = id;
650 		frag->fr_node = frnode;
651 		/* RB_INSERT cannot fail as pf_find_fragment() found nothing */
652 		RB_INSERT(pf_frag_tree, &frnode->fn_tree, frag);
653 		frnode->fn_fragments++;
654 		if (frnode->fn_fragments == 1)
655 			RB_INSERT(pf_frnode_tree, &V_pf_frnode_tree, frnode);
656 
657 		TAILQ_INSERT_HEAD(&V_pf_fragqueue, frag, frag_next);
658 
659 		/* We do not have a previous fragment, cannot fail. */
660 		pf_frent_insert(frag, frent, NULL);
661 
662 		return (frag);
663 	}
664 
665 	KASSERT(!TAILQ_EMPTY(&frag->fr_queue), ("!TAILQ_EMPTY()->fr_queue"));
666 	MPASS(frag->fr_node);
667 
668 	/* Remember maximum fragment len for refragmentation. */
669 	if (frent->fe_len > frag->fr_maxlen)
670 		frag->fr_maxlen = frent->fe_len;
671 
672 	/* Maximum data we have seen already. */
673 	total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
674 		TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
675 
676 	/* Non terminal fragments must have more fragments flag. */
677 	if (frent->fe_off + frent->fe_len < total && !frent->fe_mff)
678 		goto free_ipv6_fragment;
679 
680 	/* Check if we saw the last fragment already. */
681 	if (!TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_mff) {
682 		if (frent->fe_off + frent->fe_len > total ||
683 		    (frent->fe_off + frent->fe_len == total && frent->fe_mff))
684 			goto free_ipv6_fragment;
685 	} else {
686 		if (frent->fe_off + frent->fe_len == total && !frent->fe_mff)
687 			goto free_ipv6_fragment;
688 	}
689 
690 	/* Find neighbors for newly inserted fragment */
691 	prev = pf_frent_previous(frag, frent);
692 	if (prev == NULL) {
693 		after = TAILQ_FIRST(&frag->fr_queue);
694 		KASSERT(after != NULL, ("after != NULL"));
695 	} else {
696 		after = TAILQ_NEXT(prev, fr_next);
697 	}
698 
699 	if (prev != NULL && prev->fe_off + prev->fe_len > frent->fe_off) {
700 		uint16_t precut;
701 
702 		if (frag->fr_node->fn_af == AF_INET6)
703 			goto free_fragment;
704 
705 		precut = prev->fe_off + prev->fe_len - frent->fe_off;
706 		if (precut >= frent->fe_len) {
707 			DPFPRINTF(PF_DEBUG_MISC, "new frag overlapped");
708 			goto drop_fragment;
709 		}
710 		DPFPRINTF(PF_DEBUG_MISC, "frag head overlap %d", precut);
711 		m_adj(frent->fe_m, precut);
712 		frent->fe_off += precut;
713 		frent->fe_len -= precut;
714 	}
715 
716 	for (; after != NULL && frent->fe_off + frent->fe_len > after->fe_off;
717 	    after = next) {
718 		uint16_t aftercut;
719 
720 		aftercut = frent->fe_off + frent->fe_len - after->fe_off;
721 		if (aftercut < after->fe_len) {
722 			DPFPRINTF(PF_DEBUG_MISC, "frag tail overlap %d",
723 			    aftercut);
724 			m_adj(after->fe_m, aftercut);
725 			/* Fragment may switch queue as fe_off changes */
726 			pf_frent_remove(frag, after);
727 			after->fe_off += aftercut;
728 			after->fe_len -= aftercut;
729 			/* Insert into correct queue */
730 			if (pf_frent_insert(frag, after, prev)) {
731 				DPFPRINTF(PF_DEBUG_MISC,
732 				    "fragment requeue limit exceeded");
733 				m_freem(after->fe_m);
734 				uma_zfree(V_pf_frent_z, after);
735 				/* There is not way to recover */
736 				goto free_fragment;
737 			}
738 			break;
739 		}
740 
741 		/* This fragment is completely overlapped, lose it. */
742 		DPFPRINTF(PF_DEBUG_MISC, "old frag overlapped");
743 		next = TAILQ_NEXT(after, fr_next);
744 		pf_frent_remove(frag, after);
745 		m_freem(after->fe_m);
746 		uma_zfree(V_pf_frent_z, after);
747 	}
748 
749 	/* If part of the queue gets too long, there is not way to recover. */
750 	if (pf_frent_insert(frag, frent, prev)) {
751 		DPFPRINTF(PF_DEBUG_MISC, "fragment queue limit exceeded");
752 		goto bad_fragment;
753 	}
754 
755 	return (frag);
756 
757 free_ipv6_fragment:
758 	if (frag->fr_node->fn_af == AF_INET)
759 		goto bad_fragment;
760 free_fragment:
761 	/*
762 	 * RFC 5722, Errata 3089:  When reassembling an IPv6 datagram, if one
763 	 * or more its constituent fragments is determined to be an overlapping
764 	 * fragment, the entire datagram (and any constituent fragments) MUST
765 	 * be silently discarded.
766 	 */
767 	DPFPRINTF(PF_DEBUG_MISC, "flush overlapping fragments");
768 	pf_free_fragment(frag);
769 
770 bad_fragment:
771 	REASON_SET(reason, PFRES_FRAG);
772 drop_fragment:
773 	uma_zfree(V_pf_frent_z, frent);
774 	return (NULL);
775 }
776 
777 static struct mbuf *
pf_join_fragment(struct pf_fragment * frag)778 pf_join_fragment(struct pf_fragment *frag)
779 {
780 	struct mbuf *m, *m2;
781 	struct pf_frent	*frent;
782 
783 	frent = TAILQ_FIRST(&frag->fr_queue);
784 	TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
785 	counter_u64_add(V_pf_status.ncounters[NCNT_FRAG_REMOVALS], 1);
786 
787 	m = frent->fe_m;
788 	if ((frent->fe_hdrlen + frent->fe_len) < m->m_pkthdr.len)
789 		m_adj(m, (frent->fe_hdrlen + frent->fe_len) - m->m_pkthdr.len);
790 	uma_zfree(V_pf_frent_z, frent);
791 	while ((frent = TAILQ_FIRST(&frag->fr_queue)) != NULL) {
792 		TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
793 		counter_u64_add(V_pf_status.ncounters[NCNT_FRAG_REMOVALS], 1);
794 
795 		m2 = frent->fe_m;
796 		/* Strip off ip header. */
797 		m_adj(m2, frent->fe_hdrlen);
798 		/* Strip off any trailing bytes. */
799 		if (frent->fe_len < m2->m_pkthdr.len)
800 			m_adj(m2, frent->fe_len - m2->m_pkthdr.len);
801 
802 		uma_zfree(V_pf_frent_z, frent);
803 		m_cat(m, m2);
804 	}
805 
806 	/* Remove from fragment queue. */
807 	pf_free_fragment(frag);
808 
809 	return (m);
810 }
811 
812 #ifdef INET
813 static int
pf_reassemble(struct mbuf ** m0,uint8_t dir,u_short * reason)814 pf_reassemble(struct mbuf **m0, uint8_t dir, u_short *reason)
815 {
816 	struct mbuf		*m = *m0;
817 	struct ip		*ip = mtod(m, struct ip *);
818 	struct pf_frent		*frent;
819 	struct pf_fragment	*frag;
820 	struct m_tag		*mtag;
821 	struct pf_fragment_tag	*ftag;
822 	struct pf_frnode	 key;
823 	uint16_t		 total, hdrlen;
824 	uint32_t		 frag_id;
825 	uint16_t		 maxlen;
826 
827 	/* Get an entry for the fragment queue */
828 	if ((frent = pf_create_fragment(reason)) == NULL)
829 		return (PF_DROP);
830 
831 	frent->fe_m = m;
832 	frent->fe_hdrlen = ip->ip_hl << 2;
833 	frent->fe_extoff = 0;
834 	frent->fe_len = ntohs(ip->ip_len) - (ip->ip_hl << 2);
835 	frent->fe_off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
836 	frent->fe_mff = ntohs(ip->ip_off) & IP_MF;
837 
838 	pf_ip2key(ip, &key, dir);
839 
840 	if ((frag = pf_fillup_fragment(&key, ip->ip_id, frent, reason)) == NULL)
841 		return (PF_DROP);
842 
843 	/* The mbuf is part of the fragment entry, no direct free or access */
844 	m = *m0 = NULL;
845 
846 	if (frag->fr_holes) {
847 		DPFPRINTF(PF_DEBUG_MISC, "frag %d, holes %d",
848 		    frag->fr_id, frag->fr_holes);
849 		return (PF_PASS);  /* drop because *m0 is NULL, no error */
850 	}
851 
852 	/* We have all the data */
853 	frent = TAILQ_FIRST(&frag->fr_queue);
854 	KASSERT(frent != NULL, ("frent != NULL"));
855 	total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
856 		TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
857 	hdrlen = frent->fe_hdrlen;
858 
859 	maxlen = frag->fr_maxlen;
860 	frag_id = frag->fr_id;
861 	m = *m0 = pf_join_fragment(frag);
862 	frag = NULL;
863 
864 	if (m->m_flags & M_PKTHDR) {
865 		int plen = 0;
866 		for (m = *m0; m; m = m->m_next)
867 			plen += m->m_len;
868 		m = *m0;
869 		m->m_pkthdr.len = plen;
870 	}
871 
872 	if ((mtag = m_tag_get(PACKET_TAG_PF_REASSEMBLED,
873 	    sizeof(struct pf_fragment_tag), M_NOWAIT)) == NULL) {
874 		REASON_SET(reason, PFRES_SHORT);
875 		/* PF_DROP requires a valid mbuf *m0 in pf_test() */
876 		return (PF_DROP);
877 	}
878 	ftag = (struct pf_fragment_tag *)(mtag + 1);
879 	ftag->ft_hdrlen = hdrlen;
880 	ftag->ft_extoff = 0;
881 	ftag->ft_maxlen = maxlen;
882 	ftag->ft_id = frag_id;
883 	m_tag_prepend(m, mtag);
884 
885 	ip = mtod(m, struct ip *);
886 	ip->ip_sum = pf_cksum_fixup(ip->ip_sum, ip->ip_len,
887 	    htons(hdrlen + total), 0);
888 	ip->ip_len = htons(hdrlen + total);
889 	ip->ip_sum = pf_cksum_fixup(ip->ip_sum, ip->ip_off,
890 	    ip->ip_off & ~(IP_MF|IP_OFFMASK), 0);
891 	ip->ip_off &= ~(IP_MF|IP_OFFMASK);
892 
893 	if (hdrlen + total > IP_MAXPACKET) {
894 		DPFPRINTF(PF_DEBUG_MISC, "drop: too big: %d", total);
895 		ip->ip_len = 0;
896 		REASON_SET(reason, PFRES_SHORT);
897 		/* PF_DROP requires a valid mbuf *m0 in pf_test() */
898 		return (PF_DROP);
899 	}
900 
901 	DPFPRINTF(PF_DEBUG_MISC, "complete: %p(%d)", m, ntohs(ip->ip_len));
902 	return (PF_PASS);
903 }
904 #endif	/* INET */
905 
906 #ifdef INET6
907 static int
pf_reassemble6(struct mbuf ** m0,struct ip6_frag * fraghdr,uint16_t hdrlen,uint16_t extoff,uint8_t dir,u_short * reason)908 pf_reassemble6(struct mbuf **m0, struct ip6_frag *fraghdr,
909     uint16_t hdrlen, uint16_t extoff, uint8_t dir, u_short *reason)
910 {
911 	struct mbuf		*m = *m0;
912 	struct ip6_hdr		*ip6 = mtod(m, struct ip6_hdr *);
913 	struct pf_frent		*frent;
914 	struct pf_fragment	*frag;
915 	struct pf_frnode	 key;
916 	struct m_tag		*mtag;
917 	struct pf_fragment_tag	*ftag;
918 	int			 off;
919 	uint32_t		 frag_id;
920 	uint16_t		 total, maxlen;
921 	uint8_t			 proto;
922 
923 	PF_FRAG_LOCK();
924 
925 	/* Get an entry for the fragment queue. */
926 	if ((frent = pf_create_fragment(reason)) == NULL) {
927 		PF_FRAG_UNLOCK();
928 		return (PF_DROP);
929 	}
930 
931 	frent->fe_m = m;
932 	frent->fe_hdrlen = hdrlen;
933 	frent->fe_extoff = extoff;
934 	frent->fe_len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen) - hdrlen;
935 	frent->fe_off = ntohs(fraghdr->ip6f_offlg & IP6F_OFF_MASK);
936 	frent->fe_mff = fraghdr->ip6f_offlg & IP6F_MORE_FRAG;
937 
938 	key.fn_src.v6 = ip6->ip6_src;
939 	key.fn_dst.v6 = ip6->ip6_dst;
940 	key.fn_af = AF_INET6;
941 	/* Only the first fragment's protocol is relevant. */
942 	key.fn_proto = 0;
943 	key.fn_direction = dir;
944 
945 	if ((frag = pf_fillup_fragment(&key, fraghdr->ip6f_ident, frent, reason)) == NULL) {
946 		PF_FRAG_UNLOCK();
947 		return (PF_DROP);
948 	}
949 
950 	/* The mbuf is part of the fragment entry, no direct free or access. */
951 	m = *m0 = NULL;
952 
953 	if (frag->fr_holes) {
954 		DPFPRINTF(PF_DEBUG_MISC, "frag %d, holes %d", frag->fr_id,
955 		    frag->fr_holes);
956 		PF_FRAG_UNLOCK();
957 		return (PF_PASS);  /* Drop because *m0 is NULL, no error. */
958 	}
959 
960 	/* We have all the data. */
961 	frent = TAILQ_FIRST(&frag->fr_queue);
962 	KASSERT(frent != NULL, ("frent != NULL"));
963 	extoff = frent->fe_extoff;
964 	maxlen = frag->fr_maxlen;
965 	frag_id = frag->fr_id;
966 	total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
967 		TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
968 	hdrlen = frent->fe_hdrlen - sizeof(struct ip6_frag);
969 
970 	m = *m0 = pf_join_fragment(frag);
971 	frag = NULL;
972 
973 	PF_FRAG_UNLOCK();
974 
975 	/* Take protocol from first fragment header. */
976 	m = m_getptr(m, hdrlen + offsetof(struct ip6_frag, ip6f_nxt), &off);
977 	KASSERT(m, ("%s: short mbuf chain", __func__));
978 	proto = *(mtod(m, uint8_t *) + off);
979 	m = *m0;
980 
981 	/* Delete frag6 header */
982 	if (ip6_deletefraghdr(m, hdrlen, M_NOWAIT) != 0)
983 		goto fail;
984 
985 	if (m->m_flags & M_PKTHDR) {
986 		int plen = 0;
987 		for (m = *m0; m; m = m->m_next)
988 			plen += m->m_len;
989 		m = *m0;
990 		m->m_pkthdr.len = plen;
991 	}
992 
993 	if ((mtag = m_tag_get(PACKET_TAG_PF_REASSEMBLED,
994 	    sizeof(struct pf_fragment_tag), M_NOWAIT)) == NULL)
995 		goto fail;
996 	ftag = (struct pf_fragment_tag *)(mtag + 1);
997 	ftag->ft_hdrlen = hdrlen;
998 	ftag->ft_extoff = extoff;
999 	ftag->ft_maxlen = maxlen;
1000 	ftag->ft_id = frag_id;
1001 	m_tag_prepend(m, mtag);
1002 
1003 	ip6 = mtod(m, struct ip6_hdr *);
1004 	ip6->ip6_plen = htons(hdrlen - sizeof(struct ip6_hdr) + total);
1005 	if (extoff) {
1006 		/* Write protocol into next field of last extension header. */
1007 		m = m_getptr(m, extoff + offsetof(struct ip6_ext, ip6e_nxt),
1008 		    &off);
1009 		KASSERT(m, ("%s: short mbuf chain", __func__));
1010 		*(mtod(m, char *) + off) = proto;
1011 		m = *m0;
1012 	} else
1013 		ip6->ip6_nxt = proto;
1014 
1015 	if (hdrlen - sizeof(struct ip6_hdr) + total > IPV6_MAXPACKET) {
1016 		DPFPRINTF(PF_DEBUG_MISC, "drop: too big: %d", total);
1017 		ip6->ip6_plen = 0;
1018 		REASON_SET(reason, PFRES_SHORT);
1019 		/* PF_DROP requires a valid mbuf *m0 in pf_test6(). */
1020 		return (PF_DROP);
1021 	}
1022 
1023 	DPFPRINTF(PF_DEBUG_MISC, "complete: %p(%d)", m,
1024 	    ntohs(ip6->ip6_plen));
1025 	return (PF_PASS);
1026 
1027 fail:
1028 	REASON_SET(reason, PFRES_MEMORY);
1029 	/* PF_DROP requires a valid mbuf *m0 in pf_test6(), will free later. */
1030 	return (PF_DROP);
1031 }
1032 #endif	/* INET6 */
1033 
1034 #ifdef INET6
1035 int
pf_max_frag_size(struct mbuf * m)1036 pf_max_frag_size(struct mbuf *m)
1037 {
1038 	struct m_tag *tag;
1039 	struct pf_fragment_tag *ftag;
1040 
1041 	tag = m_tag_find(m, PACKET_TAG_PF_REASSEMBLED, NULL);
1042 	if (tag == NULL)
1043 		return (m->m_pkthdr.len);
1044 
1045 	ftag = (struct pf_fragment_tag *)(tag + 1);
1046 
1047 	return (ftag->ft_maxlen);
1048 }
1049 
1050 int
pf_refragment6(struct ifnet * ifp,struct mbuf ** m0,struct m_tag * mtag,struct ifnet * rt,bool forward)1051 pf_refragment6(struct ifnet *ifp, struct mbuf **m0, struct m_tag *mtag,
1052     struct ifnet *rt, bool forward)
1053 {
1054 	struct mbuf		*m = *m0, *t;
1055 	struct ip6_hdr		*hdr;
1056 	struct pf_fragment_tag	*ftag = (struct pf_fragment_tag *)(mtag + 1);
1057 	struct pf_pdesc		 pd;
1058 	uint32_t		 frag_id;
1059 	uint16_t		 hdrlen, extoff, maxlen;
1060 	uint8_t			 proto;
1061 	int			 error, action;
1062 
1063 	hdrlen = ftag->ft_hdrlen;
1064 	extoff = ftag->ft_extoff;
1065 	maxlen = ftag->ft_maxlen;
1066 	frag_id = ftag->ft_id;
1067 	m_tag_delete(m, mtag);
1068 	mtag = NULL;
1069 	ftag = NULL;
1070 
1071 	if (extoff) {
1072 		int off;
1073 
1074 		/* Use protocol from next field of last extension header */
1075 		m = m_getptr(m, extoff + offsetof(struct ip6_ext, ip6e_nxt),
1076 		    &off);
1077 		KASSERT((m != NULL), ("pf_refragment6: short mbuf chain"));
1078 		proto = *(mtod(m, uint8_t *) + off);
1079 		*(mtod(m, char *) + off) = IPPROTO_FRAGMENT;
1080 		m = *m0;
1081 	} else {
1082 		hdr = mtod(m, struct ip6_hdr *);
1083 		proto = hdr->ip6_nxt;
1084 		hdr->ip6_nxt = IPPROTO_FRAGMENT;
1085 	}
1086 
1087 	/* In case of link-local traffic we'll need a scope set. */
1088 	hdr = mtod(m, struct ip6_hdr *);
1089 
1090 	in6_setscope(&hdr->ip6_src, ifp, NULL);
1091 	in6_setscope(&hdr->ip6_dst, ifp, NULL);
1092 
1093 	/* The MTU must be a multiple of 8 bytes, or we risk doing the
1094 	 * fragmentation wrong. */
1095 	maxlen = maxlen & ~7;
1096 
1097 	/*
1098 	 * Maxlen may be less than 8 if there was only a single
1099 	 * fragment.  As it was fragmented before, add a fragment
1100 	 * header also for a single fragment.  If total or maxlen
1101 	 * is less than 8, ip6_fragment() will return EMSGSIZE and
1102 	 * we drop the packet.
1103 	 */
1104 	error = ip6_fragment(ifp, m, hdrlen, proto, maxlen, frag_id);
1105 	m = (*m0)->m_nextpkt;
1106 	(*m0)->m_nextpkt = NULL;
1107 	if (error == 0) {
1108 		/* The first mbuf contains the unfragmented packet. */
1109 		m_freem(*m0);
1110 		*m0 = NULL;
1111 		action = PF_PASS;
1112 	} else {
1113 		/* Drop expects an mbuf to free. */
1114 		DPFPRINTF(PF_DEBUG_MISC, "refragment error %d", error);
1115 		action = PF_DROP;
1116 	}
1117 	for (; m; m = t) {
1118 		t = m->m_nextpkt;
1119 		m->m_nextpkt = NULL;
1120 		m->m_flags |= M_SKIP_FIREWALL;
1121 		memset(&pd, 0, sizeof(pd));
1122 		pd.pf_mtag = pf_find_mtag(m);
1123 		if (error != 0) {
1124 			m_freem(m);
1125 			continue;
1126 		}
1127 		if (rt != NULL) {
1128 			struct sockaddr_in6	dst;
1129 			hdr = mtod(m, struct ip6_hdr *);
1130 
1131 			bzero(&dst, sizeof(dst));
1132 			dst.sin6_family = AF_INET6;
1133 			dst.sin6_len = sizeof(dst);
1134 			dst.sin6_addr = hdr->ip6_dst;
1135 
1136 			if (m->m_pkthdr.len <= if_getmtu(ifp)) {
1137 				nd6_output_ifp(rt, rt, m, &dst, NULL);
1138 			} else {
1139 				in6_ifstat_inc(ifp, ifs6_in_toobig);
1140 				icmp6_error(m, ICMP6_PACKET_TOO_BIG, 0,
1141 				    if_getmtu(ifp));
1142 			}
1143 		} else if (forward) {
1144 			MPASS(m->m_pkthdr.rcvif != NULL);
1145 			ip6_forward(m, 0);
1146 		} else {
1147 			(void)ip6_output(m, NULL, NULL, 0, NULL, NULL,
1148 			    NULL);
1149 		}
1150 	}
1151 
1152 	return (action);
1153 }
1154 #endif /* INET6 */
1155 
1156 #ifdef INET
1157 int
pf_normalize_ip(u_short * reason,struct pf_pdesc * pd)1158 pf_normalize_ip(u_short *reason, struct pf_pdesc *pd)
1159 {
1160 	struct pf_krule		*r;
1161 	struct ip		*h = mtod(pd->m, struct ip *);
1162 	int			 mff = (ntohs(h->ip_off) & IP_MF);
1163 	int			 hlen = h->ip_hl << 2;
1164 	u_int16_t		 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
1165 	u_int16_t		 max;
1166 	int			 ip_len;
1167 	int			 tag = -1;
1168 	int			 verdict;
1169 	bool			 scrub_compat;
1170 
1171 	PF_RULES_RASSERT();
1172 
1173 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1174 	/*
1175 	 * Check if there are any scrub rules, matching or not.
1176 	 * Lack of scrub rules means:
1177 	 *  - enforced packet normalization operation just like in OpenBSD
1178 	 *  - fragment reassembly depends on V_pf_status.reass
1179 	 * With scrub rules:
1180 	 *  - packet normalization is performed if there is a matching scrub rule
1181 	 *  - fragment reassembly is performed if the matching rule has no
1182 	 *    PFRULE_FRAGMENT_NOREASS flag
1183 	 */
1184 	scrub_compat = (r != NULL);
1185 	while (r != NULL) {
1186 		pf_counter_u64_add(&r->evaluations, 1);
1187 		if (pfi_kkif_match(r->kif, pd->kif) == r->ifnot)
1188 			r = r->skip[PF_SKIP_IFP];
1189 		else if (r->direction && r->direction != pd->dir)
1190 			r = r->skip[PF_SKIP_DIR];
1191 		else if (r->af && r->af != AF_INET)
1192 			r = r->skip[PF_SKIP_AF];
1193 		else if (r->proto && r->proto != h->ip_p)
1194 			r = r->skip[PF_SKIP_PROTO];
1195 		else if (PF_MISMATCHAW(&r->src.addr,
1196 		    (struct pf_addr *)&h->ip_src.s_addr, AF_INET,
1197 		    r->src.neg, pd->kif, M_GETFIB(pd->m)))
1198 			r = r->skip[PF_SKIP_SRC_ADDR];
1199 		else if (PF_MISMATCHAW(&r->dst.addr,
1200 		    (struct pf_addr *)&h->ip_dst.s_addr, AF_INET,
1201 		    r->dst.neg, NULL, M_GETFIB(pd->m)))
1202 			r = r->skip[PF_SKIP_DST_ADDR];
1203 		else if (r->match_tag && !pf_match_tag(pd->m, r, &tag,
1204 		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
1205 			r = TAILQ_NEXT(r, entries);
1206 		else
1207 			break;
1208 	}
1209 
1210 	if (scrub_compat) {
1211 		/* With scrub rules present IPv4 normalization happens only
1212 		 * if one of rules has matched and it's not a "no scrub" rule */
1213 		if (r == NULL || r->action == PF_NOSCRUB)
1214 			return (PF_PASS);
1215 
1216 		pf_counter_u64_critical_enter();
1217 		pf_counter_u64_add_protected(&r->packets[pd->dir == PF_OUT], 1);
1218 		pf_counter_u64_add_protected(&r->bytes[pd->dir == PF_OUT], pd->tot_len);
1219 		pf_counter_u64_critical_exit();
1220 		pf_rule_to_actions(r, &pd->act);
1221 	}
1222 
1223 	/* Check for illegal packets */
1224 	if (hlen < (int)sizeof(struct ip)) {
1225 		REASON_SET(reason, PFRES_NORM);
1226 		goto drop;
1227 	}
1228 
1229 	if (hlen > ntohs(h->ip_len)) {
1230 		REASON_SET(reason, PFRES_NORM);
1231 		goto drop;
1232 	}
1233 
1234 	/* Clear IP_DF if the rule uses the no-df option or we're in no-df mode */
1235 	if (((!scrub_compat && V_pf_status.reass & PF_REASS_NODF) ||
1236 	    (r != NULL && r->rule_flag & PFRULE_NODF)) &&
1237 	    (h->ip_off & htons(IP_DF))
1238 	) {
1239 		u_int16_t ip_off = h->ip_off;
1240 
1241 		h->ip_off &= htons(~IP_DF);
1242 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1243 	}
1244 
1245 	/* We will need other tests here */
1246 	if (!fragoff && !mff)
1247 		goto no_fragment;
1248 
1249 	/* We're dealing with a fragment now. Don't allow fragments
1250 	 * with IP_DF to enter the cache. If the flag was cleared by
1251 	 * no-df above, fine. Otherwise drop it.
1252 	 */
1253 	if (h->ip_off & htons(IP_DF)) {
1254 		DPFPRINTF(PF_DEBUG_MISC, "IP_DF");
1255 		goto bad;
1256 	}
1257 
1258 	ip_len = ntohs(h->ip_len) - hlen;
1259 
1260 	/* All fragments are 8 byte aligned */
1261 	if (mff && (ip_len & 0x7)) {
1262 		DPFPRINTF(PF_DEBUG_MISC, "mff and %d", ip_len);
1263 		goto bad;
1264 	}
1265 
1266 	/* Respect maximum length */
1267 	if (fragoff + ip_len > IP_MAXPACKET) {
1268 		DPFPRINTF(PF_DEBUG_MISC, "max packet %d", fragoff + ip_len);
1269 		goto bad;
1270 	}
1271 
1272 	if ((!scrub_compat && V_pf_status.reass) ||
1273 	    (r != NULL && !(r->rule_flag & PFRULE_FRAGMENT_NOREASS))
1274 	) {
1275 		max = fragoff + ip_len;
1276 
1277 		/* Fully buffer all of the fragments
1278 		 * Might return a completely reassembled mbuf, or NULL */
1279 		PF_FRAG_LOCK();
1280 		DPFPRINTF(PF_DEBUG_MISC, "reass frag %d @ %d-%d",
1281 		    h->ip_id, fragoff, max);
1282 		verdict = pf_reassemble(&pd->m, pd->dir, reason);
1283 		PF_FRAG_UNLOCK();
1284 
1285 		if (verdict != PF_PASS)
1286 			return (PF_DROP);
1287 
1288 		if (pd->m == NULL)
1289 			return (PF_DROP);
1290 
1291 		h = mtod(pd->m, struct ip *);
1292 		pd->tot_len = htons(h->ip_len);
1293 
1294  no_fragment:
1295 		/* At this point, only IP_DF is allowed in ip_off */
1296 		if (h->ip_off & ~htons(IP_DF)) {
1297 			u_int16_t ip_off = h->ip_off;
1298 
1299 			h->ip_off &= htons(IP_DF);
1300 			h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1301 		}
1302 	}
1303 
1304 	return (PF_PASS);
1305 
1306  bad:
1307 	DPFPRINTF(PF_DEBUG_MISC, "dropping bad fragment");
1308 	REASON_SET(reason, PFRES_FRAG);
1309  drop:
1310 	if (r != NULL && r->log)
1311 		PFLOG_PACKET(PF_DROP, *reason, r, NULL, NULL, pd, 1, NULL);
1312 
1313 	return (PF_DROP);
1314 }
1315 #endif
1316 
1317 #ifdef INET6
1318 int
pf_normalize_ip6(int off,u_short * reason,struct pf_pdesc * pd)1319 pf_normalize_ip6(int off, u_short *reason,
1320     struct pf_pdesc *pd)
1321 {
1322 	struct pf_krule		*r;
1323 	struct ip6_hdr		*h;
1324 	struct ip6_frag		 frag;
1325 	bool			 scrub_compat;
1326 
1327 	PF_RULES_RASSERT();
1328 
1329 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1330 	/*
1331 	 * Check if there are any scrub rules, matching or not.
1332 	 * Lack of scrub rules means:
1333 	 *  - enforced packet normalization operation just like in OpenBSD
1334 	 * With scrub rules:
1335 	 *  - packet normalization is performed if there is a matching scrub rule
1336 	 * XXX: Fragment reassembly always performed for IPv6!
1337 	 */
1338 	scrub_compat = (r != NULL);
1339 	while (r != NULL) {
1340 		pf_counter_u64_add(&r->evaluations, 1);
1341 		if (pfi_kkif_match(r->kif, pd->kif) == r->ifnot)
1342 			r = r->skip[PF_SKIP_IFP];
1343 		else if (r->direction && r->direction != pd->dir)
1344 			r = r->skip[PF_SKIP_DIR];
1345 		else if (r->af && r->af != AF_INET6)
1346 			r = r->skip[PF_SKIP_AF];
1347 		else if (r->proto && r->proto != pd->proto)
1348 			r = r->skip[PF_SKIP_PROTO];
1349 		else if (PF_MISMATCHAW(&r->src.addr,
1350 		    (struct pf_addr *)&pd->src, AF_INET6,
1351 		    r->src.neg, pd->kif, M_GETFIB(pd->m)))
1352 			r = r->skip[PF_SKIP_SRC_ADDR];
1353 		else if (PF_MISMATCHAW(&r->dst.addr,
1354 		    (struct pf_addr *)&pd->dst, AF_INET6,
1355 		    r->dst.neg, NULL, M_GETFIB(pd->m)))
1356 			r = r->skip[PF_SKIP_DST_ADDR];
1357 		else
1358 			break;
1359 	}
1360 
1361 	if (scrub_compat) {
1362 		/* With scrub rules present IPv6 normalization happens only
1363 		 * if one of rules has matched and it's not a "no scrub" rule */
1364 		if (r == NULL || r->action == PF_NOSCRUB)
1365 			return (PF_PASS);
1366 
1367 		pf_counter_u64_critical_enter();
1368 		pf_counter_u64_add_protected(&r->packets[pd->dir == PF_OUT], 1);
1369 		pf_counter_u64_add_protected(&r->bytes[pd->dir == PF_OUT], pd->tot_len);
1370 		pf_counter_u64_critical_exit();
1371 		pf_rule_to_actions(r, &pd->act);
1372 	}
1373 
1374 	if (!pf_pull_hdr(pd->m, off, &frag, sizeof(frag), reason, AF_INET6))
1375 		return (PF_DROP);
1376 
1377 	/* Offset now points to data portion. */
1378 	off += sizeof(frag);
1379 
1380 	if (pd->virtual_proto == PF_VPROTO_FRAGMENT) {
1381 		/* Returns PF_DROP or *m0 is NULL or completely reassembled
1382 		 * mbuf. */
1383 		if (pf_reassemble6(&pd->m, &frag, off, pd->extoff, pd->dir, reason)
1384 		    != PF_PASS)
1385 			return (PF_DROP);
1386 		if (pd->m == NULL)
1387 			return (PF_DROP);
1388 		h = mtod(pd->m, struct ip6_hdr *);
1389 		pd->tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
1390 	}
1391 
1392 	return (PF_PASS);
1393 }
1394 #endif /* INET6 */
1395 
1396 int
pf_normalize_tcp(struct pf_pdesc * pd)1397 pf_normalize_tcp(struct pf_pdesc *pd)
1398 {
1399 	struct pf_krule	*r, *rm = NULL;
1400 	struct tcphdr	*th = &pd->hdr.tcp;
1401 	int		 rewrite = 0;
1402 	u_short		 reason;
1403 	u_int16_t	 flags;
1404 	sa_family_t	 af = pd->af;
1405 	int		 srs;
1406 
1407 	PF_RULES_RASSERT();
1408 
1409 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1410 	/* Check if there any scrub rules. Lack of scrub rules means enforced
1411 	 * packet normalization operation just like in OpenBSD. */
1412 	srs = (r != NULL);
1413 	while (r != NULL) {
1414 		pf_counter_u64_add(&r->evaluations, 1);
1415 		if (pfi_kkif_match(r->kif, pd->kif) == r->ifnot)
1416 			r = r->skip[PF_SKIP_IFP];
1417 		else if (r->direction && r->direction != pd->dir)
1418 			r = r->skip[PF_SKIP_DIR];
1419 		else if (r->af && r->af != af)
1420 			r = r->skip[PF_SKIP_AF];
1421 		else if (r->proto && r->proto != pd->proto)
1422 			r = r->skip[PF_SKIP_PROTO];
1423 		else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
1424 		    r->src.neg, pd->kif, M_GETFIB(pd->m)))
1425 			r = r->skip[PF_SKIP_SRC_ADDR];
1426 		else if (r->src.port_op && !pf_match_port(r->src.port_op,
1427 			    r->src.port[0], r->src.port[1], th->th_sport))
1428 			r = r->skip[PF_SKIP_SRC_PORT];
1429 		else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
1430 		    r->dst.neg, NULL, M_GETFIB(pd->m)))
1431 			r = r->skip[PF_SKIP_DST_ADDR];
1432 		else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1433 			    r->dst.port[0], r->dst.port[1], th->th_dport))
1434 			r = r->skip[PF_SKIP_DST_PORT];
1435 		else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1436 			    pf_osfp_fingerprint(pd, th),
1437 			    r->os_fingerprint))
1438 			r = TAILQ_NEXT(r, entries);
1439 		else {
1440 			rm = r;
1441 			break;
1442 		}
1443 	}
1444 
1445 	if (srs) {
1446 		/* With scrub rules present TCP normalization happens only
1447 		 * if one of rules has matched and it's not a "no scrub" rule */
1448 		if (rm == NULL || rm->action == PF_NOSCRUB)
1449 			return (PF_PASS);
1450 
1451 		pf_counter_u64_critical_enter();
1452 		pf_counter_u64_add_protected(&r->packets[pd->dir == PF_OUT], 1);
1453 		pf_counter_u64_add_protected(&r->bytes[pd->dir == PF_OUT], pd->tot_len);
1454 		pf_counter_u64_critical_exit();
1455 		pf_rule_to_actions(rm, &pd->act);
1456 	}
1457 
1458 	if (rm && rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1459 		pd->flags |= PFDESC_TCP_NORM;
1460 
1461 	flags = tcp_get_flags(th);
1462 	if (flags & TH_SYN) {
1463 		/* Illegal packet */
1464 		if (flags & TH_RST)
1465 			goto tcp_drop;
1466 
1467 		if (flags & TH_FIN)
1468 			goto tcp_drop;
1469 	} else {
1470 		/* Illegal packet */
1471 		if (!(flags & (TH_ACK|TH_RST)))
1472 			goto tcp_drop;
1473 	}
1474 
1475 	if (!(flags & TH_ACK)) {
1476 		/* These flags are only valid if ACK is set */
1477 		if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1478 			goto tcp_drop;
1479 	}
1480 
1481 	/* Check for illegal header length */
1482 	if (th->th_off < (sizeof(struct tcphdr) >> 2))
1483 		goto tcp_drop;
1484 
1485 	/* If flags changed, or reserved data set, then adjust */
1486 	if (flags != tcp_get_flags(th) ||
1487 	    (tcp_get_flags(th) & (TH_RES1|TH_RES2|TH_RES2)) != 0) {
1488 		u_int16_t	ov, nv;
1489 
1490 		ov = *(u_int16_t *)(&th->th_ack + 1);
1491 		flags &= ~(TH_RES1 | TH_RES2 | TH_RES3);
1492 		tcp_set_flags(th, flags);
1493 		nv = *(u_int16_t *)(&th->th_ack + 1);
1494 
1495 		th->th_sum = pf_proto_cksum_fixup(pd->m, th->th_sum, ov, nv, 0);
1496 		rewrite = 1;
1497 	}
1498 
1499 	/* Remove urgent pointer, if TH_URG is not set */
1500 	if (!(flags & TH_URG) && th->th_urp) {
1501 		th->th_sum = pf_proto_cksum_fixup(pd->m, th->th_sum, th->th_urp,
1502 		    0, 0);
1503 		th->th_urp = 0;
1504 		rewrite = 1;
1505 	}
1506 
1507 	/* copy back packet headers if we sanitized */
1508 	if (rewrite)
1509 		m_copyback(pd->m, pd->off, sizeof(*th), (caddr_t)th);
1510 
1511 	return (PF_PASS);
1512 
1513  tcp_drop:
1514 	REASON_SET(&reason, PFRES_NORM);
1515 	if (rm != NULL && r->log)
1516 		PFLOG_PACKET(PF_DROP, reason, r, NULL, NULL, pd, 1, NULL);
1517 	return (PF_DROP);
1518 }
1519 
1520 int
pf_normalize_tcp_init(struct pf_pdesc * pd,struct tcphdr * th,struct pf_state_peer * src)1521 pf_normalize_tcp_init(struct pf_pdesc *pd, struct tcphdr *th,
1522     struct pf_state_peer *src)
1523 {
1524 	u_int32_t tsval, tsecr;
1525 	int		 olen;
1526 	uint8_t		 opts[MAX_TCPOPTLEN], *opt;
1527 
1528 	KASSERT((src->scrub == NULL),
1529 	    ("pf_normalize_tcp_init: src->scrub != NULL"));
1530 
1531 	src->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT);
1532 	if (src->scrub == NULL)
1533 		return (1);
1534 
1535 	switch (pd->af) {
1536 #ifdef INET
1537 	case AF_INET: {
1538 		struct ip *h = mtod(pd->m, struct ip *);
1539 		src->scrub->pfss_ttl = h->ip_ttl;
1540 		break;
1541 	}
1542 #endif /* INET */
1543 #ifdef INET6
1544 	case AF_INET6: {
1545 		struct ip6_hdr *h = mtod(pd->m, struct ip6_hdr *);
1546 		src->scrub->pfss_ttl = h->ip6_hlim;
1547 		break;
1548 	}
1549 #endif /* INET6 */
1550 	default:
1551 		unhandled_af(pd->af);
1552 	}
1553 
1554 	/*
1555 	 * All normalizations below are only begun if we see the start of
1556 	 * the connections.  They must all set an enabled bit in pfss_flags
1557 	 */
1558 	if ((tcp_get_flags(th) & TH_SYN) == 0)
1559 		return (0);
1560 
1561 	olen = (th->th_off << 2) - sizeof(*th);
1562 	if (olen < TCPOLEN_TIMESTAMP || !pf_pull_hdr(pd->m,
1563 	    pd->off + sizeof(*th), opts, olen, NULL, pd->af))
1564 		return (0);
1565 
1566 	opt = opts;
1567 	while ((opt = pf_find_tcpopt(opt, opts, olen,
1568 	    TCPOPT_TIMESTAMP, TCPOLEN_TIMESTAMP)) != NULL) {
1569 		src->scrub->pfss_flags |= PFSS_TIMESTAMP;
1570 		src->scrub->pfss_ts_mod = arc4random();
1571 		/* note PFSS_PAWS not set yet */
1572 		memcpy(&tsval, &opt[2], sizeof(u_int32_t));
1573 		memcpy(&tsecr, &opt[6], sizeof(u_int32_t));
1574 		src->scrub->pfss_tsval0 = ntohl(tsval);
1575 		src->scrub->pfss_tsval = ntohl(tsval);
1576 		src->scrub->pfss_tsecr = ntohl(tsecr);
1577 		getmicrouptime(&src->scrub->pfss_last);
1578 
1579 		opt += opt[1];
1580 	}
1581 
1582 	return (0);
1583 }
1584 
1585 void
pf_normalize_tcp_cleanup(struct pf_kstate * state)1586 pf_normalize_tcp_cleanup(struct pf_kstate *state)
1587 {
1588 	/* XXX Note: this also cleans up SCTP. */
1589 	uma_zfree(V_pf_state_scrub_z, state->src.scrub);
1590 	uma_zfree(V_pf_state_scrub_z, state->dst.scrub);
1591 
1592 	/* Someday... flush the TCP segment reassembly descriptors. */
1593 }
1594 int
pf_normalize_sctp_init(struct pf_pdesc * pd,struct pf_state_peer * src,struct pf_state_peer * dst)1595 pf_normalize_sctp_init(struct pf_pdesc *pd, struct pf_state_peer *src,
1596     struct pf_state_peer *dst)
1597 {
1598 	src->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT);
1599 	if (src->scrub == NULL)
1600 		return (1);
1601 
1602 	dst->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT);
1603 	if (dst->scrub == NULL) {
1604 		uma_zfree(V_pf_state_scrub_z, src);
1605 		return (1);
1606 	}
1607 
1608 	dst->scrub->pfss_v_tag = pd->sctp_initiate_tag;
1609 
1610 	return (0);
1611 }
1612 
1613 int
pf_normalize_tcp_stateful(struct pf_pdesc * pd,u_short * reason,struct tcphdr * th,struct pf_kstate * state,struct pf_state_peer * src,struct pf_state_peer * dst,int * writeback)1614 pf_normalize_tcp_stateful(struct pf_pdesc *pd,
1615     u_short *reason, struct tcphdr *th, struct pf_kstate *state,
1616     struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1617 {
1618 	struct timeval uptime;
1619 	u_int tsval_from_last;
1620 	uint32_t tsval, tsecr;
1621 	int copyback = 0;
1622 	int got_ts = 0;
1623 	int olen;
1624 	uint8_t opts[MAX_TCPOPTLEN], *opt;
1625 
1626 	KASSERT((src->scrub || dst->scrub),
1627 	    ("%s: src->scrub && dst->scrub!", __func__));
1628 
1629 	/*
1630 	 * Enforce the minimum TTL seen for this connection.  Negate a common
1631 	 * technique to evade an intrusion detection system and confuse
1632 	 * firewall state code.
1633 	 */
1634 	switch (pd->af) {
1635 #ifdef INET
1636 	case AF_INET: {
1637 		if (src->scrub) {
1638 			struct ip *h = mtod(pd->m, struct ip *);
1639 			if (h->ip_ttl > src->scrub->pfss_ttl)
1640 				src->scrub->pfss_ttl = h->ip_ttl;
1641 			h->ip_ttl = src->scrub->pfss_ttl;
1642 		}
1643 		break;
1644 	}
1645 #endif /* INET */
1646 #ifdef INET6
1647 	case AF_INET6: {
1648 		if (src->scrub) {
1649 			struct ip6_hdr *h = mtod(pd->m, struct ip6_hdr *);
1650 			if (h->ip6_hlim > src->scrub->pfss_ttl)
1651 				src->scrub->pfss_ttl = h->ip6_hlim;
1652 			h->ip6_hlim = src->scrub->pfss_ttl;
1653 		}
1654 		break;
1655 	}
1656 #endif /* INET6 */
1657 	default:
1658 		unhandled_af(pd->af);
1659 	}
1660 
1661 	olen = (th->th_off << 2) - sizeof(*th);
1662 
1663 	if (olen >= TCPOLEN_TIMESTAMP &&
1664 	    ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1665 	    (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1666 	    pf_pull_hdr(pd->m, pd->off + sizeof(*th), opts, olen, NULL, pd->af)) {
1667 		/* Modulate the timestamps.  Can be used for NAT detection, OS
1668 		 * uptime determination or reboot detection.
1669 		 */
1670 		opt = opts;
1671 		while ((opt = pf_find_tcpopt(opt, opts, olen,
1672 		    TCPOPT_TIMESTAMP, TCPOLEN_TIMESTAMP)) != NULL) {
1673 			uint8_t *ts = opt + 2;
1674 			uint8_t *tsr = opt + 6;
1675 
1676 			if (got_ts) {
1677 				/* Huh?  Multiple timestamps!? */
1678 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
1679 					printf("pf: %s: multiple TS??", __func__);
1680 					pf_print_state(state);
1681 					printf("\n");
1682 				}
1683 				REASON_SET(reason, PFRES_TS);
1684 				return (PF_DROP);
1685 			}
1686 
1687 			memcpy(&tsval, ts, sizeof(u_int32_t));
1688 			memcpy(&tsecr, tsr, sizeof(u_int32_t));
1689 
1690 			/* modulate TS */
1691 			if (tsval && src->scrub &&
1692 			    (src->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1693 				/* tsval used further on */
1694 				tsval = ntohl(tsval);
1695 				pf_patch_32(pd,
1696 				    ts, htonl(tsval + src->scrub->pfss_ts_mod),
1697 				    PF_ALGNMNT(ts - opts));
1698 				copyback = 1;
1699 			}
1700 
1701 			/* modulate TS reply if any (!0) */
1702 			if (tsecr && dst->scrub &&
1703 			    (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1704 				/* tsecr used further on */
1705 				tsecr = ntohl(tsecr) - dst->scrub->pfss_ts_mod;
1706 				pf_patch_32(pd, tsr, htonl(tsecr),
1707 				    PF_ALGNMNT(tsr - opts));
1708 				copyback = 1;
1709 			}
1710 
1711 			got_ts = 1;
1712 			opt += opt[1];
1713 		}
1714 
1715 		if (copyback) {
1716 			/* Copyback the options, caller copys back header */
1717 			*writeback = 1;
1718 			m_copyback(pd->m, pd->off + sizeof(*th), olen, opts);
1719 		}
1720 	}
1721 
1722 	/*
1723 	 * Must invalidate PAWS checks on connections idle for too long.
1724 	 * The fastest allowed timestamp clock is 1ms.  That turns out to
1725 	 * be about 24 days before it wraps.  XXX Right now our lowerbound
1726 	 * TS echo check only works for the first 12 days of a connection
1727 	 * when the TS has exhausted half its 32bit space
1728 	 */
1729 #define TS_MAX_IDLE	(24*24*60*60)
1730 #define TS_MAX_CONN	(12*24*60*60)	/* XXX remove when better tsecr check */
1731 
1732 	getmicrouptime(&uptime);
1733 	if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1734 	    (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1735 	    time_uptime - (state->creation / 1000) > TS_MAX_CONN))  {
1736 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
1737 			DPFPRINTF(PF_DEBUG_MISC, "src idled out of PAWS");
1738 			pf_print_state(state);
1739 			printf("\n");
1740 		}
1741 		src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1742 		    | PFSS_PAWS_IDLED;
1743 	}
1744 	if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1745 	    uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1746 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
1747 			DPFPRINTF(PF_DEBUG_MISC, "dst idled out of PAWS");
1748 			pf_print_state(state);
1749 			printf("\n");
1750 		}
1751 		dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1752 		    | PFSS_PAWS_IDLED;
1753 	}
1754 
1755 	if (got_ts && src->scrub && dst->scrub &&
1756 	    (src->scrub->pfss_flags & PFSS_PAWS) &&
1757 	    (dst->scrub->pfss_flags & PFSS_PAWS)) {
1758 		/* Validate that the timestamps are "in-window".
1759 		 * RFC1323 describes TCP Timestamp options that allow
1760 		 * measurement of RTT (round trip time) and PAWS
1761 		 * (protection against wrapped sequence numbers).  PAWS
1762 		 * gives us a set of rules for rejecting packets on
1763 		 * long fat pipes (packets that were somehow delayed
1764 		 * in transit longer than the time it took to send the
1765 		 * full TCP sequence space of 4Gb).  We can use these
1766 		 * rules and infer a few others that will let us treat
1767 		 * the 32bit timestamp and the 32bit echoed timestamp
1768 		 * as sequence numbers to prevent a blind attacker from
1769 		 * inserting packets into a connection.
1770 		 *
1771 		 * RFC1323 tells us:
1772 		 *  - The timestamp on this packet must be greater than
1773 		 *    or equal to the last value echoed by the other
1774 		 *    endpoint.  The RFC says those will be discarded
1775 		 *    since it is a dup that has already been acked.
1776 		 *    This gives us a lowerbound on the timestamp.
1777 		 *        timestamp >= other last echoed timestamp
1778 		 *  - The timestamp will be less than or equal to
1779 		 *    the last timestamp plus the time between the
1780 		 *    last packet and now.  The RFC defines the max
1781 		 *    clock rate as 1ms.  We will allow clocks to be
1782 		 *    up to 10% fast and will allow a total difference
1783 		 *    or 30 seconds due to a route change.  And this
1784 		 *    gives us an upperbound on the timestamp.
1785 		 *        timestamp <= last timestamp + max ticks
1786 		 *    We have to be careful here.  Windows will send an
1787 		 *    initial timestamp of zero and then initialize it
1788 		 *    to a random value after the 3whs; presumably to
1789 		 *    avoid a DoS by having to call an expensive RNG
1790 		 *    during a SYN flood.  Proof MS has at least one
1791 		 *    good security geek.
1792 		 *
1793 		 *  - The TCP timestamp option must also echo the other
1794 		 *    endpoints timestamp.  The timestamp echoed is the
1795 		 *    one carried on the earliest unacknowledged segment
1796 		 *    on the left edge of the sequence window.  The RFC
1797 		 *    states that the host will reject any echoed
1798 		 *    timestamps that were larger than any ever sent.
1799 		 *    This gives us an upperbound on the TS echo.
1800 		 *        tescr <= largest_tsval
1801 		 *  - The lowerbound on the TS echo is a little more
1802 		 *    tricky to determine.  The other endpoint's echoed
1803 		 *    values will not decrease.  But there may be
1804 		 *    network conditions that re-order packets and
1805 		 *    cause our view of them to decrease.  For now the
1806 		 *    only lowerbound we can safely determine is that
1807 		 *    the TS echo will never be less than the original
1808 		 *    TS.  XXX There is probably a better lowerbound.
1809 		 *    Remove TS_MAX_CONN with better lowerbound check.
1810 		 *        tescr >= other original TS
1811 		 *
1812 		 * It is also important to note that the fastest
1813 		 * timestamp clock of 1ms will wrap its 32bit space in
1814 		 * 24 days.  So we just disable TS checking after 24
1815 		 * days of idle time.  We actually must use a 12d
1816 		 * connection limit until we can come up with a better
1817 		 * lowerbound to the TS echo check.
1818 		 */
1819 		struct timeval delta_ts;
1820 		int ts_fudge;
1821 
1822 		/*
1823 		 * PFTM_TS_DIFF is how many seconds of leeway to allow
1824 		 * a host's timestamp.  This can happen if the previous
1825 		 * packet got delayed in transit for much longer than
1826 		 * this packet.
1827 		 */
1828 		if ((ts_fudge = state->rule->timeout[PFTM_TS_DIFF]) == 0)
1829 			ts_fudge = V_pf_default_rule.timeout[PFTM_TS_DIFF];
1830 
1831 		/* Calculate max ticks since the last timestamp */
1832 #define TS_MAXFREQ	1100		/* RFC max TS freq of 1Khz + 10% skew */
1833 #define TS_MICROSECS	1000000		/* microseconds per second */
1834 		delta_ts = uptime;
1835 		timevalsub(&delta_ts, &src->scrub->pfss_last);
1836 		tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1837 		tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1838 
1839 		if ((src->state >= TCPS_ESTABLISHED &&
1840 		    dst->state >= TCPS_ESTABLISHED) &&
1841 		    (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1842 		    SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1843 		    (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1844 		    SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1845 			/* Bad RFC1323 implementation or an insertion attack.
1846 			 *
1847 			 * - Solaris 2.6 and 2.7 are known to send another ACK
1848 			 *   after the FIN,FIN|ACK,ACK closing that carries
1849 			 *   an old timestamp.
1850 			 */
1851 
1852 			DPFPRINTF(PF_DEBUG_MISC, "Timestamp failed %c%c%c%c",
1853 			    SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1854 			    SEQ_GT(tsval, src->scrub->pfss_tsval +
1855 			    tsval_from_last) ? '1' : ' ',
1856 			    SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1857 			    SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' ');
1858 			DPFPRINTF(PF_DEBUG_MISC, " tsval: %u  tsecr: %u  +ticks: "
1859 			    "%u  idle: %jus %lums",
1860 			    tsval, tsecr, tsval_from_last,
1861 			    (uintmax_t)delta_ts.tv_sec,
1862 			    delta_ts.tv_usec / 1000);
1863 			DPFPRINTF(PF_DEBUG_MISC, " src->tsval: %u  tsecr: %u",
1864 			    src->scrub->pfss_tsval, src->scrub->pfss_tsecr);
1865 			DPFPRINTF(PF_DEBUG_MISC, " dst->tsval: %u  tsecr: %u  "
1866 			    "tsval0: %u", dst->scrub->pfss_tsval,
1867 			    dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0);
1868 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
1869 				pf_print_state(state);
1870 				pf_print_flags(tcp_get_flags(th));
1871 				printf("\n");
1872 			}
1873 			REASON_SET(reason, PFRES_TS);
1874 			return (PF_DROP);
1875 		}
1876 
1877 		/* XXX I'd really like to require tsecr but it's optional */
1878 
1879 	} else if (!got_ts && (tcp_get_flags(th) & TH_RST) == 0 &&
1880 	    ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1881 	    || pd->p_len > 0 || (tcp_get_flags(th) & TH_SYN)) &&
1882 	    src->scrub && dst->scrub &&
1883 	    (src->scrub->pfss_flags & PFSS_PAWS) &&
1884 	    (dst->scrub->pfss_flags & PFSS_PAWS)) {
1885 		/* Didn't send a timestamp.  Timestamps aren't really useful
1886 		 * when:
1887 		 *  - connection opening or closing (often not even sent).
1888 		 *    but we must not let an attacker to put a FIN on a
1889 		 *    data packet to sneak it through our ESTABLISHED check.
1890 		 *  - on a TCP reset.  RFC suggests not even looking at TS.
1891 		 *  - on an empty ACK.  The TS will not be echoed so it will
1892 		 *    probably not help keep the RTT calculation in sync and
1893 		 *    there isn't as much danger when the sequence numbers
1894 		 *    got wrapped.  So some stacks don't include TS on empty
1895 		 *    ACKs :-(
1896 		 *
1897 		 * To minimize the disruption to mostly RFC1323 conformant
1898 		 * stacks, we will only require timestamps on data packets.
1899 		 *
1900 		 * And what do ya know, we cannot require timestamps on data
1901 		 * packets.  There appear to be devices that do legitimate
1902 		 * TCP connection hijacking.  There are HTTP devices that allow
1903 		 * a 3whs (with timestamps) and then buffer the HTTP request.
1904 		 * If the intermediate device has the HTTP response cache, it
1905 		 * will spoof the response but not bother timestamping its
1906 		 * packets.  So we can look for the presence of a timestamp in
1907 		 * the first data packet and if there, require it in all future
1908 		 * packets.
1909 		 */
1910 
1911 		if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1912 			/*
1913 			 * Hey!  Someone tried to sneak a packet in.  Or the
1914 			 * stack changed its RFC1323 behavior?!?!
1915 			 */
1916 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
1917 				DPFPRINTF(PF_DEBUG_MISC, "Did not receive expected "
1918 				    "RFC1323 timestamp");
1919 				pf_print_state(state);
1920 				pf_print_flags(tcp_get_flags(th));
1921 				printf("\n");
1922 			}
1923 			REASON_SET(reason, PFRES_TS);
1924 			return (PF_DROP);
1925 		}
1926 	}
1927 
1928 	/*
1929 	 * We will note if a host sends his data packets with or without
1930 	 * timestamps.  And require all data packets to contain a timestamp
1931 	 * if the first does.  PAWS implicitly requires that all data packets be
1932 	 * timestamped.  But I think there are middle-man devices that hijack
1933 	 * TCP streams immediately after the 3whs and don't timestamp their
1934 	 * packets (seen in a WWW accelerator or cache).
1935 	 */
1936 	if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1937 	    (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1938 		if (got_ts)
1939 			src->scrub->pfss_flags |= PFSS_DATA_TS;
1940 		else {
1941 			src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1942 			if (V_pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1943 			    (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1944 				/* Don't warn if other host rejected RFC1323 */
1945 				DPFPRINTF(PF_DEBUG_MISC, "Broken RFC1323 stack did "
1946 				    "not timestamp data packet. Disabled PAWS "
1947 				    "security.");
1948 				pf_print_state(state);
1949 				pf_print_flags(tcp_get_flags(th));
1950 				printf("\n");
1951 			}
1952 		}
1953 	}
1954 
1955 	/*
1956 	 * Update PAWS values
1957 	 */
1958 	if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1959 	    (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1960 		getmicrouptime(&src->scrub->pfss_last);
1961 		if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1962 		    (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1963 			src->scrub->pfss_tsval = tsval;
1964 
1965 		if (tsecr) {
1966 			if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1967 			    (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1968 				src->scrub->pfss_tsecr = tsecr;
1969 
1970 			if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1971 			    (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1972 			    src->scrub->pfss_tsval0 == 0)) {
1973 				/* tsval0 MUST be the lowest timestamp */
1974 				src->scrub->pfss_tsval0 = tsval;
1975 			}
1976 
1977 			/* Only fully initialized after a TS gets echoed */
1978 			if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1979 				src->scrub->pfss_flags |= PFSS_PAWS;
1980 		}
1981 	}
1982 
1983 	/* I have a dream....  TCP segment reassembly.... */
1984 	return (0);
1985 }
1986 
1987 int
pf_normalize_mss(struct pf_pdesc * pd)1988 pf_normalize_mss(struct pf_pdesc *pd)
1989 {
1990 	int		 olen, optsoff;
1991 	uint8_t		 opts[MAX_TCPOPTLEN], *opt;
1992 
1993 	olen = (pd->hdr.tcp.th_off << 2) - sizeof(struct tcphdr);
1994 	optsoff = pd->off + sizeof(struct tcphdr);
1995 	if (olen < TCPOLEN_MAXSEG ||
1996 	    !pf_pull_hdr(pd->m, optsoff, opts, olen, NULL, pd->af))
1997 		return (0);
1998 
1999 	opt = opts;
2000 	while ((opt = pf_find_tcpopt(opt, opts, olen,
2001 	    TCPOPT_MAXSEG, TCPOLEN_MAXSEG)) != NULL) {
2002 		uint16_t	 mss;
2003 		uint8_t		*mssp = opt + 2;
2004 		memcpy(&mss, mssp, sizeof(mss));
2005 		if (ntohs(mss) > pd->act.max_mss) {
2006 			size_t mssoffopts = mssp - opts;
2007 			pf_patch_16(pd, &mss,
2008 			    htons(pd->act.max_mss), PF_ALGNMNT(mssoffopts));
2009 			m_copyback(pd->m, optsoff + mssoffopts,
2010 			    sizeof(mss), (caddr_t)&mss);
2011 			m_copyback(pd->m, pd->off,
2012 			    sizeof(struct tcphdr), (caddr_t)&pd->hdr.tcp);
2013 		}
2014 
2015 		opt += opt[1];
2016 	}
2017 
2018 	return (0);
2019 }
2020 
2021 int
pf_scan_sctp(struct pf_pdesc * pd)2022 pf_scan_sctp(struct pf_pdesc *pd)
2023 {
2024 	struct sctp_chunkhdr ch = { };
2025 	int chunk_off = sizeof(struct sctphdr);
2026 	int chunk_start;
2027 	int ret;
2028 
2029 	while (pd->off + chunk_off < pd->tot_len) {
2030 		if (!pf_pull_hdr(pd->m, pd->off + chunk_off, &ch, sizeof(ch),
2031 		    NULL, pd->af))
2032 			return (PF_DROP);
2033 
2034 		/* Length includes the header, this must be at least 4. */
2035 		if (ntohs(ch.chunk_length) < 4)
2036 			return (PF_DROP);
2037 
2038 		chunk_start = chunk_off;
2039 		chunk_off += roundup(ntohs(ch.chunk_length), 4);
2040 
2041 		switch (ch.chunk_type) {
2042 		case SCTP_INITIATION:
2043 		case SCTP_INITIATION_ACK: {
2044 			struct sctp_init_chunk init;
2045 
2046 			if (!pf_pull_hdr(pd->m, pd->off + chunk_start, &init,
2047 			    sizeof(init), NULL, pd->af))
2048 				return (PF_DROP);
2049 
2050 			/*
2051 			 * RFC 9620, Section 3.3.2, "The Initiate Tag is allowed to have
2052 			 * any value except 0."
2053 			 */
2054 			if (init.init.initiate_tag == 0)
2055 				return (PF_DROP);
2056 			if (init.init.num_inbound_streams == 0)
2057 				return (PF_DROP);
2058 			if (init.init.num_outbound_streams == 0)
2059 				return (PF_DROP);
2060 			if (ntohl(init.init.a_rwnd) < SCTP_MIN_RWND)
2061 				return (PF_DROP);
2062 
2063 			/*
2064 			 * RFC 9260, Section 3.1, INIT chunks MUST have zero
2065 			 * verification tag.
2066 			 */
2067 			if (ch.chunk_type == SCTP_INITIATION &&
2068 			    pd->hdr.sctp.v_tag != 0)
2069 				return (PF_DROP);
2070 
2071 			pd->sctp_initiate_tag = init.init.initiate_tag;
2072 
2073 			if (ch.chunk_type == SCTP_INITIATION)
2074 				pd->sctp_flags |= PFDESC_SCTP_INIT;
2075 			else
2076 				pd->sctp_flags |= PFDESC_SCTP_INIT_ACK;
2077 
2078 			ret = pf_multihome_scan_init(pd->off + chunk_start,
2079 			    ntohs(init.ch.chunk_length), pd);
2080 			if (ret != PF_PASS)
2081 				return (ret);
2082 
2083 			break;
2084 		}
2085 		case SCTP_ABORT_ASSOCIATION:
2086 			pd->sctp_flags |= PFDESC_SCTP_ABORT;
2087 			break;
2088 		case SCTP_SHUTDOWN:
2089 		case SCTP_SHUTDOWN_ACK:
2090 			pd->sctp_flags |= PFDESC_SCTP_SHUTDOWN;
2091 			break;
2092 		case SCTP_SHUTDOWN_COMPLETE:
2093 			pd->sctp_flags |= PFDESC_SCTP_SHUTDOWN_COMPLETE;
2094 			break;
2095 		case SCTP_COOKIE_ECHO:
2096 			pd->sctp_flags |= PFDESC_SCTP_COOKIE;
2097 			break;
2098 		case SCTP_COOKIE_ACK:
2099 			pd->sctp_flags |= PFDESC_SCTP_COOKIE_ACK;
2100 			break;
2101 		case SCTP_DATA:
2102 			pd->sctp_flags |= PFDESC_SCTP_DATA;
2103 			break;
2104 		case SCTP_HEARTBEAT_REQUEST:
2105 			pd->sctp_flags |= PFDESC_SCTP_HEARTBEAT;
2106 			break;
2107 		case SCTP_HEARTBEAT_ACK:
2108 			pd->sctp_flags |= PFDESC_SCTP_HEARTBEAT_ACK;
2109 			break;
2110 		case SCTP_ASCONF:
2111 			pd->sctp_flags |= PFDESC_SCTP_ASCONF;
2112 
2113 			ret = pf_multihome_scan_asconf(pd->off + chunk_start,
2114 			    ntohs(ch.chunk_length), pd);
2115 			if (ret != PF_PASS)
2116 				return (ret);
2117 			break;
2118 		default:
2119 			pd->sctp_flags |= PFDESC_SCTP_OTHER;
2120 			break;
2121 		}
2122 	}
2123 
2124 	/* Validate chunk lengths vs. packet length. */
2125 	if (pd->off + chunk_off != pd->tot_len)
2126 		return (PF_DROP);
2127 
2128 	/*
2129 	 * INIT, INIT_ACK or SHUTDOWN_COMPLETE chunks must always be the only
2130 	 * one in a packet.
2131 	 */
2132 	if ((pd->sctp_flags & PFDESC_SCTP_INIT) &&
2133 	    (pd->sctp_flags & ~PFDESC_SCTP_INIT))
2134 		return (PF_DROP);
2135 	if ((pd->sctp_flags & PFDESC_SCTP_INIT_ACK) &&
2136 	    (pd->sctp_flags & ~PFDESC_SCTP_INIT_ACK))
2137 		return (PF_DROP);
2138 	if ((pd->sctp_flags & PFDESC_SCTP_SHUTDOWN_COMPLETE) &&
2139 	    (pd->sctp_flags & ~PFDESC_SCTP_SHUTDOWN_COMPLETE))
2140 		return (PF_DROP);
2141 	if ((pd->sctp_flags & PFDESC_SCTP_ABORT) &&
2142 	    (pd->sctp_flags & PFDESC_SCTP_DATA)) {
2143 		/*
2144 		 * RFC4960 3.3.7: DATA chunks MUST NOT be
2145 		 * bundled with ABORT.
2146 		 */
2147 		return (PF_DROP);
2148 	}
2149 
2150 	return (PF_PASS);
2151 }
2152 
2153 int
pf_normalize_sctp(struct pf_pdesc * pd)2154 pf_normalize_sctp(struct pf_pdesc *pd)
2155 {
2156 	struct pf_krule	*r, *rm = NULL;
2157 	struct sctphdr	*sh = &pd->hdr.sctp;
2158 	u_short		 reason;
2159 	sa_family_t	 af = pd->af;
2160 	int		 srs;
2161 
2162 	PF_RULES_RASSERT();
2163 
2164 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
2165 	/* Check if there any scrub rules. Lack of scrub rules means enforced
2166 	 * packet normalization operation just like in OpenBSD. */
2167 	srs = (r != NULL);
2168 	while (r != NULL) {
2169 		pf_counter_u64_add(&r->evaluations, 1);
2170 		if (pfi_kkif_match(r->kif, pd->kif) == r->ifnot)
2171 			r = r->skip[PF_SKIP_IFP];
2172 		else if (r->direction && r->direction != pd->dir)
2173 			r = r->skip[PF_SKIP_DIR];
2174 		else if (r->af && r->af != af)
2175 			r = r->skip[PF_SKIP_AF];
2176 		else if (r->proto && r->proto != pd->proto)
2177 			r = r->skip[PF_SKIP_PROTO];
2178 		else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
2179 		    r->src.neg, pd->kif, M_GETFIB(pd->m)))
2180 			r = r->skip[PF_SKIP_SRC_ADDR];
2181 		else if (r->src.port_op && !pf_match_port(r->src.port_op,
2182 			    r->src.port[0], r->src.port[1], sh->src_port))
2183 			r = r->skip[PF_SKIP_SRC_PORT];
2184 		else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
2185 		    r->dst.neg, NULL, M_GETFIB(pd->m)))
2186 			r = r->skip[PF_SKIP_DST_ADDR];
2187 		else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
2188 			    r->dst.port[0], r->dst.port[1], sh->dest_port))
2189 			r = r->skip[PF_SKIP_DST_PORT];
2190 		else {
2191 			rm = r;
2192 			break;
2193 		}
2194 	}
2195 
2196 	if (srs) {
2197 		/* With scrub rules present SCTP normalization happens only
2198 		 * if one of rules has matched and it's not a "no scrub" rule */
2199 		if (rm == NULL || rm->action == PF_NOSCRUB)
2200 			return (PF_PASS);
2201 
2202 		pf_counter_u64_critical_enter();
2203 		pf_counter_u64_add_protected(&r->packets[pd->dir == PF_OUT], 1);
2204 		pf_counter_u64_add_protected(&r->bytes[pd->dir == PF_OUT], pd->tot_len);
2205 		pf_counter_u64_critical_exit();
2206 	}
2207 
2208 	/* Verify we're a multiple of 4 bytes long */
2209 	if ((pd->tot_len - pd->off - sizeof(struct sctphdr)) % 4)
2210 		goto sctp_drop;
2211 
2212 	/* INIT chunk needs to be the only chunk */
2213 	if (pd->sctp_flags & PFDESC_SCTP_INIT)
2214 		if (pd->sctp_flags & ~PFDESC_SCTP_INIT)
2215 			goto sctp_drop;
2216 
2217 	return (PF_PASS);
2218 
2219 sctp_drop:
2220 	REASON_SET(&reason, PFRES_NORM);
2221 	if (rm != NULL && r->log)
2222 		PFLOG_PACKET(PF_DROP, reason, r, NULL, NULL, pd,
2223 		    1, NULL);
2224 
2225 	return (PF_DROP);
2226 }
2227 
2228 #if defined(INET) || defined(INET6)
2229 void
pf_scrub(struct pf_pdesc * pd)2230 pf_scrub(struct pf_pdesc *pd)
2231 {
2232 
2233 	struct ip		*h = mtod(pd->m, struct ip *);
2234 #ifdef INET6
2235 	struct ip6_hdr		*h6 = mtod(pd->m, struct ip6_hdr *);
2236 #endif /* INET6 */
2237 
2238 	/* Clear IP_DF if no-df was requested */
2239 	if (pd->af == AF_INET && pd->act.flags & PFSTATE_NODF &&
2240 	    h->ip_off & htons(IP_DF))
2241 	{
2242 		u_int16_t ip_off = h->ip_off;
2243 
2244 		h->ip_off &= htons(~IP_DF);
2245 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
2246 	}
2247 
2248 	/* Enforce a minimum ttl, may cause endless packet loops */
2249 	if (pd->af == AF_INET && pd->act.min_ttl &&
2250 	    h->ip_ttl < pd->act.min_ttl) {
2251 		u_int16_t ip_ttl = h->ip_ttl;
2252 
2253 		pd->ttl = h->ip_ttl = pd->act.min_ttl;
2254 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
2255 	}
2256 #ifdef INET6
2257 	/* Enforce a minimum ttl, may cause endless packet loops */
2258 	if (pd->af == AF_INET6 && pd->act.min_ttl &&
2259 	    h6->ip6_hlim < pd->act.min_ttl)
2260 		pd->ttl = h6->ip6_hlim = pd->act.min_ttl;
2261 #endif /* INET6 */
2262 	/* Enforce tos */
2263 	if (pd->act.flags & PFSTATE_SETTOS) {
2264 		switch (pd->af) {
2265 		case AF_INET: {
2266 			u_int16_t	ov, nv;
2267 
2268 			ov = *(u_int16_t *)h;
2269 			h->ip_tos = pd->act.set_tos | (h->ip_tos & IPTOS_ECN_MASK);
2270 			pd->tos = h->ip_tos & ~IPTOS_ECN_MASK;
2271 			nv = *(u_int16_t *)h;
2272 
2273 			h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
2274 			break;
2275 		}
2276 #ifdef INET6
2277 		case AF_INET6:
2278 			h6->ip6_flow &= IPV6_FLOWLABEL_MASK | IPV6_VERSION_MASK;
2279 			h6->ip6_flow |= htonl((pd->act.set_tos | IPV6_ECN(h6)) << 20);
2280 			pd->tos = IPV6_DSCP(h6);
2281 			break;
2282 #endif /* INET6 */
2283 		}
2284 	}
2285 
2286 	/* random-id, but not for fragments */
2287 #ifdef INET
2288 	if (pd->af == AF_INET &&
2289 	    pd->act.flags & PFSTATE_RANDOMID && !(h->ip_off & ~htons(IP_DF))) {
2290 		uint16_t ip_id = h->ip_id;
2291 
2292 		ip_fillid(h, V_ip_random_id);
2293 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
2294 	}
2295 #endif /* INET */
2296 }
2297 #endif /* INET || INET6 */
2298