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