pf.c revision 251681
1/*-
2 * Copyright (c) 2001 Daniel Hartmeier
3 * Copyright (c) 2002 - 2008 Henning Brauer
4 * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 *    - Redistributions of source code must retain the above copyright
12 *      notice, this list of conditions and the following disclaimer.
13 *    - Redistributions in binary form must reproduce the above
14 *      copyright notice, this list of conditions and the following
15 *      disclaimer in the documentation and/or other materials provided
16 *      with the distribution.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 *
31 * Effort sponsored in part by the Defense Advanced Research Projects
32 * Agency (DARPA) and Air Force Research Laboratory, Air Force
33 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
34 *
35 *	$OpenBSD: pf.c,v 1.634 2009/02/27 12:37:45 henning Exp $
36 */
37
38#include <sys/cdefs.h>
39__FBSDID("$FreeBSD: head/sys/netpfil/pf/pf.c 251681 2013-06-13 06:07:19Z glebius $");
40
41#include "opt_inet.h"
42#include "opt_inet6.h"
43#include "opt_bpf.h"
44#include "opt_pf.h"
45
46#include <sys/param.h>
47#include <sys/bus.h>
48#include <sys/endian.h>
49#include <sys/hash.h>
50#include <sys/interrupt.h>
51#include <sys/kernel.h>
52#include <sys/kthread.h>
53#include <sys/limits.h>
54#include <sys/mbuf.h>
55#include <sys/md5.h>
56#include <sys/random.h>
57#include <sys/refcount.h>
58#include <sys/socket.h>
59#include <sys/sysctl.h>
60#include <sys/taskqueue.h>
61#include <sys/ucred.h>
62
63#include <net/if.h>
64#include <net/if_types.h>
65#include <net/route.h>
66#include <net/radix_mpath.h>
67#include <net/vnet.h>
68
69#include <net/pfvar.h>
70#include <net/pf_mtag.h>
71#include <net/if_pflog.h>
72#include <net/if_pfsync.h>
73
74#include <netinet/in_pcb.h>
75#include <netinet/in_var.h>
76#include <netinet/ip.h>
77#include <netinet/ip_fw.h>
78#include <netinet/ip_icmp.h>
79#include <netinet/icmp_var.h>
80#include <netinet/ip_var.h>
81#include <netinet/tcp.h>
82#include <netinet/tcp_fsm.h>
83#include <netinet/tcp_seq.h>
84#include <netinet/tcp_timer.h>
85#include <netinet/tcp_var.h>
86#include <netinet/udp.h>
87#include <netinet/udp_var.h>
88
89#include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
90
91#ifdef INET6
92#include <netinet/ip6.h>
93#include <netinet/icmp6.h>
94#include <netinet6/nd6.h>
95#include <netinet6/ip6_var.h>
96#include <netinet6/in6_pcb.h>
97#endif /* INET6 */
98
99#include <machine/in_cksum.h>
100#include <security/mac/mac_framework.h>
101
102#define	DPFPRINTF(n, x)	if (V_pf_status.debug >= (n)) printf x
103
104/*
105 * Global variables
106 */
107
108/* state tables */
109VNET_DEFINE(struct pf_altqqueue,	 pf_altqs[2]);
110VNET_DEFINE(struct pf_palist,		 pf_pabuf);
111VNET_DEFINE(struct pf_altqqueue *,	 pf_altqs_active);
112VNET_DEFINE(struct pf_altqqueue *,	 pf_altqs_inactive);
113VNET_DEFINE(struct pf_status,		 pf_status);
114
115VNET_DEFINE(u_int32_t,			 ticket_altqs_active);
116VNET_DEFINE(u_int32_t,			 ticket_altqs_inactive);
117VNET_DEFINE(int,			 altqs_inactive_open);
118VNET_DEFINE(u_int32_t,			 ticket_pabuf);
119
120VNET_DEFINE(MD5_CTX,			 pf_tcp_secret_ctx);
121#define	V_pf_tcp_secret_ctx		 VNET(pf_tcp_secret_ctx)
122VNET_DEFINE(u_char,			 pf_tcp_secret[16]);
123#define	V_pf_tcp_secret			 VNET(pf_tcp_secret)
124VNET_DEFINE(int,			 pf_tcp_secret_init);
125#define	V_pf_tcp_secret_init		 VNET(pf_tcp_secret_init)
126VNET_DEFINE(int,			 pf_tcp_iss_off);
127#define	V_pf_tcp_iss_off		 VNET(pf_tcp_iss_off)
128
129/*
130 * Queue for pf_intr() sends.
131 */
132static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
133struct pf_send_entry {
134	STAILQ_ENTRY(pf_send_entry)	pfse_next;
135	struct mbuf			*pfse_m;
136	enum {
137		PFSE_IP,
138		PFSE_IP6,
139		PFSE_ICMP,
140		PFSE_ICMP6,
141	}				pfse_type;
142	union {
143		struct route		ro;
144		struct {
145			int		type;
146			int		code;
147			int		mtu;
148		} icmpopts;
149	} u;
150#define	pfse_ro		u.ro
151#define	pfse_icmp_type	u.icmpopts.type
152#define	pfse_icmp_code	u.icmpopts.code
153#define	pfse_icmp_mtu	u.icmpopts.mtu
154};
155
156STAILQ_HEAD(pf_send_head, pf_send_entry);
157static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
158#define	V_pf_sendqueue	VNET(pf_sendqueue)
159
160static struct mtx pf_sendqueue_mtx;
161#define	PF_SENDQ_LOCK()		mtx_lock(&pf_sendqueue_mtx)
162#define	PF_SENDQ_UNLOCK()	mtx_unlock(&pf_sendqueue_mtx)
163
164/*
165 * Queue for pf_overload_task() tasks.
166 */
167struct pf_overload_entry {
168	SLIST_ENTRY(pf_overload_entry)	next;
169	struct pf_addr  		addr;
170	sa_family_t			af;
171	uint8_t				dir;
172	struct pf_rule  		*rule;
173};
174
175SLIST_HEAD(pf_overload_head, pf_overload_entry);
176static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
177#define V_pf_overloadqueue	VNET(pf_overloadqueue)
178static VNET_DEFINE(struct task, pf_overloadtask);
179#define	V_pf_overloadtask	VNET(pf_overloadtask)
180
181static struct mtx pf_overloadqueue_mtx;
182#define	PF_OVERLOADQ_LOCK()	mtx_lock(&pf_overloadqueue_mtx)
183#define	PF_OVERLOADQ_UNLOCK()	mtx_unlock(&pf_overloadqueue_mtx)
184
185VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
186struct mtx pf_unlnkdrules_mtx;
187
188static VNET_DEFINE(uma_zone_t,	pf_sources_z);
189#define	V_pf_sources_z	VNET(pf_sources_z)
190static VNET_DEFINE(uma_zone_t,	pf_mtag_z);
191#define	V_pf_mtag_z	VNET(pf_mtag_z)
192VNET_DEFINE(uma_zone_t,	 pf_state_z);
193VNET_DEFINE(uma_zone_t,	 pf_state_key_z);
194
195VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
196#define	PFID_CPUBITS	8
197#define	PFID_CPUSHIFT	(sizeof(uint64_t) * NBBY - PFID_CPUBITS)
198#define	PFID_CPUMASK	((uint64_t)((1 << PFID_CPUBITS) - 1) <<	PFID_CPUSHIFT)
199#define	PFID_MAXID	(~PFID_CPUMASK)
200CTASSERT((1 << PFID_CPUBITS) > MAXCPU);
201
202static void		 pf_src_tree_remove_state(struct pf_state *);
203static void		 pf_init_threshold(struct pf_threshold *, u_int32_t,
204			    u_int32_t);
205static void		 pf_add_threshold(struct pf_threshold *);
206static int		 pf_check_threshold(struct pf_threshold *);
207
208static void		 pf_change_ap(struct pf_addr *, u_int16_t *,
209			    u_int16_t *, u_int16_t *, struct pf_addr *,
210			    u_int16_t, u_int8_t, sa_family_t);
211static int		 pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
212			    struct tcphdr *, struct pf_state_peer *);
213static void		 pf_change_icmp(struct pf_addr *, u_int16_t *,
214			    struct pf_addr *, struct pf_addr *, u_int16_t,
215			    u_int16_t *, u_int16_t *, u_int16_t *,
216			    u_int16_t *, u_int8_t, sa_family_t);
217static void		 pf_send_tcp(struct mbuf *,
218			    const struct pf_rule *, sa_family_t,
219			    const struct pf_addr *, const struct pf_addr *,
220			    u_int16_t, u_int16_t, u_int32_t, u_int32_t,
221			    u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
222			    u_int16_t, struct ifnet *);
223static void		 pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
224			    sa_family_t, struct pf_rule *);
225static void		 pf_detach_state(struct pf_state *);
226static int		 pf_state_key_attach(struct pf_state_key *,
227			    struct pf_state_key *, struct pf_state *);
228static void		 pf_state_key_detach(struct pf_state *, int);
229static int		 pf_state_key_ctor(void *, int, void *, int);
230static u_int32_t	 pf_tcp_iss(struct pf_pdesc *);
231static int		 pf_test_rule(struct pf_rule **, struct pf_state **,
232			    int, struct pfi_kif *, struct mbuf *, int,
233			    struct pf_pdesc *, struct pf_rule **,
234			    struct pf_ruleset **, struct inpcb *);
235static int		 pf_create_state(struct pf_rule *, struct pf_rule *,
236			    struct pf_rule *, struct pf_pdesc *,
237			    struct pf_src_node *, struct pf_state_key *,
238			    struct pf_state_key *, struct mbuf *, int,
239			    u_int16_t, u_int16_t, int *, struct pfi_kif *,
240			    struct pf_state **, int, u_int16_t, u_int16_t,
241			    int);
242static int		 pf_test_fragment(struct pf_rule **, int,
243			    struct pfi_kif *, struct mbuf *, void *,
244			    struct pf_pdesc *, struct pf_rule **,
245			    struct pf_ruleset **);
246static int		 pf_tcp_track_full(struct pf_state_peer *,
247			    struct pf_state_peer *, struct pf_state **,
248			    struct pfi_kif *, struct mbuf *, int,
249			    struct pf_pdesc *, u_short *, int *);
250static int		 pf_tcp_track_sloppy(struct pf_state_peer *,
251			    struct pf_state_peer *, struct pf_state **,
252			    struct pf_pdesc *, u_short *);
253static int		 pf_test_state_tcp(struct pf_state **, int,
254			    struct pfi_kif *, struct mbuf *, int,
255			    void *, struct pf_pdesc *, u_short *);
256static int		 pf_test_state_udp(struct pf_state **, int,
257			    struct pfi_kif *, struct mbuf *, int,
258			    void *, struct pf_pdesc *);
259static int		 pf_test_state_icmp(struct pf_state **, int,
260			    struct pfi_kif *, struct mbuf *, int,
261			    void *, struct pf_pdesc *, u_short *);
262static int		 pf_test_state_other(struct pf_state **, int,
263			    struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
264static u_int8_t		 pf_get_wscale(struct mbuf *, int, u_int16_t,
265			    sa_family_t);
266static u_int16_t	 pf_get_mss(struct mbuf *, int, u_int16_t,
267			    sa_family_t);
268static u_int16_t	 pf_calc_mss(struct pf_addr *, sa_family_t,
269				int, u_int16_t);
270static void		 pf_set_rt_ifp(struct pf_state *,
271			    struct pf_addr *);
272static int		 pf_check_proto_cksum(struct mbuf *, int, int,
273			    u_int8_t, sa_family_t);
274static void		 pf_print_state_parts(struct pf_state *,
275			    struct pf_state_key *, struct pf_state_key *);
276static int		 pf_addr_wrap_neq(struct pf_addr_wrap *,
277			    struct pf_addr_wrap *);
278static struct pf_state	*pf_find_state(struct pfi_kif *,
279			    struct pf_state_key_cmp *, u_int);
280static int		 pf_src_connlimit(struct pf_state **);
281static void		 pf_overload_task(void *c, int pending);
282static int		 pf_insert_src_node(struct pf_src_node **,
283			    struct pf_rule *, struct pf_addr *, sa_family_t);
284static u_int		 pf_purge_expired_states(u_int, int);
285static void		 pf_purge_unlinked_rules(void);
286static int		 pf_mtag_init(void *, int, int);
287static void		 pf_mtag_free(struct m_tag *);
288#ifdef INET
289static void		 pf_route(struct mbuf **, struct pf_rule *, int,
290			    struct ifnet *, struct pf_state *,
291			    struct pf_pdesc *);
292#endif /* INET */
293#ifdef INET6
294static void		 pf_change_a6(struct pf_addr *, u_int16_t *,
295			    struct pf_addr *, u_int8_t);
296static void		 pf_route6(struct mbuf **, struct pf_rule *, int,
297			    struct ifnet *, struct pf_state *,
298			    struct pf_pdesc *);
299#endif /* INET6 */
300
301int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
302
303VNET_DECLARE(int, pf_end_threads);
304
305VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
306
307#define	PACKET_LOOPED(pd)	((pd)->pf_mtag &&			\
308				 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
309
310#define	STATE_LOOKUP(i, k, d, s, pd)					\
311	do {								\
312		(s) = pf_find_state((i), (k), (d));			\
313		if ((s) == NULL || (s)->timeout == PFTM_PURGE)		\
314			return (PF_DROP);				\
315		if (PACKET_LOOPED(pd))					\
316			return (PF_PASS);				\
317		if ((d) == PF_OUT &&					\
318		    (((s)->rule.ptr->rt == PF_ROUTETO &&		\
319		    (s)->rule.ptr->direction == PF_OUT) ||		\
320		    ((s)->rule.ptr->rt == PF_REPLYTO &&			\
321		    (s)->rule.ptr->direction == PF_IN)) &&		\
322		    (s)->rt_kif != NULL &&				\
323		    (s)->rt_kif != (i))					\
324			return (PF_PASS);				\
325	} while (0)
326
327#define	BOUND_IFACE(r, k) \
328	((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
329
330#define	STATE_INC_COUNTERS(s)				\
331	do {						\
332		s->rule.ptr->states_cur++;		\
333		s->rule.ptr->states_tot++;		\
334		if (s->anchor.ptr != NULL) {		\
335			s->anchor.ptr->states_cur++;	\
336			s->anchor.ptr->states_tot++;	\
337		}					\
338		if (s->nat_rule.ptr != NULL) {		\
339			s->nat_rule.ptr->states_cur++;	\
340			s->nat_rule.ptr->states_tot++;	\
341		}					\
342	} while (0)
343
344#define	STATE_DEC_COUNTERS(s)				\
345	do {						\
346		if (s->nat_rule.ptr != NULL)		\
347			s->nat_rule.ptr->states_cur--;	\
348		if (s->anchor.ptr != NULL)		\
349			s->anchor.ptr->states_cur--;	\
350		s->rule.ptr->states_cur--;		\
351	} while (0)
352
353static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
354VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
355VNET_DEFINE(struct pf_idhash *, pf_idhash);
356VNET_DEFINE(u_long, pf_hashmask);
357VNET_DEFINE(struct pf_srchash *, pf_srchash);
358VNET_DEFINE(u_long, pf_srchashmask);
359
360SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
361
362VNET_DEFINE(u_long, pf_hashsize);
363#define	V_pf_hashsize	VNET(pf_hashsize)
364SYSCTL_VNET_UINT(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
365    &VNET_NAME(pf_hashsize), 0, "Size of pf(4) states hashtable");
366
367VNET_DEFINE(u_long, pf_srchashsize);
368#define	V_pf_srchashsize	VNET(pf_srchashsize)
369SYSCTL_VNET_UINT(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
370    &VNET_NAME(pf_srchashsize), 0, "Size of pf(4) source nodes hashtable");
371
372VNET_DEFINE(void *, pf_swi_cookie);
373
374VNET_DEFINE(uint32_t, pf_hashseed);
375#define	V_pf_hashseed	VNET(pf_hashseed)
376
377static __inline uint32_t
378pf_hashkey(struct pf_state_key *sk)
379{
380	uint32_t h;
381
382	h = jenkins_hash32((uint32_t *)sk,
383	    sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
384	    V_pf_hashseed);
385
386	return (h & V_pf_hashmask);
387}
388
389static __inline uint32_t
390pf_hashsrc(struct pf_addr *addr, sa_family_t af)
391{
392	uint32_t h;
393
394	switch (af) {
395	case AF_INET:
396		h = jenkins_hash32((uint32_t *)&addr->v4,
397		    sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
398		break;
399	case AF_INET6:
400		h = jenkins_hash32((uint32_t *)&addr->v6,
401		    sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
402		break;
403	default:
404		panic("%s: unknown address family %u", __func__, af);
405	}
406
407	return (h & V_pf_srchashmask);
408}
409
410#ifdef INET6
411void
412pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
413{
414	switch (af) {
415#ifdef INET
416	case AF_INET:
417		dst->addr32[0] = src->addr32[0];
418		break;
419#endif /* INET */
420	case AF_INET6:
421		dst->addr32[0] = src->addr32[0];
422		dst->addr32[1] = src->addr32[1];
423		dst->addr32[2] = src->addr32[2];
424		dst->addr32[3] = src->addr32[3];
425		break;
426	}
427}
428#endif /* INET6 */
429
430static void
431pf_init_threshold(struct pf_threshold *threshold,
432    u_int32_t limit, u_int32_t seconds)
433{
434	threshold->limit = limit * PF_THRESHOLD_MULT;
435	threshold->seconds = seconds;
436	threshold->count = 0;
437	threshold->last = time_uptime;
438}
439
440static void
441pf_add_threshold(struct pf_threshold *threshold)
442{
443	u_int32_t t = time_uptime, diff = t - threshold->last;
444
445	if (diff >= threshold->seconds)
446		threshold->count = 0;
447	else
448		threshold->count -= threshold->count * diff /
449		    threshold->seconds;
450	threshold->count += PF_THRESHOLD_MULT;
451	threshold->last = t;
452}
453
454static int
455pf_check_threshold(struct pf_threshold *threshold)
456{
457	return (threshold->count > threshold->limit);
458}
459
460static int
461pf_src_connlimit(struct pf_state **state)
462{
463	struct pf_overload_entry *pfoe;
464	int bad = 0;
465
466	PF_STATE_LOCK_ASSERT(*state);
467
468	(*state)->src_node->conn++;
469	(*state)->src.tcp_est = 1;
470	pf_add_threshold(&(*state)->src_node->conn_rate);
471
472	if ((*state)->rule.ptr->max_src_conn &&
473	    (*state)->rule.ptr->max_src_conn <
474	    (*state)->src_node->conn) {
475		V_pf_status.lcounters[LCNT_SRCCONN]++;
476		bad++;
477	}
478
479	if ((*state)->rule.ptr->max_src_conn_rate.limit &&
480	    pf_check_threshold(&(*state)->src_node->conn_rate)) {
481		V_pf_status.lcounters[LCNT_SRCCONNRATE]++;
482		bad++;
483	}
484
485	if (!bad)
486		return (0);
487
488	/* Kill this state. */
489	(*state)->timeout = PFTM_PURGE;
490	(*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
491
492	if ((*state)->rule.ptr->overload_tbl == NULL)
493		return (1);
494
495	/* Schedule overloading and flushing task. */
496	pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
497	if (pfoe == NULL)
498		return (1);	/* too bad :( */
499
500	bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
501	pfoe->af = (*state)->key[PF_SK_WIRE]->af;
502	pfoe->rule = (*state)->rule.ptr;
503	pfoe->dir = (*state)->direction;
504	PF_OVERLOADQ_LOCK();
505	SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
506	PF_OVERLOADQ_UNLOCK();
507	taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
508
509	return (1);
510}
511
512static void
513pf_overload_task(void *c, int pending)
514{
515	struct pf_overload_head queue;
516	struct pfr_addr p;
517	struct pf_overload_entry *pfoe, *pfoe1;
518	uint32_t killed = 0;
519
520	PF_OVERLOADQ_LOCK();
521	queue = *(struct pf_overload_head *)c;
522	SLIST_INIT((struct pf_overload_head *)c);
523	PF_OVERLOADQ_UNLOCK();
524
525	bzero(&p, sizeof(p));
526	SLIST_FOREACH(pfoe, &queue, next) {
527		V_pf_status.lcounters[LCNT_OVERLOAD_TABLE]++;
528		if (V_pf_status.debug >= PF_DEBUG_MISC) {
529			printf("%s: blocking address ", __func__);
530			pf_print_host(&pfoe->addr, 0, pfoe->af);
531			printf("\n");
532		}
533
534		p.pfra_af = pfoe->af;
535		switch (pfoe->af) {
536#ifdef INET
537		case AF_INET:
538			p.pfra_net = 32;
539			p.pfra_ip4addr = pfoe->addr.v4;
540			break;
541#endif
542#ifdef INET6
543		case AF_INET6:
544			p.pfra_net = 128;
545			p.pfra_ip6addr = pfoe->addr.v6;
546			break;
547#endif
548		}
549
550		PF_RULES_WLOCK();
551		pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
552		PF_RULES_WUNLOCK();
553	}
554
555	/*
556	 * Remove those entries, that don't need flushing.
557	 */
558	SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
559		if (pfoe->rule->flush == 0) {
560			SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
561			free(pfoe, M_PFTEMP);
562		} else
563			V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH]++;
564
565	/* If nothing to flush, return. */
566	if (SLIST_EMPTY(&queue))
567		return;
568
569	for (int i = 0; i <= V_pf_hashmask; i++) {
570		struct pf_idhash *ih = &V_pf_idhash[i];
571		struct pf_state_key *sk;
572		struct pf_state *s;
573
574		PF_HASHROW_LOCK(ih);
575		LIST_FOREACH(s, &ih->states, entry) {
576		    sk = s->key[PF_SK_WIRE];
577		    SLIST_FOREACH(pfoe, &queue, next)
578			if (sk->af == pfoe->af &&
579			    ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
580			    pfoe->rule == s->rule.ptr) &&
581			    ((pfoe->dir == PF_OUT &&
582			    PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
583			    (pfoe->dir == PF_IN &&
584			    PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
585				s->timeout = PFTM_PURGE;
586				s->src.state = s->dst.state = TCPS_CLOSED;
587				killed++;
588			}
589		}
590		PF_HASHROW_UNLOCK(ih);
591	}
592	SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
593		free(pfoe, M_PFTEMP);
594	if (V_pf_status.debug >= PF_DEBUG_MISC)
595		printf("%s: %u states killed", __func__, killed);
596}
597
598/*
599 * Can return locked on failure, so that we can consistently
600 * allocate and insert a new one.
601 */
602struct pf_src_node *
603pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
604	int returnlocked)
605{
606	struct pf_srchash *sh;
607	struct pf_src_node *n;
608
609	V_pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
610
611	sh = &V_pf_srchash[pf_hashsrc(src, af)];
612	PF_HASHROW_LOCK(sh);
613	LIST_FOREACH(n, &sh->nodes, entry)
614		if (n->rule.ptr == rule && n->af == af &&
615		    ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
616		    (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
617			break;
618	if (n != NULL || returnlocked == 0)
619		PF_HASHROW_UNLOCK(sh);
620
621	return (n);
622}
623
624static int
625pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
626    struct pf_addr *src, sa_family_t af)
627{
628
629	KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
630	    rule->rpool.opts & PF_POOL_STICKYADDR),
631	    ("%s for non-tracking rule %p", __func__, rule));
632
633	if (*sn == NULL)
634		*sn = pf_find_src_node(src, rule, af, 1);
635
636	if (*sn == NULL) {
637		struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
638
639		PF_HASHROW_ASSERT(sh);
640
641		if (!rule->max_src_nodes ||
642		    rule->src_nodes < rule->max_src_nodes)
643			(*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
644		else
645			V_pf_status.lcounters[LCNT_SRCNODES]++;
646		if ((*sn) == NULL) {
647			PF_HASHROW_UNLOCK(sh);
648			return (-1);
649		}
650
651		pf_init_threshold(&(*sn)->conn_rate,
652		    rule->max_src_conn_rate.limit,
653		    rule->max_src_conn_rate.seconds);
654
655		(*sn)->af = af;
656		(*sn)->rule.ptr = rule;
657		PF_ACPY(&(*sn)->addr, src, af);
658		LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
659		(*sn)->creation = time_uptime;
660		(*sn)->ruletype = rule->action;
661		if ((*sn)->rule.ptr != NULL)
662			(*sn)->rule.ptr->src_nodes++;
663		PF_HASHROW_UNLOCK(sh);
664		V_pf_status.scounters[SCNT_SRC_NODE_INSERT]++;
665		V_pf_status.src_nodes++;
666	} else {
667		if (rule->max_src_states &&
668		    (*sn)->states >= rule->max_src_states) {
669			V_pf_status.lcounters[LCNT_SRCSTATES]++;
670			return (-1);
671		}
672	}
673	return (0);
674}
675
676static void
677pf_remove_src_node(struct pf_src_node *src)
678{
679	struct pf_srchash *sh;
680
681	sh = &V_pf_srchash[pf_hashsrc(&src->addr, src->af)];
682	PF_HASHROW_LOCK(sh);
683	LIST_REMOVE(src, entry);
684	PF_HASHROW_UNLOCK(sh);
685
686	V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
687	V_pf_status.src_nodes--;
688
689	uma_zfree(V_pf_sources_z, src);
690}
691
692/* Data storage structures initialization. */
693void
694pf_initialize()
695{
696	struct pf_keyhash	*kh;
697	struct pf_idhash	*ih;
698	struct pf_srchash	*sh;
699	u_int i;
700
701	TUNABLE_ULONG_FETCH("net.pf.states_hashsize", &V_pf_hashsize);
702	if (V_pf_hashsize == 0 || !powerof2(V_pf_hashsize))
703		V_pf_hashsize = PF_HASHSIZ;
704	TUNABLE_ULONG_FETCH("net.pf.source_nodes_hashsize", &V_pf_srchashsize);
705	if (V_pf_srchashsize == 0 || !powerof2(V_pf_srchashsize))
706		V_pf_srchashsize = PF_HASHSIZ / 4;
707
708	V_pf_hashseed = arc4random();
709
710	/* States and state keys storage. */
711	V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
712	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
713	V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
714	uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
715	uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
716
717	V_pf_state_key_z = uma_zcreate("pf state keys",
718	    sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
719	    UMA_ALIGN_PTR, 0);
720	V_pf_keyhash = malloc(V_pf_hashsize * sizeof(struct pf_keyhash),
721	    M_PFHASH, M_WAITOK | M_ZERO);
722	V_pf_idhash = malloc(V_pf_hashsize * sizeof(struct pf_idhash),
723	    M_PFHASH, M_WAITOK | M_ZERO);
724	V_pf_hashmask = V_pf_hashsize - 1;
725	for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= V_pf_hashmask;
726	    i++, kh++, ih++) {
727		mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
728		mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
729	}
730
731	/* Source nodes. */
732	V_pf_sources_z = uma_zcreate("pf source nodes",
733	    sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
734	    0);
735	V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
736	uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
737	uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
738	V_pf_srchash = malloc(V_pf_srchashsize * sizeof(struct pf_srchash),
739	  M_PFHASH, M_WAITOK|M_ZERO);
740	V_pf_srchashmask = V_pf_srchashsize - 1;
741	for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask; i++, sh++)
742		mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
743
744	/* ALTQ */
745	TAILQ_INIT(&V_pf_altqs[0]);
746	TAILQ_INIT(&V_pf_altqs[1]);
747	TAILQ_INIT(&V_pf_pabuf);
748	V_pf_altqs_active = &V_pf_altqs[0];
749	V_pf_altqs_inactive = &V_pf_altqs[1];
750
751	/* Mbuf tags */
752	V_pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
753	    sizeof(struct pf_mtag), NULL, NULL, pf_mtag_init, NULL,
754	    UMA_ALIGN_PTR, 0);
755
756	/* Send & overload+flush queues. */
757	STAILQ_INIT(&V_pf_sendqueue);
758	SLIST_INIT(&V_pf_overloadqueue);
759	TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, &V_pf_overloadqueue);
760	mtx_init(&pf_sendqueue_mtx, "pf send queue", NULL, MTX_DEF);
761	mtx_init(&pf_overloadqueue_mtx, "pf overload/flush queue", NULL,
762	    MTX_DEF);
763
764	/* Unlinked, but may be referenced rules. */
765	TAILQ_INIT(&V_pf_unlinked_rules);
766	mtx_init(&pf_unlnkdrules_mtx, "pf unlinked rules", NULL, MTX_DEF);
767}
768
769void
770pf_cleanup()
771{
772	struct pf_keyhash	*kh;
773	struct pf_idhash	*ih;
774	struct pf_srchash	*sh;
775	struct pf_send_entry	*pfse, *next;
776	u_int i;
777
778	for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= V_pf_hashmask;
779	    i++, kh++, ih++) {
780		KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
781		    __func__));
782		KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
783		    __func__));
784		mtx_destroy(&kh->lock);
785		mtx_destroy(&ih->lock);
786	}
787	free(V_pf_keyhash, M_PFHASH);
788	free(V_pf_idhash, M_PFHASH);
789
790	for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask; i++, sh++) {
791		KASSERT(LIST_EMPTY(&sh->nodes),
792		    ("%s: source node hash not empty", __func__));
793		mtx_destroy(&sh->lock);
794	}
795	free(V_pf_srchash, M_PFHASH);
796
797	STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
798		m_freem(pfse->pfse_m);
799		free(pfse, M_PFTEMP);
800	}
801
802	mtx_destroy(&pf_sendqueue_mtx);
803	mtx_destroy(&pf_overloadqueue_mtx);
804	mtx_destroy(&pf_unlnkdrules_mtx);
805
806	uma_zdestroy(V_pf_mtag_z);
807	uma_zdestroy(V_pf_sources_z);
808	uma_zdestroy(V_pf_state_z);
809	uma_zdestroy(V_pf_state_key_z);
810}
811
812static int
813pf_mtag_init(void *mem, int size, int how)
814{
815	struct m_tag *t;
816
817	t = (struct m_tag *)mem;
818	t->m_tag_cookie = MTAG_ABI_COMPAT;
819	t->m_tag_id = PACKET_TAG_PF;
820	t->m_tag_len = sizeof(struct pf_mtag);
821	t->m_tag_free = pf_mtag_free;
822
823	return (0);
824}
825
826static void
827pf_mtag_free(struct m_tag *t)
828{
829
830	uma_zfree(V_pf_mtag_z, t);
831}
832
833struct pf_mtag *
834pf_get_mtag(struct mbuf *m)
835{
836	struct m_tag *mtag;
837
838	if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
839		return ((struct pf_mtag *)(mtag + 1));
840
841	mtag = uma_zalloc(V_pf_mtag_z, M_NOWAIT);
842	if (mtag == NULL)
843		return (NULL);
844	bzero(mtag + 1, sizeof(struct pf_mtag));
845	m_tag_prepend(m, mtag);
846
847	return ((struct pf_mtag *)(mtag + 1));
848}
849
850static int
851pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
852    struct pf_state *s)
853{
854	struct pf_keyhash	*khs, *khw, *kh;
855	struct pf_state_key	*sk, *cur;
856	struct pf_state		*si, *olds = NULL;
857	int idx;
858
859	KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
860	KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
861	KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
862
863	/*
864	 * We need to lock hash slots of both keys. To avoid deadlock
865	 * we always lock the slot with lower address first. Unlock order
866	 * isn't important.
867	 *
868	 * We also need to lock ID hash slot before dropping key
869	 * locks. On success we return with ID hash slot locked.
870	 */
871
872	if (skw == sks) {
873		khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
874		PF_HASHROW_LOCK(khs);
875	} else {
876		khs = &V_pf_keyhash[pf_hashkey(sks)];
877		khw = &V_pf_keyhash[pf_hashkey(skw)];
878		if (khs == khw) {
879			PF_HASHROW_LOCK(khs);
880		} else if (khs < khw) {
881			PF_HASHROW_LOCK(khs);
882			PF_HASHROW_LOCK(khw);
883		} else {
884			PF_HASHROW_LOCK(khw);
885			PF_HASHROW_LOCK(khs);
886		}
887	}
888
889#define	KEYS_UNLOCK()	do {			\
890	if (khs != khw) {			\
891		PF_HASHROW_UNLOCK(khs);		\
892		PF_HASHROW_UNLOCK(khw);		\
893	} else					\
894		PF_HASHROW_UNLOCK(khs);		\
895} while (0)
896
897	/*
898	 * First run: start with wire key.
899	 */
900	sk = skw;
901	kh = khw;
902	idx = PF_SK_WIRE;
903
904keyattach:
905	LIST_FOREACH(cur, &kh->keys, entry)
906		if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
907			break;
908
909	if (cur != NULL) {
910		/* Key exists. Check for same kif, if none, add to key. */
911		TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
912			struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
913
914			PF_HASHROW_LOCK(ih);
915			if (si->kif == s->kif &&
916			    si->direction == s->direction) {
917				if (sk->proto == IPPROTO_TCP &&
918				    si->src.state >= TCPS_FIN_WAIT_2 &&
919				    si->dst.state >= TCPS_FIN_WAIT_2) {
920					/*
921					 * New state matches an old >FIN_WAIT_2
922					 * state. We can't drop key hash locks,
923					 * thus we can't unlink it properly.
924					 *
925					 * As a workaround we drop it into
926					 * TCPS_CLOSED state, schedule purge
927					 * ASAP and push it into the very end
928					 * of the slot TAILQ, so that it won't
929					 * conflict with our new state.
930					 */
931					si->src.state = si->dst.state =
932					    TCPS_CLOSED;
933					si->timeout = PFTM_PURGE;
934					olds = si;
935				} else {
936					if (V_pf_status.debug >= PF_DEBUG_MISC) {
937						printf("pf: %s key attach "
938						    "failed on %s: ",
939						    (idx == PF_SK_WIRE) ?
940						    "wire" : "stack",
941						    s->kif->pfik_name);
942						pf_print_state_parts(s,
943						    (idx == PF_SK_WIRE) ?
944						    sk : NULL,
945						    (idx == PF_SK_STACK) ?
946						    sk : NULL);
947						printf(", existing: ");
948						pf_print_state_parts(si,
949						    (idx == PF_SK_WIRE) ?
950						    sk : NULL,
951						    (idx == PF_SK_STACK) ?
952						    sk : NULL);
953						printf("\n");
954					}
955					PF_HASHROW_UNLOCK(ih);
956					KEYS_UNLOCK();
957					uma_zfree(V_pf_state_key_z, sk);
958					if (idx == PF_SK_STACK)
959						pf_detach_state(s);
960					return (EEXIST); /* collision! */
961				}
962			}
963			PF_HASHROW_UNLOCK(ih);
964		}
965		uma_zfree(V_pf_state_key_z, sk);
966		s->key[idx] = cur;
967	} else {
968		LIST_INSERT_HEAD(&kh->keys, sk, entry);
969		s->key[idx] = sk;
970	}
971
972stateattach:
973	/* List is sorted, if-bound states before floating. */
974	if (s->kif == V_pfi_all)
975		TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
976	else
977		TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
978
979	if (olds) {
980		TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
981		TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
982		    key_list[idx]);
983		olds = NULL;
984	}
985
986	/*
987	 * Attach done. See how should we (or should not?)
988	 * attach a second key.
989	 */
990	if (sks == skw) {
991		s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
992		idx = PF_SK_STACK;
993		sks = NULL;
994		goto stateattach;
995	} else if (sks != NULL) {
996		/*
997		 * Continue attaching with stack key.
998		 */
999		sk = sks;
1000		kh = khs;
1001		idx = PF_SK_STACK;
1002		sks = NULL;
1003		goto keyattach;
1004	}
1005
1006	PF_STATE_LOCK(s);
1007	KEYS_UNLOCK();
1008
1009	KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1010	    ("%s failure", __func__));
1011
1012	return (0);
1013#undef	KEYS_UNLOCK
1014}
1015
1016static void
1017pf_detach_state(struct pf_state *s)
1018{
1019	struct pf_state_key *sks = s->key[PF_SK_STACK];
1020	struct pf_keyhash *kh;
1021
1022	if (sks != NULL) {
1023		kh = &V_pf_keyhash[pf_hashkey(sks)];
1024		PF_HASHROW_LOCK(kh);
1025		if (s->key[PF_SK_STACK] != NULL)
1026			pf_state_key_detach(s, PF_SK_STACK);
1027		/*
1028		 * If both point to same key, then we are done.
1029		 */
1030		if (sks == s->key[PF_SK_WIRE]) {
1031			pf_state_key_detach(s, PF_SK_WIRE);
1032			PF_HASHROW_UNLOCK(kh);
1033			return;
1034		}
1035		PF_HASHROW_UNLOCK(kh);
1036	}
1037
1038	if (s->key[PF_SK_WIRE] != NULL) {
1039		kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1040		PF_HASHROW_LOCK(kh);
1041		if (s->key[PF_SK_WIRE] != NULL)
1042			pf_state_key_detach(s, PF_SK_WIRE);
1043		PF_HASHROW_UNLOCK(kh);
1044	}
1045}
1046
1047static void
1048pf_state_key_detach(struct pf_state *s, int idx)
1049{
1050	struct pf_state_key *sk = s->key[idx];
1051#ifdef INVARIANTS
1052	struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1053
1054	PF_HASHROW_ASSERT(kh);
1055#endif
1056	TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1057	s->key[idx] = NULL;
1058
1059	if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1060		LIST_REMOVE(sk, entry);
1061		uma_zfree(V_pf_state_key_z, sk);
1062	}
1063}
1064
1065static int
1066pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1067{
1068	struct pf_state_key *sk = mem;
1069
1070	bzero(sk, sizeof(struct pf_state_key_cmp));
1071	TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1072	TAILQ_INIT(&sk->states[PF_SK_STACK]);
1073
1074	return (0);
1075}
1076
1077struct pf_state_key *
1078pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1079	struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1080{
1081	struct pf_state_key *sk;
1082
1083	sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1084	if (sk == NULL)
1085		return (NULL);
1086
1087	PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1088	PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1089	sk->port[pd->sidx] = sport;
1090	sk->port[pd->didx] = dport;
1091	sk->proto = pd->proto;
1092	sk->af = pd->af;
1093
1094	return (sk);
1095}
1096
1097struct pf_state_key *
1098pf_state_key_clone(struct pf_state_key *orig)
1099{
1100	struct pf_state_key *sk;
1101
1102	sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1103	if (sk == NULL)
1104		return (NULL);
1105
1106	bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1107
1108	return (sk);
1109}
1110
1111int
1112pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1113    struct pf_state_key *sks, struct pf_state *s)
1114{
1115	struct pf_idhash *ih;
1116	struct pf_state *cur;
1117	int error;
1118
1119	KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1120	    ("%s: sks not pristine", __func__));
1121	KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1122	    ("%s: skw not pristine", __func__));
1123	KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1124
1125	s->kif = kif;
1126
1127	if (s->id == 0 && s->creatorid == 0) {
1128		/* XXX: should be atomic, but probability of collision low */
1129		if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1130			V_pf_stateid[curcpu] = 1;
1131		s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1132		s->id = htobe64(s->id);
1133		s->creatorid = V_pf_status.hostid;
1134	}
1135
1136	/* Returns with ID locked on success. */
1137	if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1138		return (error);
1139
1140	ih = &V_pf_idhash[PF_IDHASH(s)];
1141	PF_HASHROW_ASSERT(ih);
1142	LIST_FOREACH(cur, &ih->states, entry)
1143		if (cur->id == s->id && cur->creatorid == s->creatorid)
1144			break;
1145
1146	if (cur != NULL) {
1147		PF_HASHROW_UNLOCK(ih);
1148		if (V_pf_status.debug >= PF_DEBUG_MISC) {
1149			printf("pf: state ID collision: "
1150			    "id: %016llx creatorid: %08x\n",
1151			    (unsigned long long)be64toh(s->id),
1152			    ntohl(s->creatorid));
1153		}
1154		pf_detach_state(s);
1155		return (EEXIST);
1156	}
1157	LIST_INSERT_HEAD(&ih->states, s, entry);
1158	/* One for keys, one for ID hash. */
1159	refcount_init(&s->refs, 2);
1160
1161	V_pf_status.fcounters[FCNT_STATE_INSERT]++;
1162	if (pfsync_insert_state_ptr != NULL)
1163		pfsync_insert_state_ptr(s);
1164
1165	/* Returns locked. */
1166	return (0);
1167}
1168
1169/*
1170 * Find state by ID: returns with locked row on success.
1171 */
1172struct pf_state *
1173pf_find_state_byid(uint64_t id, uint32_t creatorid)
1174{
1175	struct pf_idhash *ih;
1176	struct pf_state *s;
1177
1178	V_pf_status.fcounters[FCNT_STATE_SEARCH]++;
1179
1180	ih = &V_pf_idhash[(be64toh(id) % (V_pf_hashmask + 1))];
1181
1182	PF_HASHROW_LOCK(ih);
1183	LIST_FOREACH(s, &ih->states, entry)
1184		if (s->id == id && s->creatorid == creatorid)
1185			break;
1186
1187	if (s == NULL)
1188		PF_HASHROW_UNLOCK(ih);
1189
1190	return (s);
1191}
1192
1193/*
1194 * Find state by key.
1195 * Returns with ID hash slot locked on success.
1196 */
1197static struct pf_state *
1198pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1199{
1200	struct pf_keyhash	*kh;
1201	struct pf_state_key	*sk;
1202	struct pf_state		*s;
1203	int idx;
1204
1205	V_pf_status.fcounters[FCNT_STATE_SEARCH]++;
1206
1207	kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1208
1209	PF_HASHROW_LOCK(kh);
1210	LIST_FOREACH(sk, &kh->keys, entry)
1211		if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1212			break;
1213	if (sk == NULL) {
1214		PF_HASHROW_UNLOCK(kh);
1215		return (NULL);
1216	}
1217
1218	idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1219
1220	/* List is sorted, if-bound states before floating ones. */
1221	TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1222		if (s->kif == V_pfi_all || s->kif == kif) {
1223			PF_STATE_LOCK(s);
1224			PF_HASHROW_UNLOCK(kh);
1225			if (s->timeout == PFTM_UNLINKED) {
1226				/*
1227				 * State is being processed
1228				 * by pf_unlink_state() in
1229				 * an other thread.
1230				 */
1231				PF_STATE_UNLOCK(s);
1232				return (NULL);
1233			}
1234			return (s);
1235		}
1236	PF_HASHROW_UNLOCK(kh);
1237
1238	return (NULL);
1239}
1240
1241struct pf_state *
1242pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1243{
1244	struct pf_keyhash	*kh;
1245	struct pf_state_key	*sk;
1246	struct pf_state		*s, *ret = NULL;
1247	int			 idx, inout = 0;
1248
1249	V_pf_status.fcounters[FCNT_STATE_SEARCH]++;
1250
1251	kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1252
1253	PF_HASHROW_LOCK(kh);
1254	LIST_FOREACH(sk, &kh->keys, entry)
1255		if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1256			break;
1257	if (sk == NULL) {
1258		PF_HASHROW_UNLOCK(kh);
1259		return (NULL);
1260	}
1261	switch (dir) {
1262	case PF_IN:
1263		idx = PF_SK_WIRE;
1264		break;
1265	case PF_OUT:
1266		idx = PF_SK_STACK;
1267		break;
1268	case PF_INOUT:
1269		idx = PF_SK_WIRE;
1270		inout = 1;
1271		break;
1272	default:
1273		panic("%s: dir %u", __func__, dir);
1274	}
1275second_run:
1276	TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1277		if (more == NULL) {
1278			PF_HASHROW_UNLOCK(kh);
1279			return (s);
1280		}
1281
1282		if (ret)
1283			(*more)++;
1284		else
1285			ret = s;
1286	}
1287	if (inout == 1) {
1288		inout = 0;
1289		idx = PF_SK_STACK;
1290		goto second_run;
1291	}
1292	PF_HASHROW_UNLOCK(kh);
1293
1294	return (ret);
1295}
1296
1297/* END state table stuff */
1298
1299static void
1300pf_send(struct pf_send_entry *pfse)
1301{
1302
1303	PF_SENDQ_LOCK();
1304	STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1305	PF_SENDQ_UNLOCK();
1306	swi_sched(V_pf_swi_cookie, 0);
1307}
1308
1309void
1310pf_intr(void *v)
1311{
1312	struct pf_send_head queue;
1313	struct pf_send_entry *pfse, *next;
1314
1315	CURVNET_SET((struct vnet *)v);
1316
1317	PF_SENDQ_LOCK();
1318	queue = V_pf_sendqueue;
1319	STAILQ_INIT(&V_pf_sendqueue);
1320	PF_SENDQ_UNLOCK();
1321
1322	STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1323		switch (pfse->pfse_type) {
1324#ifdef INET
1325		case PFSE_IP:
1326			ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1327			break;
1328		case PFSE_ICMP:
1329			icmp_error(pfse->pfse_m, pfse->pfse_icmp_type,
1330			    pfse->pfse_icmp_code, 0, pfse->pfse_icmp_mtu);
1331			break;
1332#endif /* INET */
1333#ifdef INET6
1334		case PFSE_IP6:
1335			ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1336			    NULL);
1337			break;
1338		case PFSE_ICMP6:
1339			icmp6_error(pfse->pfse_m, pfse->pfse_icmp_type,
1340			    pfse->pfse_icmp_code, pfse->pfse_icmp_mtu);
1341			break;
1342#endif /* INET6 */
1343		default:
1344			panic("%s: unknown type", __func__);
1345		}
1346		free(pfse, M_PFTEMP);
1347	}
1348	CURVNET_RESTORE();
1349}
1350
1351void
1352pf_purge_thread(void *v)
1353{
1354	u_int idx = 0;
1355
1356	CURVNET_SET((struct vnet *)v);
1357
1358	for (;;) {
1359		PF_RULES_RLOCK();
1360		rw_sleep(pf_purge_thread, &pf_rules_lock, 0, "pftm", hz / 10);
1361
1362		if (V_pf_end_threads) {
1363			/*
1364			 * To cleanse up all kifs and rules we need
1365			 * two runs: first one clears reference flags,
1366			 * then pf_purge_expired_states() doesn't
1367			 * raise them, and then second run frees.
1368			 */
1369			PF_RULES_RUNLOCK();
1370			pf_purge_unlinked_rules();
1371			pfi_kif_purge();
1372
1373			/*
1374			 * Now purge everything.
1375			 */
1376			pf_purge_expired_states(0, V_pf_hashmask);
1377			pf_purge_expired_fragments();
1378			pf_purge_expired_src_nodes();
1379
1380			/*
1381			 * Now all kifs & rules should be unreferenced,
1382			 * thus should be successfully freed.
1383			 */
1384			pf_purge_unlinked_rules();
1385			pfi_kif_purge();
1386
1387			/*
1388			 * Announce success and exit.
1389			 */
1390			PF_RULES_RLOCK();
1391			V_pf_end_threads++;
1392			PF_RULES_RUNLOCK();
1393			wakeup(pf_purge_thread);
1394			kproc_exit(0);
1395		}
1396		PF_RULES_RUNLOCK();
1397
1398		/* Process 1/interval fraction of the state table every run. */
1399		idx = pf_purge_expired_states(idx, V_pf_hashmask /
1400			    (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1401
1402		/* Purge other expired types every PFTM_INTERVAL seconds. */
1403		if (idx == 0) {
1404			/*
1405			 * Order is important:
1406			 * - states and src nodes reference rules
1407			 * - states and rules reference kifs
1408			 */
1409			pf_purge_expired_fragments();
1410			pf_purge_expired_src_nodes();
1411			pf_purge_unlinked_rules();
1412			pfi_kif_purge();
1413		}
1414	}
1415	/* not reached */
1416	CURVNET_RESTORE();
1417}
1418
1419u_int32_t
1420pf_state_expires(const struct pf_state *state)
1421{
1422	u_int32_t	timeout;
1423	u_int32_t	start;
1424	u_int32_t	end;
1425	u_int32_t	states;
1426
1427	/* handle all PFTM_* > PFTM_MAX here */
1428	if (state->timeout == PFTM_PURGE)
1429		return (time_uptime);
1430	if (state->timeout == PFTM_UNTIL_PACKET)
1431		return (0);
1432	KASSERT(state->timeout != PFTM_UNLINKED,
1433	    ("pf_state_expires: timeout == PFTM_UNLINKED"));
1434	KASSERT((state->timeout < PFTM_MAX),
1435	    ("pf_state_expires: timeout > PFTM_MAX"));
1436	timeout = state->rule.ptr->timeout[state->timeout];
1437	if (!timeout)
1438		timeout = V_pf_default_rule.timeout[state->timeout];
1439	start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1440	if (start) {
1441		end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1442		states = state->rule.ptr->states_cur;	/* XXXGL */
1443	} else {
1444		start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1445		end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1446		states = V_pf_status.states;
1447	}
1448	if (end && states > start && start < end) {
1449		if (states < end)
1450			return (state->expire + timeout * (end - states) /
1451			    (end - start));
1452		else
1453			return (time_uptime);
1454	}
1455	return (state->expire + timeout);
1456}
1457
1458void
1459pf_purge_expired_src_nodes()
1460{
1461	struct pf_srchash	*sh;
1462	struct pf_src_node	*cur, *next;
1463	int i;
1464
1465	for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask; i++, sh++) {
1466	    PF_HASHROW_LOCK(sh);
1467	    LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1468		if (cur->states <= 0 && cur->expire <= time_uptime) {
1469			if (cur->rule.ptr != NULL)
1470				cur->rule.ptr->src_nodes--;
1471			LIST_REMOVE(cur, entry);
1472			V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
1473			V_pf_status.src_nodes--;
1474			uma_zfree(V_pf_sources_z, cur);
1475		} else if (cur->rule.ptr != NULL)
1476			cur->rule.ptr->rule_flag |= PFRULE_REFS;
1477	    PF_HASHROW_UNLOCK(sh);
1478	}
1479}
1480
1481static void
1482pf_src_tree_remove_state(struct pf_state *s)
1483{
1484	u_int32_t timeout;
1485
1486	if (s->src_node != NULL) {
1487		if (s->src.tcp_est)
1488			--s->src_node->conn;
1489		if (--s->src_node->states <= 0) {
1490			timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1491			if (!timeout)
1492				timeout =
1493				    V_pf_default_rule.timeout[PFTM_SRC_NODE];
1494			s->src_node->expire = time_uptime + timeout;
1495		}
1496	}
1497	if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1498		if (--s->nat_src_node->states <= 0) {
1499			timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1500			if (!timeout)
1501				timeout =
1502				    V_pf_default_rule.timeout[PFTM_SRC_NODE];
1503			s->nat_src_node->expire = time_uptime + timeout;
1504		}
1505	}
1506	s->src_node = s->nat_src_node = NULL;
1507}
1508
1509/*
1510 * Unlink and potentilly free a state. Function may be
1511 * called with ID hash row locked, but always returns
1512 * unlocked, since it needs to go through key hash locking.
1513 */
1514int
1515pf_unlink_state(struct pf_state *s, u_int flags)
1516{
1517	struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1518
1519	if ((flags & PF_ENTER_LOCKED) == 0)
1520		PF_HASHROW_LOCK(ih);
1521	else
1522		PF_HASHROW_ASSERT(ih);
1523
1524	if (s->timeout == PFTM_UNLINKED) {
1525		/*
1526		 * State is being processed
1527		 * by pf_unlink_state() in
1528		 * an other thread.
1529		 */
1530		PF_HASHROW_UNLOCK(ih);
1531		return (0);	/* XXXGL: undefined actually */
1532	}
1533
1534	if (s->src.state == PF_TCPS_PROXY_DST) {
1535		/* XXX wire key the right one? */
1536		pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1537		    &s->key[PF_SK_WIRE]->addr[1],
1538		    &s->key[PF_SK_WIRE]->addr[0],
1539		    s->key[PF_SK_WIRE]->port[1],
1540		    s->key[PF_SK_WIRE]->port[0],
1541		    s->src.seqhi, s->src.seqlo + 1,
1542		    TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1543	}
1544
1545	LIST_REMOVE(s, entry);
1546	pf_src_tree_remove_state(s);
1547
1548	if (pfsync_delete_state_ptr != NULL)
1549		pfsync_delete_state_ptr(s);
1550
1551	--s->rule.ptr->states_cur;
1552	if (s->nat_rule.ptr != NULL)
1553		--s->nat_rule.ptr->states_cur;
1554	if (s->anchor.ptr != NULL)
1555		--s->anchor.ptr->states_cur;
1556
1557	s->timeout = PFTM_UNLINKED;
1558
1559	PF_HASHROW_UNLOCK(ih);
1560
1561	pf_detach_state(s);
1562	refcount_release(&s->refs);
1563
1564	return (pf_release_state(s));
1565}
1566
1567void
1568pf_free_state(struct pf_state *cur)
1569{
1570
1571	KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1572	KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1573	    cur->timeout));
1574
1575	pf_normalize_tcp_cleanup(cur);
1576	uma_zfree(V_pf_state_z, cur);
1577	V_pf_status.fcounters[FCNT_STATE_REMOVALS]++;
1578}
1579
1580/*
1581 * Called only from pf_purge_thread(), thus serialized.
1582 */
1583static u_int
1584pf_purge_expired_states(u_int i, int maxcheck)
1585{
1586	struct pf_idhash *ih;
1587	struct pf_state *s;
1588
1589	V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1590
1591	/*
1592	 * Go through hash and unlink states that expire now.
1593	 */
1594	while (maxcheck > 0) {
1595
1596		ih = &V_pf_idhash[i];
1597relock:
1598		PF_HASHROW_LOCK(ih);
1599		LIST_FOREACH(s, &ih->states, entry) {
1600			if (pf_state_expires(s) <= time_uptime) {
1601				V_pf_status.states -=
1602				    pf_unlink_state(s, PF_ENTER_LOCKED);
1603				goto relock;
1604			}
1605			s->rule.ptr->rule_flag |= PFRULE_REFS;
1606			if (s->nat_rule.ptr != NULL)
1607				s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1608			if (s->anchor.ptr != NULL)
1609				s->anchor.ptr->rule_flag |= PFRULE_REFS;
1610			s->kif->pfik_flags |= PFI_IFLAG_REFS;
1611			if (s->rt_kif)
1612				s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1613		}
1614		PF_HASHROW_UNLOCK(ih);
1615
1616		/* Return when we hit end of hash. */
1617		if (++i > V_pf_hashmask) {
1618			V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1619			return (0);
1620		}
1621
1622		maxcheck--;
1623	}
1624
1625	V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1626
1627	return (i);
1628}
1629
1630static void
1631pf_purge_unlinked_rules()
1632{
1633	struct pf_rulequeue tmpq;
1634	struct pf_rule *r, *r1;
1635
1636	/*
1637	 * If we have overloading task pending, then we'd
1638	 * better skip purging this time. There is a tiny
1639	 * probability that overloading task references
1640	 * an already unlinked rule.
1641	 */
1642	PF_OVERLOADQ_LOCK();
1643	if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1644		PF_OVERLOADQ_UNLOCK();
1645		return;
1646	}
1647	PF_OVERLOADQ_UNLOCK();
1648
1649	/*
1650	 * Do naive mark-and-sweep garbage collecting of old rules.
1651	 * Reference flag is raised by pf_purge_expired_states()
1652	 * and pf_purge_expired_src_nodes().
1653	 *
1654	 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1655	 * use a temporary queue.
1656	 */
1657	TAILQ_INIT(&tmpq);
1658	PF_UNLNKDRULES_LOCK();
1659	TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1660		if (!(r->rule_flag & PFRULE_REFS)) {
1661			TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1662			TAILQ_INSERT_TAIL(&tmpq, r, entries);
1663		} else
1664			r->rule_flag &= ~PFRULE_REFS;
1665	}
1666	PF_UNLNKDRULES_UNLOCK();
1667
1668	if (!TAILQ_EMPTY(&tmpq)) {
1669		PF_RULES_WLOCK();
1670		TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1671			TAILQ_REMOVE(&tmpq, r, entries);
1672			pf_free_rule(r);
1673		}
1674		PF_RULES_WUNLOCK();
1675	}
1676}
1677
1678void
1679pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1680{
1681	switch (af) {
1682#ifdef INET
1683	case AF_INET: {
1684		u_int32_t a = ntohl(addr->addr32[0]);
1685		printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1686		    (a>>8)&255, a&255);
1687		if (p) {
1688			p = ntohs(p);
1689			printf(":%u", p);
1690		}
1691		break;
1692	}
1693#endif /* INET */
1694#ifdef INET6
1695	case AF_INET6: {
1696		u_int16_t b;
1697		u_int8_t i, curstart, curend, maxstart, maxend;
1698		curstart = curend = maxstart = maxend = 255;
1699		for (i = 0; i < 8; i++) {
1700			if (!addr->addr16[i]) {
1701				if (curstart == 255)
1702					curstart = i;
1703				curend = i;
1704			} else {
1705				if ((curend - curstart) >
1706				    (maxend - maxstart)) {
1707					maxstart = curstart;
1708					maxend = curend;
1709				}
1710				curstart = curend = 255;
1711			}
1712		}
1713		if ((curend - curstart) >
1714		    (maxend - maxstart)) {
1715			maxstart = curstart;
1716			maxend = curend;
1717		}
1718		for (i = 0; i < 8; i++) {
1719			if (i >= maxstart && i <= maxend) {
1720				if (i == 0)
1721					printf(":");
1722				if (i == maxend)
1723					printf(":");
1724			} else {
1725				b = ntohs(addr->addr16[i]);
1726				printf("%x", b);
1727				if (i < 7)
1728					printf(":");
1729			}
1730		}
1731		if (p) {
1732			p = ntohs(p);
1733			printf("[%u]", p);
1734		}
1735		break;
1736	}
1737#endif /* INET6 */
1738	}
1739}
1740
1741void
1742pf_print_state(struct pf_state *s)
1743{
1744	pf_print_state_parts(s, NULL, NULL);
1745}
1746
1747static void
1748pf_print_state_parts(struct pf_state *s,
1749    struct pf_state_key *skwp, struct pf_state_key *sksp)
1750{
1751	struct pf_state_key *skw, *sks;
1752	u_int8_t proto, dir;
1753
1754	/* Do our best to fill these, but they're skipped if NULL */
1755	skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1756	sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1757	proto = skw ? skw->proto : (sks ? sks->proto : 0);
1758	dir = s ? s->direction : 0;
1759
1760	switch (proto) {
1761	case IPPROTO_IPV4:
1762		printf("IPv4");
1763		break;
1764	case IPPROTO_IPV6:
1765		printf("IPv6");
1766		break;
1767	case IPPROTO_TCP:
1768		printf("TCP");
1769		break;
1770	case IPPROTO_UDP:
1771		printf("UDP");
1772		break;
1773	case IPPROTO_ICMP:
1774		printf("ICMP");
1775		break;
1776	case IPPROTO_ICMPV6:
1777		printf("ICMPv6");
1778		break;
1779	default:
1780		printf("%u", skw->proto);
1781		break;
1782	}
1783	switch (dir) {
1784	case PF_IN:
1785		printf(" in");
1786		break;
1787	case PF_OUT:
1788		printf(" out");
1789		break;
1790	}
1791	if (skw) {
1792		printf(" wire: ");
1793		pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1794		printf(" ");
1795		pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1796	}
1797	if (sks) {
1798		printf(" stack: ");
1799		if (sks != skw) {
1800			pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1801			printf(" ");
1802			pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1803		} else
1804			printf("-");
1805	}
1806	if (s) {
1807		if (proto == IPPROTO_TCP) {
1808			printf(" [lo=%u high=%u win=%u modulator=%u",
1809			    s->src.seqlo, s->src.seqhi,
1810			    s->src.max_win, s->src.seqdiff);
1811			if (s->src.wscale && s->dst.wscale)
1812				printf(" wscale=%u",
1813				    s->src.wscale & PF_WSCALE_MASK);
1814			printf("]");
1815			printf(" [lo=%u high=%u win=%u modulator=%u",
1816			    s->dst.seqlo, s->dst.seqhi,
1817			    s->dst.max_win, s->dst.seqdiff);
1818			if (s->src.wscale && s->dst.wscale)
1819				printf(" wscale=%u",
1820				s->dst.wscale & PF_WSCALE_MASK);
1821			printf("]");
1822		}
1823		printf(" %u:%u", s->src.state, s->dst.state);
1824	}
1825}
1826
1827void
1828pf_print_flags(u_int8_t f)
1829{
1830	if (f)
1831		printf(" ");
1832	if (f & TH_FIN)
1833		printf("F");
1834	if (f & TH_SYN)
1835		printf("S");
1836	if (f & TH_RST)
1837		printf("R");
1838	if (f & TH_PUSH)
1839		printf("P");
1840	if (f & TH_ACK)
1841		printf("A");
1842	if (f & TH_URG)
1843		printf("U");
1844	if (f & TH_ECE)
1845		printf("E");
1846	if (f & TH_CWR)
1847		printf("W");
1848}
1849
1850#define	PF_SET_SKIP_STEPS(i)					\
1851	do {							\
1852		while (head[i] != cur) {			\
1853			head[i]->skip[i].ptr = cur;		\
1854			head[i] = TAILQ_NEXT(head[i], entries);	\
1855		}						\
1856	} while (0)
1857
1858void
1859pf_calc_skip_steps(struct pf_rulequeue *rules)
1860{
1861	struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1862	int i;
1863
1864	cur = TAILQ_FIRST(rules);
1865	prev = cur;
1866	for (i = 0; i < PF_SKIP_COUNT; ++i)
1867		head[i] = cur;
1868	while (cur != NULL) {
1869
1870		if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1871			PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1872		if (cur->direction != prev->direction)
1873			PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1874		if (cur->af != prev->af)
1875			PF_SET_SKIP_STEPS(PF_SKIP_AF);
1876		if (cur->proto != prev->proto)
1877			PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1878		if (cur->src.neg != prev->src.neg ||
1879		    pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1880			PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1881		if (cur->src.port[0] != prev->src.port[0] ||
1882		    cur->src.port[1] != prev->src.port[1] ||
1883		    cur->src.port_op != prev->src.port_op)
1884			PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1885		if (cur->dst.neg != prev->dst.neg ||
1886		    pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1887			PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1888		if (cur->dst.port[0] != prev->dst.port[0] ||
1889		    cur->dst.port[1] != prev->dst.port[1] ||
1890		    cur->dst.port_op != prev->dst.port_op)
1891			PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1892
1893		prev = cur;
1894		cur = TAILQ_NEXT(cur, entries);
1895	}
1896	for (i = 0; i < PF_SKIP_COUNT; ++i)
1897		PF_SET_SKIP_STEPS(i);
1898}
1899
1900static int
1901pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1902{
1903	if (aw1->type != aw2->type)
1904		return (1);
1905	switch (aw1->type) {
1906	case PF_ADDR_ADDRMASK:
1907	case PF_ADDR_RANGE:
1908		if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1909			return (1);
1910		if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1911			return (1);
1912		return (0);
1913	case PF_ADDR_DYNIFTL:
1914		return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1915	case PF_ADDR_NOROUTE:
1916	case PF_ADDR_URPFFAILED:
1917		return (0);
1918	case PF_ADDR_TABLE:
1919		return (aw1->p.tbl != aw2->p.tbl);
1920	default:
1921		printf("invalid address type: %d\n", aw1->type);
1922		return (1);
1923	}
1924}
1925
1926u_int16_t
1927pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
1928{
1929	u_int32_t	l;
1930
1931	if (udp && !cksum)
1932		return (0x0000);
1933	l = cksum + old - new;
1934	l = (l >> 16) + (l & 65535);
1935	l = l & 65535;
1936	if (udp && !l)
1937		return (0xFFFF);
1938	return (l);
1939}
1940
1941static void
1942pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
1943    struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
1944{
1945	struct pf_addr	ao;
1946	u_int16_t	po = *p;
1947
1948	PF_ACPY(&ao, a, af);
1949	PF_ACPY(a, an, af);
1950
1951	*p = pn;
1952
1953	switch (af) {
1954#ifdef INET
1955	case AF_INET:
1956		*ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1957		    ao.addr16[0], an->addr16[0], 0),
1958		    ao.addr16[1], an->addr16[1], 0);
1959		*p = pn;
1960		*pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1961		    ao.addr16[0], an->addr16[0], u),
1962		    ao.addr16[1], an->addr16[1], u),
1963		    po, pn, u);
1964		break;
1965#endif /* INET */
1966#ifdef INET6
1967	case AF_INET6:
1968		*pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1969		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1970		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1971		    ao.addr16[0], an->addr16[0], u),
1972		    ao.addr16[1], an->addr16[1], u),
1973		    ao.addr16[2], an->addr16[2], u),
1974		    ao.addr16[3], an->addr16[3], u),
1975		    ao.addr16[4], an->addr16[4], u),
1976		    ao.addr16[5], an->addr16[5], u),
1977		    ao.addr16[6], an->addr16[6], u),
1978		    ao.addr16[7], an->addr16[7], u),
1979		    po, pn, u);
1980		break;
1981#endif /* INET6 */
1982	}
1983}
1984
1985
1986/* Changes a u_int32_t.  Uses a void * so there are no align restrictions */
1987void
1988pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
1989{
1990	u_int32_t	ao;
1991
1992	memcpy(&ao, a, sizeof(ao));
1993	memcpy(a, &an, sizeof(u_int32_t));
1994	*c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
1995	    ao % 65536, an % 65536, u);
1996}
1997
1998#ifdef INET6
1999static void
2000pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2001{
2002	struct pf_addr	ao;
2003
2004	PF_ACPY(&ao, a, AF_INET6);
2005	PF_ACPY(a, an, AF_INET6);
2006
2007	*c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2008	    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2009	    pf_cksum_fixup(pf_cksum_fixup(*c,
2010	    ao.addr16[0], an->addr16[0], u),
2011	    ao.addr16[1], an->addr16[1], u),
2012	    ao.addr16[2], an->addr16[2], u),
2013	    ao.addr16[3], an->addr16[3], u),
2014	    ao.addr16[4], an->addr16[4], u),
2015	    ao.addr16[5], an->addr16[5], u),
2016	    ao.addr16[6], an->addr16[6], u),
2017	    ao.addr16[7], an->addr16[7], u);
2018}
2019#endif /* INET6 */
2020
2021static void
2022pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2023    struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2024    u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2025{
2026	struct pf_addr	oia, ooa;
2027
2028	PF_ACPY(&oia, ia, af);
2029	if (oa)
2030		PF_ACPY(&ooa, oa, af);
2031
2032	/* Change inner protocol port, fix inner protocol checksum. */
2033	if (ip != NULL) {
2034		u_int16_t	oip = *ip;
2035		u_int32_t	opc;
2036
2037		if (pc != NULL)
2038			opc = *pc;
2039		*ip = np;
2040		if (pc != NULL)
2041			*pc = pf_cksum_fixup(*pc, oip, *ip, u);
2042		*ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2043		if (pc != NULL)
2044			*ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2045	}
2046	/* Change inner ip address, fix inner ip and icmp checksums. */
2047	PF_ACPY(ia, na, af);
2048	switch (af) {
2049#ifdef INET
2050	case AF_INET: {
2051		u_int32_t	 oh2c = *h2c;
2052
2053		*h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2054		    oia.addr16[0], ia->addr16[0], 0),
2055		    oia.addr16[1], ia->addr16[1], 0);
2056		*ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2057		    oia.addr16[0], ia->addr16[0], 0),
2058		    oia.addr16[1], ia->addr16[1], 0);
2059		*ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2060		break;
2061	}
2062#endif /* INET */
2063#ifdef INET6
2064	case AF_INET6:
2065		*ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2066		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2067		    pf_cksum_fixup(pf_cksum_fixup(*ic,
2068		    oia.addr16[0], ia->addr16[0], u),
2069		    oia.addr16[1], ia->addr16[1], u),
2070		    oia.addr16[2], ia->addr16[2], u),
2071		    oia.addr16[3], ia->addr16[3], u),
2072		    oia.addr16[4], ia->addr16[4], u),
2073		    oia.addr16[5], ia->addr16[5], u),
2074		    oia.addr16[6], ia->addr16[6], u),
2075		    oia.addr16[7], ia->addr16[7], u);
2076		break;
2077#endif /* INET6 */
2078	}
2079	/* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2080	if (oa) {
2081		PF_ACPY(oa, na, af);
2082		switch (af) {
2083#ifdef INET
2084		case AF_INET:
2085			*hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2086			    ooa.addr16[0], oa->addr16[0], 0),
2087			    ooa.addr16[1], oa->addr16[1], 0);
2088			break;
2089#endif /* INET */
2090#ifdef INET6
2091		case AF_INET6:
2092			*ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2093			    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2094			    pf_cksum_fixup(pf_cksum_fixup(*ic,
2095			    ooa.addr16[0], oa->addr16[0], u),
2096			    ooa.addr16[1], oa->addr16[1], u),
2097			    ooa.addr16[2], oa->addr16[2], u),
2098			    ooa.addr16[3], oa->addr16[3], u),
2099			    ooa.addr16[4], oa->addr16[4], u),
2100			    ooa.addr16[5], oa->addr16[5], u),
2101			    ooa.addr16[6], oa->addr16[6], u),
2102			    ooa.addr16[7], oa->addr16[7], u);
2103			break;
2104#endif /* INET6 */
2105		}
2106	}
2107}
2108
2109
2110/*
2111 * Need to modulate the sequence numbers in the TCP SACK option
2112 * (credits to Krzysztof Pfaff for report and patch)
2113 */
2114static int
2115pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2116    struct tcphdr *th, struct pf_state_peer *dst)
2117{
2118	int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2119	u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2120	int copyback = 0, i, olen;
2121	struct sackblk sack;
2122
2123#define	TCPOLEN_SACKLEN	(TCPOLEN_SACK + 2)
2124	if (hlen < TCPOLEN_SACKLEN ||
2125	    !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2126		return 0;
2127
2128	while (hlen >= TCPOLEN_SACKLEN) {
2129		olen = opt[1];
2130		switch (*opt) {
2131		case TCPOPT_EOL:	/* FALLTHROUGH */
2132		case TCPOPT_NOP:
2133			opt++;
2134			hlen--;
2135			break;
2136		case TCPOPT_SACK:
2137			if (olen > hlen)
2138				olen = hlen;
2139			if (olen >= TCPOLEN_SACKLEN) {
2140				for (i = 2; i + TCPOLEN_SACK <= olen;
2141				    i += TCPOLEN_SACK) {
2142					memcpy(&sack, &opt[i], sizeof(sack));
2143					pf_change_a(&sack.start, &th->th_sum,
2144					    htonl(ntohl(sack.start) -
2145					    dst->seqdiff), 0);
2146					pf_change_a(&sack.end, &th->th_sum,
2147					    htonl(ntohl(sack.end) -
2148					    dst->seqdiff), 0);
2149					memcpy(&opt[i], &sack, sizeof(sack));
2150				}
2151				copyback = 1;
2152			}
2153			/* FALLTHROUGH */
2154		default:
2155			if (olen < 2)
2156				olen = 2;
2157			hlen -= olen;
2158			opt += olen;
2159		}
2160	}
2161
2162	if (copyback)
2163		m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2164	return (copyback);
2165}
2166
2167static void
2168pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2169    const struct pf_addr *saddr, const struct pf_addr *daddr,
2170    u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2171    u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2172    u_int16_t rtag, struct ifnet *ifp)
2173{
2174	struct pf_send_entry *pfse;
2175	struct mbuf	*m;
2176	int		 len, tlen;
2177#ifdef INET
2178	struct ip	*h = NULL;
2179#endif /* INET */
2180#ifdef INET6
2181	struct ip6_hdr	*h6 = NULL;
2182#endif /* INET6 */
2183	struct tcphdr	*th;
2184	char		*opt;
2185	struct pf_mtag  *pf_mtag;
2186
2187	len = 0;
2188	th = NULL;
2189
2190	/* maximum segment size tcp option */
2191	tlen = sizeof(struct tcphdr);
2192	if (mss)
2193		tlen += 4;
2194
2195	switch (af) {
2196#ifdef INET
2197	case AF_INET:
2198		len = sizeof(struct ip) + tlen;
2199		break;
2200#endif /* INET */
2201#ifdef INET6
2202	case AF_INET6:
2203		len = sizeof(struct ip6_hdr) + tlen;
2204		break;
2205#endif /* INET6 */
2206	default:
2207		panic("%s: unsupported af %d", __func__, af);
2208	}
2209
2210	/* Allocate outgoing queue entry, mbuf and mbuf tag. */
2211	pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2212	if (pfse == NULL)
2213		return;
2214	m = m_gethdr(M_NOWAIT, MT_DATA);
2215	if (m == NULL) {
2216		free(pfse, M_PFTEMP);
2217		return;
2218	}
2219#ifdef MAC
2220	mac_netinet_firewall_send(m);
2221#endif
2222	if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2223		free(pfse, M_PFTEMP);
2224		m_freem(m);
2225		return;
2226	}
2227	if (tag)
2228		m->m_flags |= M_SKIP_FIREWALL;
2229	pf_mtag->tag = rtag;
2230
2231	if (r != NULL && r->rtableid >= 0)
2232		M_SETFIB(m, r->rtableid);
2233
2234#ifdef ALTQ
2235	if (r != NULL && r->qid) {
2236		pf_mtag->qid = r->qid;
2237
2238		/* add hints for ecn */
2239		pf_mtag->hdr = mtod(m, struct ip *);
2240	}
2241#endif /* ALTQ */
2242	m->m_data += max_linkhdr;
2243	m->m_pkthdr.len = m->m_len = len;
2244	m->m_pkthdr.rcvif = NULL;
2245	bzero(m->m_data, len);
2246	switch (af) {
2247#ifdef INET
2248	case AF_INET:
2249		h = mtod(m, struct ip *);
2250
2251		/* IP header fields included in the TCP checksum */
2252		h->ip_p = IPPROTO_TCP;
2253		h->ip_len = htons(tlen);
2254		h->ip_src.s_addr = saddr->v4.s_addr;
2255		h->ip_dst.s_addr = daddr->v4.s_addr;
2256
2257		th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2258		break;
2259#endif /* INET */
2260#ifdef INET6
2261	case AF_INET6:
2262		h6 = mtod(m, struct ip6_hdr *);
2263
2264		/* IP header fields included in the TCP checksum */
2265		h6->ip6_nxt = IPPROTO_TCP;
2266		h6->ip6_plen = htons(tlen);
2267		memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2268		memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2269
2270		th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2271		break;
2272#endif /* INET6 */
2273	}
2274
2275	/* TCP header */
2276	th->th_sport = sport;
2277	th->th_dport = dport;
2278	th->th_seq = htonl(seq);
2279	th->th_ack = htonl(ack);
2280	th->th_off = tlen >> 2;
2281	th->th_flags = flags;
2282	th->th_win = htons(win);
2283
2284	if (mss) {
2285		opt = (char *)(th + 1);
2286		opt[0] = TCPOPT_MAXSEG;
2287		opt[1] = 4;
2288		HTONS(mss);
2289		bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2290	}
2291
2292	switch (af) {
2293#ifdef INET
2294	case AF_INET:
2295		/* TCP checksum */
2296		th->th_sum = in_cksum(m, len);
2297
2298		/* Finish the IP header */
2299		h->ip_v = 4;
2300		h->ip_hl = sizeof(*h) >> 2;
2301		h->ip_tos = IPTOS_LOWDELAY;
2302		h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2303		h->ip_len = htons(len);
2304		h->ip_ttl = ttl ? ttl : V_ip_defttl;
2305		h->ip_sum = 0;
2306
2307		pfse->pfse_type = PFSE_IP;
2308		break;
2309#endif /* INET */
2310#ifdef INET6
2311	case AF_INET6:
2312		/* TCP checksum */
2313		th->th_sum = in6_cksum(m, IPPROTO_TCP,
2314		    sizeof(struct ip6_hdr), tlen);
2315
2316		h6->ip6_vfc |= IPV6_VERSION;
2317		h6->ip6_hlim = IPV6_DEFHLIM;
2318
2319		pfse->pfse_type = PFSE_IP6;
2320		break;
2321#endif /* INET6 */
2322	}
2323	pfse->pfse_m = m;
2324	pf_send(pfse);
2325}
2326
2327static void
2328pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2329    struct pf_rule *r)
2330{
2331	struct pf_send_entry *pfse;
2332	struct mbuf *m0;
2333	struct pf_mtag *pf_mtag;
2334
2335	/* Allocate outgoing queue entry, mbuf and mbuf tag. */
2336	pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2337	if (pfse == NULL)
2338		return;
2339
2340	if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2341		free(pfse, M_PFTEMP);
2342		return;
2343	}
2344
2345	if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2346		free(pfse, M_PFTEMP);
2347		return;
2348	}
2349	/* XXX: revisit */
2350	m0->m_flags |= M_SKIP_FIREWALL;
2351
2352	if (r->rtableid >= 0)
2353		M_SETFIB(m0, r->rtableid);
2354
2355#ifdef ALTQ
2356	if (r->qid) {
2357		pf_mtag->qid = r->qid;
2358		/* add hints for ecn */
2359		pf_mtag->hdr = mtod(m0, struct ip *);
2360	}
2361#endif /* ALTQ */
2362
2363	switch (af) {
2364#ifdef INET
2365	case AF_INET:
2366		pfse->pfse_type = PFSE_ICMP;
2367		break;
2368#endif /* INET */
2369#ifdef INET6
2370	case AF_INET6:
2371		pfse->pfse_type = PFSE_ICMP6;
2372		break;
2373#endif /* INET6 */
2374	}
2375	pfse->pfse_m = m0;
2376	pfse->pfse_icmp_type = type;
2377	pfse->pfse_icmp_code = code;
2378	pf_send(pfse);
2379}
2380
2381/*
2382 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2383 * If n is 0, they match if they are equal. If n is != 0, they match if they
2384 * are different.
2385 */
2386int
2387pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2388    struct pf_addr *b, sa_family_t af)
2389{
2390	int	match = 0;
2391
2392	switch (af) {
2393#ifdef INET
2394	case AF_INET:
2395		if ((a->addr32[0] & m->addr32[0]) ==
2396		    (b->addr32[0] & m->addr32[0]))
2397			match++;
2398		break;
2399#endif /* INET */
2400#ifdef INET6
2401	case AF_INET6:
2402		if (((a->addr32[0] & m->addr32[0]) ==
2403		     (b->addr32[0] & m->addr32[0])) &&
2404		    ((a->addr32[1] & m->addr32[1]) ==
2405		     (b->addr32[1] & m->addr32[1])) &&
2406		    ((a->addr32[2] & m->addr32[2]) ==
2407		     (b->addr32[2] & m->addr32[2])) &&
2408		    ((a->addr32[3] & m->addr32[3]) ==
2409		     (b->addr32[3] & m->addr32[3])))
2410			match++;
2411		break;
2412#endif /* INET6 */
2413	}
2414	if (match) {
2415		if (n)
2416			return (0);
2417		else
2418			return (1);
2419	} else {
2420		if (n)
2421			return (1);
2422		else
2423			return (0);
2424	}
2425}
2426
2427/*
2428 * Return 1 if b <= a <= e, otherwise return 0.
2429 */
2430int
2431pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2432    struct pf_addr *a, sa_family_t af)
2433{
2434	switch (af) {
2435#ifdef INET
2436	case AF_INET:
2437		if ((a->addr32[0] < b->addr32[0]) ||
2438		    (a->addr32[0] > e->addr32[0]))
2439			return (0);
2440		break;
2441#endif /* INET */
2442#ifdef INET6
2443	case AF_INET6: {
2444		int	i;
2445
2446		/* check a >= b */
2447		for (i = 0; i < 4; ++i)
2448			if (a->addr32[i] > b->addr32[i])
2449				break;
2450			else if (a->addr32[i] < b->addr32[i])
2451				return (0);
2452		/* check a <= e */
2453		for (i = 0; i < 4; ++i)
2454			if (a->addr32[i] < e->addr32[i])
2455				break;
2456			else if (a->addr32[i] > e->addr32[i])
2457				return (0);
2458		break;
2459	}
2460#endif /* INET6 */
2461	}
2462	return (1);
2463}
2464
2465static int
2466pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2467{
2468	switch (op) {
2469	case PF_OP_IRG:
2470		return ((p > a1) && (p < a2));
2471	case PF_OP_XRG:
2472		return ((p < a1) || (p > a2));
2473	case PF_OP_RRG:
2474		return ((p >= a1) && (p <= a2));
2475	case PF_OP_EQ:
2476		return (p == a1);
2477	case PF_OP_NE:
2478		return (p != a1);
2479	case PF_OP_LT:
2480		return (p < a1);
2481	case PF_OP_LE:
2482		return (p <= a1);
2483	case PF_OP_GT:
2484		return (p > a1);
2485	case PF_OP_GE:
2486		return (p >= a1);
2487	}
2488	return (0); /* never reached */
2489}
2490
2491int
2492pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2493{
2494	NTOHS(a1);
2495	NTOHS(a2);
2496	NTOHS(p);
2497	return (pf_match(op, a1, a2, p));
2498}
2499
2500static int
2501pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2502{
2503	if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2504		return (0);
2505	return (pf_match(op, a1, a2, u));
2506}
2507
2508static int
2509pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2510{
2511	if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2512		return (0);
2513	return (pf_match(op, a1, a2, g));
2514}
2515
2516int
2517pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2518{
2519	if (*tag == -1)
2520		*tag = mtag;
2521
2522	return ((!r->match_tag_not && r->match_tag == *tag) ||
2523	    (r->match_tag_not && r->match_tag != *tag));
2524}
2525
2526int
2527pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2528{
2529
2530	KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2531
2532	if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2533		return (ENOMEM);
2534
2535	pd->pf_mtag->tag = tag;
2536
2537	return (0);
2538}
2539
2540#define	PF_ANCHOR_STACKSIZE	32
2541struct pf_anchor_stackframe {
2542	struct pf_ruleset	*rs;
2543	struct pf_rule		*r;	/* XXX: + match bit */
2544	struct pf_anchor	*child;
2545};
2546
2547/*
2548 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2549 */
2550#define	PF_ANCHORSTACK_MATCH	0x00000001
2551#define	PF_ANCHORSTACK_MASK	(PF_ANCHORSTACK_MATCH)
2552
2553#define	PF_ANCHOR_MATCH(f)	((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2554#define	PF_ANCHOR_RULE(f)	(struct pf_rule *)			\
2555				((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2556#define	PF_ANCHOR_SET_MATCH(f)	do { (f)->r = (void *) 			\
2557				((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH);  \
2558} while (0)
2559
2560void
2561pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2562    struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2563    int *match)
2564{
2565	struct pf_anchor_stackframe	*f;
2566
2567	PF_RULES_RASSERT();
2568
2569	if (match)
2570		*match = 0;
2571	if (*depth >= PF_ANCHOR_STACKSIZE) {
2572		printf("%s: anchor stack overflow on %s\n",
2573		    __func__, (*r)->anchor->name);
2574		*r = TAILQ_NEXT(*r, entries);
2575		return;
2576	} else if (*depth == 0 && a != NULL)
2577		*a = *r;
2578	f = stack + (*depth)++;
2579	f->rs = *rs;
2580	f->r = *r;
2581	if ((*r)->anchor_wildcard) {
2582		struct pf_anchor_node *parent = &(*r)->anchor->children;
2583
2584		if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2585			*r = NULL;
2586			return;
2587		}
2588		*rs = &f->child->ruleset;
2589	} else {
2590		f->child = NULL;
2591		*rs = &(*r)->anchor->ruleset;
2592	}
2593	*r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2594}
2595
2596int
2597pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2598    struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2599    int *match)
2600{
2601	struct pf_anchor_stackframe	*f;
2602	struct pf_rule *fr;
2603	int quick = 0;
2604
2605	PF_RULES_RASSERT();
2606
2607	do {
2608		if (*depth <= 0)
2609			break;
2610		f = stack + *depth - 1;
2611		fr = PF_ANCHOR_RULE(f);
2612		if (f->child != NULL) {
2613			struct pf_anchor_node *parent;
2614
2615			/*
2616			 * This block traverses through
2617			 * a wildcard anchor.
2618			 */
2619			parent = &fr->anchor->children;
2620			if (match != NULL && *match) {
2621				/*
2622				 * If any of "*" matched, then
2623				 * "foo/ *" matched, mark frame
2624				 * appropriately.
2625				 */
2626				PF_ANCHOR_SET_MATCH(f);
2627				*match = 0;
2628			}
2629			f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2630			if (f->child != NULL) {
2631				*rs = &f->child->ruleset;
2632				*r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2633				if (*r == NULL)
2634					continue;
2635				else
2636					break;
2637			}
2638		}
2639		(*depth)--;
2640		if (*depth == 0 && a != NULL)
2641			*a = NULL;
2642		*rs = f->rs;
2643		if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2644			quick = fr->quick;
2645		*r = TAILQ_NEXT(fr, entries);
2646	} while (*r == NULL);
2647
2648	return (quick);
2649}
2650
2651#ifdef INET6
2652void
2653pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2654    struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2655{
2656	switch (af) {
2657#ifdef INET
2658	case AF_INET:
2659		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2660		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2661		break;
2662#endif /* INET */
2663	case AF_INET6:
2664		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2665		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2666		naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2667		((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2668		naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2669		((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2670		naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2671		((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2672		break;
2673	}
2674}
2675
2676void
2677pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2678{
2679	switch (af) {
2680#ifdef INET
2681	case AF_INET:
2682		addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2683		break;
2684#endif /* INET */
2685	case AF_INET6:
2686		if (addr->addr32[3] == 0xffffffff) {
2687			addr->addr32[3] = 0;
2688			if (addr->addr32[2] == 0xffffffff) {
2689				addr->addr32[2] = 0;
2690				if (addr->addr32[1] == 0xffffffff) {
2691					addr->addr32[1] = 0;
2692					addr->addr32[0] =
2693					    htonl(ntohl(addr->addr32[0]) + 1);
2694				} else
2695					addr->addr32[1] =
2696					    htonl(ntohl(addr->addr32[1]) + 1);
2697			} else
2698				addr->addr32[2] =
2699				    htonl(ntohl(addr->addr32[2]) + 1);
2700		} else
2701			addr->addr32[3] =
2702			    htonl(ntohl(addr->addr32[3]) + 1);
2703		break;
2704	}
2705}
2706#endif /* INET6 */
2707
2708int
2709pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2710{
2711	struct pf_addr		*saddr, *daddr;
2712	u_int16_t		 sport, dport;
2713	struct inpcbinfo	*pi;
2714	struct inpcb		*inp;
2715
2716	pd->lookup.uid = UID_MAX;
2717	pd->lookup.gid = GID_MAX;
2718
2719	switch (pd->proto) {
2720	case IPPROTO_TCP:
2721		if (pd->hdr.tcp == NULL)
2722			return (-1);
2723		sport = pd->hdr.tcp->th_sport;
2724		dport = pd->hdr.tcp->th_dport;
2725		pi = &V_tcbinfo;
2726		break;
2727	case IPPROTO_UDP:
2728		if (pd->hdr.udp == NULL)
2729			return (-1);
2730		sport = pd->hdr.udp->uh_sport;
2731		dport = pd->hdr.udp->uh_dport;
2732		pi = &V_udbinfo;
2733		break;
2734	default:
2735		return (-1);
2736	}
2737	if (direction == PF_IN) {
2738		saddr = pd->src;
2739		daddr = pd->dst;
2740	} else {
2741		u_int16_t	p;
2742
2743		p = sport;
2744		sport = dport;
2745		dport = p;
2746		saddr = pd->dst;
2747		daddr = pd->src;
2748	}
2749	switch (pd->af) {
2750#ifdef INET
2751	case AF_INET:
2752		inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
2753		    dport, INPLOOKUP_RLOCKPCB, NULL, m);
2754		if (inp == NULL) {
2755			inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
2756			   daddr->v4, dport, INPLOOKUP_WILDCARD |
2757			   INPLOOKUP_RLOCKPCB, NULL, m);
2758			if (inp == NULL)
2759				return (-1);
2760		}
2761		break;
2762#endif /* INET */
2763#ifdef INET6
2764	case AF_INET6:
2765		inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
2766		    dport, INPLOOKUP_RLOCKPCB, NULL, m);
2767		if (inp == NULL) {
2768			inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
2769			    &daddr->v6, dport, INPLOOKUP_WILDCARD |
2770			    INPLOOKUP_RLOCKPCB, NULL, m);
2771			if (inp == NULL)
2772				return (-1);
2773		}
2774		break;
2775#endif /* INET6 */
2776
2777	default:
2778		return (-1);
2779	}
2780	INP_RLOCK_ASSERT(inp);
2781	pd->lookup.uid = inp->inp_cred->cr_uid;
2782	pd->lookup.gid = inp->inp_cred->cr_groups[0];
2783	INP_RUNLOCK(inp);
2784
2785	return (1);
2786}
2787
2788static u_int8_t
2789pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2790{
2791	int		 hlen;
2792	u_int8_t	 hdr[60];
2793	u_int8_t	*opt, optlen;
2794	u_int8_t	 wscale = 0;
2795
2796	hlen = th_off << 2;		/* hlen <= sizeof(hdr) */
2797	if (hlen <= sizeof(struct tcphdr))
2798		return (0);
2799	if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2800		return (0);
2801	opt = hdr + sizeof(struct tcphdr);
2802	hlen -= sizeof(struct tcphdr);
2803	while (hlen >= 3) {
2804		switch (*opt) {
2805		case TCPOPT_EOL:
2806		case TCPOPT_NOP:
2807			++opt;
2808			--hlen;
2809			break;
2810		case TCPOPT_WINDOW:
2811			wscale = opt[2];
2812			if (wscale > TCP_MAX_WINSHIFT)
2813				wscale = TCP_MAX_WINSHIFT;
2814			wscale |= PF_WSCALE_FLAG;
2815			/* FALLTHROUGH */
2816		default:
2817			optlen = opt[1];
2818			if (optlen < 2)
2819				optlen = 2;
2820			hlen -= optlen;
2821			opt += optlen;
2822			break;
2823		}
2824	}
2825	return (wscale);
2826}
2827
2828static u_int16_t
2829pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2830{
2831	int		 hlen;
2832	u_int8_t	 hdr[60];
2833	u_int8_t	*opt, optlen;
2834	u_int16_t	 mss = V_tcp_mssdflt;
2835
2836	hlen = th_off << 2;	/* hlen <= sizeof(hdr) */
2837	if (hlen <= sizeof(struct tcphdr))
2838		return (0);
2839	if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2840		return (0);
2841	opt = hdr + sizeof(struct tcphdr);
2842	hlen -= sizeof(struct tcphdr);
2843	while (hlen >= TCPOLEN_MAXSEG) {
2844		switch (*opt) {
2845		case TCPOPT_EOL:
2846		case TCPOPT_NOP:
2847			++opt;
2848			--hlen;
2849			break;
2850		case TCPOPT_MAXSEG:
2851			bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
2852			NTOHS(mss);
2853			/* FALLTHROUGH */
2854		default:
2855			optlen = opt[1];
2856			if (optlen < 2)
2857				optlen = 2;
2858			hlen -= optlen;
2859			opt += optlen;
2860			break;
2861		}
2862	}
2863	return (mss);
2864}
2865
2866static u_int16_t
2867pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
2868{
2869#ifdef INET
2870	struct sockaddr_in	*dst;
2871	struct route		 ro;
2872#endif /* INET */
2873#ifdef INET6
2874	struct sockaddr_in6	*dst6;
2875	struct route_in6	 ro6;
2876#endif /* INET6 */
2877	struct rtentry		*rt = NULL;
2878	int			 hlen = 0;
2879	u_int16_t		 mss = V_tcp_mssdflt;
2880
2881	switch (af) {
2882#ifdef INET
2883	case AF_INET:
2884		hlen = sizeof(struct ip);
2885		bzero(&ro, sizeof(ro));
2886		dst = (struct sockaddr_in *)&ro.ro_dst;
2887		dst->sin_family = AF_INET;
2888		dst->sin_len = sizeof(*dst);
2889		dst->sin_addr = addr->v4;
2890		in_rtalloc_ign(&ro, 0, rtableid);
2891		rt = ro.ro_rt;
2892		break;
2893#endif /* INET */
2894#ifdef INET6
2895	case AF_INET6:
2896		hlen = sizeof(struct ip6_hdr);
2897		bzero(&ro6, sizeof(ro6));
2898		dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
2899		dst6->sin6_family = AF_INET6;
2900		dst6->sin6_len = sizeof(*dst6);
2901		dst6->sin6_addr = addr->v6;
2902		in6_rtalloc_ign(&ro6, 0, rtableid);
2903		rt = ro6.ro_rt;
2904		break;
2905#endif /* INET6 */
2906	}
2907
2908	if (rt && rt->rt_ifp) {
2909		mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
2910		mss = max(V_tcp_mssdflt, mss);
2911		RTFREE(rt);
2912	}
2913	mss = min(mss, offer);
2914	mss = max(mss, 64);		/* sanity - at least max opt space */
2915	return (mss);
2916}
2917
2918static void
2919pf_set_rt_ifp(struct pf_state *s, struct pf_addr *saddr)
2920{
2921	struct pf_rule *r = s->rule.ptr;
2922	struct pf_src_node *sn = NULL;
2923
2924	s->rt_kif = NULL;
2925	if (!r->rt || r->rt == PF_FASTROUTE)
2926		return;
2927	switch (s->key[PF_SK_WIRE]->af) {
2928#ifdef INET
2929	case AF_INET:
2930		pf_map_addr(AF_INET, r, saddr, &s->rt_addr, NULL, &sn);
2931		s->rt_kif = r->rpool.cur->kif;
2932		break;
2933#endif /* INET */
2934#ifdef INET6
2935	case AF_INET6:
2936		pf_map_addr(AF_INET6, r, saddr, &s->rt_addr, NULL, &sn);
2937		s->rt_kif = r->rpool.cur->kif;
2938		break;
2939#endif /* INET6 */
2940	}
2941}
2942
2943static u_int32_t
2944pf_tcp_iss(struct pf_pdesc *pd)
2945{
2946	MD5_CTX ctx;
2947	u_int32_t digest[4];
2948
2949	if (V_pf_tcp_secret_init == 0) {
2950		read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
2951		MD5Init(&V_pf_tcp_secret_ctx);
2952		MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
2953		    sizeof(V_pf_tcp_secret));
2954		V_pf_tcp_secret_init = 1;
2955	}
2956
2957	ctx = V_pf_tcp_secret_ctx;
2958
2959	MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
2960	MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
2961	if (pd->af == AF_INET6) {
2962		MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
2963		MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
2964	} else {
2965		MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
2966		MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
2967	}
2968	MD5Final((u_char *)digest, &ctx);
2969	V_pf_tcp_iss_off += 4096;
2970#define	ISN_RANDOM_INCREMENT (4096 - 1)
2971	return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
2972	    V_pf_tcp_iss_off);
2973#undef	ISN_RANDOM_INCREMENT
2974}
2975
2976static int
2977pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
2978    struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
2979    struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
2980{
2981	struct pf_rule		*nr = NULL;
2982	struct pf_addr		* const saddr = pd->src;
2983	struct pf_addr		* const daddr = pd->dst;
2984	sa_family_t		 af = pd->af;
2985	struct pf_rule		*r, *a = NULL;
2986	struct pf_ruleset	*ruleset = NULL;
2987	struct pf_src_node	*nsn = NULL;
2988	struct tcphdr		*th = pd->hdr.tcp;
2989	struct pf_state_key	*sk = NULL, *nk = NULL;
2990	u_short			 reason;
2991	int			 rewrite = 0, hdrlen = 0;
2992	int			 tag = -1, rtableid = -1;
2993	int			 asd = 0;
2994	int			 match = 0;
2995	int			 state_icmp = 0;
2996	u_int16_t		 sport = 0, dport = 0;
2997	u_int16_t		 bproto_sum = 0, bip_sum = 0;
2998	u_int8_t		 icmptype = 0, icmpcode = 0;
2999	struct pf_anchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
3000
3001	PF_RULES_RASSERT();
3002
3003	if (inp != NULL) {
3004		INP_LOCK_ASSERT(inp);
3005		pd->lookup.uid = inp->inp_cred->cr_uid;
3006		pd->lookup.gid = inp->inp_cred->cr_groups[0];
3007		pd->lookup.done = 1;
3008	}
3009
3010	switch (pd->proto) {
3011	case IPPROTO_TCP:
3012		sport = th->th_sport;
3013		dport = th->th_dport;
3014		hdrlen = sizeof(*th);
3015		break;
3016	case IPPROTO_UDP:
3017		sport = pd->hdr.udp->uh_sport;
3018		dport = pd->hdr.udp->uh_dport;
3019		hdrlen = sizeof(*pd->hdr.udp);
3020		break;
3021#ifdef INET
3022	case IPPROTO_ICMP:
3023		if (pd->af != AF_INET)
3024			break;
3025		sport = dport = pd->hdr.icmp->icmp_id;
3026		hdrlen = sizeof(*pd->hdr.icmp);
3027		icmptype = pd->hdr.icmp->icmp_type;
3028		icmpcode = pd->hdr.icmp->icmp_code;
3029
3030		if (icmptype == ICMP_UNREACH ||
3031		    icmptype == ICMP_SOURCEQUENCH ||
3032		    icmptype == ICMP_REDIRECT ||
3033		    icmptype == ICMP_TIMXCEED ||
3034		    icmptype == ICMP_PARAMPROB)
3035			state_icmp++;
3036		break;
3037#endif /* INET */
3038#ifdef INET6
3039	case IPPROTO_ICMPV6:
3040		if (af != AF_INET6)
3041			break;
3042		sport = dport = pd->hdr.icmp6->icmp6_id;
3043		hdrlen = sizeof(*pd->hdr.icmp6);
3044		icmptype = pd->hdr.icmp6->icmp6_type;
3045		icmpcode = pd->hdr.icmp6->icmp6_code;
3046
3047		if (icmptype == ICMP6_DST_UNREACH ||
3048		    icmptype == ICMP6_PACKET_TOO_BIG ||
3049		    icmptype == ICMP6_TIME_EXCEEDED ||
3050		    icmptype == ICMP6_PARAM_PROB)
3051			state_icmp++;
3052		break;
3053#endif /* INET6 */
3054	default:
3055		sport = dport = hdrlen = 0;
3056		break;
3057	}
3058
3059	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3060
3061	/* check packet for BINAT/NAT/RDR */
3062	if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3063	    &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3064		KASSERT(sk != NULL, ("%s: null sk", __func__));
3065		KASSERT(nk != NULL, ("%s: null nk", __func__));
3066
3067		if (pd->ip_sum)
3068			bip_sum = *pd->ip_sum;
3069
3070		switch (pd->proto) {
3071		case IPPROTO_TCP:
3072			bproto_sum = th->th_sum;
3073			pd->proto_sum = &th->th_sum;
3074
3075			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3076			    nk->port[pd->sidx] != sport) {
3077				pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3078				    &th->th_sum, &nk->addr[pd->sidx],
3079				    nk->port[pd->sidx], 0, af);
3080				pd->sport = &th->th_sport;
3081				sport = th->th_sport;
3082			}
3083
3084			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3085			    nk->port[pd->didx] != dport) {
3086				pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3087				    &th->th_sum, &nk->addr[pd->didx],
3088				    nk->port[pd->didx], 0, af);
3089				dport = th->th_dport;
3090				pd->dport = &th->th_dport;
3091			}
3092			rewrite++;
3093			break;
3094		case IPPROTO_UDP:
3095			bproto_sum = pd->hdr.udp->uh_sum;
3096			pd->proto_sum = &pd->hdr.udp->uh_sum;
3097
3098			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3099			    nk->port[pd->sidx] != sport) {
3100				pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3101				    pd->ip_sum, &pd->hdr.udp->uh_sum,
3102				    &nk->addr[pd->sidx],
3103				    nk->port[pd->sidx], 1, af);
3104				sport = pd->hdr.udp->uh_sport;
3105				pd->sport = &pd->hdr.udp->uh_sport;
3106			}
3107
3108			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3109			    nk->port[pd->didx] != dport) {
3110				pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3111				    pd->ip_sum, &pd->hdr.udp->uh_sum,
3112				    &nk->addr[pd->didx],
3113				    nk->port[pd->didx], 1, af);
3114				dport = pd->hdr.udp->uh_dport;
3115				pd->dport = &pd->hdr.udp->uh_dport;
3116			}
3117			rewrite++;
3118			break;
3119#ifdef INET
3120		case IPPROTO_ICMP:
3121			nk->port[0] = nk->port[1];
3122			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3123				pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3124				    nk->addr[pd->sidx].v4.s_addr, 0);
3125
3126			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3127				pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3128				    nk->addr[pd->didx].v4.s_addr, 0);
3129
3130			if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3131				pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3132				    pd->hdr.icmp->icmp_cksum, sport,
3133				    nk->port[1], 0);
3134				pd->hdr.icmp->icmp_id = nk->port[1];
3135				pd->sport = &pd->hdr.icmp->icmp_id;
3136			}
3137			m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3138			break;
3139#endif /* INET */
3140#ifdef INET6
3141		case IPPROTO_ICMPV6:
3142			nk->port[0] = nk->port[1];
3143			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3144				pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3145				    &nk->addr[pd->sidx], 0);
3146
3147			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3148				pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3149				    &nk->addr[pd->didx], 0);
3150			rewrite++;
3151			break;
3152#endif /* INET */
3153		default:
3154			switch (af) {
3155#ifdef INET
3156			case AF_INET:
3157				if (PF_ANEQ(saddr,
3158				    &nk->addr[pd->sidx], AF_INET))
3159					pf_change_a(&saddr->v4.s_addr,
3160					    pd->ip_sum,
3161					    nk->addr[pd->sidx].v4.s_addr, 0);
3162
3163				if (PF_ANEQ(daddr,
3164				    &nk->addr[pd->didx], AF_INET))
3165					pf_change_a(&daddr->v4.s_addr,
3166					    pd->ip_sum,
3167					    nk->addr[pd->didx].v4.s_addr, 0);
3168				break;
3169#endif /* INET */
3170#ifdef INET6
3171			case AF_INET6:
3172				if (PF_ANEQ(saddr,
3173				    &nk->addr[pd->sidx], AF_INET6))
3174					PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3175
3176				if (PF_ANEQ(daddr,
3177				    &nk->addr[pd->didx], AF_INET6))
3178					PF_ACPY(saddr, &nk->addr[pd->didx], af);
3179				break;
3180#endif /* INET */
3181			}
3182			break;
3183		}
3184		if (nr->natpass)
3185			r = NULL;
3186		pd->nat_rule = nr;
3187	}
3188
3189	while (r != NULL) {
3190		r->evaluations++;
3191		if (pfi_kif_match(r->kif, kif) == r->ifnot)
3192			r = r->skip[PF_SKIP_IFP].ptr;
3193		else if (r->direction && r->direction != direction)
3194			r = r->skip[PF_SKIP_DIR].ptr;
3195		else if (r->af && r->af != af)
3196			r = r->skip[PF_SKIP_AF].ptr;
3197		else if (r->proto && r->proto != pd->proto)
3198			r = r->skip[PF_SKIP_PROTO].ptr;
3199		else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3200		    r->src.neg, kif, M_GETFIB(m)))
3201			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3202		/* tcp/udp only. port_op always 0 in other cases */
3203		else if (r->src.port_op && !pf_match_port(r->src.port_op,
3204		    r->src.port[0], r->src.port[1], sport))
3205			r = r->skip[PF_SKIP_SRC_PORT].ptr;
3206		else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3207		    r->dst.neg, NULL, M_GETFIB(m)))
3208			r = r->skip[PF_SKIP_DST_ADDR].ptr;
3209		/* tcp/udp only. port_op always 0 in other cases */
3210		else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3211		    r->dst.port[0], r->dst.port[1], dport))
3212			r = r->skip[PF_SKIP_DST_PORT].ptr;
3213		/* icmp only. type always 0 in other cases */
3214		else if (r->type && r->type != icmptype + 1)
3215			r = TAILQ_NEXT(r, entries);
3216		/* icmp only. type always 0 in other cases */
3217		else if (r->code && r->code != icmpcode + 1)
3218			r = TAILQ_NEXT(r, entries);
3219		else if (r->tos && !(r->tos == pd->tos))
3220			r = TAILQ_NEXT(r, entries);
3221		else if (r->rule_flag & PFRULE_FRAGMENT)
3222			r = TAILQ_NEXT(r, entries);
3223		else if (pd->proto == IPPROTO_TCP &&
3224		    (r->flagset & th->th_flags) != r->flags)
3225			r = TAILQ_NEXT(r, entries);
3226		/* tcp/udp only. uid.op always 0 in other cases */
3227		else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3228		    pf_socket_lookup(direction, pd, m), 1)) &&
3229		    !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3230		    pd->lookup.uid))
3231			r = TAILQ_NEXT(r, entries);
3232		/* tcp/udp only. gid.op always 0 in other cases */
3233		else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3234		    pf_socket_lookup(direction, pd, m), 1)) &&
3235		    !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3236		    pd->lookup.gid))
3237			r = TAILQ_NEXT(r, entries);
3238		else if (r->prob &&
3239		    r->prob <= arc4random())
3240			r = TAILQ_NEXT(r, entries);
3241		else if (r->match_tag && !pf_match_tag(m, r, &tag,
3242		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
3243			r = TAILQ_NEXT(r, entries);
3244		else if (r->os_fingerprint != PF_OSFP_ANY &&
3245		    (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3246		    pf_osfp_fingerprint(pd, m, off, th),
3247		    r->os_fingerprint)))
3248			r = TAILQ_NEXT(r, entries);
3249		else {
3250			if (r->tag)
3251				tag = r->tag;
3252			if (r->rtableid >= 0)
3253				rtableid = r->rtableid;
3254			if (r->anchor == NULL) {
3255				match = 1;
3256				*rm = r;
3257				*am = a;
3258				*rsm = ruleset;
3259				if ((*rm)->quick)
3260					break;
3261				r = TAILQ_NEXT(r, entries);
3262			} else
3263				pf_step_into_anchor(anchor_stack, &asd,
3264				    &ruleset, PF_RULESET_FILTER, &r, &a,
3265				    &match);
3266		}
3267		if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3268		    &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3269			break;
3270	}
3271	r = *rm;
3272	a = *am;
3273	ruleset = *rsm;
3274
3275	REASON_SET(&reason, PFRES_MATCH);
3276
3277	if (r->log || (nr != NULL && nr->log)) {
3278		if (rewrite)
3279			m_copyback(m, off, hdrlen, pd->hdr.any);
3280		PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3281		    ruleset, pd, 1);
3282	}
3283
3284	if ((r->action == PF_DROP) &&
3285	    ((r->rule_flag & PFRULE_RETURNRST) ||
3286	    (r->rule_flag & PFRULE_RETURNICMP) ||
3287	    (r->rule_flag & PFRULE_RETURN))) {
3288		/* undo NAT changes, if they have taken place */
3289		if (nr != NULL) {
3290			PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3291			PF_ACPY(daddr, &sk->addr[pd->didx], af);
3292			if (pd->sport)
3293				*pd->sport = sk->port[pd->sidx];
3294			if (pd->dport)
3295				*pd->dport = sk->port[pd->didx];
3296			if (pd->proto_sum)
3297				*pd->proto_sum = bproto_sum;
3298			if (pd->ip_sum)
3299				*pd->ip_sum = bip_sum;
3300			m_copyback(m, off, hdrlen, pd->hdr.any);
3301		}
3302		if (pd->proto == IPPROTO_TCP &&
3303		    ((r->rule_flag & PFRULE_RETURNRST) ||
3304		    (r->rule_flag & PFRULE_RETURN)) &&
3305		    !(th->th_flags & TH_RST)) {
3306			u_int32_t	 ack = ntohl(th->th_seq) + pd->p_len;
3307			int		 len = 0;
3308#ifdef INET
3309			struct ip	*h4;
3310#endif
3311#ifdef INET6
3312			struct ip6_hdr	*h6;
3313#endif
3314
3315			switch (af) {
3316#ifdef INET
3317			case AF_INET:
3318				h4 = mtod(m, struct ip *);
3319				len = ntohs(h4->ip_len) - off;
3320				break;
3321#endif
3322#ifdef INET6
3323			case AF_INET6:
3324				h6 = mtod(m, struct ip6_hdr *);
3325				len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3326				break;
3327#endif
3328			}
3329
3330			if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3331				REASON_SET(&reason, PFRES_PROTCKSUM);
3332			else {
3333				if (th->th_flags & TH_SYN)
3334					ack++;
3335				if (th->th_flags & TH_FIN)
3336					ack++;
3337				pf_send_tcp(m, r, af, pd->dst,
3338				    pd->src, th->th_dport, th->th_sport,
3339				    ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3340				    r->return_ttl, 1, 0, kif->pfik_ifp);
3341			}
3342		} else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3343		    r->return_icmp)
3344			pf_send_icmp(m, r->return_icmp >> 8,
3345			    r->return_icmp & 255, af, r);
3346		else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3347		    r->return_icmp6)
3348			pf_send_icmp(m, r->return_icmp6 >> 8,
3349			    r->return_icmp6 & 255, af, r);
3350	}
3351
3352	if (r->action == PF_DROP)
3353		goto cleanup;
3354
3355	if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3356		REASON_SET(&reason, PFRES_MEMORY);
3357		goto cleanup;
3358	}
3359	if (rtableid >= 0)
3360		M_SETFIB(m, rtableid);
3361
3362	if (!state_icmp && (r->keep_state || nr != NULL ||
3363	    (pd->flags & PFDESC_TCP_NORM))) {
3364		int action;
3365		action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3366		    sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3367		    hdrlen);
3368		if (action != PF_PASS)
3369			return (action);
3370	} else {
3371		if (sk != NULL)
3372			uma_zfree(V_pf_state_key_z, sk);
3373		if (nk != NULL)
3374			uma_zfree(V_pf_state_key_z, nk);
3375	}
3376
3377	/* copy back packet headers if we performed NAT operations */
3378	if (rewrite)
3379		m_copyback(m, off, hdrlen, pd->hdr.any);
3380
3381	if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3382	    direction == PF_OUT &&
3383	    pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3384		/*
3385		 * We want the state created, but we dont
3386		 * want to send this in case a partner
3387		 * firewall has to know about it to allow
3388		 * replies through it.
3389		 */
3390		return (PF_DEFER);
3391
3392	return (PF_PASS);
3393
3394cleanup:
3395	if (sk != NULL)
3396		uma_zfree(V_pf_state_key_z, sk);
3397	if (nk != NULL)
3398		uma_zfree(V_pf_state_key_z, nk);
3399	return (PF_DROP);
3400}
3401
3402static int
3403pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3404    struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3405    struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3406    u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3407    int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3408{
3409	struct pf_state		*s = NULL;
3410	struct pf_src_node	*sn = NULL;
3411	struct tcphdr		*th = pd->hdr.tcp;
3412	u_int16_t		 mss = V_tcp_mssdflt;
3413	u_short			 reason;
3414
3415	/* check maximums */
3416	if (r->max_states && (r->states_cur >= r->max_states)) {
3417		V_pf_status.lcounters[LCNT_STATES]++;
3418		REASON_SET(&reason, PFRES_MAXSTATES);
3419		return (PF_DROP);
3420	}
3421	/* src node for filter rule */
3422	if ((r->rule_flag & PFRULE_SRCTRACK ||
3423	    r->rpool.opts & PF_POOL_STICKYADDR) &&
3424	    pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3425		REASON_SET(&reason, PFRES_SRCLIMIT);
3426		goto csfailed;
3427	}
3428	/* src node for translation rule */
3429	if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3430	    pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3431		REASON_SET(&reason, PFRES_SRCLIMIT);
3432		goto csfailed;
3433	}
3434	s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3435	if (s == NULL) {
3436		REASON_SET(&reason, PFRES_MEMORY);
3437		goto csfailed;
3438	}
3439	s->rule.ptr = r;
3440	s->nat_rule.ptr = nr;
3441	s->anchor.ptr = a;
3442	STATE_INC_COUNTERS(s);
3443	if (r->allow_opts)
3444		s->state_flags |= PFSTATE_ALLOWOPTS;
3445	if (r->rule_flag & PFRULE_STATESLOPPY)
3446		s->state_flags |= PFSTATE_SLOPPY;
3447	s->log = r->log & PF_LOG_ALL;
3448	s->sync_state = PFSYNC_S_NONE;
3449	if (nr != NULL)
3450		s->log |= nr->log & PF_LOG_ALL;
3451	switch (pd->proto) {
3452	case IPPROTO_TCP:
3453		s->src.seqlo = ntohl(th->th_seq);
3454		s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3455		if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3456		    r->keep_state == PF_STATE_MODULATE) {
3457			/* Generate sequence number modulator */
3458			if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3459			    0)
3460				s->src.seqdiff = 1;
3461			pf_change_a(&th->th_seq, &th->th_sum,
3462			    htonl(s->src.seqlo + s->src.seqdiff), 0);
3463			*rewrite = 1;
3464		} else
3465			s->src.seqdiff = 0;
3466		if (th->th_flags & TH_SYN) {
3467			s->src.seqhi++;
3468			s->src.wscale = pf_get_wscale(m, off,
3469			    th->th_off, pd->af);
3470		}
3471		s->src.max_win = MAX(ntohs(th->th_win), 1);
3472		if (s->src.wscale & PF_WSCALE_MASK) {
3473			/* Remove scale factor from initial window */
3474			int win = s->src.max_win;
3475			win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3476			s->src.max_win = (win - 1) >>
3477			    (s->src.wscale & PF_WSCALE_MASK);
3478		}
3479		if (th->th_flags & TH_FIN)
3480			s->src.seqhi++;
3481		s->dst.seqhi = 1;
3482		s->dst.max_win = 1;
3483		s->src.state = TCPS_SYN_SENT;
3484		s->dst.state = TCPS_CLOSED;
3485		s->timeout = PFTM_TCP_FIRST_PACKET;
3486		break;
3487	case IPPROTO_UDP:
3488		s->src.state = PFUDPS_SINGLE;
3489		s->dst.state = PFUDPS_NO_TRAFFIC;
3490		s->timeout = PFTM_UDP_FIRST_PACKET;
3491		break;
3492	case IPPROTO_ICMP:
3493#ifdef INET6
3494	case IPPROTO_ICMPV6:
3495#endif
3496		s->timeout = PFTM_ICMP_FIRST_PACKET;
3497		break;
3498	default:
3499		s->src.state = PFOTHERS_SINGLE;
3500		s->dst.state = PFOTHERS_NO_TRAFFIC;
3501		s->timeout = PFTM_OTHER_FIRST_PACKET;
3502	}
3503
3504	s->creation = time_uptime;
3505	s->expire = time_uptime;
3506
3507	if (sn != NULL) {
3508		s->src_node = sn;
3509		s->src_node->states++;
3510	}
3511	if (nsn != NULL) {
3512		/* XXX We only modify one side for now. */
3513		PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3514		s->nat_src_node = nsn;
3515		s->nat_src_node->states++;
3516	}
3517	if (pd->proto == IPPROTO_TCP) {
3518		if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3519		    off, pd, th, &s->src, &s->dst)) {
3520			REASON_SET(&reason, PFRES_MEMORY);
3521			pf_src_tree_remove_state(s);
3522			STATE_DEC_COUNTERS(s);
3523			uma_zfree(V_pf_state_z, s);
3524			return (PF_DROP);
3525		}
3526		if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3527		    pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3528		    &s->src, &s->dst, rewrite)) {
3529			/* This really shouldn't happen!!! */
3530			DPFPRINTF(PF_DEBUG_URGENT,
3531			    ("pf_normalize_tcp_stateful failed on first pkt"));
3532			pf_normalize_tcp_cleanup(s);
3533			pf_src_tree_remove_state(s);
3534			STATE_DEC_COUNTERS(s);
3535			uma_zfree(V_pf_state_z, s);
3536			return (PF_DROP);
3537		}
3538	}
3539	s->direction = pd->dir;
3540
3541	/*
3542	 * sk/nk could already been setup by pf_get_translation().
3543	 */
3544	if (nr == NULL) {
3545		KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3546		    __func__, nr, sk, nk));
3547		sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3548		if (sk == NULL)
3549			goto csfailed;
3550		nk = sk;
3551	} else
3552		KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3553		    __func__, nr, sk, nk));
3554
3555	/* Swap sk/nk for PF_OUT. */
3556	if (pf_state_insert(BOUND_IFACE(r, kif),
3557	    (pd->dir == PF_IN) ? sk : nk,
3558	    (pd->dir == PF_IN) ? nk : sk, s)) {
3559		if (pd->proto == IPPROTO_TCP)
3560			pf_normalize_tcp_cleanup(s);
3561		REASON_SET(&reason, PFRES_STATEINS);
3562		pf_src_tree_remove_state(s);
3563		STATE_DEC_COUNTERS(s);
3564		uma_zfree(V_pf_state_z, s);
3565		return (PF_DROP);
3566	} else
3567		*sm = s;
3568
3569	pf_set_rt_ifp(s, pd->src);	/* needs s->state_key set */
3570	if (tag > 0)
3571		s->tag = tag;
3572	if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3573	    TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3574		s->src.state = PF_TCPS_PROXY_SRC;
3575		/* undo NAT changes, if they have taken place */
3576		if (nr != NULL) {
3577			struct pf_state_key *skt = s->key[PF_SK_WIRE];
3578			if (pd->dir == PF_OUT)
3579				skt = s->key[PF_SK_STACK];
3580			PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3581			PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3582			if (pd->sport)
3583				*pd->sport = skt->port[pd->sidx];
3584			if (pd->dport)
3585				*pd->dport = skt->port[pd->didx];
3586			if (pd->proto_sum)
3587				*pd->proto_sum = bproto_sum;
3588			if (pd->ip_sum)
3589				*pd->ip_sum = bip_sum;
3590			m_copyback(m, off, hdrlen, pd->hdr.any);
3591		}
3592		s->src.seqhi = htonl(arc4random());
3593		/* Find mss option */
3594		int rtid = M_GETFIB(m);
3595		mss = pf_get_mss(m, off, th->th_off, pd->af);
3596		mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3597		mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3598		s->src.mss = mss;
3599		pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3600		    th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3601		    TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3602		REASON_SET(&reason, PFRES_SYNPROXY);
3603		return (PF_SYNPROXY_DROP);
3604	}
3605
3606	return (PF_PASS);
3607
3608csfailed:
3609	if (sk != NULL)
3610		uma_zfree(V_pf_state_key_z, sk);
3611	if (nk != NULL)
3612		uma_zfree(V_pf_state_key_z, nk);
3613
3614	if (sn != NULL && sn->states == 0 && sn->expire == 0)
3615		pf_remove_src_node(sn);
3616
3617	if (nsn != sn && nsn != NULL && nsn->states == 0 && nsn->expire == 0)
3618		pf_remove_src_node(nsn);
3619
3620	return (PF_DROP);
3621}
3622
3623static int
3624pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3625    struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3626    struct pf_ruleset **rsm)
3627{
3628	struct pf_rule		*r, *a = NULL;
3629	struct pf_ruleset	*ruleset = NULL;
3630	sa_family_t		 af = pd->af;
3631	u_short			 reason;
3632	int			 tag = -1;
3633	int			 asd = 0;
3634	int			 match = 0;
3635	struct pf_anchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
3636
3637	PF_RULES_RASSERT();
3638
3639	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3640	while (r != NULL) {
3641		r->evaluations++;
3642		if (pfi_kif_match(r->kif, kif) == r->ifnot)
3643			r = r->skip[PF_SKIP_IFP].ptr;
3644		else if (r->direction && r->direction != direction)
3645			r = r->skip[PF_SKIP_DIR].ptr;
3646		else if (r->af && r->af != af)
3647			r = r->skip[PF_SKIP_AF].ptr;
3648		else if (r->proto && r->proto != pd->proto)
3649			r = r->skip[PF_SKIP_PROTO].ptr;
3650		else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3651		    r->src.neg, kif, M_GETFIB(m)))
3652			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3653		else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3654		    r->dst.neg, NULL, M_GETFIB(m)))
3655			r = r->skip[PF_SKIP_DST_ADDR].ptr;
3656		else if (r->tos && !(r->tos == pd->tos))
3657			r = TAILQ_NEXT(r, entries);
3658		else if (r->os_fingerprint != PF_OSFP_ANY)
3659			r = TAILQ_NEXT(r, entries);
3660		else if (pd->proto == IPPROTO_UDP &&
3661		    (r->src.port_op || r->dst.port_op))
3662			r = TAILQ_NEXT(r, entries);
3663		else if (pd->proto == IPPROTO_TCP &&
3664		    (r->src.port_op || r->dst.port_op || r->flagset))
3665			r = TAILQ_NEXT(r, entries);
3666		else if ((pd->proto == IPPROTO_ICMP ||
3667		    pd->proto == IPPROTO_ICMPV6) &&
3668		    (r->type || r->code))
3669			r = TAILQ_NEXT(r, entries);
3670		else if (r->prob && r->prob <=
3671		    (arc4random() % (UINT_MAX - 1) + 1))
3672			r = TAILQ_NEXT(r, entries);
3673		else if (r->match_tag && !pf_match_tag(m, r, &tag,
3674		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
3675			r = TAILQ_NEXT(r, entries);
3676		else {
3677			if (r->anchor == NULL) {
3678				match = 1;
3679				*rm = r;
3680				*am = a;
3681				*rsm = ruleset;
3682				if ((*rm)->quick)
3683					break;
3684				r = TAILQ_NEXT(r, entries);
3685			} else
3686				pf_step_into_anchor(anchor_stack, &asd,
3687				    &ruleset, PF_RULESET_FILTER, &r, &a,
3688				    &match);
3689		}
3690		if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3691		    &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3692			break;
3693	}
3694	r = *rm;
3695	a = *am;
3696	ruleset = *rsm;
3697
3698	REASON_SET(&reason, PFRES_MATCH);
3699
3700	if (r->log)
3701		PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3702		    1);
3703
3704	if (r->action != PF_PASS)
3705		return (PF_DROP);
3706
3707	if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3708		REASON_SET(&reason, PFRES_MEMORY);
3709		return (PF_DROP);
3710	}
3711
3712	return (PF_PASS);
3713}
3714
3715static int
3716pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3717	struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3718	struct pf_pdesc *pd, u_short *reason, int *copyback)
3719{
3720	struct tcphdr		*th = pd->hdr.tcp;
3721	u_int16_t		 win = ntohs(th->th_win);
3722	u_int32_t		 ack, end, seq, orig_seq;
3723	u_int8_t		 sws, dws;
3724	int			 ackskew;
3725
3726	if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3727		sws = src->wscale & PF_WSCALE_MASK;
3728		dws = dst->wscale & PF_WSCALE_MASK;
3729	} else
3730		sws = dws = 0;
3731
3732	/*
3733	 * Sequence tracking algorithm from Guido van Rooij's paper:
3734	 *   http://www.madison-gurkha.com/publications/tcp_filtering/
3735	 *	tcp_filtering.ps
3736	 */
3737
3738	orig_seq = seq = ntohl(th->th_seq);
3739	if (src->seqlo == 0) {
3740		/* First packet from this end. Set its state */
3741
3742		if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3743		    src->scrub == NULL) {
3744			if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3745				REASON_SET(reason, PFRES_MEMORY);
3746				return (PF_DROP);
3747			}
3748		}
3749
3750		/* Deferred generation of sequence number modulator */
3751		if (dst->seqdiff && !src->seqdiff) {
3752			/* use random iss for the TCP server */
3753			while ((src->seqdiff = arc4random() - seq) == 0)
3754				;
3755			ack = ntohl(th->th_ack) - dst->seqdiff;
3756			pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3757			    src->seqdiff), 0);
3758			pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3759			*copyback = 1;
3760		} else {
3761			ack = ntohl(th->th_ack);
3762		}
3763
3764		end = seq + pd->p_len;
3765		if (th->th_flags & TH_SYN) {
3766			end++;
3767			if (dst->wscale & PF_WSCALE_FLAG) {
3768				src->wscale = pf_get_wscale(m, off, th->th_off,
3769				    pd->af);
3770				if (src->wscale & PF_WSCALE_FLAG) {
3771					/* Remove scale factor from initial
3772					 * window */
3773					sws = src->wscale & PF_WSCALE_MASK;
3774					win = ((u_int32_t)win + (1 << sws) - 1)
3775					    >> sws;
3776					dws = dst->wscale & PF_WSCALE_MASK;
3777				} else {
3778					/* fixup other window */
3779					dst->max_win <<= dst->wscale &
3780					    PF_WSCALE_MASK;
3781					/* in case of a retrans SYN|ACK */
3782					dst->wscale = 0;
3783				}
3784			}
3785		}
3786		if (th->th_flags & TH_FIN)
3787			end++;
3788
3789		src->seqlo = seq;
3790		if (src->state < TCPS_SYN_SENT)
3791			src->state = TCPS_SYN_SENT;
3792
3793		/*
3794		 * May need to slide the window (seqhi may have been set by
3795		 * the crappy stack check or if we picked up the connection
3796		 * after establishment)
3797		 */
3798		if (src->seqhi == 1 ||
3799		    SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3800			src->seqhi = end + MAX(1, dst->max_win << dws);
3801		if (win > src->max_win)
3802			src->max_win = win;
3803
3804	} else {
3805		ack = ntohl(th->th_ack) - dst->seqdiff;
3806		if (src->seqdiff) {
3807			/* Modulate sequence numbers */
3808			pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3809			    src->seqdiff), 0);
3810			pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3811			*copyback = 1;
3812		}
3813		end = seq + pd->p_len;
3814		if (th->th_flags & TH_SYN)
3815			end++;
3816		if (th->th_flags & TH_FIN)
3817			end++;
3818	}
3819
3820	if ((th->th_flags & TH_ACK) == 0) {
3821		/* Let it pass through the ack skew check */
3822		ack = dst->seqlo;
3823	} else if ((ack == 0 &&
3824	    (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
3825	    /* broken tcp stacks do not set ack */
3826	    (dst->state < TCPS_SYN_SENT)) {
3827		/*
3828		 * Many stacks (ours included) will set the ACK number in an
3829		 * FIN|ACK if the SYN times out -- no sequence to ACK.
3830		 */
3831		ack = dst->seqlo;
3832	}
3833
3834	if (seq == end) {
3835		/* Ease sequencing restrictions on no data packets */
3836		seq = src->seqlo;
3837		end = seq;
3838	}
3839
3840	ackskew = dst->seqlo - ack;
3841
3842
3843	/*
3844	 * Need to demodulate the sequence numbers in any TCP SACK options
3845	 * (Selective ACK). We could optionally validate the SACK values
3846	 * against the current ACK window, either forwards or backwards, but
3847	 * I'm not confident that SACK has been implemented properly
3848	 * everywhere. It wouldn't surprise me if several stacks accidently
3849	 * SACK too far backwards of previously ACKed data. There really aren't
3850	 * any security implications of bad SACKing unless the target stack
3851	 * doesn't validate the option length correctly. Someone trying to
3852	 * spoof into a TCP connection won't bother blindly sending SACK
3853	 * options anyway.
3854	 */
3855	if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
3856		if (pf_modulate_sack(m, off, pd, th, dst))
3857			*copyback = 1;
3858	}
3859
3860
3861#define	MAXACKWINDOW (0xffff + 1500)	/* 1500 is an arbitrary fudge factor */
3862	if (SEQ_GEQ(src->seqhi, end) &&
3863	    /* Last octet inside other's window space */
3864	    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
3865	    /* Retrans: not more than one window back */
3866	    (ackskew >= -MAXACKWINDOW) &&
3867	    /* Acking not more than one reassembled fragment backwards */
3868	    (ackskew <= (MAXACKWINDOW << sws)) &&
3869	    /* Acking not more than one window forward */
3870	    ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
3871	    (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
3872	    (pd->flags & PFDESC_IP_REAS) == 0)) {
3873	    /* Require an exact/+1 sequence match on resets when possible */
3874
3875		if (dst->scrub || src->scrub) {
3876			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
3877			    *state, src, dst, copyback))
3878				return (PF_DROP);
3879		}
3880
3881		/* update max window */
3882		if (src->max_win < win)
3883			src->max_win = win;
3884		/* synchronize sequencing */
3885		if (SEQ_GT(end, src->seqlo))
3886			src->seqlo = end;
3887		/* slide the window of what the other end can send */
3888		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
3889			dst->seqhi = ack + MAX((win << sws), 1);
3890
3891
3892		/* update states */
3893		if (th->th_flags & TH_SYN)
3894			if (src->state < TCPS_SYN_SENT)
3895				src->state = TCPS_SYN_SENT;
3896		if (th->th_flags & TH_FIN)
3897			if (src->state < TCPS_CLOSING)
3898				src->state = TCPS_CLOSING;
3899		if (th->th_flags & TH_ACK) {
3900			if (dst->state == TCPS_SYN_SENT) {
3901				dst->state = TCPS_ESTABLISHED;
3902				if (src->state == TCPS_ESTABLISHED &&
3903				    (*state)->src_node != NULL &&
3904				    pf_src_connlimit(state)) {
3905					REASON_SET(reason, PFRES_SRCLIMIT);
3906					return (PF_DROP);
3907				}
3908			} else if (dst->state == TCPS_CLOSING)
3909				dst->state = TCPS_FIN_WAIT_2;
3910		}
3911		if (th->th_flags & TH_RST)
3912			src->state = dst->state = TCPS_TIME_WAIT;
3913
3914		/* update expire time */
3915		(*state)->expire = time_uptime;
3916		if (src->state >= TCPS_FIN_WAIT_2 &&
3917		    dst->state >= TCPS_FIN_WAIT_2)
3918			(*state)->timeout = PFTM_TCP_CLOSED;
3919		else if (src->state >= TCPS_CLOSING &&
3920		    dst->state >= TCPS_CLOSING)
3921			(*state)->timeout = PFTM_TCP_FIN_WAIT;
3922		else if (src->state < TCPS_ESTABLISHED ||
3923		    dst->state < TCPS_ESTABLISHED)
3924			(*state)->timeout = PFTM_TCP_OPENING;
3925		else if (src->state >= TCPS_CLOSING ||
3926		    dst->state >= TCPS_CLOSING)
3927			(*state)->timeout = PFTM_TCP_CLOSING;
3928		else
3929			(*state)->timeout = PFTM_TCP_ESTABLISHED;
3930
3931		/* Fall through to PASS packet */
3932
3933	} else if ((dst->state < TCPS_SYN_SENT ||
3934		dst->state >= TCPS_FIN_WAIT_2 ||
3935		src->state >= TCPS_FIN_WAIT_2) &&
3936	    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
3937	    /* Within a window forward of the originating packet */
3938	    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
3939	    /* Within a window backward of the originating packet */
3940
3941		/*
3942		 * This currently handles three situations:
3943		 *  1) Stupid stacks will shotgun SYNs before their peer
3944		 *     replies.
3945		 *  2) When PF catches an already established stream (the
3946		 *     firewall rebooted, the state table was flushed, routes
3947		 *     changed...)
3948		 *  3) Packets get funky immediately after the connection
3949		 *     closes (this should catch Solaris spurious ACK|FINs
3950		 *     that web servers like to spew after a close)
3951		 *
3952		 * This must be a little more careful than the above code
3953		 * since packet floods will also be caught here. We don't
3954		 * update the TTL here to mitigate the damage of a packet
3955		 * flood and so the same code can handle awkward establishment
3956		 * and a loosened connection close.
3957		 * In the establishment case, a correct peer response will
3958		 * validate the connection, go through the normal state code
3959		 * and keep updating the state TTL.
3960		 */
3961
3962		if (V_pf_status.debug >= PF_DEBUG_MISC) {
3963			printf("pf: loose state match: ");
3964			pf_print_state(*state);
3965			pf_print_flags(th->th_flags);
3966			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
3967			    "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
3968			    pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
3969			    (unsigned long long)(*state)->packets[1],
3970			    pd->dir == PF_IN ? "in" : "out",
3971			    pd->dir == (*state)->direction ? "fwd" : "rev");
3972		}
3973
3974		if (dst->scrub || src->scrub) {
3975			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
3976			    *state, src, dst, copyback))
3977				return (PF_DROP);
3978		}
3979
3980		/* update max window */
3981		if (src->max_win < win)
3982			src->max_win = win;
3983		/* synchronize sequencing */
3984		if (SEQ_GT(end, src->seqlo))
3985			src->seqlo = end;
3986		/* slide the window of what the other end can send */
3987		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
3988			dst->seqhi = ack + MAX((win << sws), 1);
3989
3990		/*
3991		 * Cannot set dst->seqhi here since this could be a shotgunned
3992		 * SYN and not an already established connection.
3993		 */
3994
3995		if (th->th_flags & TH_FIN)
3996			if (src->state < TCPS_CLOSING)
3997				src->state = TCPS_CLOSING;
3998		if (th->th_flags & TH_RST)
3999			src->state = dst->state = TCPS_TIME_WAIT;
4000
4001		/* Fall through to PASS packet */
4002
4003	} else {
4004		if ((*state)->dst.state == TCPS_SYN_SENT &&
4005		    (*state)->src.state == TCPS_SYN_SENT) {
4006			/* Send RST for state mismatches during handshake */
4007			if (!(th->th_flags & TH_RST))
4008				pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4009				    pd->dst, pd->src, th->th_dport,
4010				    th->th_sport, ntohl(th->th_ack), 0,
4011				    TH_RST, 0, 0,
4012				    (*state)->rule.ptr->return_ttl, 1, 0,
4013				    kif->pfik_ifp);
4014			src->seqlo = 0;
4015			src->seqhi = 1;
4016			src->max_win = 1;
4017		} else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4018			printf("pf: BAD state: ");
4019			pf_print_state(*state);
4020			pf_print_flags(th->th_flags);
4021			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4022			    "pkts=%llu:%llu dir=%s,%s\n",
4023			    seq, orig_seq, ack, pd->p_len, ackskew,
4024			    (unsigned long long)(*state)->packets[0],
4025			    (unsigned long long)(*state)->packets[1],
4026			    pd->dir == PF_IN ? "in" : "out",
4027			    pd->dir == (*state)->direction ? "fwd" : "rev");
4028			printf("pf: State failure on: %c %c %c %c | %c %c\n",
4029			    SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4030			    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4031			    ' ': '2',
4032			    (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4033			    (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4034			    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4035			    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4036		}
4037		REASON_SET(reason, PFRES_BADSTATE);
4038		return (PF_DROP);
4039	}
4040
4041	return (PF_PASS);
4042}
4043
4044static int
4045pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4046	struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4047{
4048	struct tcphdr		*th = pd->hdr.tcp;
4049
4050	if (th->th_flags & TH_SYN)
4051		if (src->state < TCPS_SYN_SENT)
4052			src->state = TCPS_SYN_SENT;
4053	if (th->th_flags & TH_FIN)
4054		if (src->state < TCPS_CLOSING)
4055			src->state = TCPS_CLOSING;
4056	if (th->th_flags & TH_ACK) {
4057		if (dst->state == TCPS_SYN_SENT) {
4058			dst->state = TCPS_ESTABLISHED;
4059			if (src->state == TCPS_ESTABLISHED &&
4060			    (*state)->src_node != NULL &&
4061			    pf_src_connlimit(state)) {
4062				REASON_SET(reason, PFRES_SRCLIMIT);
4063				return (PF_DROP);
4064			}
4065		} else if (dst->state == TCPS_CLOSING) {
4066			dst->state = TCPS_FIN_WAIT_2;
4067		} else if (src->state == TCPS_SYN_SENT &&
4068		    dst->state < TCPS_SYN_SENT) {
4069			/*
4070			 * Handle a special sloppy case where we only see one
4071			 * half of the connection. If there is a ACK after
4072			 * the initial SYN without ever seeing a packet from
4073			 * the destination, set the connection to established.
4074			 */
4075			dst->state = src->state = TCPS_ESTABLISHED;
4076			if ((*state)->src_node != NULL &&
4077			    pf_src_connlimit(state)) {
4078				REASON_SET(reason, PFRES_SRCLIMIT);
4079				return (PF_DROP);
4080			}
4081		} else if (src->state == TCPS_CLOSING &&
4082		    dst->state == TCPS_ESTABLISHED &&
4083		    dst->seqlo == 0) {
4084			/*
4085			 * Handle the closing of half connections where we
4086			 * don't see the full bidirectional FIN/ACK+ACK
4087			 * handshake.
4088			 */
4089			dst->state = TCPS_CLOSING;
4090		}
4091	}
4092	if (th->th_flags & TH_RST)
4093		src->state = dst->state = TCPS_TIME_WAIT;
4094
4095	/* update expire time */
4096	(*state)->expire = time_uptime;
4097	if (src->state >= TCPS_FIN_WAIT_2 &&
4098	    dst->state >= TCPS_FIN_WAIT_2)
4099		(*state)->timeout = PFTM_TCP_CLOSED;
4100	else if (src->state >= TCPS_CLOSING &&
4101	    dst->state >= TCPS_CLOSING)
4102		(*state)->timeout = PFTM_TCP_FIN_WAIT;
4103	else if (src->state < TCPS_ESTABLISHED ||
4104	    dst->state < TCPS_ESTABLISHED)
4105		(*state)->timeout = PFTM_TCP_OPENING;
4106	else if (src->state >= TCPS_CLOSING ||
4107	    dst->state >= TCPS_CLOSING)
4108		(*state)->timeout = PFTM_TCP_CLOSING;
4109	else
4110		(*state)->timeout = PFTM_TCP_ESTABLISHED;
4111
4112	return (PF_PASS);
4113}
4114
4115static int
4116pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4117    struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4118    u_short *reason)
4119{
4120	struct pf_state_key_cmp	 key;
4121	struct tcphdr		*th = pd->hdr.tcp;
4122	int			 copyback = 0;
4123	struct pf_state_peer	*src, *dst;
4124	struct pf_state_key	*sk;
4125
4126	bzero(&key, sizeof(key));
4127	key.af = pd->af;
4128	key.proto = IPPROTO_TCP;
4129	if (direction == PF_IN)	{	/* wire side, straight */
4130		PF_ACPY(&key.addr[0], pd->src, key.af);
4131		PF_ACPY(&key.addr[1], pd->dst, key.af);
4132		key.port[0] = th->th_sport;
4133		key.port[1] = th->th_dport;
4134	} else {			/* stack side, reverse */
4135		PF_ACPY(&key.addr[1], pd->src, key.af);
4136		PF_ACPY(&key.addr[0], pd->dst, key.af);
4137		key.port[1] = th->th_sport;
4138		key.port[0] = th->th_dport;
4139	}
4140
4141	STATE_LOOKUP(kif, &key, direction, *state, pd);
4142
4143	if (direction == (*state)->direction) {
4144		src = &(*state)->src;
4145		dst = &(*state)->dst;
4146	} else {
4147		src = &(*state)->dst;
4148		dst = &(*state)->src;
4149	}
4150
4151	sk = (*state)->key[pd->didx];
4152
4153	if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4154		if (direction != (*state)->direction) {
4155			REASON_SET(reason, PFRES_SYNPROXY);
4156			return (PF_SYNPROXY_DROP);
4157		}
4158		if (th->th_flags & TH_SYN) {
4159			if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4160				REASON_SET(reason, PFRES_SYNPROXY);
4161				return (PF_DROP);
4162			}
4163			pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4164			    pd->src, th->th_dport, th->th_sport,
4165			    (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4166			    TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4167			REASON_SET(reason, PFRES_SYNPROXY);
4168			return (PF_SYNPROXY_DROP);
4169		} else if (!(th->th_flags & TH_ACK) ||
4170		    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4171		    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4172			REASON_SET(reason, PFRES_SYNPROXY);
4173			return (PF_DROP);
4174		} else if ((*state)->src_node != NULL &&
4175		    pf_src_connlimit(state)) {
4176			REASON_SET(reason, PFRES_SRCLIMIT);
4177			return (PF_DROP);
4178		} else
4179			(*state)->src.state = PF_TCPS_PROXY_DST;
4180	}
4181	if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4182		if (direction == (*state)->direction) {
4183			if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4184			    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4185			    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4186				REASON_SET(reason, PFRES_SYNPROXY);
4187				return (PF_DROP);
4188			}
4189			(*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4190			if ((*state)->dst.seqhi == 1)
4191				(*state)->dst.seqhi = htonl(arc4random());
4192			pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4193			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
4194			    sk->port[pd->sidx], sk->port[pd->didx],
4195			    (*state)->dst.seqhi, 0, TH_SYN, 0,
4196			    (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4197			REASON_SET(reason, PFRES_SYNPROXY);
4198			return (PF_SYNPROXY_DROP);
4199		} else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4200		    (TH_SYN|TH_ACK)) ||
4201		    (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4202			REASON_SET(reason, PFRES_SYNPROXY);
4203			return (PF_DROP);
4204		} else {
4205			(*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4206			(*state)->dst.seqlo = ntohl(th->th_seq);
4207			pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4208			    pd->src, th->th_dport, th->th_sport,
4209			    ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4210			    TH_ACK, (*state)->src.max_win, 0, 0, 0,
4211			    (*state)->tag, NULL);
4212			pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4213			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
4214			    sk->port[pd->sidx], sk->port[pd->didx],
4215			    (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4216			    TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4217			(*state)->src.seqdiff = (*state)->dst.seqhi -
4218			    (*state)->src.seqlo;
4219			(*state)->dst.seqdiff = (*state)->src.seqhi -
4220			    (*state)->dst.seqlo;
4221			(*state)->src.seqhi = (*state)->src.seqlo +
4222			    (*state)->dst.max_win;
4223			(*state)->dst.seqhi = (*state)->dst.seqlo +
4224			    (*state)->src.max_win;
4225			(*state)->src.wscale = (*state)->dst.wscale = 0;
4226			(*state)->src.state = (*state)->dst.state =
4227			    TCPS_ESTABLISHED;
4228			REASON_SET(reason, PFRES_SYNPROXY);
4229			return (PF_SYNPROXY_DROP);
4230		}
4231	}
4232
4233	if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4234	    dst->state >= TCPS_FIN_WAIT_2 &&
4235	    src->state >= TCPS_FIN_WAIT_2) {
4236		if (V_pf_status.debug >= PF_DEBUG_MISC) {
4237			printf("pf: state reuse ");
4238			pf_print_state(*state);
4239			pf_print_flags(th->th_flags);
4240			printf("\n");
4241		}
4242		/* XXX make sure it's the same direction ?? */
4243		(*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4244		pf_unlink_state(*state, PF_ENTER_LOCKED);
4245		*state = NULL;
4246		return (PF_DROP);
4247	}
4248
4249	if ((*state)->state_flags & PFSTATE_SLOPPY) {
4250		if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4251			return (PF_DROP);
4252	} else {
4253		if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4254		    &copyback) == PF_DROP)
4255			return (PF_DROP);
4256	}
4257
4258	/* translate source/destination address, if necessary */
4259	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4260		struct pf_state_key *nk = (*state)->key[pd->didx];
4261
4262		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4263		    nk->port[pd->sidx] != th->th_sport)
4264			pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
4265			    &th->th_sum, &nk->addr[pd->sidx],
4266			    nk->port[pd->sidx], 0, pd->af);
4267
4268		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4269		    nk->port[pd->didx] != th->th_dport)
4270			pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
4271			    &th->th_sum, &nk->addr[pd->didx],
4272			    nk->port[pd->didx], 0, pd->af);
4273		copyback = 1;
4274	}
4275
4276	/* Copyback sequence modulation or stateful scrub changes if needed */
4277	if (copyback)
4278		m_copyback(m, off, sizeof(*th), (caddr_t)th);
4279
4280	return (PF_PASS);
4281}
4282
4283static int
4284pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4285    struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4286{
4287	struct pf_state_peer	*src, *dst;
4288	struct pf_state_key_cmp	 key;
4289	struct udphdr		*uh = pd->hdr.udp;
4290
4291	bzero(&key, sizeof(key));
4292	key.af = pd->af;
4293	key.proto = IPPROTO_UDP;
4294	if (direction == PF_IN)	{	/* wire side, straight */
4295		PF_ACPY(&key.addr[0], pd->src, key.af);
4296		PF_ACPY(&key.addr[1], pd->dst, key.af);
4297		key.port[0] = uh->uh_sport;
4298		key.port[1] = uh->uh_dport;
4299	} else {			/* stack side, reverse */
4300		PF_ACPY(&key.addr[1], pd->src, key.af);
4301		PF_ACPY(&key.addr[0], pd->dst, key.af);
4302		key.port[1] = uh->uh_sport;
4303		key.port[0] = uh->uh_dport;
4304	}
4305
4306	STATE_LOOKUP(kif, &key, direction, *state, pd);
4307
4308	if (direction == (*state)->direction) {
4309		src = &(*state)->src;
4310		dst = &(*state)->dst;
4311	} else {
4312		src = &(*state)->dst;
4313		dst = &(*state)->src;
4314	}
4315
4316	/* update states */
4317	if (src->state < PFUDPS_SINGLE)
4318		src->state = PFUDPS_SINGLE;
4319	if (dst->state == PFUDPS_SINGLE)
4320		dst->state = PFUDPS_MULTIPLE;
4321
4322	/* update expire time */
4323	(*state)->expire = time_uptime;
4324	if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4325		(*state)->timeout = PFTM_UDP_MULTIPLE;
4326	else
4327		(*state)->timeout = PFTM_UDP_SINGLE;
4328
4329	/* translate source/destination address, if necessary */
4330	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4331		struct pf_state_key *nk = (*state)->key[pd->didx];
4332
4333		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4334		    nk->port[pd->sidx] != uh->uh_sport)
4335			pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
4336			    &uh->uh_sum, &nk->addr[pd->sidx],
4337			    nk->port[pd->sidx], 1, pd->af);
4338
4339		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4340		    nk->port[pd->didx] != uh->uh_dport)
4341			pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
4342			    &uh->uh_sum, &nk->addr[pd->didx],
4343			    nk->port[pd->didx], 1, pd->af);
4344		m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4345	}
4346
4347	return (PF_PASS);
4348}
4349
4350static int
4351pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4352    struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4353{
4354	struct pf_addr  *saddr = pd->src, *daddr = pd->dst;
4355	u_int16_t	 icmpid = 0, *icmpsum;
4356	u_int8_t	 icmptype;
4357	int		 state_icmp = 0;
4358	struct pf_state_key_cmp key;
4359
4360	bzero(&key, sizeof(key));
4361	switch (pd->proto) {
4362#ifdef INET
4363	case IPPROTO_ICMP:
4364		icmptype = pd->hdr.icmp->icmp_type;
4365		icmpid = pd->hdr.icmp->icmp_id;
4366		icmpsum = &pd->hdr.icmp->icmp_cksum;
4367
4368		if (icmptype == ICMP_UNREACH ||
4369		    icmptype == ICMP_SOURCEQUENCH ||
4370		    icmptype == ICMP_REDIRECT ||
4371		    icmptype == ICMP_TIMXCEED ||
4372		    icmptype == ICMP_PARAMPROB)
4373			state_icmp++;
4374		break;
4375#endif /* INET */
4376#ifdef INET6
4377	case IPPROTO_ICMPV6:
4378		icmptype = pd->hdr.icmp6->icmp6_type;
4379		icmpid = pd->hdr.icmp6->icmp6_id;
4380		icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4381
4382		if (icmptype == ICMP6_DST_UNREACH ||
4383		    icmptype == ICMP6_PACKET_TOO_BIG ||
4384		    icmptype == ICMP6_TIME_EXCEEDED ||
4385		    icmptype == ICMP6_PARAM_PROB)
4386			state_icmp++;
4387		break;
4388#endif /* INET6 */
4389	}
4390
4391	if (!state_icmp) {
4392
4393		/*
4394		 * ICMP query/reply message not related to a TCP/UDP packet.
4395		 * Search for an ICMP state.
4396		 */
4397		key.af = pd->af;
4398		key.proto = pd->proto;
4399		key.port[0] = key.port[1] = icmpid;
4400		if (direction == PF_IN)	{	/* wire side, straight */
4401			PF_ACPY(&key.addr[0], pd->src, key.af);
4402			PF_ACPY(&key.addr[1], pd->dst, key.af);
4403		} else {			/* stack side, reverse */
4404			PF_ACPY(&key.addr[1], pd->src, key.af);
4405			PF_ACPY(&key.addr[0], pd->dst, key.af);
4406		}
4407
4408		STATE_LOOKUP(kif, &key, direction, *state, pd);
4409
4410		(*state)->expire = time_uptime;
4411		(*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4412
4413		/* translate source/destination address, if necessary */
4414		if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4415			struct pf_state_key *nk = (*state)->key[pd->didx];
4416
4417			switch (pd->af) {
4418#ifdef INET
4419			case AF_INET:
4420				if (PF_ANEQ(pd->src,
4421				    &nk->addr[pd->sidx], AF_INET))
4422					pf_change_a(&saddr->v4.s_addr,
4423					    pd->ip_sum,
4424					    nk->addr[pd->sidx].v4.s_addr, 0);
4425
4426				if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4427				    AF_INET))
4428					pf_change_a(&daddr->v4.s_addr,
4429					    pd->ip_sum,
4430					    nk->addr[pd->didx].v4.s_addr, 0);
4431
4432				if (nk->port[0] !=
4433				    pd->hdr.icmp->icmp_id) {
4434					pd->hdr.icmp->icmp_cksum =
4435					    pf_cksum_fixup(
4436					    pd->hdr.icmp->icmp_cksum, icmpid,
4437					    nk->port[pd->sidx], 0);
4438					pd->hdr.icmp->icmp_id =
4439					    nk->port[pd->sidx];
4440				}
4441
4442				m_copyback(m, off, ICMP_MINLEN,
4443				    (caddr_t )pd->hdr.icmp);
4444				break;
4445#endif /* INET */
4446#ifdef INET6
4447			case AF_INET6:
4448				if (PF_ANEQ(pd->src,
4449				    &nk->addr[pd->sidx], AF_INET6))
4450					pf_change_a6(saddr,
4451					    &pd->hdr.icmp6->icmp6_cksum,
4452					    &nk->addr[pd->sidx], 0);
4453
4454				if (PF_ANEQ(pd->dst,
4455				    &nk->addr[pd->didx], AF_INET6))
4456					pf_change_a6(daddr,
4457					    &pd->hdr.icmp6->icmp6_cksum,
4458					    &nk->addr[pd->didx], 0);
4459
4460				m_copyback(m, off, sizeof(struct icmp6_hdr),
4461				    (caddr_t )pd->hdr.icmp6);
4462				break;
4463#endif /* INET6 */
4464			}
4465		}
4466		return (PF_PASS);
4467
4468	} else {
4469		/*
4470		 * ICMP error message in response to a TCP/UDP packet.
4471		 * Extract the inner TCP/UDP header and search for that state.
4472		 */
4473
4474		struct pf_pdesc	pd2;
4475		bzero(&pd2, sizeof pd2);
4476#ifdef INET
4477		struct ip	h2;
4478#endif /* INET */
4479#ifdef INET6
4480		struct ip6_hdr	h2_6;
4481		int		terminal = 0;
4482#endif /* INET6 */
4483		int		ipoff2 = 0;
4484		int		off2 = 0;
4485
4486		pd2.af = pd->af;
4487		/* Payload packet is from the opposite direction. */
4488		pd2.sidx = (direction == PF_IN) ? 1 : 0;
4489		pd2.didx = (direction == PF_IN) ? 0 : 1;
4490		switch (pd->af) {
4491#ifdef INET
4492		case AF_INET:
4493			/* offset of h2 in mbuf chain */
4494			ipoff2 = off + ICMP_MINLEN;
4495
4496			if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4497			    NULL, reason, pd2.af)) {
4498				DPFPRINTF(PF_DEBUG_MISC,
4499				    ("pf: ICMP error message too short "
4500				    "(ip)\n"));
4501				return (PF_DROP);
4502			}
4503			/*
4504			 * ICMP error messages don't refer to non-first
4505			 * fragments
4506			 */
4507			if (h2.ip_off & htons(IP_OFFMASK)) {
4508				REASON_SET(reason, PFRES_FRAG);
4509				return (PF_DROP);
4510			}
4511
4512			/* offset of protocol header that follows h2 */
4513			off2 = ipoff2 + (h2.ip_hl << 2);
4514
4515			pd2.proto = h2.ip_p;
4516			pd2.src = (struct pf_addr *)&h2.ip_src;
4517			pd2.dst = (struct pf_addr *)&h2.ip_dst;
4518			pd2.ip_sum = &h2.ip_sum;
4519			break;
4520#endif /* INET */
4521#ifdef INET6
4522		case AF_INET6:
4523			ipoff2 = off + sizeof(struct icmp6_hdr);
4524
4525			if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4526			    NULL, reason, pd2.af)) {
4527				DPFPRINTF(PF_DEBUG_MISC,
4528				    ("pf: ICMP error message too short "
4529				    "(ip6)\n"));
4530				return (PF_DROP);
4531			}
4532			pd2.proto = h2_6.ip6_nxt;
4533			pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4534			pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4535			pd2.ip_sum = NULL;
4536			off2 = ipoff2 + sizeof(h2_6);
4537			do {
4538				switch (pd2.proto) {
4539				case IPPROTO_FRAGMENT:
4540					/*
4541					 * ICMPv6 error messages for
4542					 * non-first fragments
4543					 */
4544					REASON_SET(reason, PFRES_FRAG);
4545					return (PF_DROP);
4546				case IPPROTO_AH:
4547				case IPPROTO_HOPOPTS:
4548				case IPPROTO_ROUTING:
4549				case IPPROTO_DSTOPTS: {
4550					/* get next header and header length */
4551					struct ip6_ext opt6;
4552
4553					if (!pf_pull_hdr(m, off2, &opt6,
4554					    sizeof(opt6), NULL, reason,
4555					    pd2.af)) {
4556						DPFPRINTF(PF_DEBUG_MISC,
4557						    ("pf: ICMPv6 short opt\n"));
4558						return (PF_DROP);
4559					}
4560					if (pd2.proto == IPPROTO_AH)
4561						off2 += (opt6.ip6e_len + 2) * 4;
4562					else
4563						off2 += (opt6.ip6e_len + 1) * 8;
4564					pd2.proto = opt6.ip6e_nxt;
4565					/* goto the next header */
4566					break;
4567				}
4568				default:
4569					terminal++;
4570					break;
4571				}
4572			} while (!terminal);
4573			break;
4574#endif /* INET6 */
4575		}
4576
4577		switch (pd2.proto) {
4578		case IPPROTO_TCP: {
4579			struct tcphdr		 th;
4580			u_int32_t		 seq;
4581			struct pf_state_peer	*src, *dst;
4582			u_int8_t		 dws;
4583			int			 copyback = 0;
4584
4585			/*
4586			 * Only the first 8 bytes of the TCP header can be
4587			 * expected. Don't access any TCP header fields after
4588			 * th_seq, an ackskew test is not possible.
4589			 */
4590			if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4591			    pd2.af)) {
4592				DPFPRINTF(PF_DEBUG_MISC,
4593				    ("pf: ICMP error message too short "
4594				    "(tcp)\n"));
4595				return (PF_DROP);
4596			}
4597
4598			key.af = pd2.af;
4599			key.proto = IPPROTO_TCP;
4600			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4601			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4602			key.port[pd2.sidx] = th.th_sport;
4603			key.port[pd2.didx] = th.th_dport;
4604
4605			STATE_LOOKUP(kif, &key, direction, *state, pd);
4606
4607			if (direction == (*state)->direction) {
4608				src = &(*state)->dst;
4609				dst = &(*state)->src;
4610			} else {
4611				src = &(*state)->src;
4612				dst = &(*state)->dst;
4613			}
4614
4615			if (src->wscale && dst->wscale)
4616				dws = dst->wscale & PF_WSCALE_MASK;
4617			else
4618				dws = 0;
4619
4620			/* Demodulate sequence number */
4621			seq = ntohl(th.th_seq) - src->seqdiff;
4622			if (src->seqdiff) {
4623				pf_change_a(&th.th_seq, icmpsum,
4624				    htonl(seq), 0);
4625				copyback = 1;
4626			}
4627
4628			if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4629			    (!SEQ_GEQ(src->seqhi, seq) ||
4630			    !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4631				if (V_pf_status.debug >= PF_DEBUG_MISC) {
4632					printf("pf: BAD ICMP %d:%d ",
4633					    icmptype, pd->hdr.icmp->icmp_code);
4634					pf_print_host(pd->src, 0, pd->af);
4635					printf(" -> ");
4636					pf_print_host(pd->dst, 0, pd->af);
4637					printf(" state: ");
4638					pf_print_state(*state);
4639					printf(" seq=%u\n", seq);
4640				}
4641				REASON_SET(reason, PFRES_BADSTATE);
4642				return (PF_DROP);
4643			} else {
4644				if (V_pf_status.debug >= PF_DEBUG_MISC) {
4645					printf("pf: OK ICMP %d:%d ",
4646					    icmptype, pd->hdr.icmp->icmp_code);
4647					pf_print_host(pd->src, 0, pd->af);
4648					printf(" -> ");
4649					pf_print_host(pd->dst, 0, pd->af);
4650					printf(" state: ");
4651					pf_print_state(*state);
4652					printf(" seq=%u\n", seq);
4653				}
4654			}
4655
4656			/* translate source/destination address, if necessary */
4657			if ((*state)->key[PF_SK_WIRE] !=
4658			    (*state)->key[PF_SK_STACK]) {
4659				struct pf_state_key *nk =
4660				    (*state)->key[pd->didx];
4661
4662				if (PF_ANEQ(pd2.src,
4663				    &nk->addr[pd2.sidx], pd2.af) ||
4664				    nk->port[pd2.sidx] != th.th_sport)
4665					pf_change_icmp(pd2.src, &th.th_sport,
4666					    daddr, &nk->addr[pd2.sidx],
4667					    nk->port[pd2.sidx], NULL,
4668					    pd2.ip_sum, icmpsum,
4669					    pd->ip_sum, 0, pd2.af);
4670
4671				if (PF_ANEQ(pd2.dst,
4672				    &nk->addr[pd2.didx], pd2.af) ||
4673				    nk->port[pd2.didx] != th.th_dport)
4674					pf_change_icmp(pd2.dst, &th.th_dport,
4675					    NULL, /* XXX Inbound NAT? */
4676					    &nk->addr[pd2.didx],
4677					    nk->port[pd2.didx], NULL,
4678					    pd2.ip_sum, icmpsum,
4679					    pd->ip_sum, 0, pd2.af);
4680				copyback = 1;
4681			}
4682
4683			if (copyback) {
4684				switch (pd2.af) {
4685#ifdef INET
4686				case AF_INET:
4687					m_copyback(m, off, ICMP_MINLEN,
4688					    (caddr_t )pd->hdr.icmp);
4689					m_copyback(m, ipoff2, sizeof(h2),
4690					    (caddr_t )&h2);
4691					break;
4692#endif /* INET */
4693#ifdef INET6
4694				case AF_INET6:
4695					m_copyback(m, off,
4696					    sizeof(struct icmp6_hdr),
4697					    (caddr_t )pd->hdr.icmp6);
4698					m_copyback(m, ipoff2, sizeof(h2_6),
4699					    (caddr_t )&h2_6);
4700					break;
4701#endif /* INET6 */
4702				}
4703				m_copyback(m, off2, 8, (caddr_t)&th);
4704			}
4705
4706			return (PF_PASS);
4707			break;
4708		}
4709		case IPPROTO_UDP: {
4710			struct udphdr		uh;
4711
4712			if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4713			    NULL, reason, pd2.af)) {
4714				DPFPRINTF(PF_DEBUG_MISC,
4715				    ("pf: ICMP error message too short "
4716				    "(udp)\n"));
4717				return (PF_DROP);
4718			}
4719
4720			key.af = pd2.af;
4721			key.proto = IPPROTO_UDP;
4722			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4723			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4724			key.port[pd2.sidx] = uh.uh_sport;
4725			key.port[pd2.didx] = uh.uh_dport;
4726
4727			STATE_LOOKUP(kif, &key, direction, *state, pd);
4728
4729			/* translate source/destination address, if necessary */
4730			if ((*state)->key[PF_SK_WIRE] !=
4731			    (*state)->key[PF_SK_STACK]) {
4732				struct pf_state_key *nk =
4733				    (*state)->key[pd->didx];
4734
4735				if (PF_ANEQ(pd2.src,
4736				    &nk->addr[pd2.sidx], pd2.af) ||
4737				    nk->port[pd2.sidx] != uh.uh_sport)
4738					pf_change_icmp(pd2.src, &uh.uh_sport,
4739					    daddr, &nk->addr[pd2.sidx],
4740					    nk->port[pd2.sidx], &uh.uh_sum,
4741					    pd2.ip_sum, icmpsum,
4742					    pd->ip_sum, 1, pd2.af);
4743
4744				if (PF_ANEQ(pd2.dst,
4745				    &nk->addr[pd2.didx], pd2.af) ||
4746				    nk->port[pd2.didx] != uh.uh_dport)
4747					pf_change_icmp(pd2.dst, &uh.uh_dport,
4748					    NULL, /* XXX Inbound NAT? */
4749					    &nk->addr[pd2.didx],
4750					    nk->port[pd2.didx], &uh.uh_sum,
4751					    pd2.ip_sum, icmpsum,
4752					    pd->ip_sum, 1, pd2.af);
4753
4754				switch (pd2.af) {
4755#ifdef INET
4756				case AF_INET:
4757					m_copyback(m, off, ICMP_MINLEN,
4758					    (caddr_t )pd->hdr.icmp);
4759					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4760					break;
4761#endif /* INET */
4762#ifdef INET6
4763				case AF_INET6:
4764					m_copyback(m, off,
4765					    sizeof(struct icmp6_hdr),
4766					    (caddr_t )pd->hdr.icmp6);
4767					m_copyback(m, ipoff2, sizeof(h2_6),
4768					    (caddr_t )&h2_6);
4769					break;
4770#endif /* INET6 */
4771				}
4772				m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4773			}
4774			return (PF_PASS);
4775			break;
4776		}
4777#ifdef INET
4778		case IPPROTO_ICMP: {
4779			struct icmp		iih;
4780
4781			if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4782			    NULL, reason, pd2.af)) {
4783				DPFPRINTF(PF_DEBUG_MISC,
4784				    ("pf: ICMP error message too short i"
4785				    "(icmp)\n"));
4786				return (PF_DROP);
4787			}
4788
4789			key.af = pd2.af;
4790			key.proto = IPPROTO_ICMP;
4791			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4792			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4793			key.port[0] = key.port[1] = iih.icmp_id;
4794
4795			STATE_LOOKUP(kif, &key, direction, *state, pd);
4796
4797			/* translate source/destination address, if necessary */
4798			if ((*state)->key[PF_SK_WIRE] !=
4799			    (*state)->key[PF_SK_STACK]) {
4800				struct pf_state_key *nk =
4801				    (*state)->key[pd->didx];
4802
4803				if (PF_ANEQ(pd2.src,
4804				    &nk->addr[pd2.sidx], pd2.af) ||
4805				    nk->port[pd2.sidx] != iih.icmp_id)
4806					pf_change_icmp(pd2.src, &iih.icmp_id,
4807					    daddr, &nk->addr[pd2.sidx],
4808					    nk->port[pd2.sidx], NULL,
4809					    pd2.ip_sum, icmpsum,
4810					    pd->ip_sum, 0, AF_INET);
4811
4812				if (PF_ANEQ(pd2.dst,
4813				    &nk->addr[pd2.didx], pd2.af) ||
4814				    nk->port[pd2.didx] != iih.icmp_id)
4815					pf_change_icmp(pd2.dst, &iih.icmp_id,
4816					    NULL, /* XXX Inbound NAT? */
4817					    &nk->addr[pd2.didx],
4818					    nk->port[pd2.didx], NULL,
4819					    pd2.ip_sum, icmpsum,
4820					    pd->ip_sum, 0, AF_INET);
4821
4822				m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
4823				m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4824				m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
4825			}
4826			return (PF_PASS);
4827			break;
4828		}
4829#endif /* INET */
4830#ifdef INET6
4831		case IPPROTO_ICMPV6: {
4832			struct icmp6_hdr	iih;
4833
4834			if (!pf_pull_hdr(m, off2, &iih,
4835			    sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
4836				DPFPRINTF(PF_DEBUG_MISC,
4837				    ("pf: ICMP error message too short "
4838				    "(icmp6)\n"));
4839				return (PF_DROP);
4840			}
4841
4842			key.af = pd2.af;
4843			key.proto = IPPROTO_ICMPV6;
4844			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4845			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4846			key.port[0] = key.port[1] = iih.icmp6_id;
4847
4848			STATE_LOOKUP(kif, &key, direction, *state, pd);
4849
4850			/* translate source/destination address, if necessary */
4851			if ((*state)->key[PF_SK_WIRE] !=
4852			    (*state)->key[PF_SK_STACK]) {
4853				struct pf_state_key *nk =
4854				    (*state)->key[pd->didx];
4855
4856				if (PF_ANEQ(pd2.src,
4857				    &nk->addr[pd2.sidx], pd2.af) ||
4858				    nk->port[pd2.sidx] != iih.icmp6_id)
4859					pf_change_icmp(pd2.src, &iih.icmp6_id,
4860					    daddr, &nk->addr[pd2.sidx],
4861					    nk->port[pd2.sidx], NULL,
4862					    pd2.ip_sum, icmpsum,
4863					    pd->ip_sum, 0, AF_INET6);
4864
4865				if (PF_ANEQ(pd2.dst,
4866				    &nk->addr[pd2.didx], pd2.af) ||
4867				    nk->port[pd2.didx] != iih.icmp6_id)
4868					pf_change_icmp(pd2.dst, &iih.icmp6_id,
4869					    NULL, /* XXX Inbound NAT? */
4870					    &nk->addr[pd2.didx],
4871					    nk->port[pd2.didx], NULL,
4872					    pd2.ip_sum, icmpsum,
4873					    pd->ip_sum, 0, AF_INET6);
4874
4875				m_copyback(m, off, sizeof(struct icmp6_hdr),
4876				    (caddr_t)pd->hdr.icmp6);
4877				m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
4878				m_copyback(m, off2, sizeof(struct icmp6_hdr),
4879				    (caddr_t)&iih);
4880			}
4881			return (PF_PASS);
4882			break;
4883		}
4884#endif /* INET6 */
4885		default: {
4886			key.af = pd2.af;
4887			key.proto = pd2.proto;
4888			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4889			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4890			key.port[0] = key.port[1] = 0;
4891
4892			STATE_LOOKUP(kif, &key, direction, *state, pd);
4893
4894			/* translate source/destination address, if necessary */
4895			if ((*state)->key[PF_SK_WIRE] !=
4896			    (*state)->key[PF_SK_STACK]) {
4897				struct pf_state_key *nk =
4898				    (*state)->key[pd->didx];
4899
4900				if (PF_ANEQ(pd2.src,
4901				    &nk->addr[pd2.sidx], pd2.af))
4902					pf_change_icmp(pd2.src, NULL, daddr,
4903					    &nk->addr[pd2.sidx], 0, NULL,
4904					    pd2.ip_sum, icmpsum,
4905					    pd->ip_sum, 0, pd2.af);
4906
4907				if (PF_ANEQ(pd2.dst,
4908				    &nk->addr[pd2.didx], pd2.af))
4909					pf_change_icmp(pd2.src, NULL,
4910					    NULL, /* XXX Inbound NAT? */
4911					    &nk->addr[pd2.didx], 0, NULL,
4912					    pd2.ip_sum, icmpsum,
4913					    pd->ip_sum, 0, pd2.af);
4914
4915				switch (pd2.af) {
4916#ifdef INET
4917				case AF_INET:
4918					m_copyback(m, off, ICMP_MINLEN,
4919					    (caddr_t)pd->hdr.icmp);
4920					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4921					break;
4922#endif /* INET */
4923#ifdef INET6
4924				case AF_INET6:
4925					m_copyback(m, off,
4926					    sizeof(struct icmp6_hdr),
4927					    (caddr_t )pd->hdr.icmp6);
4928					m_copyback(m, ipoff2, sizeof(h2_6),
4929					    (caddr_t )&h2_6);
4930					break;
4931#endif /* INET6 */
4932				}
4933			}
4934			return (PF_PASS);
4935			break;
4936		}
4937		}
4938	}
4939}
4940
4941static int
4942pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
4943    struct mbuf *m, struct pf_pdesc *pd)
4944{
4945	struct pf_state_peer	*src, *dst;
4946	struct pf_state_key_cmp	 key;
4947
4948	bzero(&key, sizeof(key));
4949	key.af = pd->af;
4950	key.proto = pd->proto;
4951	if (direction == PF_IN)	{
4952		PF_ACPY(&key.addr[0], pd->src, key.af);
4953		PF_ACPY(&key.addr[1], pd->dst, key.af);
4954		key.port[0] = key.port[1] = 0;
4955	} else {
4956		PF_ACPY(&key.addr[1], pd->src, key.af);
4957		PF_ACPY(&key.addr[0], pd->dst, key.af);
4958		key.port[1] = key.port[0] = 0;
4959	}
4960
4961	STATE_LOOKUP(kif, &key, direction, *state, pd);
4962
4963	if (direction == (*state)->direction) {
4964		src = &(*state)->src;
4965		dst = &(*state)->dst;
4966	} else {
4967		src = &(*state)->dst;
4968		dst = &(*state)->src;
4969	}
4970
4971	/* update states */
4972	if (src->state < PFOTHERS_SINGLE)
4973		src->state = PFOTHERS_SINGLE;
4974	if (dst->state == PFOTHERS_SINGLE)
4975		dst->state = PFOTHERS_MULTIPLE;
4976
4977	/* update expire time */
4978	(*state)->expire = time_uptime;
4979	if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
4980		(*state)->timeout = PFTM_OTHER_MULTIPLE;
4981	else
4982		(*state)->timeout = PFTM_OTHER_SINGLE;
4983
4984	/* translate source/destination address, if necessary */
4985	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4986		struct pf_state_key *nk = (*state)->key[pd->didx];
4987
4988		KASSERT(nk, ("%s: nk is null", __func__));
4989		KASSERT(pd, ("%s: pd is null", __func__));
4990		KASSERT(pd->src, ("%s: pd->src is null", __func__));
4991		KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
4992		switch (pd->af) {
4993#ifdef INET
4994		case AF_INET:
4995			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
4996				pf_change_a(&pd->src->v4.s_addr,
4997				    pd->ip_sum,
4998				    nk->addr[pd->sidx].v4.s_addr,
4999				    0);
5000
5001
5002			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5003				pf_change_a(&pd->dst->v4.s_addr,
5004				    pd->ip_sum,
5005				    nk->addr[pd->didx].v4.s_addr,
5006				    0);
5007
5008				break;
5009#endif /* INET */
5010#ifdef INET6
5011		case AF_INET6:
5012			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5013				PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5014
5015			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5016				PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5017#endif /* INET6 */
5018		}
5019	}
5020	return (PF_PASS);
5021}
5022
5023/*
5024 * ipoff and off are measured from the start of the mbuf chain.
5025 * h must be at "ipoff" on the mbuf chain.
5026 */
5027void *
5028pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5029    u_short *actionp, u_short *reasonp, sa_family_t af)
5030{
5031	switch (af) {
5032#ifdef INET
5033	case AF_INET: {
5034		struct ip	*h = mtod(m, struct ip *);
5035		u_int16_t	 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5036
5037		if (fragoff) {
5038			if (fragoff >= len)
5039				ACTION_SET(actionp, PF_PASS);
5040			else {
5041				ACTION_SET(actionp, PF_DROP);
5042				REASON_SET(reasonp, PFRES_FRAG);
5043			}
5044			return (NULL);
5045		}
5046		if (m->m_pkthdr.len < off + len ||
5047		    ntohs(h->ip_len) < off + len) {
5048			ACTION_SET(actionp, PF_DROP);
5049			REASON_SET(reasonp, PFRES_SHORT);
5050			return (NULL);
5051		}
5052		break;
5053	}
5054#endif /* INET */
5055#ifdef INET6
5056	case AF_INET6: {
5057		struct ip6_hdr	*h = mtod(m, struct ip6_hdr *);
5058
5059		if (m->m_pkthdr.len < off + len ||
5060		    (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5061		    (unsigned)(off + len)) {
5062			ACTION_SET(actionp, PF_DROP);
5063			REASON_SET(reasonp, PFRES_SHORT);
5064			return (NULL);
5065		}
5066		break;
5067	}
5068#endif /* INET6 */
5069	}
5070	m_copydata(m, off, len, p);
5071	return (p);
5072}
5073
5074int
5075pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5076    int rtableid)
5077{
5078#ifdef RADIX_MPATH
5079	struct radix_node_head	*rnh;
5080#endif
5081	struct sockaddr_in	*dst;
5082	int			 ret = 1;
5083	int			 check_mpath;
5084#ifdef INET6
5085	struct sockaddr_in6	*dst6;
5086	struct route_in6	 ro;
5087#else
5088	struct route		 ro;
5089#endif
5090	struct radix_node	*rn;
5091	struct rtentry		*rt;
5092	struct ifnet		*ifp;
5093
5094	check_mpath = 0;
5095#ifdef RADIX_MPATH
5096	/* XXX: stick to table 0 for now */
5097	rnh = rt_tables_get_rnh(0, af);
5098	if (rnh != NULL && rn_mpath_capable(rnh))
5099		check_mpath = 1;
5100#endif
5101	bzero(&ro, sizeof(ro));
5102	switch (af) {
5103	case AF_INET:
5104		dst = satosin(&ro.ro_dst);
5105		dst->sin_family = AF_INET;
5106		dst->sin_len = sizeof(*dst);
5107		dst->sin_addr = addr->v4;
5108		break;
5109#ifdef INET6
5110	case AF_INET6:
5111		/*
5112		 * Skip check for addresses with embedded interface scope,
5113		 * as they would always match anyway.
5114		 */
5115		if (IN6_IS_SCOPE_EMBED(&addr->v6))
5116			goto out;
5117		dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5118		dst6->sin6_family = AF_INET6;
5119		dst6->sin6_len = sizeof(*dst6);
5120		dst6->sin6_addr = addr->v6;
5121		break;
5122#endif /* INET6 */
5123	default:
5124		return (0);
5125	}
5126
5127	/* Skip checks for ipsec interfaces */
5128	if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5129		goto out;
5130
5131	switch (af) {
5132#ifdef INET6
5133	case AF_INET6:
5134		in6_rtalloc_ign(&ro, 0, rtableid);
5135		break;
5136#endif
5137#ifdef INET
5138	case AF_INET:
5139		in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5140		break;
5141#endif
5142	default:
5143		rtalloc_ign((struct route *)&ro, 0);	/* No/default FIB. */
5144		break;
5145	}
5146
5147	if (ro.ro_rt != NULL) {
5148		/* No interface given, this is a no-route check */
5149		if (kif == NULL)
5150			goto out;
5151
5152		if (kif->pfik_ifp == NULL) {
5153			ret = 0;
5154			goto out;
5155		}
5156
5157		/* Perform uRPF check if passed input interface */
5158		ret = 0;
5159		rn = (struct radix_node *)ro.ro_rt;
5160		do {
5161			rt = (struct rtentry *)rn;
5162			ifp = rt->rt_ifp;
5163
5164			if (kif->pfik_ifp == ifp)
5165				ret = 1;
5166#ifdef RADIX_MPATH
5167			rn = rn_mpath_next(rn);
5168#endif
5169		} while (check_mpath == 1 && rn != NULL && ret == 0);
5170	} else
5171		ret = 0;
5172out:
5173	if (ro.ro_rt != NULL)
5174		RTFREE(ro.ro_rt);
5175	return (ret);
5176}
5177
5178#ifdef INET
5179static void
5180pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5181    struct pf_state *s, struct pf_pdesc *pd)
5182{
5183	struct mbuf		*m0, *m1;
5184	struct sockaddr_in	dst;
5185	struct ip		*ip;
5186	struct ifnet		*ifp = NULL;
5187	struct pf_addr		 naddr;
5188	struct pf_src_node	*sn = NULL;
5189	int			 error = 0;
5190	uint16_t		 ip_len, ip_off;
5191
5192	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5193	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5194	    __func__));
5195
5196	if ((pd->pf_mtag == NULL &&
5197	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5198	    pd->pf_mtag->routed++ > 3) {
5199		m0 = *m;
5200		*m = NULL;
5201		goto bad_locked;
5202	}
5203
5204	if (r->rt == PF_DUPTO) {
5205		if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5206			if (s)
5207				PF_STATE_UNLOCK(s);
5208			return;
5209		}
5210	} else {
5211		if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5212			if (s)
5213				PF_STATE_UNLOCK(s);
5214			return;
5215		}
5216		m0 = *m;
5217	}
5218
5219	ip = mtod(m0, struct ip *);
5220
5221	bzero(&dst, sizeof(dst));
5222	dst.sin_family = AF_INET;
5223	dst.sin_len = sizeof(dst);
5224	dst.sin_addr = ip->ip_dst;
5225
5226	if (r->rt == PF_FASTROUTE) {
5227		struct rtentry *rt;
5228
5229		if (s)
5230			PF_STATE_UNLOCK(s);
5231		rt = rtalloc1_fib(sintosa(&dst), 0, 0, M_GETFIB(m0));
5232		if (rt == NULL) {
5233			RTFREE_LOCKED(rt);
5234			KMOD_IPSTAT_INC(ips_noroute);
5235			error = EHOSTUNREACH;
5236			goto bad;
5237		}
5238
5239		ifp = rt->rt_ifp;
5240		rt->rt_rmx.rmx_pksent++;
5241
5242		if (rt->rt_flags & RTF_GATEWAY)
5243			bcopy(satosin(rt->rt_gateway), &dst, sizeof(dst));
5244		RTFREE_LOCKED(rt);
5245	} else {
5246		if (TAILQ_EMPTY(&r->rpool.list)) {
5247			DPFPRINTF(PF_DEBUG_URGENT,
5248			    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5249			goto bad_locked;
5250		}
5251		if (s == NULL) {
5252			pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5253			    &naddr, NULL, &sn);
5254			if (!PF_AZERO(&naddr, AF_INET))
5255				dst.sin_addr.s_addr = naddr.v4.s_addr;
5256			ifp = r->rpool.cur->kif ?
5257			    r->rpool.cur->kif->pfik_ifp : NULL;
5258		} else {
5259			if (!PF_AZERO(&s->rt_addr, AF_INET))
5260				dst.sin_addr.s_addr =
5261				    s->rt_addr.v4.s_addr;
5262			ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5263			PF_STATE_UNLOCK(s);
5264		}
5265	}
5266	if (ifp == NULL)
5267		goto bad;
5268
5269	if (oifp != ifp) {
5270		if (pf_test(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5271			goto bad;
5272		else if (m0 == NULL)
5273			goto done;
5274		if (m0->m_len < sizeof(struct ip)) {
5275			DPFPRINTF(PF_DEBUG_URGENT,
5276			    ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5277			goto bad;
5278		}
5279		ip = mtod(m0, struct ip *);
5280	}
5281
5282	if (ifp->if_flags & IFF_LOOPBACK)
5283		m0->m_flags |= M_SKIP_FIREWALL;
5284
5285	ip_len = ntohs(ip->ip_len);
5286	ip_off = ntohs(ip->ip_off);
5287
5288	/* Copied from FreeBSD 10.0-CURRENT ip_output. */
5289	m0->m_pkthdr.csum_flags |= CSUM_IP;
5290	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5291		in_delayed_cksum(m0);
5292		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5293	}
5294#ifdef SCTP
5295	if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5296		sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5297		m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5298	}
5299#endif
5300
5301	/*
5302	 * If small enough for interface, or the interface will take
5303	 * care of the fragmentation for us, we can just send directly.
5304	 */
5305	if (ip_len <= ifp->if_mtu ||
5306	    (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0 ||
5307	    ((ip_off & IP_DF) == 0 && (ifp->if_hwassist & CSUM_FRAGMENT))) {
5308		ip->ip_sum = 0;
5309		if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5310			ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5311			m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5312		}
5313		m0->m_flags &= ~(M_PROTOFLAGS);
5314		error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5315		goto done;
5316	}
5317
5318	/* Balk when DF bit is set or the interface didn't support TSO. */
5319	if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5320		error = EMSGSIZE;
5321		KMOD_IPSTAT_INC(ips_cantfrag);
5322		if (r->rt != PF_DUPTO) {
5323			icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5324			    ifp->if_mtu);
5325			goto done;
5326		} else
5327			goto bad;
5328	}
5329
5330	error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5331	if (error)
5332		goto bad;
5333
5334	for (; m0; m0 = m1) {
5335		m1 = m0->m_nextpkt;
5336		m0->m_nextpkt = NULL;
5337		if (error == 0) {
5338			m0->m_flags &= ~(M_PROTOFLAGS);
5339			error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5340		} else
5341			m_freem(m0);
5342	}
5343
5344	if (error == 0)
5345		KMOD_IPSTAT_INC(ips_fragmented);
5346
5347done:
5348	if (r->rt != PF_DUPTO)
5349		*m = NULL;
5350	return;
5351
5352bad_locked:
5353	if (s)
5354		PF_STATE_UNLOCK(s);
5355bad:
5356	m_freem(m0);
5357	goto done;
5358}
5359#endif /* INET */
5360
5361#ifdef INET6
5362static void
5363pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5364    struct pf_state *s, struct pf_pdesc *pd)
5365{
5366	struct mbuf		*m0;
5367	struct sockaddr_in6	dst;
5368	struct ip6_hdr		*ip6;
5369	struct ifnet		*ifp = NULL;
5370	struct pf_addr		 naddr;
5371	struct pf_src_node	*sn = NULL;
5372
5373	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5374	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5375	    __func__));
5376
5377	if ((pd->pf_mtag == NULL &&
5378	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5379	    pd->pf_mtag->routed++ > 3) {
5380		m0 = *m;
5381		*m = NULL;
5382		goto bad_locked;
5383	}
5384
5385	if (r->rt == PF_DUPTO) {
5386		if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5387			if (s)
5388				PF_STATE_UNLOCK(s);
5389			return;
5390		}
5391	} else {
5392		if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5393			if (s)
5394				PF_STATE_UNLOCK(s);
5395			return;
5396		}
5397		m0 = *m;
5398	}
5399
5400	ip6 = mtod(m0, struct ip6_hdr *);
5401
5402	bzero(&dst, sizeof(dst));
5403	dst.sin6_family = AF_INET6;
5404	dst.sin6_len = sizeof(dst);
5405	dst.sin6_addr = ip6->ip6_dst;
5406
5407	/* Cheat. XXX why only in the v6 case??? */
5408	if (r->rt == PF_FASTROUTE) {
5409		if (s)
5410			PF_STATE_UNLOCK(s);
5411		m0->m_flags |= M_SKIP_FIREWALL;
5412		ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5413		return;
5414	}
5415
5416	if (TAILQ_EMPTY(&r->rpool.list)) {
5417		DPFPRINTF(PF_DEBUG_URGENT,
5418		    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5419		goto bad_locked;
5420	}
5421	if (s == NULL) {
5422		pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5423		    &naddr, NULL, &sn);
5424		if (!PF_AZERO(&naddr, AF_INET6))
5425			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5426			    &naddr, AF_INET6);
5427		ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5428	} else {
5429		if (!PF_AZERO(&s->rt_addr, AF_INET6))
5430			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5431			    &s->rt_addr, AF_INET6);
5432		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5433	}
5434
5435	if (s)
5436		PF_STATE_UNLOCK(s);
5437
5438	if (ifp == NULL)
5439		goto bad;
5440
5441	if (oifp != ifp) {
5442		if (pf_test6(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5443			goto bad;
5444		else if (m0 == NULL)
5445			goto done;
5446		if (m0->m_len < sizeof(struct ip6_hdr)) {
5447			DPFPRINTF(PF_DEBUG_URGENT,
5448			    ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5449			    __func__));
5450			goto bad;
5451		}
5452		ip6 = mtod(m0, struct ip6_hdr *);
5453	}
5454
5455	if (ifp->if_flags & IFF_LOOPBACK)
5456		m0->m_flags |= M_SKIP_FIREWALL;
5457
5458	/*
5459	 * If the packet is too large for the outgoing interface,
5460	 * send back an icmp6 error.
5461	 */
5462	if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5463		dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5464	if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5465		nd6_output(ifp, ifp, m0, &dst, NULL);
5466	else {
5467		in6_ifstat_inc(ifp, ifs6_in_toobig);
5468		if (r->rt != PF_DUPTO)
5469			icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5470		else
5471			goto bad;
5472	}
5473
5474done:
5475	if (r->rt != PF_DUPTO)
5476		*m = NULL;
5477	return;
5478
5479bad_locked:
5480	if (s)
5481		PF_STATE_UNLOCK(s);
5482bad:
5483	m_freem(m0);
5484	goto done;
5485}
5486#endif /* INET6 */
5487
5488/*
5489 * FreeBSD supports cksum offloads for the following drivers.
5490 *  em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5491 *   ti(4), txp(4), xl(4)
5492 *
5493 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5494 *  network driver performed cksum including pseudo header, need to verify
5495 *   csum_data
5496 * CSUM_DATA_VALID :
5497 *  network driver performed cksum, needs to additional pseudo header
5498 *  cksum computation with partial csum_data(i.e. lack of H/W support for
5499 *  pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5500 *
5501 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5502 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5503 * TCP/UDP layer.
5504 * Also, set csum_data to 0xffff to force cksum validation.
5505 */
5506static int
5507pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5508{
5509	u_int16_t sum = 0;
5510	int hw_assist = 0;
5511	struct ip *ip;
5512
5513	if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5514		return (1);
5515	if (m->m_pkthdr.len < off + len)
5516		return (1);
5517
5518	switch (p) {
5519	case IPPROTO_TCP:
5520		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5521			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5522				sum = m->m_pkthdr.csum_data;
5523			} else {
5524				ip = mtod(m, struct ip *);
5525				sum = in_pseudo(ip->ip_src.s_addr,
5526				ip->ip_dst.s_addr, htonl((u_short)len +
5527				m->m_pkthdr.csum_data + IPPROTO_TCP));
5528			}
5529			sum ^= 0xffff;
5530			++hw_assist;
5531		}
5532		break;
5533	case IPPROTO_UDP:
5534		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5535			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5536				sum = m->m_pkthdr.csum_data;
5537			} else {
5538				ip = mtod(m, struct ip *);
5539				sum = in_pseudo(ip->ip_src.s_addr,
5540				ip->ip_dst.s_addr, htonl((u_short)len +
5541				m->m_pkthdr.csum_data + IPPROTO_UDP));
5542			}
5543			sum ^= 0xffff;
5544			++hw_assist;
5545		}
5546		break;
5547	case IPPROTO_ICMP:
5548#ifdef INET6
5549	case IPPROTO_ICMPV6:
5550#endif /* INET6 */
5551		break;
5552	default:
5553		return (1);
5554	}
5555
5556	if (!hw_assist) {
5557		switch (af) {
5558		case AF_INET:
5559			if (p == IPPROTO_ICMP) {
5560				if (m->m_len < off)
5561					return (1);
5562				m->m_data += off;
5563				m->m_len -= off;
5564				sum = in_cksum(m, len);
5565				m->m_data -= off;
5566				m->m_len += off;
5567			} else {
5568				if (m->m_len < sizeof(struct ip))
5569					return (1);
5570				sum = in4_cksum(m, p, off, len);
5571			}
5572			break;
5573#ifdef INET6
5574		case AF_INET6:
5575			if (m->m_len < sizeof(struct ip6_hdr))
5576				return (1);
5577			sum = in6_cksum(m, p, off, len);
5578			break;
5579#endif /* INET6 */
5580		default:
5581			return (1);
5582		}
5583	}
5584	if (sum) {
5585		switch (p) {
5586		case IPPROTO_TCP:
5587		    {
5588			KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5589			break;
5590		    }
5591		case IPPROTO_UDP:
5592		    {
5593			KMOD_UDPSTAT_INC(udps_badsum);
5594			break;
5595		    }
5596#ifdef INET
5597		case IPPROTO_ICMP:
5598		    {
5599			KMOD_ICMPSTAT_INC(icps_checksum);
5600			break;
5601		    }
5602#endif
5603#ifdef INET6
5604		case IPPROTO_ICMPV6:
5605		    {
5606			KMOD_ICMP6STAT_INC(icp6s_checksum);
5607			break;
5608		    }
5609#endif /* INET6 */
5610		}
5611		return (1);
5612	} else {
5613		if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5614			m->m_pkthdr.csum_flags |=
5615			    (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5616			m->m_pkthdr.csum_data = 0xffff;
5617		}
5618	}
5619	return (0);
5620}
5621
5622
5623#ifdef INET
5624int
5625pf_test(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5626{
5627	struct pfi_kif		*kif;
5628	u_short			 action, reason = 0, log = 0;
5629	struct mbuf		*m = *m0;
5630	struct ip		*h = NULL;
5631	struct m_tag		*ipfwtag;
5632	struct pf_rule		*a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5633	struct pf_state		*s = NULL;
5634	struct pf_ruleset	*ruleset = NULL;
5635	struct pf_pdesc		 pd;
5636	int			 off, dirndx, pqid = 0;
5637
5638	M_ASSERTPKTHDR(m);
5639
5640	if (!V_pf_status.running)
5641		return (PF_PASS);
5642
5643	memset(&pd, 0, sizeof(pd));
5644
5645	kif = (struct pfi_kif *)ifp->if_pf_kif;
5646
5647	if (kif == NULL) {
5648		DPFPRINTF(PF_DEBUG_URGENT,
5649		    ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5650		return (PF_DROP);
5651	}
5652	if (kif->pfik_flags & PFI_IFLAG_SKIP)
5653		return (PF_PASS);
5654
5655	if (m->m_flags & M_SKIP_FIREWALL)
5656		return (PF_PASS);
5657
5658	pd.pf_mtag = pf_find_mtag(m);
5659
5660	PF_RULES_RLOCK();
5661
5662	if (ip_divert_ptr != NULL &&
5663	    ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5664		struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5665		if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5666			if (pd.pf_mtag == NULL &&
5667			    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5668				action = PF_DROP;
5669				goto done;
5670			}
5671			pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5672			m_tag_delete(m, ipfwtag);
5673		}
5674		if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5675			m->m_flags |= M_FASTFWD_OURS;
5676			pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5677		}
5678	} else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5679		/* We do IP header normalization and packet reassembly here */
5680		action = PF_DROP;
5681		goto done;
5682	}
5683	m = *m0;	/* pf_normalize messes with m0 */
5684	h = mtod(m, struct ip *);
5685
5686	off = h->ip_hl << 2;
5687	if (off < (int)sizeof(struct ip)) {
5688		action = PF_DROP;
5689		REASON_SET(&reason, PFRES_SHORT);
5690		log = 1;
5691		goto done;
5692	}
5693
5694	pd.src = (struct pf_addr *)&h->ip_src;
5695	pd.dst = (struct pf_addr *)&h->ip_dst;
5696	pd.sport = pd.dport = NULL;
5697	pd.ip_sum = &h->ip_sum;
5698	pd.proto_sum = NULL;
5699	pd.proto = h->ip_p;
5700	pd.dir = dir;
5701	pd.sidx = (dir == PF_IN) ? 0 : 1;
5702	pd.didx = (dir == PF_IN) ? 1 : 0;
5703	pd.af = AF_INET;
5704	pd.tos = h->ip_tos;
5705	pd.tot_len = ntohs(h->ip_len);
5706
5707	/* handle fragments that didn't get reassembled by normalization */
5708	if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5709		action = pf_test_fragment(&r, dir, kif, m, h,
5710		    &pd, &a, &ruleset);
5711		goto done;
5712	}
5713
5714	switch (h->ip_p) {
5715
5716	case IPPROTO_TCP: {
5717		struct tcphdr	th;
5718
5719		pd.hdr.tcp = &th;
5720		if (!pf_pull_hdr(m, off, &th, sizeof(th),
5721		    &action, &reason, AF_INET)) {
5722			log = action != PF_PASS;
5723			goto done;
5724		}
5725		pd.p_len = pd.tot_len - off - (th.th_off << 2);
5726		if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5727			pqid = 1;
5728		action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5729		if (action == PF_DROP)
5730			goto done;
5731		action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5732		    &reason);
5733		if (action == PF_PASS) {
5734			if (pfsync_update_state_ptr != NULL)
5735				pfsync_update_state_ptr(s);
5736			r = s->rule.ptr;
5737			a = s->anchor.ptr;
5738			log = s->log;
5739		} else if (s == NULL)
5740			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5741			    &a, &ruleset, inp);
5742		break;
5743	}
5744
5745	case IPPROTO_UDP: {
5746		struct udphdr	uh;
5747
5748		pd.hdr.udp = &uh;
5749		if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5750		    &action, &reason, AF_INET)) {
5751			log = action != PF_PASS;
5752			goto done;
5753		}
5754		if (uh.uh_dport == 0 ||
5755		    ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5756		    ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5757			action = PF_DROP;
5758			REASON_SET(&reason, PFRES_SHORT);
5759			goto done;
5760		}
5761		action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5762		if (action == PF_PASS) {
5763			if (pfsync_update_state_ptr != NULL)
5764				pfsync_update_state_ptr(s);
5765			r = s->rule.ptr;
5766			a = s->anchor.ptr;
5767			log = s->log;
5768		} else if (s == NULL)
5769			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5770			    &a, &ruleset, inp);
5771		break;
5772	}
5773
5774	case IPPROTO_ICMP: {
5775		struct icmp	ih;
5776
5777		pd.hdr.icmp = &ih;
5778		if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5779		    &action, &reason, AF_INET)) {
5780			log = action != PF_PASS;
5781			goto done;
5782		}
5783		action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5784		    &reason);
5785		if (action == PF_PASS) {
5786			if (pfsync_update_state_ptr != NULL)
5787				pfsync_update_state_ptr(s);
5788			r = s->rule.ptr;
5789			a = s->anchor.ptr;
5790			log = s->log;
5791		} else if (s == NULL)
5792			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5793			    &a, &ruleset, inp);
5794		break;
5795	}
5796
5797#ifdef INET6
5798	case IPPROTO_ICMPV6: {
5799		action = PF_DROP;
5800		DPFPRINTF(PF_DEBUG_MISC,
5801		    ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
5802		goto done;
5803	}
5804#endif
5805
5806	default:
5807		action = pf_test_state_other(&s, dir, kif, m, &pd);
5808		if (action == PF_PASS) {
5809			if (pfsync_update_state_ptr != NULL)
5810				pfsync_update_state_ptr(s);
5811			r = s->rule.ptr;
5812			a = s->anchor.ptr;
5813			log = s->log;
5814		} else if (s == NULL)
5815			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5816			    &a, &ruleset, inp);
5817		break;
5818	}
5819
5820done:
5821	PF_RULES_RUNLOCK();
5822	if (action == PF_PASS && h->ip_hl > 5 &&
5823	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
5824		action = PF_DROP;
5825		REASON_SET(&reason, PFRES_IPOPTIONS);
5826		log = 1;
5827		DPFPRINTF(PF_DEBUG_MISC,
5828		    ("pf: dropping packet with ip options\n"));
5829	}
5830
5831	if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
5832		action = PF_DROP;
5833		REASON_SET(&reason, PFRES_MEMORY);
5834	}
5835	if (r->rtableid >= 0)
5836		M_SETFIB(m, r->rtableid);
5837
5838#ifdef ALTQ
5839	if (action == PF_PASS && r->qid) {
5840		if (pd.pf_mtag == NULL &&
5841		    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5842			action = PF_DROP;
5843			REASON_SET(&reason, PFRES_MEMORY);
5844		}
5845		if (pqid || (pd.tos & IPTOS_LOWDELAY))
5846			pd.pf_mtag->qid = r->pqid;
5847		else
5848			pd.pf_mtag->qid = r->qid;
5849		/* add hints for ecn */
5850		pd.pf_mtag->hdr = h;
5851
5852	}
5853#endif /* ALTQ */
5854
5855	/*
5856	 * connections redirected to loopback should not match sockets
5857	 * bound specifically to loopback due to security implications,
5858	 * see tcp_input() and in_pcblookup_listen().
5859	 */
5860	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
5861	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
5862	    (s->nat_rule.ptr->action == PF_RDR ||
5863	    s->nat_rule.ptr->action == PF_BINAT) &&
5864	    (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
5865		m->m_flags |= M_SKIP_FIREWALL;
5866
5867	if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
5868	    !PACKET_LOOPED(&pd)) {
5869
5870		ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
5871		    sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
5872		if (ipfwtag != NULL) {
5873			((struct ipfw_rule_ref *)(ipfwtag+1))->info =
5874			    ntohs(r->divert.port);
5875			((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
5876
5877			if (s)
5878				PF_STATE_UNLOCK(s);
5879
5880			m_tag_prepend(m, ipfwtag);
5881			if (m->m_flags & M_FASTFWD_OURS) {
5882				if (pd.pf_mtag == NULL &&
5883				    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5884					action = PF_DROP;
5885					REASON_SET(&reason, PFRES_MEMORY);
5886					log = 1;
5887					DPFPRINTF(PF_DEBUG_MISC,
5888					    ("pf: failed to allocate tag\n"));
5889				}
5890				pd.pf_mtag->flags |= PF_FASTFWD_OURS_PRESENT;
5891				m->m_flags &= ~M_FASTFWD_OURS;
5892			}
5893			ip_divert_ptr(*m0, dir ==  PF_IN ? DIR_IN : DIR_OUT);
5894			*m0 = NULL;
5895
5896			return (action);
5897		} else {
5898			/* XXX: ipfw has the same behaviour! */
5899			action = PF_DROP;
5900			REASON_SET(&reason, PFRES_MEMORY);
5901			log = 1;
5902			DPFPRINTF(PF_DEBUG_MISC,
5903			    ("pf: failed to allocate divert tag\n"));
5904		}
5905	}
5906
5907	if (log) {
5908		struct pf_rule *lr;
5909
5910		if (s != NULL && s->nat_rule.ptr != NULL &&
5911		    s->nat_rule.ptr->log & PF_LOG_ALL)
5912			lr = s->nat_rule.ptr;
5913		else
5914			lr = r;
5915		PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
5916		    (s == NULL));
5917	}
5918
5919	kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
5920	kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
5921
5922	if (action == PF_PASS || r->action == PF_DROP) {
5923		dirndx = (dir == PF_OUT);
5924		r->packets[dirndx]++;
5925		r->bytes[dirndx] += pd.tot_len;
5926		if (a != NULL) {
5927			a->packets[dirndx]++;
5928			a->bytes[dirndx] += pd.tot_len;
5929		}
5930		if (s != NULL) {
5931			if (s->nat_rule.ptr != NULL) {
5932				s->nat_rule.ptr->packets[dirndx]++;
5933				s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
5934			}
5935			if (s->src_node != NULL) {
5936				s->src_node->packets[dirndx]++;
5937				s->src_node->bytes[dirndx] += pd.tot_len;
5938			}
5939			if (s->nat_src_node != NULL) {
5940				s->nat_src_node->packets[dirndx]++;
5941				s->nat_src_node->bytes[dirndx] += pd.tot_len;
5942			}
5943			dirndx = (dir == s->direction) ? 0 : 1;
5944			s->packets[dirndx]++;
5945			s->bytes[dirndx] += pd.tot_len;
5946		}
5947		tr = r;
5948		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
5949		if (nr != NULL && r == &V_pf_default_rule)
5950			tr = nr;
5951		if (tr->src.addr.type == PF_ADDR_TABLE)
5952			pfr_update_stats(tr->src.addr.p.tbl,
5953			    (s == NULL) ? pd.src :
5954			    &s->key[(s->direction == PF_IN)]->
5955				addr[(s->direction == PF_OUT)],
5956			    pd.af, pd.tot_len, dir == PF_OUT,
5957			    r->action == PF_PASS, tr->src.neg);
5958		if (tr->dst.addr.type == PF_ADDR_TABLE)
5959			pfr_update_stats(tr->dst.addr.p.tbl,
5960			    (s == NULL) ? pd.dst :
5961			    &s->key[(s->direction == PF_IN)]->
5962				addr[(s->direction == PF_IN)],
5963			    pd.af, pd.tot_len, dir == PF_OUT,
5964			    r->action == PF_PASS, tr->dst.neg);
5965	}
5966
5967	switch (action) {
5968	case PF_SYNPROXY_DROP:
5969		m_freem(*m0);
5970	case PF_DEFER:
5971		*m0 = NULL;
5972		action = PF_PASS;
5973		break;
5974	default:
5975		/* pf_route() returns unlocked. */
5976		if (r->rt) {
5977			pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
5978			return (action);
5979		}
5980		break;
5981	}
5982	if (s)
5983		PF_STATE_UNLOCK(s);
5984
5985	return (action);
5986}
5987#endif /* INET */
5988
5989#ifdef INET6
5990int
5991pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5992{
5993	struct pfi_kif		*kif;
5994	u_short			 action, reason = 0, log = 0;
5995	struct mbuf		*m = *m0, *n = NULL;
5996	struct ip6_hdr		*h = NULL;
5997	struct pf_rule		*a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5998	struct pf_state		*s = NULL;
5999	struct pf_ruleset	*ruleset = NULL;
6000	struct pf_pdesc		 pd;
6001	int			 off, terminal = 0, dirndx, rh_cnt = 0;
6002
6003	M_ASSERTPKTHDR(m);
6004
6005	if (!V_pf_status.running)
6006		return (PF_PASS);
6007
6008	memset(&pd, 0, sizeof(pd));
6009	pd.pf_mtag = pf_find_mtag(m);
6010
6011	if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6012		return (PF_PASS);
6013
6014	kif = (struct pfi_kif *)ifp->if_pf_kif;
6015	if (kif == NULL) {
6016		DPFPRINTF(PF_DEBUG_URGENT,
6017		    ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6018		return (PF_DROP);
6019	}
6020	if (kif->pfik_flags & PFI_IFLAG_SKIP)
6021		return (PF_PASS);
6022
6023	PF_RULES_RLOCK();
6024
6025	/* We do IP header normalization and packet reassembly here */
6026	if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6027		action = PF_DROP;
6028		goto done;
6029	}
6030	m = *m0;	/* pf_normalize messes with m0 */
6031	h = mtod(m, struct ip6_hdr *);
6032
6033#if 1
6034	/*
6035	 * we do not support jumbogram yet.  if we keep going, zero ip6_plen
6036	 * will do something bad, so drop the packet for now.
6037	 */
6038	if (htons(h->ip6_plen) == 0) {
6039		action = PF_DROP;
6040		REASON_SET(&reason, PFRES_NORM);	/*XXX*/
6041		goto done;
6042	}
6043#endif
6044
6045	pd.src = (struct pf_addr *)&h->ip6_src;
6046	pd.dst = (struct pf_addr *)&h->ip6_dst;
6047	pd.sport = pd.dport = NULL;
6048	pd.ip_sum = NULL;
6049	pd.proto_sum = NULL;
6050	pd.dir = dir;
6051	pd.sidx = (dir == PF_IN) ? 0 : 1;
6052	pd.didx = (dir == PF_IN) ? 1 : 0;
6053	pd.af = AF_INET6;
6054	pd.tos = 0;
6055	pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6056
6057	off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6058	pd.proto = h->ip6_nxt;
6059	do {
6060		switch (pd.proto) {
6061		case IPPROTO_FRAGMENT:
6062			action = pf_test_fragment(&r, dir, kif, m, h,
6063			    &pd, &a, &ruleset);
6064			if (action == PF_DROP)
6065				REASON_SET(&reason, PFRES_FRAG);
6066			goto done;
6067		case IPPROTO_ROUTING: {
6068			struct ip6_rthdr rthdr;
6069
6070			if (rh_cnt++) {
6071				DPFPRINTF(PF_DEBUG_MISC,
6072				    ("pf: IPv6 more than one rthdr\n"));
6073				action = PF_DROP;
6074				REASON_SET(&reason, PFRES_IPOPTIONS);
6075				log = 1;
6076				goto done;
6077			}
6078			if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6079			    &reason, pd.af)) {
6080				DPFPRINTF(PF_DEBUG_MISC,
6081				    ("pf: IPv6 short rthdr\n"));
6082				action = PF_DROP;
6083				REASON_SET(&reason, PFRES_SHORT);
6084				log = 1;
6085				goto done;
6086			}
6087			if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6088				DPFPRINTF(PF_DEBUG_MISC,
6089				    ("pf: IPv6 rthdr0\n"));
6090				action = PF_DROP;
6091				REASON_SET(&reason, PFRES_IPOPTIONS);
6092				log = 1;
6093				goto done;
6094			}
6095			/* FALLTHROUGH */
6096		}
6097		case IPPROTO_AH:
6098		case IPPROTO_HOPOPTS:
6099		case IPPROTO_DSTOPTS: {
6100			/* get next header and header length */
6101			struct ip6_ext	opt6;
6102
6103			if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6104			    NULL, &reason, pd.af)) {
6105				DPFPRINTF(PF_DEBUG_MISC,
6106				    ("pf: IPv6 short opt\n"));
6107				action = PF_DROP;
6108				log = 1;
6109				goto done;
6110			}
6111			if (pd.proto == IPPROTO_AH)
6112				off += (opt6.ip6e_len + 2) * 4;
6113			else
6114				off += (opt6.ip6e_len + 1) * 8;
6115			pd.proto = opt6.ip6e_nxt;
6116			/* goto the next header */
6117			break;
6118		}
6119		default:
6120			terminal++;
6121			break;
6122		}
6123	} while (!terminal);
6124
6125	/* if there's no routing header, use unmodified mbuf for checksumming */
6126	if (!n)
6127		n = m;
6128
6129	switch (pd.proto) {
6130
6131	case IPPROTO_TCP: {
6132		struct tcphdr	th;
6133
6134		pd.hdr.tcp = &th;
6135		if (!pf_pull_hdr(m, off, &th, sizeof(th),
6136		    &action, &reason, AF_INET6)) {
6137			log = action != PF_PASS;
6138			goto done;
6139		}
6140		pd.p_len = pd.tot_len - off - (th.th_off << 2);
6141		action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6142		if (action == PF_DROP)
6143			goto done;
6144		action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6145		    &reason);
6146		if (action == PF_PASS) {
6147			if (pfsync_update_state_ptr != NULL)
6148				pfsync_update_state_ptr(s);
6149			r = s->rule.ptr;
6150			a = s->anchor.ptr;
6151			log = s->log;
6152		} else if (s == NULL)
6153			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6154			    &a, &ruleset, inp);
6155		break;
6156	}
6157
6158	case IPPROTO_UDP: {
6159		struct udphdr	uh;
6160
6161		pd.hdr.udp = &uh;
6162		if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6163		    &action, &reason, AF_INET6)) {
6164			log = action != PF_PASS;
6165			goto done;
6166		}
6167		if (uh.uh_dport == 0 ||
6168		    ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6169		    ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6170			action = PF_DROP;
6171			REASON_SET(&reason, PFRES_SHORT);
6172			goto done;
6173		}
6174		action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6175		if (action == PF_PASS) {
6176			if (pfsync_update_state_ptr != NULL)
6177				pfsync_update_state_ptr(s);
6178			r = s->rule.ptr;
6179			a = s->anchor.ptr;
6180			log = s->log;
6181		} else if (s == NULL)
6182			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6183			    &a, &ruleset, inp);
6184		break;
6185	}
6186
6187	case IPPROTO_ICMP: {
6188		action = PF_DROP;
6189		DPFPRINTF(PF_DEBUG_MISC,
6190		    ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6191		goto done;
6192	}
6193
6194	case IPPROTO_ICMPV6: {
6195		struct icmp6_hdr	ih;
6196
6197		pd.hdr.icmp6 = &ih;
6198		if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6199		    &action, &reason, AF_INET6)) {
6200			log = action != PF_PASS;
6201			goto done;
6202		}
6203		action = pf_test_state_icmp(&s, dir, kif,
6204		    m, off, h, &pd, &reason);
6205		if (action == PF_PASS) {
6206			if (pfsync_update_state_ptr != NULL)
6207				pfsync_update_state_ptr(s);
6208			r = s->rule.ptr;
6209			a = s->anchor.ptr;
6210			log = s->log;
6211		} else if (s == NULL)
6212			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6213			    &a, &ruleset, inp);
6214		break;
6215	}
6216
6217	default:
6218		action = pf_test_state_other(&s, dir, kif, m, &pd);
6219		if (action == PF_PASS) {
6220			if (pfsync_update_state_ptr != NULL)
6221				pfsync_update_state_ptr(s);
6222			r = s->rule.ptr;
6223			a = s->anchor.ptr;
6224			log = s->log;
6225		} else if (s == NULL)
6226			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6227			    &a, &ruleset, inp);
6228		break;
6229	}
6230
6231done:
6232	PF_RULES_RUNLOCK();
6233	if (n != m) {
6234		m_freem(n);
6235		n = NULL;
6236	}
6237
6238	/* handle dangerous IPv6 extension headers. */
6239	if (action == PF_PASS && rh_cnt &&
6240	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6241		action = PF_DROP;
6242		REASON_SET(&reason, PFRES_IPOPTIONS);
6243		log = 1;
6244		DPFPRINTF(PF_DEBUG_MISC,
6245		    ("pf: dropping packet with dangerous v6 headers\n"));
6246	}
6247
6248	if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6249		action = PF_DROP;
6250		REASON_SET(&reason, PFRES_MEMORY);
6251	}
6252	if (r->rtableid >= 0)
6253		M_SETFIB(m, r->rtableid);
6254
6255#ifdef ALTQ
6256	if (action == PF_PASS && r->qid) {
6257		if (pd.pf_mtag == NULL &&
6258		    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6259			action = PF_DROP;
6260			REASON_SET(&reason, PFRES_MEMORY);
6261		}
6262		if (pd.tos & IPTOS_LOWDELAY)
6263			pd.pf_mtag->qid = r->pqid;
6264		else
6265			pd.pf_mtag->qid = r->qid;
6266		/* add hints for ecn */
6267		pd.pf_mtag->hdr = h;
6268	}
6269#endif /* ALTQ */
6270
6271	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6272	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6273	    (s->nat_rule.ptr->action == PF_RDR ||
6274	    s->nat_rule.ptr->action == PF_BINAT) &&
6275	    IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6276		m->m_flags |= M_SKIP_FIREWALL;
6277
6278	/* XXX: Anybody working on it?! */
6279	if (r->divert.port)
6280		printf("pf: divert(9) is not supported for IPv6\n");
6281
6282	if (log) {
6283		struct pf_rule *lr;
6284
6285		if (s != NULL && s->nat_rule.ptr != NULL &&
6286		    s->nat_rule.ptr->log & PF_LOG_ALL)
6287			lr = s->nat_rule.ptr;
6288		else
6289			lr = r;
6290		PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6291		    &pd, (s == NULL));
6292	}
6293
6294	kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6295	kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6296
6297	if (action == PF_PASS || r->action == PF_DROP) {
6298		dirndx = (dir == PF_OUT);
6299		r->packets[dirndx]++;
6300		r->bytes[dirndx] += pd.tot_len;
6301		if (a != NULL) {
6302			a->packets[dirndx]++;
6303			a->bytes[dirndx] += pd.tot_len;
6304		}
6305		if (s != NULL) {
6306			if (s->nat_rule.ptr != NULL) {
6307				s->nat_rule.ptr->packets[dirndx]++;
6308				s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6309			}
6310			if (s->src_node != NULL) {
6311				s->src_node->packets[dirndx]++;
6312				s->src_node->bytes[dirndx] += pd.tot_len;
6313			}
6314			if (s->nat_src_node != NULL) {
6315				s->nat_src_node->packets[dirndx]++;
6316				s->nat_src_node->bytes[dirndx] += pd.tot_len;
6317			}
6318			dirndx = (dir == s->direction) ? 0 : 1;
6319			s->packets[dirndx]++;
6320			s->bytes[dirndx] += pd.tot_len;
6321		}
6322		tr = r;
6323		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6324		if (nr != NULL && r == &V_pf_default_rule)
6325			tr = nr;
6326		if (tr->src.addr.type == PF_ADDR_TABLE)
6327			pfr_update_stats(tr->src.addr.p.tbl,
6328			    (s == NULL) ? pd.src :
6329			    &s->key[(s->direction == PF_IN)]->addr[0],
6330			    pd.af, pd.tot_len, dir == PF_OUT,
6331			    r->action == PF_PASS, tr->src.neg);
6332		if (tr->dst.addr.type == PF_ADDR_TABLE)
6333			pfr_update_stats(tr->dst.addr.p.tbl,
6334			    (s == NULL) ? pd.dst :
6335			    &s->key[(s->direction == PF_IN)]->addr[1],
6336			    pd.af, pd.tot_len, dir == PF_OUT,
6337			    r->action == PF_PASS, tr->dst.neg);
6338	}
6339
6340	switch (action) {
6341	case PF_SYNPROXY_DROP:
6342		m_freem(*m0);
6343	case PF_DEFER:
6344		*m0 = NULL;
6345		action = PF_PASS;
6346		break;
6347	default:
6348		/* pf_route6() returns unlocked. */
6349		if (r->rt) {
6350			pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
6351			return (action);
6352		}
6353		break;
6354	}
6355
6356	if (s)
6357		PF_STATE_UNLOCK(s);
6358
6359	return (action);
6360}
6361#endif /* INET6 */
6362