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