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