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