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$");
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
63struct 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
74struct 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
82struct 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
102struct 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
109static struct mtx pf_frag_mtx;
110MTX_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
115VNET_DEFINE(uma_zone_t, pf_state_scrub_z);	/* XXX: shared with pfsync */
116
117VNET_DEFINE_STATIC(uma_zone_t, pf_frent_z);
118#define	V_pf_frent_z	VNET(pf_frent_z)
119VNET_DEFINE_STATIC(uma_zone_t, pf_frag_z);
120#define	V_pf_frag_z	VNET(pf_frag_z)
121
122TAILQ_HEAD(pf_fragqueue, pf_fragment);
123TAILQ_HEAD(pf_cachequeue, pf_fragment);
124VNET_DEFINE_STATIC(struct pf_fragqueue,	pf_fragqueue);
125#define	V_pf_fragqueue			VNET(pf_fragqueue)
126RB_HEAD(pf_frag_tree, pf_fragment);
127VNET_DEFINE_STATIC(struct pf_frag_tree,	pf_frag_tree);
128#define	V_pf_frag_tree			VNET(pf_frag_tree)
129static int		 pf_frag_compare(struct pf_fragment *,
130			    struct pf_fragment *);
131static RB_PROTOTYPE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
132static RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
133
134static void	pf_flush_fragments(void);
135static void	pf_free_fragment(struct pf_fragment *);
136static void	pf_remove_fragment(struct pf_fragment *);
137static int	pf_normalize_tcpopt(struct pf_krule *, struct mbuf *,
138		    struct tcphdr *, int, sa_family_t);
139static struct pf_frent *pf_create_fragment(u_short *);
140static int	pf_frent_holes(struct pf_frent *frent);
141static struct pf_fragment *pf_find_fragment(struct pf_fragment_cmp *key,
142		    struct pf_frag_tree *tree);
143static inline int	pf_frent_index(struct pf_frent *);
144static int	pf_frent_insert(struct pf_fragment *,
145			    struct pf_frent *, struct pf_frent *);
146void			pf_frent_remove(struct pf_fragment *,
147			    struct pf_frent *);
148struct pf_frent		*pf_frent_previous(struct pf_fragment *,
149			    struct pf_frent *);
150static struct pf_fragment *pf_fillup_fragment(struct pf_fragment_cmp *,
151		    struct pf_frent *, u_short *);
152static struct mbuf *pf_join_fragment(struct pf_fragment *);
153#ifdef INET
154static void	pf_scrub_ip(struct mbuf **, uint32_t, uint8_t, uint8_t);
155static int	pf_reassemble(struct mbuf **, struct ip *, int, u_short *);
156#endif	/* INET */
157#ifdef INET6
158static int	pf_reassemble6(struct mbuf **, struct ip6_hdr *,
159		    struct ip6_frag *, uint16_t, uint16_t, u_short *);
160static 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
171static void
172pf_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
183void
184pf_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
203void
204pf_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
212static int
213pf_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
230void
231pf_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
239void
240pf_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 */
259static void
260pf_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 */
279static void
280pf_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
298static struct pf_fragment *
299pf_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 */
317static void
318pf_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
329static struct pf_frent *
330pf_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 */
356static int
357pf_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
382static inline int
383pf_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
398static int
399pf_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
445void
446pf_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
486struct pf_frent *
487pf_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
541static struct pf_fragment *
542pf_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"));
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", 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",
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" : "reass frag %#08x @ %d-%d",
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", 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", 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"));
697		goto bad_fragment;
698	}
699
700	return (frag);
701
702bad_fragment:
703	REASON_SET(reason, PFRES_FRAG);
704drop_fragment:
705	uma_zfree(V_pf_frent_z, frent);
706	return (NULL);
707}
708
709static struct mbuf *
710pf_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
741static int
742pf_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", 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", 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
814static int
815pf_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", frag->fr_id, frag->fr_holes));
861		PF_FRAG_UNLOCK();
862		return (PF_PASS);  /* Drop because *m0 is NULL, no error. */
863	}
864
865	/* We have all the data. */
866	frent = TAILQ_FIRST(&frag->fr_queue);
867	KASSERT(frent != NULL, ("frent != NULL"));
868	extoff = frent->fe_extoff;
869	maxlen = frag->fr_maxlen;
870	frag_id = frag->fr_id;
871	total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
872		TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
873	hdrlen = frent->fe_hdrlen - sizeof(struct ip6_frag);
874
875	m = *m0 = pf_join_fragment(frag);
876	frag = NULL;
877
878	PF_FRAG_UNLOCK();
879
880	/* Take protocol from first fragment header. */
881	m = m_getptr(m, hdrlen + offsetof(struct ip6_frag, ip6f_nxt), &off);
882	KASSERT(m, ("%s: short mbuf chain", __func__));
883	proto = *(mtod(m, caddr_t) + off);
884	m = *m0;
885
886	/* Delete frag6 header */
887	if (ip6_deletefraghdr(m, hdrlen, M_NOWAIT) != 0)
888		goto fail;
889
890	if (m->m_flags & M_PKTHDR) {
891		int plen = 0;
892		for (m = *m0; m; m = m->m_next)
893			plen += m->m_len;
894		m = *m0;
895		m->m_pkthdr.len = plen;
896	}
897
898	if ((mtag = m_tag_get(PF_REASSEMBLED, sizeof(struct pf_fragment_tag),
899	    M_NOWAIT)) == NULL)
900		goto fail;
901	ftag = (struct pf_fragment_tag *)(mtag + 1);
902	ftag->ft_hdrlen = hdrlen;
903	ftag->ft_extoff = extoff;
904	ftag->ft_maxlen = maxlen;
905	ftag->ft_id = frag_id;
906	m_tag_prepend(m, mtag);
907
908	ip6 = mtod(m, struct ip6_hdr *);
909	ip6->ip6_plen = htons(hdrlen - sizeof(struct ip6_hdr) + total);
910	if (extoff) {
911		/* Write protocol into next field of last extension header. */
912		m = m_getptr(m, extoff + offsetof(struct ip6_ext, ip6e_nxt),
913		    &off);
914		KASSERT(m, ("%s: short mbuf chain", __func__));
915		*(mtod(m, char *) + off) = proto;
916		m = *m0;
917	} else
918		ip6->ip6_nxt = proto;
919
920	if (hdrlen - sizeof(struct ip6_hdr) + total > IPV6_MAXPACKET) {
921		DPFPRINTF(("drop: too big: %d", total));
922		ip6->ip6_plen = 0;
923		REASON_SET(reason, PFRES_SHORT);
924		/* PF_DROP requires a valid mbuf *m0 in pf_test6(). */
925		return (PF_DROP);
926	}
927
928	DPFPRINTF(("complete: %p(%d)", m, ntohs(ip6->ip6_plen)));
929	return (PF_PASS);
930
931fail:
932	REASON_SET(reason, PFRES_MEMORY);
933	/* PF_DROP requires a valid mbuf *m0 in pf_test6(), will free later. */
934	return (PF_DROP);
935}
936#endif	/* INET6 */
937
938#ifdef INET6
939int
940pf_refragment6(struct ifnet *ifp, struct mbuf **m0, struct m_tag *mtag)
941{
942	struct mbuf		*m = *m0, *t;
943	struct pf_fragment_tag	*ftag = (struct pf_fragment_tag *)(mtag + 1);
944	struct pf_pdesc		 pd;
945	uint32_t		 frag_id;
946	uint16_t		 hdrlen, extoff, maxlen;
947	uint8_t			 proto;
948	int			 error, action;
949
950	hdrlen = ftag->ft_hdrlen;
951	extoff = ftag->ft_extoff;
952	maxlen = ftag->ft_maxlen;
953	frag_id = ftag->ft_id;
954	m_tag_delete(m, mtag);
955	mtag = NULL;
956	ftag = NULL;
957
958	if (extoff) {
959		int off;
960
961		/* Use protocol from next field of last extension header */
962		m = m_getptr(m, extoff + offsetof(struct ip6_ext, ip6e_nxt),
963		    &off);
964		KASSERT((m != NULL), ("pf_refragment6: short mbuf chain"));
965		proto = *(mtod(m, caddr_t) + off);
966		*(mtod(m, char *) + off) = IPPROTO_FRAGMENT;
967		m = *m0;
968	} else {
969		struct ip6_hdr *hdr;
970
971		hdr = mtod(m, struct ip6_hdr *);
972		proto = hdr->ip6_nxt;
973		hdr->ip6_nxt = IPPROTO_FRAGMENT;
974	}
975
976	/* The MTU must be a multiple of 8 bytes, or we risk doing the
977	 * fragmentation wrong. */
978	maxlen = maxlen & ~7;
979
980	/*
981	 * Maxlen may be less than 8 if there was only a single
982	 * fragment.  As it was fragmented before, add a fragment
983	 * header also for a single fragment.  If total or maxlen
984	 * is less than 8, ip6_fragment() will return EMSGSIZE and
985	 * we drop the packet.
986	 */
987	error = ip6_fragment(ifp, m, hdrlen, proto, maxlen, frag_id);
988	m = (*m0)->m_nextpkt;
989	(*m0)->m_nextpkt = NULL;
990	if (error == 0) {
991		/* The first mbuf contains the unfragmented packet. */
992		m_freem(*m0);
993		*m0 = NULL;
994		action = PF_PASS;
995	} else {
996		/* Drop expects an mbuf to free. */
997		DPFPRINTF(("refragment error %d", error));
998		action = PF_DROP;
999	}
1000	for (t = m; m; m = t) {
1001		t = m->m_nextpkt;
1002		m->m_nextpkt = NULL;
1003		m->m_flags |= M_SKIP_FIREWALL;
1004		memset(&pd, 0, sizeof(pd));
1005		pd.pf_mtag = pf_find_mtag(m);
1006		if (error == 0)
1007			ip6_forward(m, 0);
1008		else
1009			m_freem(m);
1010	}
1011
1012	return (action);
1013}
1014#endif /* INET6 */
1015
1016#ifdef INET
1017int
1018pf_normalize_ip(struct mbuf **m0, int dir, struct pfi_kkif *kif, u_short *reason,
1019    struct pf_pdesc *pd)
1020{
1021	struct mbuf		*m = *m0;
1022	struct pf_krule		*r;
1023	struct ip		*h = mtod(m, struct ip *);
1024	int			 mff = (ntohs(h->ip_off) & IP_MF);
1025	int			 hlen = h->ip_hl << 2;
1026	u_int16_t		 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
1027	u_int16_t		 max;
1028	int			 ip_len;
1029	int			 ip_off;
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		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	else {
1064		counter_u64_add(r->packets[dir == PF_OUT], 1);
1065		counter_u64_add(r->bytes[dir == PF_OUT], pd->tot_len);
1066	}
1067
1068	/* Check for illegal packets */
1069	if (hlen < (int)sizeof(struct ip)) {
1070		REASON_SET(reason, PFRES_NORM);
1071		goto drop;
1072	}
1073
1074	if (hlen > ntohs(h->ip_len)) {
1075		REASON_SET(reason, PFRES_NORM);
1076		goto drop;
1077	}
1078
1079	/* Clear IP_DF if the rule uses the no-df option */
1080	if (r->rule_flag & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
1081		u_int16_t ip_off = h->ip_off;
1082
1083		h->ip_off &= htons(~IP_DF);
1084		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1085	}
1086
1087	/* We will need other tests here */
1088	if (!fragoff && !mff)
1089		goto no_fragment;
1090
1091	/* We're dealing with a fragment now. Don't allow fragments
1092	 * with IP_DF to enter the cache. If the flag was cleared by
1093	 * no-df above, fine. Otherwise drop it.
1094	 */
1095	if (h->ip_off & htons(IP_DF)) {
1096		DPFPRINTF(("IP_DF\n"));
1097		goto bad;
1098	}
1099
1100	ip_len = ntohs(h->ip_len) - hlen;
1101	ip_off = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
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
1158int
1159pf_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		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	else {
1207		counter_u64_add(r->packets[dir == PF_OUT], 1);
1208		counter_u64_add(r->bytes[dir == PF_OUT], pd->tot_len);
1209	}
1210
1211	/* Check for illegal packets */
1212	if (sizeof(struct ip6_hdr) + IPV6_MAXPACKET < m->m_pkthdr.len)
1213		goto drop;
1214
1215	extoff = 0;
1216	off = sizeof(struct ip6_hdr);
1217	proto = h->ip6_nxt;
1218	terminal = 0;
1219	do {
1220		switch (proto) {
1221		case IPPROTO_FRAGMENT:
1222			goto fragment;
1223			break;
1224		case IPPROTO_AH:
1225		case IPPROTO_ROUTING:
1226		case IPPROTO_DSTOPTS:
1227			if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1228			    NULL, AF_INET6))
1229				goto shortpkt;
1230			extoff = off;
1231			if (proto == IPPROTO_AH)
1232				off += (ext.ip6e_len + 2) * 4;
1233			else
1234				off += (ext.ip6e_len + 1) * 8;
1235			proto = ext.ip6e_nxt;
1236			break;
1237		case IPPROTO_HOPOPTS:
1238			if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1239			    NULL, AF_INET6))
1240				goto shortpkt;
1241			extoff = off;
1242			optend = off + (ext.ip6e_len + 1) * 8;
1243			ooff = off + sizeof(ext);
1244			do {
1245				if (!pf_pull_hdr(m, ooff, &opt.ip6o_type,
1246				    sizeof(opt.ip6o_type), NULL, NULL,
1247				    AF_INET6))
1248					goto shortpkt;
1249				if (opt.ip6o_type == IP6OPT_PAD1) {
1250					ooff++;
1251					continue;
1252				}
1253				if (!pf_pull_hdr(m, ooff, &opt, sizeof(opt),
1254				    NULL, NULL, AF_INET6))
1255					goto shortpkt;
1256				if (ooff + sizeof(opt) + opt.ip6o_len > optend)
1257					goto drop;
1258				switch (opt.ip6o_type) {
1259				case IP6OPT_JUMBO:
1260					if (h->ip6_plen != 0)
1261						goto drop;
1262					if (!pf_pull_hdr(m, ooff, &jumbo,
1263					    sizeof(jumbo), NULL, NULL,
1264					    AF_INET6))
1265						goto shortpkt;
1266					memcpy(&jumbolen, jumbo.ip6oj_jumbo_len,
1267					    sizeof(jumbolen));
1268					jumbolen = ntohl(jumbolen);
1269					if (jumbolen <= IPV6_MAXPACKET)
1270						goto drop;
1271					if (sizeof(struct ip6_hdr) + jumbolen !=
1272					    m->m_pkthdr.len)
1273						goto drop;
1274					break;
1275				default:
1276					break;
1277				}
1278				ooff += sizeof(opt) + opt.ip6o_len;
1279			} while (ooff < optend);
1280
1281			off = optend;
1282			proto = ext.ip6e_nxt;
1283			break;
1284		default:
1285			terminal = 1;
1286			break;
1287		}
1288	} while (!terminal);
1289
1290	/* jumbo payload option must be present, or plen > 0 */
1291	if (ntohs(h->ip6_plen) == 0)
1292		plen = jumbolen;
1293	else
1294		plen = ntohs(h->ip6_plen);
1295	if (plen == 0)
1296		goto drop;
1297	if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1298		goto shortpkt;
1299
1300	pf_scrub_ip6(&m, r->min_ttl);
1301
1302	return (PF_PASS);
1303
1304 fragment:
1305	/* Jumbo payload packets cannot be fragmented. */
1306	plen = ntohs(h->ip6_plen);
1307	if (plen == 0 || jumbolen)
1308		goto drop;
1309	if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1310		goto shortpkt;
1311
1312	if (!pf_pull_hdr(m, off, &frag, sizeof(frag), NULL, NULL, AF_INET6))
1313		goto shortpkt;
1314
1315	/* Offset now points to data portion. */
1316	off += sizeof(frag);
1317
1318	/* Returns PF_DROP or *m0 is NULL or completely reassembled mbuf. */
1319	if (pf_reassemble6(m0, h, &frag, off, extoff, reason) != PF_PASS)
1320		return (PF_DROP);
1321	m = *m0;
1322	if (m == NULL)
1323		return (PF_DROP);
1324
1325	pd->flags |= PFDESC_IP_REAS;
1326	return (PF_PASS);
1327
1328 shortpkt:
1329	REASON_SET(reason, PFRES_SHORT);
1330	if (r != NULL && r->log)
1331		PFLOG_PACKET(kif, m, AF_INET6, dir, *reason, r, NULL, NULL, pd,
1332		    1);
1333	return (PF_DROP);
1334
1335 drop:
1336	REASON_SET(reason, PFRES_NORM);
1337	if (r != NULL && r->log)
1338		PFLOG_PACKET(kif, m, AF_INET6, dir, *reason, r, NULL, NULL, pd,
1339		    1);
1340	return (PF_DROP);
1341}
1342#endif /* INET6 */
1343
1344int
1345pf_normalize_tcp(int dir, struct pfi_kkif *kif, struct mbuf *m, int ipoff,
1346    int off, void *h, struct pf_pdesc *pd)
1347{
1348	struct pf_krule	*r, *rm = NULL;
1349	struct tcphdr	*th = pd->hdr.tcp;
1350	int		 rewrite = 0;
1351	u_short		 reason;
1352	u_int8_t	 flags;
1353	sa_family_t	 af = pd->af;
1354
1355	PF_RULES_RASSERT();
1356
1357	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1358	while (r != NULL) {
1359		counter_u64_add(r->evaluations, 1);
1360		if (pfi_kkif_match(r->kif, kif) == r->ifnot)
1361			r = r->skip[PF_SKIP_IFP].ptr;
1362		else if (r->direction && r->direction != dir)
1363			r = r->skip[PF_SKIP_DIR].ptr;
1364		else if (r->af && r->af != af)
1365			r = r->skip[PF_SKIP_AF].ptr;
1366		else if (r->proto && r->proto != pd->proto)
1367			r = r->skip[PF_SKIP_PROTO].ptr;
1368		else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
1369		    r->src.neg, kif, M_GETFIB(m)))
1370			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1371		else if (r->src.port_op && !pf_match_port(r->src.port_op,
1372			    r->src.port[0], r->src.port[1], th->th_sport))
1373			r = r->skip[PF_SKIP_SRC_PORT].ptr;
1374		else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
1375		    r->dst.neg, NULL, M_GETFIB(m)))
1376			r = r->skip[PF_SKIP_DST_ADDR].ptr;
1377		else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1378			    r->dst.port[0], r->dst.port[1], th->th_dport))
1379			r = r->skip[PF_SKIP_DST_PORT].ptr;
1380		else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1381			    pf_osfp_fingerprint(pd, m, off, th),
1382			    r->os_fingerprint))
1383			r = TAILQ_NEXT(r, entries);
1384		else {
1385			rm = r;
1386			break;
1387		}
1388	}
1389
1390	if (rm == NULL || rm->action == PF_NOSCRUB)
1391		return (PF_PASS);
1392	else {
1393		counter_u64_add(r->packets[dir == PF_OUT], 1);
1394		counter_u64_add(r->bytes[dir == PF_OUT], pd->tot_len);
1395	}
1396
1397	if (rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1398		pd->flags |= PFDESC_TCP_NORM;
1399
1400	flags = th->th_flags;
1401	if (flags & TH_SYN) {
1402		/* Illegal packet */
1403		if (flags & TH_RST)
1404			goto tcp_drop;
1405
1406		if (flags & TH_FIN)
1407			goto tcp_drop;
1408	} else {
1409		/* Illegal packet */
1410		if (!(flags & (TH_ACK|TH_RST)))
1411			goto tcp_drop;
1412	}
1413
1414	if (!(flags & TH_ACK)) {
1415		/* These flags are only valid if ACK is set */
1416		if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1417			goto tcp_drop;
1418	}
1419
1420	/* Check for illegal header length */
1421	if (th->th_off < (sizeof(struct tcphdr) >> 2))
1422		goto tcp_drop;
1423
1424	/* If flags changed, or reserved data set, then adjust */
1425	if (flags != th->th_flags || th->th_x2 != 0) {
1426		u_int16_t	ov, nv;
1427
1428		ov = *(u_int16_t *)(&th->th_ack + 1);
1429		th->th_flags = flags;
1430		th->th_x2 = 0;
1431		nv = *(u_int16_t *)(&th->th_ack + 1);
1432
1433		th->th_sum = pf_proto_cksum_fixup(m, th->th_sum, ov, nv, 0);
1434		rewrite = 1;
1435	}
1436
1437	/* Remove urgent pointer, if TH_URG is not set */
1438	if (!(flags & TH_URG) && th->th_urp) {
1439		th->th_sum = pf_proto_cksum_fixup(m, th->th_sum, th->th_urp,
1440		    0, 0);
1441		th->th_urp = 0;
1442		rewrite = 1;
1443	}
1444
1445	/* Process options */
1446	if (r->max_mss && pf_normalize_tcpopt(r, m, th, off, pd->af))
1447		rewrite = 1;
1448
1449	/* copy back packet headers if we sanitized */
1450	if (rewrite)
1451		m_copyback(m, off, sizeof(*th), (caddr_t)th);
1452
1453	return (PF_PASS);
1454
1455 tcp_drop:
1456	REASON_SET(&reason, PFRES_NORM);
1457	if (rm != NULL && r->log)
1458		PFLOG_PACKET(kif, m, AF_INET, dir, reason, r, NULL, NULL, pd,
1459		    1);
1460	return (PF_DROP);
1461}
1462
1463int
1464pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1465    struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1466{
1467	u_int32_t tsval, tsecr;
1468	u_int8_t hdr[60];
1469	u_int8_t *opt;
1470
1471	KASSERT((src->scrub == NULL),
1472	    ("pf_normalize_tcp_init: src->scrub != NULL"));
1473
1474	src->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT);
1475	if (src->scrub == NULL)
1476		return (1);
1477
1478	switch (pd->af) {
1479#ifdef INET
1480	case AF_INET: {
1481		struct ip *h = mtod(m, struct ip *);
1482		src->scrub->pfss_ttl = h->ip_ttl;
1483		break;
1484	}
1485#endif /* INET */
1486#ifdef INET6
1487	case AF_INET6: {
1488		struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1489		src->scrub->pfss_ttl = h->ip6_hlim;
1490		break;
1491	}
1492#endif /* INET6 */
1493	}
1494
1495
1496	/*
1497	 * All normalizations below are only begun if we see the start of
1498	 * the connections.  They must all set an enabled bit in pfss_flags
1499	 */
1500	if ((th->th_flags & TH_SYN) == 0)
1501		return (0);
1502
1503
1504	if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1505	    pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1506		/* Diddle with TCP options */
1507		int hlen;
1508		opt = hdr + sizeof(struct tcphdr);
1509		hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1510		while (hlen >= TCPOLEN_TIMESTAMP) {
1511			switch (*opt) {
1512			case TCPOPT_EOL:	/* FALLTHROUGH */
1513			case TCPOPT_NOP:
1514				opt++;
1515				hlen--;
1516				break;
1517			case TCPOPT_TIMESTAMP:
1518				if (opt[1] >= TCPOLEN_TIMESTAMP) {
1519					src->scrub->pfss_flags |=
1520					    PFSS_TIMESTAMP;
1521					src->scrub->pfss_ts_mod =
1522					    htonl(arc4random());
1523
1524					/* note PFSS_PAWS not set yet */
1525					memcpy(&tsval, &opt[2],
1526					    sizeof(u_int32_t));
1527					memcpy(&tsecr, &opt[6],
1528					    sizeof(u_int32_t));
1529					src->scrub->pfss_tsval0 = ntohl(tsval);
1530					src->scrub->pfss_tsval = ntohl(tsval);
1531					src->scrub->pfss_tsecr = ntohl(tsecr);
1532					getmicrouptime(&src->scrub->pfss_last);
1533				}
1534				/* FALLTHROUGH */
1535			default:
1536				hlen -= MAX(opt[1], 2);
1537				opt += MAX(opt[1], 2);
1538				break;
1539			}
1540		}
1541	}
1542
1543	return (0);
1544}
1545
1546void
1547pf_normalize_tcp_cleanup(struct pf_state *state)
1548{
1549	if (state->src.scrub)
1550		uma_zfree(V_pf_state_scrub_z, state->src.scrub);
1551	if (state->dst.scrub)
1552		uma_zfree(V_pf_state_scrub_z, state->dst.scrub);
1553
1554	/* Someday... flush the TCP segment reassembly descriptors. */
1555}
1556
1557int
1558pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1559    u_short *reason, struct tcphdr *th, struct pf_state *state,
1560    struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1561{
1562	struct timeval uptime;
1563	u_int32_t tsval, tsecr;
1564	u_int tsval_from_last;
1565	u_int8_t hdr[60];
1566	u_int8_t *opt;
1567	int copyback = 0;
1568	int got_ts = 0;
1569	size_t startoff;
1570
1571	KASSERT((src->scrub || dst->scrub),
1572	    ("%s: src->scrub && dst->scrub!", __func__));
1573
1574	/*
1575	 * Enforce the minimum TTL seen for this connection.  Negate a common
1576	 * technique to evade an intrusion detection system and confuse
1577	 * firewall state code.
1578	 */
1579	switch (pd->af) {
1580#ifdef INET
1581	case AF_INET: {
1582		if (src->scrub) {
1583			struct ip *h = mtod(m, struct ip *);
1584			if (h->ip_ttl > src->scrub->pfss_ttl)
1585				src->scrub->pfss_ttl = h->ip_ttl;
1586			h->ip_ttl = src->scrub->pfss_ttl;
1587		}
1588		break;
1589	}
1590#endif /* INET */
1591#ifdef INET6
1592	case AF_INET6: {
1593		if (src->scrub) {
1594			struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1595			if (h->ip6_hlim > src->scrub->pfss_ttl)
1596				src->scrub->pfss_ttl = h->ip6_hlim;
1597			h->ip6_hlim = src->scrub->pfss_ttl;
1598		}
1599		break;
1600	}
1601#endif /* INET6 */
1602	}
1603
1604	if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1605	    ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1606	    (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1607	    pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1608		/* Diddle with TCP options */
1609		int hlen;
1610		opt = hdr + sizeof(struct tcphdr);
1611		hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1612		while (hlen >= TCPOLEN_TIMESTAMP) {
1613			startoff = opt - (hdr + sizeof(struct tcphdr));
1614			switch (*opt) {
1615			case TCPOPT_EOL:	/* FALLTHROUGH */
1616			case TCPOPT_NOP:
1617				opt++;
1618				hlen--;
1619				break;
1620			case TCPOPT_TIMESTAMP:
1621				/* Modulate the timestamps.  Can be used for
1622				 * NAT detection, OS uptime determination or
1623				 * reboot detection.
1624				 */
1625
1626				if (got_ts) {
1627					/* Huh?  Multiple timestamps!? */
1628					if (V_pf_status.debug >= PF_DEBUG_MISC) {
1629						DPFPRINTF(("multiple TS??"));
1630						pf_print_state(state);
1631						printf("\n");
1632					}
1633					REASON_SET(reason, PFRES_TS);
1634					return (PF_DROP);
1635				}
1636				if (opt[1] >= TCPOLEN_TIMESTAMP) {
1637					memcpy(&tsval, &opt[2],
1638					    sizeof(u_int32_t));
1639					if (tsval && src->scrub &&
1640					    (src->scrub->pfss_flags &
1641					    PFSS_TIMESTAMP)) {
1642						tsval = ntohl(tsval);
1643						pf_patch_32_unaligned(m,
1644						    &th->th_sum,
1645						    &opt[2],
1646						    htonl(tsval +
1647						    src->scrub->pfss_ts_mod),
1648						    PF_ALGNMNT(startoff),
1649						    0);
1650						copyback = 1;
1651					}
1652
1653					/* Modulate TS reply iff valid (!0) */
1654					memcpy(&tsecr, &opt[6],
1655					    sizeof(u_int32_t));
1656					if (tsecr && dst->scrub &&
1657					    (dst->scrub->pfss_flags &
1658					    PFSS_TIMESTAMP)) {
1659						tsecr = ntohl(tsecr)
1660						    - dst->scrub->pfss_ts_mod;
1661						pf_patch_32_unaligned(m,
1662						    &th->th_sum,
1663						    &opt[6],
1664						    htonl(tsecr),
1665						    PF_ALGNMNT(startoff),
1666						    0);
1667						copyback = 1;
1668					}
1669					got_ts = 1;
1670				}
1671				/* FALLTHROUGH */
1672			default:
1673				hlen -= MAX(opt[1], 2);
1674				opt += MAX(opt[1], 2);
1675				break;
1676			}
1677		}
1678		if (copyback) {
1679			/* Copyback the options, caller copys back header */
1680			*writeback = 1;
1681			m_copyback(m, off + sizeof(struct tcphdr),
1682			    (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1683			    sizeof(struct tcphdr));
1684		}
1685	}
1686
1687
1688	/*
1689	 * Must invalidate PAWS checks on connections idle for too long.
1690	 * The fastest allowed timestamp clock is 1ms.  That turns out to
1691	 * be about 24 days before it wraps.  XXX Right now our lowerbound
1692	 * TS echo check only works for the first 12 days of a connection
1693	 * when the TS has exhausted half its 32bit space
1694	 */
1695#define TS_MAX_IDLE	(24*24*60*60)
1696#define TS_MAX_CONN	(12*24*60*60)	/* XXX remove when better tsecr check */
1697
1698	getmicrouptime(&uptime);
1699	if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1700	    (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1701	    time_uptime - state->creation > TS_MAX_CONN))  {
1702		if (V_pf_status.debug >= PF_DEBUG_MISC) {
1703			DPFPRINTF(("src idled out of PAWS\n"));
1704			pf_print_state(state);
1705			printf("\n");
1706		}
1707		src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1708		    | PFSS_PAWS_IDLED;
1709	}
1710	if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1711	    uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1712		if (V_pf_status.debug >= PF_DEBUG_MISC) {
1713			DPFPRINTF(("dst idled out of PAWS\n"));
1714			pf_print_state(state);
1715			printf("\n");
1716		}
1717		dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1718		    | PFSS_PAWS_IDLED;
1719	}
1720
1721	if (got_ts && src->scrub && dst->scrub &&
1722	    (src->scrub->pfss_flags & PFSS_PAWS) &&
1723	    (dst->scrub->pfss_flags & PFSS_PAWS)) {
1724		/* Validate that the timestamps are "in-window".
1725		 * RFC1323 describes TCP Timestamp options that allow
1726		 * measurement of RTT (round trip time) and PAWS
1727		 * (protection against wrapped sequence numbers).  PAWS
1728		 * gives us a set of rules for rejecting packets on
1729		 * long fat pipes (packets that were somehow delayed
1730		 * in transit longer than the time it took to send the
1731		 * full TCP sequence space of 4Gb).  We can use these
1732		 * rules and infer a few others that will let us treat
1733		 * the 32bit timestamp and the 32bit echoed timestamp
1734		 * as sequence numbers to prevent a blind attacker from
1735		 * inserting packets into a connection.
1736		 *
1737		 * RFC1323 tells us:
1738		 *  - The timestamp on this packet must be greater than
1739		 *    or equal to the last value echoed by the other
1740		 *    endpoint.  The RFC says those will be discarded
1741		 *    since it is a dup that has already been acked.
1742		 *    This gives us a lowerbound on the timestamp.
1743		 *        timestamp >= other last echoed timestamp
1744		 *  - The timestamp will be less than or equal to
1745		 *    the last timestamp plus the time between the
1746		 *    last packet and now.  The RFC defines the max
1747		 *    clock rate as 1ms.  We will allow clocks to be
1748		 *    up to 10% fast and will allow a total difference
1749		 *    or 30 seconds due to a route change.  And this
1750		 *    gives us an upperbound on the timestamp.
1751		 *        timestamp <= last timestamp + max ticks
1752		 *    We have to be careful here.  Windows will send an
1753		 *    initial timestamp of zero and then initialize it
1754		 *    to a random value after the 3whs; presumably to
1755		 *    avoid a DoS by having to call an expensive RNG
1756		 *    during a SYN flood.  Proof MS has at least one
1757		 *    good security geek.
1758		 *
1759		 *  - The TCP timestamp option must also echo the other
1760		 *    endpoints timestamp.  The timestamp echoed is the
1761		 *    one carried on the earliest unacknowledged segment
1762		 *    on the left edge of the sequence window.  The RFC
1763		 *    states that the host will reject any echoed
1764		 *    timestamps that were larger than any ever sent.
1765		 *    This gives us an upperbound on the TS echo.
1766		 *        tescr <= largest_tsval
1767		 *  - The lowerbound on the TS echo is a little more
1768		 *    tricky to determine.  The other endpoint's echoed
1769		 *    values will not decrease.  But there may be
1770		 *    network conditions that re-order packets and
1771		 *    cause our view of them to decrease.  For now the
1772		 *    only lowerbound we can safely determine is that
1773		 *    the TS echo will never be less than the original
1774		 *    TS.  XXX There is probably a better lowerbound.
1775		 *    Remove TS_MAX_CONN with better lowerbound check.
1776		 *        tescr >= other original TS
1777		 *
1778		 * It is also important to note that the fastest
1779		 * timestamp clock of 1ms will wrap its 32bit space in
1780		 * 24 days.  So we just disable TS checking after 24
1781		 * days of idle time.  We actually must use a 12d
1782		 * connection limit until we can come up with a better
1783		 * lowerbound to the TS echo check.
1784		 */
1785		struct timeval delta_ts;
1786		int ts_fudge;
1787
1788
1789		/*
1790		 * PFTM_TS_DIFF is how many seconds of leeway to allow
1791		 * a host's timestamp.  This can happen if the previous
1792		 * packet got delayed in transit for much longer than
1793		 * this packet.
1794		 */
1795		if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1796			ts_fudge = V_pf_default_rule.timeout[PFTM_TS_DIFF];
1797
1798		/* Calculate max ticks since the last timestamp */
1799#define TS_MAXFREQ	1100		/* RFC max TS freq of 1Khz + 10% skew */
1800#define TS_MICROSECS	1000000		/* microseconds per second */
1801		delta_ts = uptime;
1802		timevalsub(&delta_ts, &src->scrub->pfss_last);
1803		tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1804		tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1805
1806		if ((src->state >= TCPS_ESTABLISHED &&
1807		    dst->state >= TCPS_ESTABLISHED) &&
1808		    (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1809		    SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1810		    (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1811		    SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1812			/* Bad RFC1323 implementation or an insertion attack.
1813			 *
1814			 * - Solaris 2.6 and 2.7 are known to send another ACK
1815			 *   after the FIN,FIN|ACK,ACK closing that carries
1816			 *   an old timestamp.
1817			 */
1818
1819			DPFPRINTF(("Timestamp failed %c%c%c%c\n",
1820			    SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1821			    SEQ_GT(tsval, src->scrub->pfss_tsval +
1822			    tsval_from_last) ? '1' : ' ',
1823			    SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1824			    SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '));
1825			DPFPRINTF((" tsval: %u  tsecr: %u  +ticks: %u  "
1826			    "idle: %jus %lums\n",
1827			    tsval, tsecr, tsval_from_last,
1828			    (uintmax_t)delta_ts.tv_sec,
1829			    delta_ts.tv_usec / 1000));
1830			DPFPRINTF((" src->tsval: %u  tsecr: %u\n",
1831			    src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1832			DPFPRINTF((" dst->tsval: %u  tsecr: %u  tsval0: %u"
1833			    "\n", dst->scrub->pfss_tsval,
1834			    dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1835			if (V_pf_status.debug >= PF_DEBUG_MISC) {
1836				pf_print_state(state);
1837				pf_print_flags(th->th_flags);
1838				printf("\n");
1839			}
1840			REASON_SET(reason, PFRES_TS);
1841			return (PF_DROP);
1842		}
1843
1844		/* XXX I'd really like to require tsecr but it's optional */
1845
1846	} else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1847	    ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1848	    || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1849	    src->scrub && dst->scrub &&
1850	    (src->scrub->pfss_flags & PFSS_PAWS) &&
1851	    (dst->scrub->pfss_flags & PFSS_PAWS)) {
1852		/* Didn't send a timestamp.  Timestamps aren't really useful
1853		 * when:
1854		 *  - connection opening or closing (often not even sent).
1855		 *    but we must not let an attacker to put a FIN on a
1856		 *    data packet to sneak it through our ESTABLISHED check.
1857		 *  - on a TCP reset.  RFC suggests not even looking at TS.
1858		 *  - on an empty ACK.  The TS will not be echoed so it will
1859		 *    probably not help keep the RTT calculation in sync and
1860		 *    there isn't as much danger when the sequence numbers
1861		 *    got wrapped.  So some stacks don't include TS on empty
1862		 *    ACKs :-(
1863		 *
1864		 * To minimize the disruption to mostly RFC1323 conformant
1865		 * stacks, we will only require timestamps on data packets.
1866		 *
1867		 * And what do ya know, we cannot require timestamps on data
1868		 * packets.  There appear to be devices that do legitimate
1869		 * TCP connection hijacking.  There are HTTP devices that allow
1870		 * a 3whs (with timestamps) and then buffer the HTTP request.
1871		 * If the intermediate device has the HTTP response cache, it
1872		 * will spoof the response but not bother timestamping its
1873		 * packets.  So we can look for the presence of a timestamp in
1874		 * the first data packet and if there, require it in all future
1875		 * packets.
1876		 */
1877
1878		if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1879			/*
1880			 * Hey!  Someone tried to sneak a packet in.  Or the
1881			 * stack changed its RFC1323 behavior?!?!
1882			 */
1883			if (V_pf_status.debug >= PF_DEBUG_MISC) {
1884				DPFPRINTF(("Did not receive expected RFC1323 "
1885				    "timestamp\n"));
1886				pf_print_state(state);
1887				pf_print_flags(th->th_flags);
1888				printf("\n");
1889			}
1890			REASON_SET(reason, PFRES_TS);
1891			return (PF_DROP);
1892		}
1893	}
1894
1895
1896	/*
1897	 * We will note if a host sends his data packets with or without
1898	 * timestamps.  And require all data packets to contain a timestamp
1899	 * if the first does.  PAWS implicitly requires that all data packets be
1900	 * timestamped.  But I think there are middle-man devices that hijack
1901	 * TCP streams immediately after the 3whs and don't timestamp their
1902	 * packets (seen in a WWW accelerator or cache).
1903	 */
1904	if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1905	    (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1906		if (got_ts)
1907			src->scrub->pfss_flags |= PFSS_DATA_TS;
1908		else {
1909			src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1910			if (V_pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1911			    (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1912				/* Don't warn if other host rejected RFC1323 */
1913				DPFPRINTF(("Broken RFC1323 stack did not "
1914				    "timestamp data packet. Disabled PAWS "
1915				    "security.\n"));
1916				pf_print_state(state);
1917				pf_print_flags(th->th_flags);
1918				printf("\n");
1919			}
1920		}
1921	}
1922
1923
1924	/*
1925	 * Update PAWS values
1926	 */
1927	if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1928	    (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1929		getmicrouptime(&src->scrub->pfss_last);
1930		if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1931		    (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1932			src->scrub->pfss_tsval = tsval;
1933
1934		if (tsecr) {
1935			if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1936			    (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1937				src->scrub->pfss_tsecr = tsecr;
1938
1939			if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1940			    (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1941			    src->scrub->pfss_tsval0 == 0)) {
1942				/* tsval0 MUST be the lowest timestamp */
1943				src->scrub->pfss_tsval0 = tsval;
1944			}
1945
1946			/* Only fully initialized after a TS gets echoed */
1947			if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1948				src->scrub->pfss_flags |= PFSS_PAWS;
1949		}
1950	}
1951
1952	/* I have a dream....  TCP segment reassembly.... */
1953	return (0);
1954}
1955
1956static int
1957pf_normalize_tcpopt(struct pf_krule *r, struct mbuf *m, struct tcphdr *th,
1958    int off, sa_family_t af)
1959{
1960	u_int16_t	*mss;
1961	int		 thoff;
1962	int		 opt, cnt, optlen = 0;
1963	int		 rewrite = 0;
1964	u_char		 opts[TCP_MAXOLEN];
1965	u_char		*optp = opts;
1966	size_t		 startoff;
1967
1968	thoff = th->th_off << 2;
1969	cnt = thoff - sizeof(struct tcphdr);
1970
1971	if (cnt > 0 && !pf_pull_hdr(m, off + sizeof(*th), opts, cnt,
1972	    NULL, NULL, af))
1973		return (rewrite);
1974
1975	for (; cnt > 0; cnt -= optlen, optp += optlen) {
1976		startoff = optp - opts;
1977		opt = optp[0];
1978		if (opt == TCPOPT_EOL)
1979			break;
1980		if (opt == TCPOPT_NOP)
1981			optlen = 1;
1982		else {
1983			if (cnt < 2)
1984				break;
1985			optlen = optp[1];
1986			if (optlen < 2 || optlen > cnt)
1987				break;
1988		}
1989		switch (opt) {
1990		case TCPOPT_MAXSEG:
1991			mss = (u_int16_t *)(optp + 2);
1992			if ((ntohs(*mss)) > r->max_mss) {
1993				pf_patch_16_unaligned(m,
1994				    &th->th_sum,
1995				    mss, htons(r->max_mss),
1996				    PF_ALGNMNT(startoff),
1997				    0);
1998				rewrite = 1;
1999			}
2000			break;
2001		default:
2002			break;
2003		}
2004	}
2005
2006	if (rewrite)
2007		m_copyback(m, off + sizeof(*th), thoff - sizeof(*th), opts);
2008
2009	return (rewrite);
2010}
2011
2012#ifdef INET
2013static void
2014pf_scrub_ip(struct mbuf **m0, u_int32_t flags, u_int8_t min_ttl, u_int8_t tos)
2015{
2016	struct mbuf		*m = *m0;
2017	struct ip		*h = mtod(m, struct ip *);
2018
2019	/* Clear IP_DF if no-df was requested */
2020	if (flags & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
2021		u_int16_t ip_off = h->ip_off;
2022
2023		h->ip_off &= htons(~IP_DF);
2024		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
2025	}
2026
2027	/* Enforce a minimum ttl, may cause endless packet loops */
2028	if (min_ttl && h->ip_ttl < min_ttl) {
2029		u_int16_t ip_ttl = h->ip_ttl;
2030
2031		h->ip_ttl = min_ttl;
2032		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
2033	}
2034
2035	/* Enforce tos */
2036	if (flags & PFRULE_SET_TOS) {
2037		u_int16_t	ov, nv;
2038
2039		ov = *(u_int16_t *)h;
2040		h->ip_tos = tos | (h->ip_tos & IPTOS_ECN_MASK);
2041		nv = *(u_int16_t *)h;
2042
2043		h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
2044	}
2045
2046	/* random-id, but not for fragments */
2047	if (flags & PFRULE_RANDOMID && !(h->ip_off & ~htons(IP_DF))) {
2048		uint16_t ip_id = h->ip_id;
2049
2050		ip_fillid(h);
2051		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
2052	}
2053}
2054#endif /* INET */
2055
2056#ifdef INET6
2057static void
2058pf_scrub_ip6(struct mbuf **m0, u_int8_t min_ttl)
2059{
2060	struct mbuf		*m = *m0;
2061	struct ip6_hdr		*h = mtod(m, struct ip6_hdr *);
2062
2063	/* Enforce a minimum ttl, may cause endless packet loops */
2064	if (min_ttl && h->ip6_hlim < min_ttl)
2065		h->ip6_hlim = min_ttl;
2066}
2067#endif
2068