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