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