xref: /openbsd/sys/net/pf_norm.c (revision 19e99d06)
1 /*	$OpenBSD: pf_norm.c,v 1.230 2024/04/22 13:30:22 bluhm Exp $ */
2 
3 /*
4  * Copyright 2001 Niels Provos <provos@citi.umich.edu>
5  * Copyright 2009 Henning Brauer <henning@openbsd.org>
6  * Copyright 2011-2018 Alexander Bluhm <bluhm@openbsd.org>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include "pflog.h"
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/mbuf.h>
35 #include <sys/filio.h>
36 #include <sys/fcntl.h>
37 #include <sys/socket.h>
38 #include <sys/kernel.h>
39 #include <sys/time.h>
40 #include <sys/pool.h>
41 #include <sys/syslog.h>
42 #include <sys/mutex.h>
43 
44 #include <net/if.h>
45 #include <net/if_var.h>
46 #include <net/if_pflog.h>
47 
48 #include <netinet/in.h>
49 #include <netinet/ip.h>
50 #include <netinet/ip_var.h>
51 #include <netinet/ip_icmp.h>
52 #include <netinet/tcp.h>
53 #include <netinet/tcp_seq.h>
54 #include <netinet/tcp_fsm.h>
55 #include <netinet/udp.h>
56 
57 #ifdef INET6
58 #include <netinet6/in6_var.h>
59 #include <netinet/ip6.h>
60 #include <netinet6/ip6_var.h>
61 #include <netinet/icmp6.h>
62 #include <netinet6/nd6.h>
63 #endif /* INET6 */
64 
65 #include <net/pfvar.h>
66 #include <net/pfvar_priv.h>
67 
68 struct pf_frent {
69 	TAILQ_ENTRY(pf_frent) fr_next;
70 	struct mbuf	*fe_m;
71 	u_int16_t	 fe_hdrlen;	/* ipv4 header length with ip options
72 					   ipv6, extension, fragment header */
73 	u_int16_t	 fe_extoff;	/* last extension header offset or 0 */
74 	u_int16_t	 fe_len;	/* fragment length */
75 	u_int16_t	 fe_off;	/* fragment offset */
76 	u_int16_t	 fe_mff;	/* more fragment flag */
77 };
78 
79 RB_HEAD(pf_frag_tree, pf_fragment);
80 struct pf_frnode {
81 	struct pf_addr	fn_src;		/* ip source address */
82 	struct pf_addr	fn_dst;		/* ip destination address */
83 	sa_family_t	fn_af;		/* address family */
84 	u_int8_t	fn_proto;	/* protocol for fragments in fn_tree */
85 	u_int8_t	fn_direction;	/* pf packet direction */
86 	u_int32_t	fn_fragments;	/* number of entries in fn_tree */
87 	u_int32_t	fn_gen;		/* fr_gen of newest entry in fn_tree */
88 
89 	RB_ENTRY(pf_frnode) fn_entry;
90 	struct pf_frag_tree fn_tree;	/* matching fragments, lookup by id */
91 };
92 
93 struct pf_fragment {
94 	struct pf_frent	*fr_firstoff[PF_FRAG_ENTRY_POINTS];
95 					/* pointers to queue element */
96 	u_int8_t	fr_entries[PF_FRAG_ENTRY_POINTS];
97 					/* count entries between pointers */
98 	RB_ENTRY(pf_fragment) fr_entry;
99 	TAILQ_ENTRY(pf_fragment) frag_next;
100 	TAILQ_HEAD(pf_fragq, pf_frent) fr_queue;
101 	u_int32_t	fr_id;		/* fragment id for reassemble */
102 	int32_t		fr_timeout;
103 	u_int32_t	fr_gen;		/* generation number (per pf_frnode) */
104 	u_int16_t	fr_maxlen;	/* maximum length of single fragment */
105 	u_int16_t	fr_holes;	/* number of holes in the queue */
106 	struct pf_frnode *fr_node;	/* ip src/dst/proto/af for fragments */
107 };
108 
109 struct pf_fragment_tag {
110 	u_int16_t	 ft_hdrlen;	/* header length of reassembled pkt */
111 	u_int16_t	 ft_extoff;	/* last extension header offset or 0 */
112 	u_int16_t	 ft_maxlen;	/* maximum fragment payload length */
113 };
114 
115 TAILQ_HEAD(pf_fragqueue, pf_fragment)	pf_fragqueue;
116 
117 static __inline int	 pf_frnode_compare(struct pf_frnode *,
118 			    struct pf_frnode *);
119 RB_HEAD(pf_frnode_tree, pf_frnode)	pf_frnode_tree;
120 RB_PROTOTYPE(pf_frnode_tree, pf_frnode, fn_entry, pf_frnode_compare);
121 RB_GENERATE(pf_frnode_tree, pf_frnode, fn_entry, pf_frnode_compare);
122 
123 static __inline int	 pf_frag_compare(struct pf_fragment *,
124 			    struct pf_fragment *);
125 RB_PROTOTYPE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
126 RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
127 
128 /* Private prototypes */
129 void			 pf_flush_fragments(void);
130 void			 pf_free_fragment(struct pf_fragment *);
131 struct pf_fragment	*pf_find_fragment(struct pf_frnode *, u_int32_t);
132 struct pf_frent		*pf_create_fragment(u_short *);
133 int			 pf_frent_holes(struct pf_frent *);
134 static inline int	 pf_frent_index(struct pf_frent *);
135 int			 pf_frent_insert(struct pf_fragment *,
136 			    struct pf_frent *, struct pf_frent *);
137 void			 pf_frent_remove(struct pf_fragment *,
138 			    struct pf_frent *);
139 struct pf_frent		*pf_frent_previous(struct pf_fragment *,
140 			    struct pf_frent *);
141 struct pf_fragment	*pf_fillup_fragment(struct pf_frnode *, u_int32_t,
142 			    struct pf_frent *, u_short *);
143 struct mbuf		*pf_join_fragment(struct pf_fragment *);
144 int			 pf_reassemble(struct mbuf **, int, u_short *);
145 #ifdef INET6
146 int			 pf_reassemble6(struct mbuf **, struct ip6_frag *,
147 			    u_int16_t, u_int16_t, int, u_short *);
148 #endif /* INET6 */
149 
150 /* Globals */
151 struct pool		 pf_frent_pl, pf_frag_pl, pf_frnode_pl;
152 struct pool		 pf_state_scrub_pl;
153 
154 struct mutex		 pf_frag_mtx;
155 
156 #define PF_FRAG_LOCK_INIT()	mtx_init(&pf_frag_mtx, IPL_SOFTNET)
157 
158 void
pf_normalize_init(void)159 pf_normalize_init(void)
160 {
161 	pool_init(&pf_frent_pl, sizeof(struct pf_frent), 0,
162 	    IPL_SOFTNET, 0, "pffrent", NULL);
163 	pool_init(&pf_frnode_pl, sizeof(struct pf_frnode), 0,
164 	    IPL_SOFTNET, 0, "pffrnode", NULL);
165 	pool_init(&pf_frag_pl, sizeof(struct pf_fragment), 0,
166 	    IPL_SOFTNET, 0, "pffrag", NULL);
167 	pool_init(&pf_state_scrub_pl, sizeof(struct pf_state_scrub), 0,
168 	    IPL_SOFTNET, 0, "pfstscr", NULL);
169 
170 	pool_sethiwat(&pf_frag_pl, PFFRAG_FRAG_HIWAT);
171 	pool_sethardlimit(&pf_frent_pl, PFFRAG_FRENT_HIWAT, NULL, 0);
172 
173 	TAILQ_INIT(&pf_fragqueue);
174 
175 	PF_FRAG_LOCK_INIT();
176 }
177 
178 static __inline int
pf_frnode_compare(struct pf_frnode * a,struct pf_frnode * b)179 pf_frnode_compare(struct pf_frnode *a, struct pf_frnode *b)
180 {
181 	int	diff;
182 
183 	if ((diff = a->fn_proto - b->fn_proto) != 0)
184 		return (diff);
185 	if ((diff = a->fn_af - b->fn_af) != 0)
186 		return (diff);
187 	if ((diff = pf_addr_compare(&a->fn_src, &b->fn_src, a->fn_af)) != 0)
188 		return (diff);
189 	if ((diff = pf_addr_compare(&a->fn_dst, &b->fn_dst, a->fn_af)) != 0)
190 		return (diff);
191 
192 	return (0);
193 }
194 
195 static __inline int
pf_frag_compare(struct pf_fragment * a,struct pf_fragment * b)196 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b)
197 {
198 	int	diff;
199 
200 	if ((diff = a->fr_id - b->fr_id) != 0)
201 		return (diff);
202 
203 	return (0);
204 }
205 
206 void
pf_purge_expired_fragments(void)207 pf_purge_expired_fragments(void)
208 {
209 	struct pf_fragment	*frag;
210 	int32_t			 expire;
211 
212 	PF_ASSERT_UNLOCKED();
213 
214 	expire = getuptime() - pf_default_rule.timeout[PFTM_FRAG];
215 
216 	PF_FRAG_LOCK();
217 	while ((frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue)) != NULL) {
218 		if (frag->fr_timeout > expire)
219 			break;
220 		DPFPRINTF(LOG_NOTICE, "expiring %d(%p)", frag->fr_id, frag);
221 		pf_free_fragment(frag);
222 	}
223 	PF_FRAG_UNLOCK();
224 }
225 
226 /*
227  * Try to flush old fragments to make space for new ones
228  */
229 void
pf_flush_fragments(void)230 pf_flush_fragments(void)
231 {
232 	struct pf_fragment	*frag;
233 	u_int			 goal;
234 
235 	goal = pf_status.fragments * 9 / 10;
236 	DPFPRINTF(LOG_NOTICE, "trying to free > %u frents",
237 	    pf_status.fragments - goal);
238 	while (goal < pf_status.fragments) {
239 		if ((frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue)) == NULL)
240 			break;
241 		pf_free_fragment(frag);
242 	}
243 }
244 
245 /*
246  * Remove a fragment from the fragment queue, free its fragment entries,
247  * and free the fragment itself.
248  */
249 void
pf_free_fragment(struct pf_fragment * frag)250 pf_free_fragment(struct pf_fragment *frag)
251 {
252 	struct pf_frent		*frent;
253 	struct pf_frnode	*frnode;
254 
255 	frnode = frag->fr_node;
256 	RB_REMOVE(pf_frag_tree, &frnode->fn_tree, frag);
257 	KASSERT(frnode->fn_fragments >= 1);
258 	frnode->fn_fragments--;
259 	if (frnode->fn_fragments == 0) {
260 		KASSERT(RB_EMPTY(&frnode->fn_tree));
261 		RB_REMOVE(pf_frnode_tree, &pf_frnode_tree, frnode);
262 		pool_put(&pf_frnode_pl, frnode);
263 	}
264 	TAILQ_REMOVE(&pf_fragqueue, frag, frag_next);
265 
266 	/* Free all fragment entries */
267 	while ((frent = TAILQ_FIRST(&frag->fr_queue)) != NULL) {
268 		TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
269 		pf_status.ncounters[NCNT_FRAG_REMOVALS]++;
270 		m_freem(frent->fe_m);
271 		pool_put(&pf_frent_pl, frent);
272 		pf_status.fragments--;
273 	}
274 	pool_put(&pf_frag_pl, frag);
275 }
276 
277 struct pf_fragment *
pf_find_fragment(struct pf_frnode * key,u_int32_t id)278 pf_find_fragment(struct pf_frnode *key, u_int32_t id)
279 {
280 	struct pf_fragment	*frag, idkey;
281 	struct pf_frnode	*frnode;
282 	u_int32_t		 stale;
283 
284 	frnode = RB_FIND(pf_frnode_tree, &pf_frnode_tree, key);
285 	pf_status.ncounters[NCNT_FRAG_SEARCH]++;
286 	if (frnode == NULL)
287 		return (NULL);
288 	KASSERT(frnode->fn_fragments >= 1);
289 	idkey.fr_id = id;
290 	frag = RB_FIND(pf_frag_tree, &frnode->fn_tree, &idkey);
291 	if (frag == NULL)
292 		return (NULL);
293 	/*
294 	 * Limit the number of fragments we accept for each (proto,src,dst,af)
295 	 * combination (aka pf_frnode), so we can deal better with a high rate
296 	 * of fragments.  Problem analysis is in RFC 4963.
297 	 * Store the current generation for each pf_frnode in fn_gen and on
298 	 * lookup discard 'stale' fragments (pf_fragment, based on the fr_gen
299 	 * member).  Instead of adding another button interpret the pf fragment
300 	 * timeout in multiples of 200 fragments.  This way the default of 60s
301 	 * means: pf_fragment objects older than 60*200 = 12,000 generations
302 	 * are considered stale.
303 	 */
304 	stale = pf_default_rule.timeout[PFTM_FRAG] * PF_FRAG_STALE;
305 	if ((frnode->fn_gen - frag->fr_gen) >= stale) {
306 		DPFPRINTF(LOG_NOTICE, "stale fragment %d(%p), gen %u, num %u",
307 		    frag->fr_id, frag, frag->fr_gen, frnode->fn_fragments);
308 		pf_free_fragment(frag);
309 		return (NULL);
310 	}
311 	TAILQ_REMOVE(&pf_fragqueue, frag, frag_next);
312 	TAILQ_INSERT_HEAD(&pf_fragqueue, frag, frag_next);
313 
314 	return (frag);
315 }
316 
317 struct pf_frent *
pf_create_fragment(u_short * reason)318 pf_create_fragment(u_short *reason)
319 {
320 	struct pf_frent	*frent;
321 
322 	frent = pool_get(&pf_frent_pl, PR_NOWAIT);
323 	if (frent == NULL) {
324 		pf_flush_fragments();
325 		frent = pool_get(&pf_frent_pl, PR_NOWAIT);
326 		if (frent == NULL) {
327 			REASON_SET(reason, PFRES_MEMORY);
328 			return (NULL);
329 		}
330 	}
331 	pf_status.fragments++;
332 
333 	return (frent);
334 }
335 
336 /*
337  * Calculate the additional holes that were created in the fragment
338  * queue by inserting this fragment.  A fragment in the middle
339  * creates one more hole by splitting.  For each connected side,
340  * it loses one hole.
341  * Fragment entry must be in the queue when calling this function.
342  */
343 int
pf_frent_holes(struct pf_frent * frent)344 pf_frent_holes(struct pf_frent *frent)
345 {
346 	struct pf_frent *prev = TAILQ_PREV(frent, pf_fragq, fr_next);
347 	struct pf_frent *next = TAILQ_NEXT(frent, fr_next);
348 	int holes = 1;
349 
350 	if (prev == NULL) {
351 		if (frent->fe_off == 0)
352 			holes--;
353 	} else {
354 		KASSERT(frent->fe_off != 0);
355 		if (frent->fe_off == prev->fe_off + prev->fe_len)
356 			holes--;
357 	}
358 	if (next == NULL) {
359 		if (!frent->fe_mff)
360 			holes--;
361 	} else {
362 		KASSERT(frent->fe_mff);
363 		if (next->fe_off == frent->fe_off + frent->fe_len)
364 			holes--;
365 	}
366 	return holes;
367 }
368 
369 static inline int
pf_frent_index(struct pf_frent * frent)370 pf_frent_index(struct pf_frent *frent)
371 {
372 	/*
373 	 * We have an array of 16 entry points to the queue.  A full size
374 	 * 65535 octet IP packet can have 8192 fragments.  So the queue
375 	 * traversal length is at most 512 and at most 16 entry points are
376 	 * checked.  We need 128 additional bytes on a 64 bit architecture.
377 	 */
378 	CTASSERT(((u_int16_t)0xffff &~ 7) / (0x10000 / PF_FRAG_ENTRY_POINTS) ==
379 	    16 - 1);
380 	CTASSERT(((u_int16_t)0xffff >> 3) / PF_FRAG_ENTRY_POINTS == 512 - 1);
381 
382 	return frent->fe_off / (0x10000 / PF_FRAG_ENTRY_POINTS);
383 }
384 
385 int
pf_frent_insert(struct pf_fragment * frag,struct pf_frent * frent,struct pf_frent * prev)386 pf_frent_insert(struct pf_fragment *frag, struct pf_frent *frent,
387     struct pf_frent *prev)
388 {
389 	CTASSERT(PF_FRAG_ENTRY_LIMIT <= 0xff);
390 	int index;
391 
392 	/*
393 	 * A packet has at most 65536 octets.  With 16 entry points, each one
394 	 * spawns 4096 octets.  We limit these to 64 fragments each, which
395 	 * means on average every fragment must have at least 64 octets.
396 	 */
397 	index = pf_frent_index(frent);
398 	if (frag->fr_entries[index] >= PF_FRAG_ENTRY_LIMIT)
399 		return ENOBUFS;
400 	frag->fr_entries[index]++;
401 
402 	if (prev == NULL) {
403 		TAILQ_INSERT_HEAD(&frag->fr_queue, frent, fr_next);
404 	} else {
405 		KASSERT(prev->fe_off + prev->fe_len <= frent->fe_off);
406 		TAILQ_INSERT_AFTER(&frag->fr_queue, prev, frent, fr_next);
407 	}
408 	pf_status.ncounters[NCNT_FRAG_INSERT]++;
409 
410 	if (frag->fr_firstoff[index] == NULL) {
411 		KASSERT(prev == NULL || pf_frent_index(prev) < index);
412 		frag->fr_firstoff[index] = frent;
413 	} else {
414 		if (frent->fe_off < frag->fr_firstoff[index]->fe_off) {
415 			KASSERT(prev == NULL || pf_frent_index(prev) < index);
416 			frag->fr_firstoff[index] = frent;
417 		} else {
418 			KASSERT(prev != NULL);
419 			KASSERT(pf_frent_index(prev) == index);
420 		}
421 	}
422 
423 	frag->fr_holes += pf_frent_holes(frent);
424 
425 	return 0;
426 }
427 
428 void
pf_frent_remove(struct pf_fragment * frag,struct pf_frent * frent)429 pf_frent_remove(struct pf_fragment *frag, struct pf_frent *frent)
430 {
431 #ifdef DIAGNOSTIC
432 	struct pf_frent *prev = TAILQ_PREV(frent, pf_fragq, fr_next);
433 #endif
434 	struct pf_frent *next = TAILQ_NEXT(frent, fr_next);
435 	int index;
436 
437 	frag->fr_holes -= pf_frent_holes(frent);
438 
439 	index = pf_frent_index(frent);
440 	KASSERT(frag->fr_firstoff[index] != NULL);
441 	if (frag->fr_firstoff[index]->fe_off == frent->fe_off) {
442 		if (next == NULL) {
443 			frag->fr_firstoff[index] = NULL;
444 		} else {
445 			KASSERT(frent->fe_off + frent->fe_len <= next->fe_off);
446 			if (pf_frent_index(next) == index) {
447 				frag->fr_firstoff[index] = next;
448 			} else {
449 				frag->fr_firstoff[index] = NULL;
450 			}
451 		}
452 	} else {
453 		KASSERT(frag->fr_firstoff[index]->fe_off < frent->fe_off);
454 		KASSERT(prev != NULL);
455 		KASSERT(prev->fe_off + prev->fe_len <= frent->fe_off);
456 		KASSERT(pf_frent_index(prev) == index);
457 	}
458 
459 	TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
460 	pf_status.ncounters[NCNT_FRAG_REMOVALS]++;
461 
462 	KASSERT(frag->fr_entries[index] > 0);
463 	frag->fr_entries[index]--;
464 }
465 
466 struct pf_frent *
pf_frent_previous(struct pf_fragment * frag,struct pf_frent * frent)467 pf_frent_previous(struct pf_fragment *frag, struct pf_frent *frent)
468 {
469 	struct pf_frent *prev, *next;
470 	int index;
471 
472 	/*
473 	 * If there are no fragments after frag, take the final one.  Assume
474 	 * that the global queue is not empty.
475 	 */
476 	prev = TAILQ_LAST(&frag->fr_queue, pf_fragq);
477 	KASSERT(prev != NULL);
478 	if (prev->fe_off <= frent->fe_off)
479 		return prev;
480 	/*
481 	 * We want to find a fragment entry that is before frag, but still
482 	 * close to it.  Find the first fragment entry that is in the same
483 	 * entry point or in the first entry point after that.  As we have
484 	 * already checked that there are entries behind frag, this will
485 	 * succeed.
486 	 */
487 	for (index = pf_frent_index(frent); index < PF_FRAG_ENTRY_POINTS;
488 	    index++) {
489 		prev = frag->fr_firstoff[index];
490 		if (prev != NULL)
491 			break;
492 	}
493 	KASSERT(prev != NULL);
494 	/*
495 	 * In prev we may have a fragment from the same entry point that is
496 	 * before frent, or one that is just one position behind frent.
497 	 * In the latter case, we go back one step and have the predecessor.
498 	 * There may be none if the new fragment will be the first one.
499 	 */
500 	if (prev->fe_off > frent->fe_off) {
501 		prev = TAILQ_PREV(prev, pf_fragq, fr_next);
502 		if (prev == NULL)
503 			return NULL;
504 		KASSERT(prev->fe_off <= frent->fe_off);
505 		return prev;
506 	}
507 	/*
508 	 * In prev is the first fragment of the entry point.  The offset
509 	 * of frag is behind it.  Find the closest previous fragment.
510 	 */
511 	for (next = TAILQ_NEXT(prev, fr_next); next != NULL;
512 	    next = TAILQ_NEXT(next, fr_next)) {
513 		if (next->fe_off > frent->fe_off)
514 			break;
515 		prev = next;
516 	}
517 	return prev;
518 }
519 
520 struct pf_fragment *
pf_fillup_fragment(struct pf_frnode * key,u_int32_t id,struct pf_frent * frent,u_short * reason)521 pf_fillup_fragment(struct pf_frnode *key, u_int32_t id,
522     struct pf_frent *frent, u_short *reason)
523 {
524 	struct pf_frent		*after, *next, *prev;
525 	struct pf_fragment	*frag;
526 	struct pf_frnode	*frnode;
527 	u_int16_t		 total;
528 
529 	/* No empty fragments */
530 	if (frent->fe_len == 0) {
531 		DPFPRINTF(LOG_NOTICE, "bad fragment: len 0");
532 		goto bad_fragment;
533 	}
534 
535 	/* All fragments are 8 byte aligned */
536 	if (frent->fe_mff && (frent->fe_len & 0x7)) {
537 		DPFPRINTF(LOG_NOTICE, "bad fragment: mff and len %d",
538 		    frent->fe_len);
539 		goto bad_fragment;
540 	}
541 
542 	/* Respect maximum length, IP_MAXPACKET == IPV6_MAXPACKET */
543 	if (frent->fe_off + frent->fe_len > IP_MAXPACKET) {
544 		DPFPRINTF(LOG_NOTICE, "bad fragment: max packet %d",
545 		    frent->fe_off + frent->fe_len);
546 		goto bad_fragment;
547 	}
548 
549 	DPFPRINTF(LOG_INFO, key->fn_af == AF_INET ?
550 	    "reass frag %d @ %d-%d" : "reass frag %#08x @ %d-%d",
551 	    id, frent->fe_off, frent->fe_off + frent->fe_len);
552 
553 	/* Fully buffer all of the fragments in this fragment queue */
554 	frag = pf_find_fragment(key, id);
555 
556 	/* Create a new reassembly queue for this packet */
557 	if (frag == NULL) {
558 		frag = pool_get(&pf_frag_pl, PR_NOWAIT);
559 		if (frag == NULL) {
560 			pf_flush_fragments();
561 			frag = pool_get(&pf_frag_pl, PR_NOWAIT);
562 			if (frag == NULL) {
563 				REASON_SET(reason, PFRES_MEMORY);
564 				goto drop_fragment;
565 			}
566 		}
567 		frnode = RB_FIND(pf_frnode_tree, &pf_frnode_tree, key);
568 		if (frnode == NULL) {
569 			frnode = pool_get(&pf_frnode_pl, PR_NOWAIT);
570 			if (frnode == NULL) {
571 				pf_flush_fragments();
572 				frnode = pool_get(&pf_frnode_pl, PR_NOWAIT);
573 				if (frnode == NULL) {
574 					REASON_SET(reason, PFRES_MEMORY);
575 					pool_put(&pf_frag_pl, frag);
576 					goto drop_fragment;
577 				}
578 			}
579 			*frnode = *key;
580 			RB_INIT(&frnode->fn_tree);
581 			frnode->fn_fragments = 0;
582 			frnode->fn_gen = 0;
583 		}
584 		memset(frag->fr_firstoff, 0, sizeof(frag->fr_firstoff));
585 		memset(frag->fr_entries, 0, sizeof(frag->fr_entries));
586 		TAILQ_INIT(&frag->fr_queue);
587 		frag->fr_id = id;
588 		frag->fr_timeout = getuptime();
589 		frag->fr_gen = frnode->fn_gen++;
590 		frag->fr_maxlen = frent->fe_len;
591 		frag->fr_holes = 1;
592 		frag->fr_node = frnode;
593 		/* RB_INSERT cannot fail as pf_find_fragment() found nothing */
594 		RB_INSERT(pf_frag_tree, &frnode->fn_tree, frag);
595 		frnode->fn_fragments++;
596 		if (frnode->fn_fragments == 1)
597 			RB_INSERT(pf_frnode_tree, &pf_frnode_tree, frnode);
598 		TAILQ_INSERT_HEAD(&pf_fragqueue, frag, frag_next);
599 
600 		/* We do not have a previous fragment, cannot fail. */
601 		pf_frent_insert(frag, frent, NULL);
602 
603 		return (frag);
604 	}
605 
606 	KASSERT(!TAILQ_EMPTY(&frag->fr_queue));
607 	KASSERT(frag->fr_node);
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 free_ipv6_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 free_ipv6_fragment;
626 	} else {
627 		if (frent->fe_off + frent->fe_len == total && !frent->fe_mff)
628 			goto free_ipv6_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);
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 		u_int16_t	precut;
642 
643 #ifdef INET6
644 		if (frag->fr_node->fn_af == AF_INET6)
645 			goto free_ipv6_fragment;
646 #endif /* INET6 */
647 
648 		precut = prev->fe_off + prev->fe_len - frent->fe_off;
649 		if (precut >= frent->fe_len) {
650 			DPFPRINTF(LOG_NOTICE, "new frag overlapped");
651 			goto drop_fragment;
652 		}
653 		DPFPRINTF(LOG_NOTICE, "frag head overlap %d", precut);
654 		m_adj(frent->fe_m, precut);
655 		frent->fe_off += precut;
656 		frent->fe_len -= precut;
657 	}
658 
659 	for (; after != NULL && frent->fe_off + frent->fe_len > after->fe_off;
660 	    after = next) {
661 		u_int16_t	aftercut;
662 
663 #ifdef INET6
664 		if (frag->fr_node->fn_af == AF_INET6)
665 			goto free_ipv6_fragment;
666 #endif /* INET6 */
667 
668 		aftercut = frent->fe_off + frent->fe_len - after->fe_off;
669 		if (aftercut < after->fe_len) {
670 			int old_index, new_index;
671 
672 			DPFPRINTF(LOG_NOTICE, "frag tail overlap %d", aftercut);
673 			m_adj(after->fe_m, aftercut);
674 			old_index = pf_frent_index(after);
675 			after->fe_off += aftercut;
676 			after->fe_len -= aftercut;
677 			new_index = pf_frent_index(after);
678 			if (old_index != new_index) {
679 				DPFPRINTF(LOG_DEBUG, "frag index %d, new %d",
680 				    old_index, new_index);
681 				/* Fragment switched queue as fe_off changed */
682 				after->fe_off -= aftercut;
683 				after->fe_len += aftercut;
684 				/* Remove restored fragment from old queue */
685 				pf_frent_remove(frag, after);
686 				after->fe_off += aftercut;
687 				after->fe_len -= aftercut;
688 				/* Insert into correct queue */
689 				if (pf_frent_insert(frag, after, prev)) {
690 					DPFPRINTF(LOG_WARNING,
691 					    "fragment requeue limit exceeded");
692 					m_freem(after->fe_m);
693 					pool_put(&pf_frent_pl, after);
694 					pf_status.fragments--;
695 					/* There is not way to recover */
696 					goto free_fragment;
697 				}
698 			}
699 			break;
700 		}
701 
702 		/* This fragment is completely overlapped, lose it */
703 		DPFPRINTF(LOG_NOTICE, "old frag overlapped");
704 		next = TAILQ_NEXT(after, fr_next);
705 		pf_frent_remove(frag, after);
706 		m_freem(after->fe_m);
707 		pool_put(&pf_frent_pl, after);
708 		pf_status.fragments--;
709 	}
710 
711 	/* If part of the queue gets too long, there is not way to recover. */
712 	if (pf_frent_insert(frag, frent, prev)) {
713 		DPFPRINTF(LOG_WARNING, "fragment queue limit exceeded");
714 		goto free_fragment;
715 	}
716 
717 	return (frag);
718 
719 free_ipv6_fragment:
720 	if (frag->fr_node->fn_af == AF_INET)
721 		goto bad_fragment;
722 	/*
723 	 * RFC 5722, Errata 3089:  When reassembling an IPv6 datagram, if one
724 	 * or more its constituent fragments is determined to be an overlapping
725 	 * fragment, the entire datagram (and any constituent fragments) MUST
726 	 * be silently discarded.
727 	 */
728 	DPFPRINTF(LOG_NOTICE, "flush overlapping fragments");
729 free_fragment:
730 	pf_free_fragment(frag);
731 bad_fragment:
732 	REASON_SET(reason, PFRES_FRAG);
733 drop_fragment:
734 	pool_put(&pf_frent_pl, frent);
735 	pf_status.fragments--;
736 	return (NULL);
737 }
738 
739 struct mbuf *
pf_join_fragment(struct pf_fragment * frag)740 pf_join_fragment(struct pf_fragment *frag)
741 {
742 	struct mbuf		*m, *m2;
743 	struct pf_frent		*frent;
744 
745 	frent = TAILQ_FIRST(&frag->fr_queue);
746 	TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
747 	pf_status.ncounters[NCNT_FRAG_REMOVALS]++;
748 
749 	m = frent->fe_m;
750 	/* Strip off any trailing bytes */
751 	if ((frent->fe_hdrlen + frent->fe_len) < m->m_pkthdr.len)
752 		m_adj(m, (frent->fe_hdrlen + frent->fe_len) - m->m_pkthdr.len);
753 	/* Magic from ip_input */
754 	m2 = m->m_next;
755 	m->m_next = NULL;
756 	m_cat(m, m2);
757 	pool_put(&pf_frent_pl, frent);
758 	pf_status.fragments--;
759 
760 	while ((frent = TAILQ_FIRST(&frag->fr_queue)) != NULL) {
761 		TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
762 		pf_status.ncounters[NCNT_FRAG_REMOVALS]++;
763 		m2 = frent->fe_m;
764 		/* Strip off ip header */
765 		m_adj(m2, frent->fe_hdrlen);
766 		/* Strip off any trailing bytes */
767 		if (frent->fe_len < m2->m_pkthdr.len)
768 			m_adj(m2, frent->fe_len - m2->m_pkthdr.len);
769 		pool_put(&pf_frent_pl, frent);
770 		pf_status.fragments--;
771 		m_removehdr(m2);
772 		m_cat(m, m2);
773 	}
774 
775 	/* Remove from fragment queue */
776 	pf_free_fragment(frag);
777 
778 	return (m);
779 }
780 
781 int
pf_reassemble(struct mbuf ** m0,int dir,u_short * reason)782 pf_reassemble(struct mbuf **m0, int dir, u_short *reason)
783 {
784 	struct mbuf		*m = *m0;
785 	struct ip		*ip = mtod(m, struct ip *);
786 	struct pf_frent		*frent;
787 	struct pf_fragment	*frag;
788 	struct pf_frnode	 key;
789 	u_int16_t		 total, hdrlen;
790 
791 	/* Get an entry for the fragment queue */
792 	if ((frent = pf_create_fragment(reason)) == NULL)
793 		return (PF_DROP);
794 
795 	frent->fe_m = m;
796 	frent->fe_hdrlen = ip->ip_hl << 2;
797 	frent->fe_extoff = 0;
798 	frent->fe_len = ntohs(ip->ip_len) - (ip->ip_hl << 2);
799 	frent->fe_off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
800 	frent->fe_mff = ntohs(ip->ip_off) & IP_MF;
801 
802 	key.fn_src.v4 = ip->ip_src;
803 	key.fn_dst.v4 = ip->ip_dst;
804 	key.fn_af = AF_INET;
805 	key.fn_proto = ip->ip_p;
806 	key.fn_direction = dir;
807 
808 	if ((frag = pf_fillup_fragment(&key, ip->ip_id, frent, reason))
809 	    == NULL)
810 		return (PF_DROP);
811 
812 	/* The mbuf is part of the fragment entry, no direct free or access */
813 	m = *m0 = NULL;
814 
815 	if (frag->fr_holes) {
816 		DPFPRINTF(LOG_DEBUG, "frag %d, holes %d",
817 		    frag->fr_id, frag->fr_holes);
818 		return (PF_PASS);  /* drop because *m0 is NULL, no error */
819 	}
820 
821 	/* We have all the data */
822 	frent = TAILQ_FIRST(&frag->fr_queue);
823 	KASSERT(frent != NULL);
824 	total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
825 	    TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
826 	hdrlen = frent->fe_hdrlen;
827 	m = *m0 = pf_join_fragment(frag);
828 	frag = NULL;
829 	m_calchdrlen(m);
830 
831 	ip = mtod(m, struct ip *);
832 	ip->ip_len = htons(hdrlen + total);
833 	ip->ip_off &= ~(IP_MF|IP_OFFMASK);
834 
835 	if (hdrlen + total > IP_MAXPACKET) {
836 		DPFPRINTF(LOG_NOTICE, "drop: too big: %d", total);
837 		ip->ip_len = 0;
838 		REASON_SET(reason, PFRES_SHORT);
839 		/* PF_DROP requires a valid mbuf *m0 in pf_test() */
840 		return (PF_DROP);
841 	}
842 
843 	DPFPRINTF(LOG_INFO, "complete: %p(%d)", m, ntohs(ip->ip_len));
844 	return (PF_PASS);
845 }
846 
847 #ifdef INET6
848 int
pf_reassemble6(struct mbuf ** m0,struct ip6_frag * fraghdr,u_int16_t hdrlen,u_int16_t extoff,int dir,u_short * reason)849 pf_reassemble6(struct mbuf **m0, struct ip6_frag *fraghdr,
850     u_int16_t hdrlen, u_int16_t extoff, int dir, u_short *reason)
851 {
852 	struct mbuf		*m = *m0;
853 	struct ip6_hdr		*ip6 = mtod(m, struct ip6_hdr *);
854 	struct m_tag		*mtag;
855 	struct pf_fragment_tag	*ftag;
856 	struct pf_frent		*frent;
857 	struct pf_fragment	*frag;
858 	struct pf_frnode	 key;
859 	int			 off;
860 	u_int16_t		 total, maxlen;
861 	u_int8_t		 proto;
862 
863 	/* Get an entry for the fragment queue */
864 	if ((frent = pf_create_fragment(reason)) == NULL)
865 		return (PF_DROP);
866 
867 	frent->fe_m = m;
868 	frent->fe_hdrlen = hdrlen;
869 	frent->fe_extoff = extoff;
870 	frent->fe_len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen) - hdrlen;
871 	frent->fe_off = ntohs(fraghdr->ip6f_offlg & IP6F_OFF_MASK);
872 	frent->fe_mff = fraghdr->ip6f_offlg & IP6F_MORE_FRAG;
873 
874 	key.fn_src.v6 = ip6->ip6_src;
875 	key.fn_dst.v6 = ip6->ip6_dst;
876 	key.fn_af = AF_INET6;
877 	/* Only the first fragment's protocol is relevant */
878 	key.fn_proto = 0;
879 	key.fn_direction = dir;
880 
881 	if ((frag = pf_fillup_fragment(&key, fraghdr->ip6f_ident, frent,
882 	    reason)) == NULL)
883 		return (PF_DROP);
884 
885 	/* The mbuf is part of the fragment entry, no direct free or access */
886 	m = *m0 = NULL;
887 
888 	if (frag->fr_holes) {
889 		DPFPRINTF(LOG_DEBUG, "frag %#08x, holes %d",
890 		    frag->fr_id, frag->fr_holes);
891 		return (PF_PASS);  /* drop because *m0 is NULL, no error */
892 	}
893 
894 	/* We have all the data */
895 	frent = TAILQ_FIRST(&frag->fr_queue);
896 	KASSERT(frent != NULL);
897 	extoff = frent->fe_extoff;
898 	maxlen = frag->fr_maxlen;
899 	total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
900 	    TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
901 	hdrlen = frent->fe_hdrlen - sizeof(struct ip6_frag);
902 	m = *m0 = pf_join_fragment(frag);
903 	frag = NULL;
904 
905 	/* Take protocol from first fragment header */
906 	if ((m = m_getptr(m, hdrlen + offsetof(struct ip6_frag, ip6f_nxt),
907 	    &off)) == NULL)
908 		panic("%s: short frag mbuf chain", __func__);
909 	proto = *(mtod(m, caddr_t) + off);
910 	m = *m0;
911 
912 	/* Delete frag6 header */
913 	if (frag6_deletefraghdr(m, hdrlen) != 0)
914 		goto fail;
915 
916 	m_calchdrlen(m);
917 
918 	if ((mtag = m_tag_get(PACKET_TAG_PF_REASSEMBLED, sizeof(struct
919 	    pf_fragment_tag), M_NOWAIT)) == NULL)
920 		goto fail;
921 	ftag = (struct pf_fragment_tag *)(mtag + 1);
922 	ftag->ft_hdrlen = hdrlen;
923 	ftag->ft_extoff = extoff;
924 	ftag->ft_maxlen = maxlen;
925 	m_tag_prepend(m, mtag);
926 
927 	ip6 = mtod(m, struct ip6_hdr *);
928 	ip6->ip6_plen = htons(hdrlen - sizeof(struct ip6_hdr) + total);
929 	if (extoff) {
930 		/* Write protocol into next field of last extension header */
931 		if ((m = m_getptr(m, extoff + offsetof(struct ip6_ext,
932 		    ip6e_nxt), &off)) == NULL)
933 			panic("%s: short ext mbuf chain", __func__);
934 		*(mtod(m, caddr_t) + off) = proto;
935 		m = *m0;
936 	} else
937 		ip6->ip6_nxt = proto;
938 
939 	if (hdrlen - sizeof(struct ip6_hdr) + total > IPV6_MAXPACKET) {
940 		DPFPRINTF(LOG_NOTICE, "drop: too big: %d", total);
941 		ip6->ip6_plen = 0;
942 		REASON_SET(reason, PFRES_SHORT);
943 		/* PF_DROP requires a valid mbuf *m0 in pf_test6() */
944 		return (PF_DROP);
945 	}
946 
947 	DPFPRINTF(LOG_INFO, "complete: %p(%d)", m, ntohs(ip6->ip6_plen));
948 	return (PF_PASS);
949 
950 fail:
951 	REASON_SET(reason, PFRES_MEMORY);
952 	/* PF_DROP requires a valid mbuf *m0 in pf_test6(), will free later */
953 	return (PF_DROP);
954 }
955 
956 int
pf_refragment6(struct mbuf ** m0,struct m_tag * mtag,struct sockaddr_in6 * dst,struct ifnet * ifp,struct rtentry * rt)957 pf_refragment6(struct mbuf **m0, struct m_tag *mtag, struct sockaddr_in6 *dst,
958     struct ifnet *ifp, struct rtentry *rt)
959 {
960 	struct mbuf		*m = *m0;
961 	struct mbuf_list	 ml;
962 	struct pf_fragment_tag	*ftag = (struct pf_fragment_tag *)(mtag + 1);
963 	u_int32_t		 mtu;
964 	u_int16_t		 hdrlen, extoff, maxlen;
965 	u_int8_t		 proto;
966 	int			 error;
967 
968 	hdrlen = ftag->ft_hdrlen;
969 	extoff = ftag->ft_extoff;
970 	maxlen = ftag->ft_maxlen;
971 	m_tag_delete(m, mtag);
972 	mtag = NULL;
973 	ftag = NULL;
974 
975 	/* Checksum must be calculated for the whole packet */
976 	in6_proto_cksum_out(m, NULL);
977 
978 	if (extoff) {
979 		int off;
980 
981 		/* Use protocol from next field of last extension header */
982 		if ((m = m_getptr(m, extoff + offsetof(struct ip6_ext,
983 		    ip6e_nxt), &off)) == NULL)
984 			panic("%s: short ext mbuf chain", __func__);
985 		proto = *(mtod(m, caddr_t) + off);
986 		*(mtod(m, caddr_t) + off) = IPPROTO_FRAGMENT;
987 		m = *m0;
988 	} else {
989 		struct ip6_hdr *hdr;
990 
991 		hdr = mtod(m, struct ip6_hdr *);
992 		proto = hdr->ip6_nxt;
993 		hdr->ip6_nxt = IPPROTO_FRAGMENT;
994 	}
995 
996 	/*
997 	 * Maxlen may be less than 8 iff there was only a single
998 	 * fragment.  As it was fragmented before, add a fragment
999 	 * header also for a single fragment.  If total or maxlen
1000 	 * is less than 8, ip6_fragment() will return EMSGSIZE and
1001 	 * we drop the packet.
1002 	 */
1003 	mtu = hdrlen + sizeof(struct ip6_frag) + maxlen;
1004 	error = ip6_fragment(m, &ml, hdrlen, proto, mtu);
1005 	*m0 = NULL;	/* ip6_fragment() has consumed original packet. */
1006 	if (error) {
1007 		DPFPRINTF(LOG_NOTICE, "refragment error %d", error);
1008 		return (PF_DROP);
1009 	}
1010 
1011 	while ((m = ml_dequeue(&ml)) != NULL) {
1012 		m->m_pkthdr.pf.flags |= PF_TAG_REFRAGMENTED;
1013 		if (ifp == NULL) {
1014 			ip6_forward(m, NULL, 0);
1015 		} else if ((u_long)m->m_pkthdr.len <= ifp->if_mtu) {
1016 			ifp->if_output(ifp, m, sin6tosa(dst), rt);
1017 		} else {
1018 			icmp6_error(m, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
1019 		}
1020 	}
1021 
1022 	return (PF_PASS);
1023 }
1024 #endif /* INET6 */
1025 
1026 int
pf_normalize_ip(struct pf_pdesc * pd,u_short * reason)1027 pf_normalize_ip(struct pf_pdesc *pd, u_short *reason)
1028 {
1029 	struct ip	*h = mtod(pd->m, struct ip *);
1030 	u_int16_t	 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
1031 	u_int16_t	 mff = (ntohs(h->ip_off) & IP_MF);
1032 
1033 	if (!fragoff && !mff)
1034 		goto no_fragment;
1035 
1036 	/* Clear IP_DF if we're in no-df mode */
1037 	if (pf_status.reass & PF_REASS_NODF && h->ip_off & htons(IP_DF))
1038 		h->ip_off &= htons(~IP_DF);
1039 
1040 	/* We're dealing with a fragment now. Don't allow fragments
1041 	 * with IP_DF to enter the cache. If the flag was cleared by
1042 	 * no-df above, fine. Otherwise drop it.
1043 	 */
1044 	if (h->ip_off & htons(IP_DF)) {
1045 		DPFPRINTF(LOG_NOTICE, "bad fragment: IP_DF");
1046 		REASON_SET(reason, PFRES_FRAG);
1047 		return (PF_DROP);
1048 	}
1049 
1050 	if (!pf_status.reass)
1051 		return (PF_PASS);	/* no reassembly */
1052 
1053 	/* Returns PF_DROP or m is NULL or completely reassembled mbuf */
1054 	PF_FRAG_LOCK();
1055 	if (pf_reassemble(&pd->m, pd->dir, reason) != PF_PASS) {
1056 		PF_FRAG_UNLOCK();
1057 		return (PF_DROP);
1058 	}
1059 	PF_FRAG_UNLOCK();
1060 	if (pd->m == NULL)
1061 		return (PF_PASS);  /* packet has been reassembled, no error */
1062 
1063 	h = mtod(pd->m, struct ip *);
1064 
1065 no_fragment:
1066 	/* At this point, only IP_DF is allowed in ip_off */
1067 	if (h->ip_off & ~htons(IP_DF))
1068 		h->ip_off &= htons(IP_DF);
1069 
1070 	return (PF_PASS);
1071 }
1072 
1073 #ifdef INET6
1074 int
pf_normalize_ip6(struct pf_pdesc * pd,u_short * reason)1075 pf_normalize_ip6(struct pf_pdesc *pd, u_short *reason)
1076 {
1077 	struct ip6_frag		 frag;
1078 
1079 	if (pd->fragoff == 0)
1080 		goto no_fragment;
1081 
1082 	if (!pf_pull_hdr(pd->m, pd->fragoff, &frag, sizeof(frag), reason,
1083 	    AF_INET6))
1084 		return (PF_DROP);
1085 
1086 	if (!pf_status.reass)
1087 		return (PF_PASS);	/* no reassembly */
1088 
1089 	/* Returns PF_DROP or m is NULL or completely reassembled mbuf */
1090 	PF_FRAG_LOCK();
1091 	if (pf_reassemble6(&pd->m, &frag, pd->fragoff + sizeof(frag),
1092 	    pd->extoff, pd->dir, reason) != PF_PASS) {
1093 		PF_FRAG_UNLOCK();
1094 		return (PF_DROP);
1095 	}
1096 	PF_FRAG_UNLOCK();
1097 	if (pd->m == NULL)
1098 		return (PF_PASS);  /* packet has been reassembled, no error */
1099 
1100 no_fragment:
1101 	return (PF_PASS);
1102 }
1103 #endif /* INET6 */
1104 
1105 struct pf_state_scrub *
pf_state_scrub_get(void)1106 pf_state_scrub_get(void)
1107 {
1108 	return (pool_get(&pf_state_scrub_pl, PR_NOWAIT | PR_ZERO));
1109 }
1110 
1111 void
pf_state_scrub_put(struct pf_state_scrub * scrub)1112 pf_state_scrub_put(struct pf_state_scrub *scrub)
1113 {
1114 	pool_put(&pf_state_scrub_pl, scrub);
1115 }
1116 
1117 int
pf_normalize_tcp_alloc(struct pf_state_peer * src)1118 pf_normalize_tcp_alloc(struct pf_state_peer *src)
1119 {
1120 	src->scrub = pf_state_scrub_get();
1121 	if (src->scrub == NULL)
1122 		return (ENOMEM);
1123 
1124 	return (0);
1125 }
1126 
1127 int
pf_normalize_tcp(struct pf_pdesc * pd)1128 pf_normalize_tcp(struct pf_pdesc *pd)
1129 {
1130 	struct tcphdr	*th = &pd->hdr.tcp;
1131 	u_short		 reason;
1132 	u_int8_t	 flags;
1133 	u_int		 rewrite = 0;
1134 
1135 	flags = th->th_flags;
1136 	if (flags & TH_SYN) {
1137 		/* Illegal packet */
1138 		if (flags & TH_RST)
1139 			goto tcp_drop;
1140 
1141 		if (flags & TH_FIN)	/* XXX why clear instead of drop? */
1142 			flags &= ~TH_FIN;
1143 	} else {
1144 		/* Illegal packet */
1145 		if (!(flags & (TH_ACK|TH_RST)))
1146 			goto tcp_drop;
1147 	}
1148 
1149 	if (!(flags & TH_ACK)) {
1150 		/* These flags are only valid if ACK is set */
1151 		if (flags & (TH_FIN|TH_PUSH|TH_URG))
1152 			goto tcp_drop;
1153 	}
1154 
1155 	/* If flags changed, or reserved data set, then adjust */
1156 	if (flags != th->th_flags || th->th_x2 != 0) {
1157 		/* hack: set 4-bit th_x2 = 0 */
1158 		u_int8_t *th_off = (u_int8_t*)(&th->th_ack+1);
1159 		pf_patch_8(pd, th_off, th->th_off << 4, PF_HI);
1160 
1161 		pf_patch_8(pd, &th->th_flags, flags, PF_LO);
1162 		rewrite = 1;
1163 	}
1164 
1165 	/* Remove urgent pointer, if TH_URG is not set */
1166 	if (!(flags & TH_URG) && th->th_urp) {
1167 		pf_patch_16(pd, &th->th_urp, 0);
1168 		rewrite = 1;
1169 	}
1170 
1171 	/* copy back packet headers if we sanitized */
1172 	if (rewrite) {
1173 		m_copyback(pd->m, pd->off, sizeof(*th), th, M_NOWAIT);
1174 	}
1175 
1176 	return (PF_PASS);
1177 
1178 tcp_drop:
1179 	REASON_SET(&reason, PFRES_NORM);
1180 	return (PF_DROP);
1181 }
1182 
1183 int
pf_normalize_tcp_init(struct pf_pdesc * pd,struct pf_state_peer * src)1184 pf_normalize_tcp_init(struct pf_pdesc *pd, struct pf_state_peer *src)
1185 {
1186 	struct tcphdr	*th = &pd->hdr.tcp;
1187 	u_int32_t	 tsval, tsecr;
1188 	int		 olen;
1189 	u_int8_t	 opts[MAX_TCPOPTLEN], *opt;
1190 
1191 
1192 	KASSERT(src->scrub == NULL);
1193 
1194 	if (pf_normalize_tcp_alloc(src) != 0)
1195 		return (1);
1196 
1197 	switch (pd->af) {
1198 	case AF_INET: {
1199 		struct ip *h = mtod(pd->m, struct ip *);
1200 		src->scrub->pfss_ttl = h->ip_ttl;
1201 		break;
1202 	}
1203 #ifdef INET6
1204 	case AF_INET6: {
1205 		struct ip6_hdr *h = mtod(pd->m, struct ip6_hdr *);
1206 		src->scrub->pfss_ttl = h->ip6_hlim;
1207 		break;
1208 	}
1209 #endif /* INET6 */
1210 	default:
1211 		unhandled_af(pd->af);
1212 	}
1213 
1214 	/*
1215 	 * All normalizations below are only begun if we see the start of
1216 	 * the connections.  They must all set an enabled bit in pfss_flags
1217 	 */
1218 	if ((th->th_flags & TH_SYN) == 0)
1219 		return (0);
1220 
1221 	olen = (th->th_off << 2) - sizeof(*th);
1222 	if (olen < TCPOLEN_TIMESTAMP || !pf_pull_hdr(pd->m,
1223 	    pd->off + sizeof(*th), opts, olen, NULL, pd->af))
1224 		return (0);
1225 
1226 	opt = opts;
1227 	while ((opt = pf_find_tcpopt(opt, opts, olen,
1228 		    TCPOPT_TIMESTAMP, TCPOLEN_TIMESTAMP)) != NULL) {
1229 
1230 		src->scrub->pfss_flags |= PFSS_TIMESTAMP;
1231 		src->scrub->pfss_ts_mod = arc4random();
1232 		/* note PFSS_PAWS not set yet */
1233 		memcpy(&tsval, &opt[2], sizeof(u_int32_t));
1234 		memcpy(&tsecr, &opt[6], sizeof(u_int32_t));
1235 		src->scrub->pfss_tsval0 = ntohl(tsval);
1236 		src->scrub->pfss_tsval = ntohl(tsval);
1237 		src->scrub->pfss_tsecr = ntohl(tsecr);
1238 		getmicrouptime(&src->scrub->pfss_last);
1239 
1240 		opt += opt[1];
1241 	}
1242 
1243 	return (0);
1244 }
1245 
1246 void
pf_normalize_tcp_cleanup(struct pf_state * state)1247 pf_normalize_tcp_cleanup(struct pf_state *state)
1248 {
1249 	if (state->src.scrub)
1250 		pool_put(&pf_state_scrub_pl, state->src.scrub);
1251 	if (state->dst.scrub)
1252 		pool_put(&pf_state_scrub_pl, state->dst.scrub);
1253 
1254 	/* Someday... flush the TCP segment reassembly descriptors. */
1255 }
1256 
1257 int
pf_normalize_tcp_stateful(struct pf_pdesc * pd,u_short * reason,struct pf_state * state,struct pf_state_peer * src,struct pf_state_peer * dst,int * writeback)1258 pf_normalize_tcp_stateful(struct pf_pdesc *pd, u_short *reason,
1259     struct pf_state *state, struct pf_state_peer *src,
1260     struct pf_state_peer *dst, int *writeback)
1261 {
1262 	struct tcphdr	*th = &pd->hdr.tcp;
1263 	struct timeval	 uptime;
1264 	u_int		 tsval_from_last;
1265 	u_int32_t	 tsval, tsecr;
1266 	int		 copyback = 0;
1267 	int		 got_ts = 0;
1268 	int		 olen;
1269 	u_int8_t	 opts[MAX_TCPOPTLEN], *opt;
1270 
1271 	KASSERT(src->scrub || dst->scrub);
1272 
1273 	/*
1274 	 * Enforce the minimum TTL seen for this connection.  Negate a common
1275 	 * technique to evade an intrusion detection system and confuse
1276 	 * firewall state code.
1277 	 */
1278 	switch (pd->af) {
1279 	case AF_INET:
1280 		if (src->scrub) {
1281 			struct ip *h = mtod(pd->m, struct ip *);
1282 			if (h->ip_ttl > src->scrub->pfss_ttl)
1283 				src->scrub->pfss_ttl = h->ip_ttl;
1284 			h->ip_ttl = src->scrub->pfss_ttl;
1285 		}
1286 		break;
1287 #ifdef INET6
1288 	case AF_INET6:
1289 		if (src->scrub) {
1290 			struct ip6_hdr *h = mtod(pd->m, struct ip6_hdr *);
1291 			if (h->ip6_hlim > src->scrub->pfss_ttl)
1292 				src->scrub->pfss_ttl = h->ip6_hlim;
1293 			h->ip6_hlim = src->scrub->pfss_ttl;
1294 		}
1295 		break;
1296 #endif /* INET6 */
1297 	default:
1298 		unhandled_af(pd->af);
1299 	}
1300 
1301 	olen = (th->th_off << 2) - sizeof(*th);
1302 
1303 	if (olen >= TCPOLEN_TIMESTAMP &&
1304 	    ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1305 	    (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1306 	    pf_pull_hdr(pd->m, pd->off + sizeof(*th), opts, olen, NULL,
1307 	    pd->af)) {
1308 
1309 		/* Modulate the timestamps.  Can be used for NAT detection, OS
1310 		 * uptime determination or reboot detection.
1311 		 */
1312 		opt = opts;
1313 		while ((opt = pf_find_tcpopt(opt, opts, olen,
1314 			    TCPOPT_TIMESTAMP, TCPOLEN_TIMESTAMP)) != NULL) {
1315 
1316 			u_int8_t *ts = opt + 2;
1317 			u_int8_t *tsr = opt + 6;
1318 
1319 			if (got_ts) {
1320 				/* Huh?  Multiple timestamps!? */
1321 				if (pf_status.debug >= LOG_NOTICE) {
1322 					log(LOG_NOTICE,
1323 					    "pf: %s: multiple TS??", __func__);
1324 					pf_print_state(state);
1325 					addlog("\n");
1326 				}
1327 				REASON_SET(reason, PFRES_TS);
1328 				return (PF_DROP);
1329 			}
1330 
1331 			memcpy(&tsval, ts, sizeof(u_int32_t));
1332 			memcpy(&tsecr, tsr, sizeof(u_int32_t));
1333 
1334 			/* modulate TS */
1335 			if (tsval && src->scrub &&
1336 			    (src->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1337 				/* tsval used further on */
1338 				tsval = ntohl(tsval);
1339 				pf_patch_32_unaligned(pd,
1340 				    ts, htonl(tsval + src->scrub->pfss_ts_mod),
1341 				    PF_ALGNMNT(ts - opts));
1342 				copyback = 1;
1343 			}
1344 
1345 			/* modulate TS reply if any (!0) */
1346 			if (tsecr && dst->scrub &&
1347 			    (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1348 				/* tsecr used further on */
1349 				tsecr = ntohl(tsecr) - dst->scrub->pfss_ts_mod;
1350 				pf_patch_32_unaligned(pd,
1351 				    tsr, htonl(tsecr), PF_ALGNMNT(tsr - opts));
1352 				copyback = 1;
1353 			}
1354 
1355 			got_ts = 1;
1356 			opt += opt[1];
1357 		}
1358 
1359 		if (copyback) {
1360 			/* Copyback the options, caller copies back header */
1361 			*writeback = 1;
1362 			m_copyback(pd->m, pd->off + sizeof(*th), olen, opts, M_NOWAIT);
1363 		}
1364 	}
1365 
1366 
1367 	/*
1368 	 * Must invalidate PAWS checks on connections idle for too long.
1369 	 * The fastest allowed timestamp clock is 1ms.  That turns out to
1370 	 * be about 24 days before it wraps.  XXX Right now our lowerbound
1371 	 * TS echo check only works for the first 12 days of a connection
1372 	 * when the TS has exhausted half its 32bit space
1373 	 */
1374 #define TS_MAX_IDLE	(24*24*60*60)
1375 #define TS_MAX_CONN	(12*24*60*60)	/* XXX remove when better tsecr check */
1376 
1377 	getmicrouptime(&uptime);
1378 	if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1379 	    (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1380 	    getuptime() - state->creation > TS_MAX_CONN))  {
1381 		if (pf_status.debug >= LOG_NOTICE) {
1382 			log(LOG_NOTICE, "pf: src idled out of PAWS ");
1383 			pf_print_state(state);
1384 			addlog("\n");
1385 		}
1386 		src->scrub->pfss_flags =
1387 		    (src->scrub->pfss_flags & ~PFSS_PAWS) | PFSS_PAWS_IDLED;
1388 	}
1389 	if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1390 	    uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1391 		if (pf_status.debug >= LOG_NOTICE) {
1392 			log(LOG_NOTICE, "pf: dst idled out of PAWS ");
1393 			pf_print_state(state);
1394 			addlog("\n");
1395 		}
1396 		dst->scrub->pfss_flags =
1397 		    (dst->scrub->pfss_flags & ~PFSS_PAWS) | PFSS_PAWS_IDLED;
1398 	}
1399 
1400 	if (got_ts && src->scrub && dst->scrub &&
1401 	    (src->scrub->pfss_flags & PFSS_PAWS) &&
1402 	    (dst->scrub->pfss_flags & PFSS_PAWS)) {
1403 		/* Validate that the timestamps are "in-window".
1404 		 * RFC1323 describes TCP Timestamp options that allow
1405 		 * measurement of RTT (round trip time) and PAWS
1406 		 * (protection against wrapped sequence numbers).  PAWS
1407 		 * gives us a set of rules for rejecting packets on
1408 		 * long fat pipes (packets that were somehow delayed
1409 		 * in transit longer than the time it took to send the
1410 		 * full TCP sequence space of 4Gb).  We can use these
1411 		 * rules and infer a few others that will let us treat
1412 		 * the 32bit timestamp and the 32bit echoed timestamp
1413 		 * as sequence numbers to prevent a blind attacker from
1414 		 * inserting packets into a connection.
1415 		 *
1416 		 * RFC1323 tells us:
1417 		 *  - The timestamp on this packet must be greater than
1418 		 *    or equal to the last value echoed by the other
1419 		 *    endpoint.  The RFC says those will be discarded
1420 		 *    since it is a dup that has already been acked.
1421 		 *    This gives us a lowerbound on the timestamp.
1422 		 *        timestamp >= other last echoed timestamp
1423 		 *  - The timestamp will be less than or equal to
1424 		 *    the last timestamp plus the time between the
1425 		 *    last packet and now.  The RFC defines the max
1426 		 *    clock rate as 1ms.  We will allow clocks to be
1427 		 *    up to 10% fast and will allow a total difference
1428 		 *    or 30 seconds due to a route change.  And this
1429 		 *    gives us an upperbound on the timestamp.
1430 		 *        timestamp <= last timestamp + max ticks
1431 		 *    We have to be careful here.  Windows will send an
1432 		 *    initial timestamp of zero and then initialize it
1433 		 *    to a random value after the 3whs; presumably to
1434 		 *    avoid a DoS by having to call an expensive RNG
1435 		 *    during a SYN flood.  Proof MS has at least one
1436 		 *    good security geek.
1437 		 *
1438 		 *  - The TCP timestamp option must also echo the other
1439 		 *    endpoints timestamp.  The timestamp echoed is the
1440 		 *    one carried on the earliest unacknowledged segment
1441 		 *    on the left edge of the sequence window.  The RFC
1442 		 *    states that the host will reject any echoed
1443 		 *    timestamps that were larger than any ever sent.
1444 		 *    This gives us an upperbound on the TS echo.
1445 		 *        tescr <= largest_tsval
1446 		 *  - The lowerbound on the TS echo is a little more
1447 		 *    tricky to determine.  The other endpoint's echoed
1448 		 *    values will not decrease.  But there may be
1449 		 *    network conditions that re-order packets and
1450 		 *    cause our view of them to decrease.  For now the
1451 		 *    only lowerbound we can safely determine is that
1452 		 *    the TS echo will never be less than the original
1453 		 *    TS.  XXX There is probably a better lowerbound.
1454 		 *    Remove TS_MAX_CONN with better lowerbound check.
1455 		 *        tescr >= other original TS
1456 		 *
1457 		 * It is also important to note that the fastest
1458 		 * timestamp clock of 1ms will wrap its 32bit space in
1459 		 * 24 days.  So we just disable TS checking after 24
1460 		 * days of idle time.  We actually must use a 12d
1461 		 * connection limit until we can come up with a better
1462 		 * lowerbound to the TS echo check.
1463 		 */
1464 		struct timeval	delta_ts;
1465 		int		ts_fudge;
1466 
1467 		/*
1468 		 * PFTM_TS_DIFF is how many seconds of leeway to allow
1469 		 * a host's timestamp.  This can happen if the previous
1470 		 * packet got delayed in transit for much longer than
1471 		 * this packet.
1472 		 */
1473 		if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1474 			ts_fudge = pf_default_rule.timeout[PFTM_TS_DIFF];
1475 
1476 		/* Calculate max ticks since the last timestamp */
1477 #define TS_MAXFREQ	1100		/* RFC max TS freq of 1Khz + 10% skew */
1478 #define TS_MICROSECS	1000000		/* microseconds per second */
1479 		timersub(&uptime, &src->scrub->pfss_last, &delta_ts);
1480 		tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1481 		tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1482 
1483 		if ((src->state >= TCPS_ESTABLISHED &&
1484 		    dst->state >= TCPS_ESTABLISHED) &&
1485 		    (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1486 		    SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1487 		    (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1488 		    SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1489 			/* Bad RFC1323 implementation or an insertion attack.
1490 			 *
1491 			 * - Solaris 2.6 and 2.7 are known to send another ACK
1492 			 *   after the FIN,FIN|ACK,ACK closing that carries
1493 			 *   an old timestamp.
1494 			 */
1495 
1496 			DPFPRINTF(LOG_NOTICE, "Timestamp failed %c%c%c%c",
1497 			    SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1498 			    SEQ_GT(tsval, src->scrub->pfss_tsval +
1499 			    tsval_from_last) ? '1' : ' ',
1500 			    SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1501 			    SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' ');
1502 			DPFPRINTF(LOG_NOTICE, " tsval: %u  tsecr: %u  "
1503 			    "+ticks: %u  idle: %llu.%06lus", tsval, tsecr,
1504 			    tsval_from_last, (long long)delta_ts.tv_sec,
1505 			    delta_ts.tv_usec);
1506 			DPFPRINTF(LOG_NOTICE, " src->tsval: %u  tsecr: %u",
1507 			    src->scrub->pfss_tsval, src->scrub->pfss_tsecr);
1508 			DPFPRINTF(LOG_NOTICE, " dst->tsval: %u  tsecr: %u  "
1509 			    "tsval0: %u", dst->scrub->pfss_tsval,
1510 			    dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0);
1511 			if (pf_status.debug >= LOG_NOTICE) {
1512 				log(LOG_NOTICE, "pf: ");
1513 				pf_print_state(state);
1514 				pf_print_flags(th->th_flags);
1515 				addlog("\n");
1516 			}
1517 			REASON_SET(reason, PFRES_TS);
1518 			return (PF_DROP);
1519 		}
1520 		/* XXX I'd really like to require tsecr but it's optional */
1521 	} else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1522 	    ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1523 	    || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1524 	    src->scrub && dst->scrub &&
1525 	    (src->scrub->pfss_flags & PFSS_PAWS) &&
1526 	    (dst->scrub->pfss_flags & PFSS_PAWS)) {
1527 		/* Didn't send a timestamp.  Timestamps aren't really useful
1528 		 * when:
1529 		 *  - connection opening or closing (often not even sent).
1530 		 *    but we must not let an attacker to put a FIN on a
1531 		 *    data packet to sneak it through our ESTABLISHED check.
1532 		 *  - on a TCP reset.  RFC suggests not even looking at TS.
1533 		 *  - on an empty ACK.  The TS will not be echoed so it will
1534 		 *    probably not help keep the RTT calculation in sync and
1535 		 *    there isn't as much danger when the sequence numbers
1536 		 *    got wrapped.  So some stacks don't include TS on empty
1537 		 *    ACKs :-(
1538 		 *
1539 		 * To minimize the disruption to mostly RFC1323 conformant
1540 		 * stacks, we will only require timestamps on data packets.
1541 		 *
1542 		 * And what do ya know, we cannot require timestamps on data
1543 		 * packets.  There appear to be devices that do legitimate
1544 		 * TCP connection hijacking.  There are HTTP devices that allow
1545 		 * a 3whs (with timestamps) and then buffer the HTTP request.
1546 		 * If the intermediate device has the HTTP response cache, it
1547 		 * will spoof the response but not bother timestamping its
1548 		 * packets.  So we can look for the presence of a timestamp in
1549 		 * the first data packet and if there, require it in all future
1550 		 * packets.
1551 		 */
1552 
1553 		if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1554 			/*
1555 			 * Hey!  Someone tried to sneak a packet in.  Or the
1556 			 * stack changed its RFC1323 behavior?!?!
1557 			 */
1558 			if (pf_status.debug >= LOG_NOTICE) {
1559 				log(LOG_NOTICE,
1560 				    "pf: did not receive expected RFC1323 "
1561 				    "timestamp");
1562 				pf_print_state(state);
1563 				pf_print_flags(th->th_flags);
1564 				addlog("\n");
1565 			}
1566 			REASON_SET(reason, PFRES_TS);
1567 			return (PF_DROP);
1568 		}
1569 	}
1570 
1571 	/*
1572 	 * We will note if a host sends his data packets with or without
1573 	 * timestamps.  And require all data packets to contain a timestamp
1574 	 * if the first does.  PAWS implicitly requires that all data packets be
1575 	 * timestamped.  But I think there are middle-man devices that hijack
1576 	 * TCP streams immediately after the 3whs and don't timestamp their
1577 	 * packets (seen in a WWW accelerator or cache).
1578 	 */
1579 	if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1580 	    (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1581 		if (got_ts)
1582 			src->scrub->pfss_flags |= PFSS_DATA_TS;
1583 		else {
1584 			src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1585 			if (pf_status.debug >= LOG_NOTICE && dst->scrub &&
1586 			    (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1587 				/* Don't warn if other host rejected RFC1323 */
1588 				log(LOG_NOTICE,
1589 				    "pf: broken RFC1323 stack did not "
1590 				    "timestamp data packet. Disabled PAWS "
1591 				    "security.");
1592 				pf_print_state(state);
1593 				pf_print_flags(th->th_flags);
1594 				addlog("\n");
1595 			}
1596 		}
1597 	}
1598 
1599 	/*
1600 	 * Update PAWS values
1601 	 */
1602 	if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1603 	    (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1604 		getmicrouptime(&src->scrub->pfss_last);
1605 		if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1606 		    (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1607 			src->scrub->pfss_tsval = tsval;
1608 
1609 		if (tsecr) {
1610 			if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1611 			    (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1612 				src->scrub->pfss_tsecr = tsecr;
1613 
1614 			if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1615 			    (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1616 			    src->scrub->pfss_tsval0 == 0)) {
1617 				/* tsval0 MUST be the lowest timestamp */
1618 				src->scrub->pfss_tsval0 = tsval;
1619 			}
1620 
1621 			/* Only fully initialized after a TS gets echoed */
1622 			if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1623 				src->scrub->pfss_flags |= PFSS_PAWS;
1624 		}
1625 	}
1626 
1627 	/* I have a dream....  TCP segment reassembly.... */
1628 	return (0);
1629 }
1630 
1631 int
pf_normalize_mss(struct pf_pdesc * pd,u_int16_t maxmss)1632 pf_normalize_mss(struct pf_pdesc *pd, u_int16_t maxmss)
1633 {
1634 	int		 olen, optsoff;
1635 	u_int8_t	 opts[MAX_TCPOPTLEN], *opt;
1636 
1637 	olen = (pd->hdr.tcp.th_off << 2) - sizeof(struct tcphdr);
1638 	optsoff = pd->off + sizeof(struct tcphdr);
1639 	if (olen < TCPOLEN_MAXSEG ||
1640 	    !pf_pull_hdr(pd->m, optsoff, opts, olen, NULL, pd->af))
1641 		return (0);
1642 
1643 	opt = opts;
1644 	while ((opt = pf_find_tcpopt(opt, opts, olen,
1645 		    TCPOPT_MAXSEG, TCPOLEN_MAXSEG)) != NULL) {
1646 		u_int16_t	mss;
1647 		u_int8_t       *mssp = opt + 2;
1648 		memcpy(&mss, mssp, sizeof(mss));
1649 		if (ntohs(mss) > maxmss) {
1650 			size_t mssoffopts = mssp - opts;
1651 			pf_patch_16_unaligned(pd, &mss,
1652 			    htons(maxmss), PF_ALGNMNT(mssoffopts));
1653 			m_copyback(pd->m, optsoff + mssoffopts,
1654 			    sizeof(mss), &mss, M_NOWAIT);
1655 			m_copyback(pd->m, pd->off,
1656 			    sizeof(struct tcphdr), &pd->hdr.tcp, M_NOWAIT);
1657 		}
1658 
1659 		opt += opt[1];
1660 	}
1661 
1662 	return (0);
1663 }
1664 
1665 void
pf_scrub(struct mbuf * m,u_int16_t flags,sa_family_t af,u_int8_t min_ttl,u_int8_t tos)1666 pf_scrub(struct mbuf *m, u_int16_t flags, sa_family_t af, u_int8_t min_ttl,
1667     u_int8_t tos)
1668 {
1669 	struct ip		*h = mtod(m, struct ip *);
1670 #ifdef INET6
1671 	struct ip6_hdr		*h6 = mtod(m, struct ip6_hdr *);
1672 #endif	/* INET6 */
1673 	u_int16_t		 old;
1674 
1675 	/* Clear IP_DF if no-df was requested */
1676 	if (flags & PFSTATE_NODF && af == AF_INET && h->ip_off & htons(IP_DF)) {
1677 		old = h->ip_off;
1678 		h->ip_off &= htons(~IP_DF);
1679 		pf_cksum_fixup(&h->ip_sum, old, h->ip_off, 0);
1680 	}
1681 
1682 	/* Enforce a minimum ttl, may cause endless packet loops */
1683 	if (min_ttl && af == AF_INET && h->ip_ttl < min_ttl) {
1684 		old = h->ip_ttl;
1685 		h->ip_ttl = min_ttl;
1686 		pf_cksum_fixup(&h->ip_sum, old, h->ip_ttl, 0);
1687 	}
1688 #ifdef INET6
1689 	if (min_ttl && af == AF_INET6 && h6->ip6_hlim < min_ttl)
1690 		h6->ip6_hlim = min_ttl;
1691 #endif	/* INET6 */
1692 
1693 	/* Enforce tos */
1694 	if (flags & PFSTATE_SETTOS) {
1695 		if (af == AF_INET) {
1696 			/*
1697 			 * ip_tos is 8 bit field at offset 1. Use 16 bit value
1698 			 * at offset 0.
1699 			 */
1700 			old = *(u_int16_t *)h;
1701 			h->ip_tos = tos | (h->ip_tos & IPTOS_ECN_MASK);
1702 			pf_cksum_fixup(&h->ip_sum, old, *(u_int16_t *)h, 0);
1703 		}
1704 #ifdef INET6
1705 		if (af == AF_INET6) {
1706 			/* drugs are unable to explain such idiocy */
1707 			h6->ip6_flow &= ~htonl(0x0fc00000);
1708 			h6->ip6_flow |= htonl(((u_int32_t)tos) << 20);
1709 		}
1710 #endif	/* INET6 */
1711 	}
1712 
1713 	/* random-id, but not for fragments */
1714 	if (flags & PFSTATE_RANDOMID && af == AF_INET &&
1715 	    !(h->ip_off & ~htons(IP_DF))) {
1716 		old = h->ip_id;
1717 		h->ip_id = htons(ip_randomid());
1718 		pf_cksum_fixup(&h->ip_sum, old, h->ip_id, 0);
1719 	}
1720 }
1721