xref: /freebsd/sys/netpfil/pf/pf.c (revision e17f5b1d)
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_RULESRCTRACK ||
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 
1489 			/* Wait until V_pf_default_rule is initialized. */
1490 			if (V_pf_vnet_active == 0) {
1491 				CURVNET_RESTORE();
1492 				continue;
1493 			}
1494 
1495 			/*
1496 			 *  Process 1/interval fraction of the state
1497 			 * table every run.
1498 			 */
1499 			V_pf_purge_idx =
1500 			    pf_purge_expired_states(V_pf_purge_idx, pf_hashmask /
1501 			    (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1502 
1503 			/*
1504 			 * Purge other expired types every
1505 			 * PFTM_INTERVAL seconds.
1506 			 */
1507 			if (V_pf_purge_idx == 0) {
1508 				/*
1509 				 * Order is important:
1510 				 * - states and src nodes reference rules
1511 				 * - states and rules reference kifs
1512 				 */
1513 				pf_purge_expired_fragments();
1514 				pf_purge_expired_src_nodes();
1515 				pf_purge_unlinked_rules();
1516 				pfi_kif_purge();
1517 			}
1518 			CURVNET_RESTORE();
1519 		}
1520 		VNET_LIST_RUNLOCK();
1521 	}
1522 
1523 	pf_end_threads++;
1524 	sx_xunlock(&pf_end_lock);
1525 	kproc_exit(0);
1526 }
1527 
1528 void
1529 pf_unload_vnet_purge(void)
1530 {
1531 
1532 	/*
1533 	 * To cleanse up all kifs and rules we need
1534 	 * two runs: first one clears reference flags,
1535 	 * then pf_purge_expired_states() doesn't
1536 	 * raise them, and then second run frees.
1537 	 */
1538 	pf_purge_unlinked_rules();
1539 	pfi_kif_purge();
1540 
1541 	/*
1542 	 * Now purge everything.
1543 	 */
1544 	pf_purge_expired_states(0, pf_hashmask);
1545 	pf_purge_fragments(UINT_MAX);
1546 	pf_purge_expired_src_nodes();
1547 
1548 	/*
1549 	 * Now all kifs & rules should be unreferenced,
1550 	 * thus should be successfully freed.
1551 	 */
1552 	pf_purge_unlinked_rules();
1553 	pfi_kif_purge();
1554 }
1555 
1556 
1557 u_int32_t
1558 pf_state_expires(const struct pf_state *state)
1559 {
1560 	u_int32_t	timeout;
1561 	u_int32_t	start;
1562 	u_int32_t	end;
1563 	u_int32_t	states;
1564 
1565 	/* handle all PFTM_* > PFTM_MAX here */
1566 	if (state->timeout == PFTM_PURGE)
1567 		return (time_uptime);
1568 	KASSERT(state->timeout != PFTM_UNLINKED,
1569 	    ("pf_state_expires: timeout == PFTM_UNLINKED"));
1570 	KASSERT((state->timeout < PFTM_MAX),
1571 	    ("pf_state_expires: timeout > PFTM_MAX"));
1572 	timeout = state->rule.ptr->timeout[state->timeout];
1573 	if (!timeout)
1574 		timeout = V_pf_default_rule.timeout[state->timeout];
1575 	start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1576 	if (start && state->rule.ptr != &V_pf_default_rule) {
1577 		end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1578 		states = counter_u64_fetch(state->rule.ptr->states_cur);
1579 	} else {
1580 		start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1581 		end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1582 		states = V_pf_status.states;
1583 	}
1584 	if (end && states > start && start < end) {
1585 		if (states < end) {
1586 			timeout = (u_int64_t)timeout * (end - states) /
1587 			    (end - start);
1588 			return (state->expire + timeout);
1589 		}
1590 		else
1591 			return (time_uptime);
1592 	}
1593 	return (state->expire + timeout);
1594 }
1595 
1596 void
1597 pf_purge_expired_src_nodes()
1598 {
1599 	struct pf_src_node_list	 freelist;
1600 	struct pf_srchash	*sh;
1601 	struct pf_src_node	*cur, *next;
1602 	int i;
1603 
1604 	LIST_INIT(&freelist);
1605 	for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1606 	    PF_HASHROW_LOCK(sh);
1607 	    LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1608 		if (cur->states == 0 && cur->expire <= time_uptime) {
1609 			pf_unlink_src_node(cur);
1610 			LIST_INSERT_HEAD(&freelist, cur, entry);
1611 		} else if (cur->rule.ptr != NULL)
1612 			cur->rule.ptr->rule_flag |= PFRULE_REFS;
1613 	    PF_HASHROW_UNLOCK(sh);
1614 	}
1615 
1616 	pf_free_src_nodes(&freelist);
1617 
1618 	V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1619 }
1620 
1621 static void
1622 pf_src_tree_remove_state(struct pf_state *s)
1623 {
1624 	struct pf_src_node *sn;
1625 	struct pf_srchash *sh;
1626 	uint32_t timeout;
1627 
1628 	timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1629 	    s->rule.ptr->timeout[PFTM_SRC_NODE] :
1630 	    V_pf_default_rule.timeout[PFTM_SRC_NODE];
1631 
1632 	if (s->src_node != NULL) {
1633 		sn = s->src_node;
1634 		sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1635 	    	PF_HASHROW_LOCK(sh);
1636 		if (s->src.tcp_est)
1637 			--sn->conn;
1638 		if (--sn->states == 0)
1639 			sn->expire = time_uptime + timeout;
1640 	    	PF_HASHROW_UNLOCK(sh);
1641 	}
1642 	if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1643 		sn = s->nat_src_node;
1644 		sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1645 	    	PF_HASHROW_LOCK(sh);
1646 		if (--sn->states == 0)
1647 			sn->expire = time_uptime + timeout;
1648 	    	PF_HASHROW_UNLOCK(sh);
1649 	}
1650 	s->src_node = s->nat_src_node = NULL;
1651 }
1652 
1653 /*
1654  * Unlink and potentilly free a state. Function may be
1655  * called with ID hash row locked, but always returns
1656  * unlocked, since it needs to go through key hash locking.
1657  */
1658 int
1659 pf_unlink_state(struct pf_state *s, u_int flags)
1660 {
1661 	struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1662 
1663 	if ((flags & PF_ENTER_LOCKED) == 0)
1664 		PF_HASHROW_LOCK(ih);
1665 	else
1666 		PF_HASHROW_ASSERT(ih);
1667 
1668 	if (s->timeout == PFTM_UNLINKED) {
1669 		/*
1670 		 * State is being processed
1671 		 * by pf_unlink_state() in
1672 		 * an other thread.
1673 		 */
1674 		PF_HASHROW_UNLOCK(ih);
1675 		return (0);	/* XXXGL: undefined actually */
1676 	}
1677 
1678 	if (s->src.state == PF_TCPS_PROXY_DST) {
1679 		/* XXX wire key the right one? */
1680 		pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1681 		    &s->key[PF_SK_WIRE]->addr[1],
1682 		    &s->key[PF_SK_WIRE]->addr[0],
1683 		    s->key[PF_SK_WIRE]->port[1],
1684 		    s->key[PF_SK_WIRE]->port[0],
1685 		    s->src.seqhi, s->src.seqlo + 1,
1686 		    TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1687 	}
1688 
1689 	LIST_REMOVE(s, entry);
1690 	pf_src_tree_remove_state(s);
1691 
1692 	if (V_pfsync_delete_state_ptr != NULL)
1693 		V_pfsync_delete_state_ptr(s);
1694 
1695 	STATE_DEC_COUNTERS(s);
1696 
1697 	s->timeout = PFTM_UNLINKED;
1698 
1699 	PF_HASHROW_UNLOCK(ih);
1700 
1701 	pf_detach_state(s);
1702 	/* pf_state_insert() initialises refs to 2, so we can never release the
1703 	 * last reference here, only in pf_release_state(). */
1704 	(void)refcount_release(&s->refs);
1705 
1706 	return (pf_release_state(s));
1707 }
1708 
1709 void
1710 pf_free_state(struct pf_state *cur)
1711 {
1712 
1713 	KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1714 	KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1715 	    cur->timeout));
1716 
1717 	pf_normalize_tcp_cleanup(cur);
1718 	uma_zfree(V_pf_state_z, cur);
1719 	counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1720 }
1721 
1722 /*
1723  * Called only from pf_purge_thread(), thus serialized.
1724  */
1725 static u_int
1726 pf_purge_expired_states(u_int i, int maxcheck)
1727 {
1728 	struct pf_idhash *ih;
1729 	struct pf_state *s;
1730 
1731 	V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1732 
1733 	/*
1734 	 * Go through hash and unlink states that expire now.
1735 	 */
1736 	while (maxcheck > 0) {
1737 
1738 		ih = &V_pf_idhash[i];
1739 
1740 		/* only take the lock if we expect to do work */
1741 		if (!LIST_EMPTY(&ih->states)) {
1742 relock:
1743 			PF_HASHROW_LOCK(ih);
1744 			LIST_FOREACH(s, &ih->states, entry) {
1745 				if (pf_state_expires(s) <= time_uptime) {
1746 					V_pf_status.states -=
1747 					    pf_unlink_state(s, PF_ENTER_LOCKED);
1748 					goto relock;
1749 				}
1750 				s->rule.ptr->rule_flag |= PFRULE_REFS;
1751 				if (s->nat_rule.ptr != NULL)
1752 					s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1753 				if (s->anchor.ptr != NULL)
1754 					s->anchor.ptr->rule_flag |= PFRULE_REFS;
1755 				s->kif->pfik_flags |= PFI_IFLAG_REFS;
1756 				if (s->rt_kif)
1757 					s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1758 			}
1759 			PF_HASHROW_UNLOCK(ih);
1760 		}
1761 
1762 		/* Return when we hit end of hash. */
1763 		if (++i > pf_hashmask) {
1764 			V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1765 			return (0);
1766 		}
1767 
1768 		maxcheck--;
1769 	}
1770 
1771 	V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1772 
1773 	return (i);
1774 }
1775 
1776 static void
1777 pf_purge_unlinked_rules()
1778 {
1779 	struct pf_rulequeue tmpq;
1780 	struct pf_rule *r, *r1;
1781 
1782 	/*
1783 	 * If we have overloading task pending, then we'd
1784 	 * better skip purging this time. There is a tiny
1785 	 * probability that overloading task references
1786 	 * an already unlinked rule.
1787 	 */
1788 	PF_OVERLOADQ_LOCK();
1789 	if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1790 		PF_OVERLOADQ_UNLOCK();
1791 		return;
1792 	}
1793 	PF_OVERLOADQ_UNLOCK();
1794 
1795 	/*
1796 	 * Do naive mark-and-sweep garbage collecting of old rules.
1797 	 * Reference flag is raised by pf_purge_expired_states()
1798 	 * and pf_purge_expired_src_nodes().
1799 	 *
1800 	 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1801 	 * use a temporary queue.
1802 	 */
1803 	TAILQ_INIT(&tmpq);
1804 	PF_UNLNKDRULES_LOCK();
1805 	TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1806 		if (!(r->rule_flag & PFRULE_REFS)) {
1807 			TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1808 			TAILQ_INSERT_TAIL(&tmpq, r, entries);
1809 		} else
1810 			r->rule_flag &= ~PFRULE_REFS;
1811 	}
1812 	PF_UNLNKDRULES_UNLOCK();
1813 
1814 	if (!TAILQ_EMPTY(&tmpq)) {
1815 		PF_RULES_WLOCK();
1816 		TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1817 			TAILQ_REMOVE(&tmpq, r, entries);
1818 			pf_free_rule(r);
1819 		}
1820 		PF_RULES_WUNLOCK();
1821 	}
1822 }
1823 
1824 void
1825 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1826 {
1827 	switch (af) {
1828 #ifdef INET
1829 	case AF_INET: {
1830 		u_int32_t a = ntohl(addr->addr32[0]);
1831 		printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1832 		    (a>>8)&255, a&255);
1833 		if (p) {
1834 			p = ntohs(p);
1835 			printf(":%u", p);
1836 		}
1837 		break;
1838 	}
1839 #endif /* INET */
1840 #ifdef INET6
1841 	case AF_INET6: {
1842 		u_int16_t b;
1843 		u_int8_t i, curstart, curend, maxstart, maxend;
1844 		curstart = curend = maxstart = maxend = 255;
1845 		for (i = 0; i < 8; i++) {
1846 			if (!addr->addr16[i]) {
1847 				if (curstart == 255)
1848 					curstart = i;
1849 				curend = i;
1850 			} else {
1851 				if ((curend - curstart) >
1852 				    (maxend - maxstart)) {
1853 					maxstart = curstart;
1854 					maxend = curend;
1855 				}
1856 				curstart = curend = 255;
1857 			}
1858 		}
1859 		if ((curend - curstart) >
1860 		    (maxend - maxstart)) {
1861 			maxstart = curstart;
1862 			maxend = curend;
1863 		}
1864 		for (i = 0; i < 8; i++) {
1865 			if (i >= maxstart && i <= maxend) {
1866 				if (i == 0)
1867 					printf(":");
1868 				if (i == maxend)
1869 					printf(":");
1870 			} else {
1871 				b = ntohs(addr->addr16[i]);
1872 				printf("%x", b);
1873 				if (i < 7)
1874 					printf(":");
1875 			}
1876 		}
1877 		if (p) {
1878 			p = ntohs(p);
1879 			printf("[%u]", p);
1880 		}
1881 		break;
1882 	}
1883 #endif /* INET6 */
1884 	}
1885 }
1886 
1887 void
1888 pf_print_state(struct pf_state *s)
1889 {
1890 	pf_print_state_parts(s, NULL, NULL);
1891 }
1892 
1893 static void
1894 pf_print_state_parts(struct pf_state *s,
1895     struct pf_state_key *skwp, struct pf_state_key *sksp)
1896 {
1897 	struct pf_state_key *skw, *sks;
1898 	u_int8_t proto, dir;
1899 
1900 	/* Do our best to fill these, but they're skipped if NULL */
1901 	skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1902 	sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1903 	proto = skw ? skw->proto : (sks ? sks->proto : 0);
1904 	dir = s ? s->direction : 0;
1905 
1906 	switch (proto) {
1907 	case IPPROTO_IPV4:
1908 		printf("IPv4");
1909 		break;
1910 	case IPPROTO_IPV6:
1911 		printf("IPv6");
1912 		break;
1913 	case IPPROTO_TCP:
1914 		printf("TCP");
1915 		break;
1916 	case IPPROTO_UDP:
1917 		printf("UDP");
1918 		break;
1919 	case IPPROTO_ICMP:
1920 		printf("ICMP");
1921 		break;
1922 	case IPPROTO_ICMPV6:
1923 		printf("ICMPv6");
1924 		break;
1925 	default:
1926 		printf("%u", proto);
1927 		break;
1928 	}
1929 	switch (dir) {
1930 	case PF_IN:
1931 		printf(" in");
1932 		break;
1933 	case PF_OUT:
1934 		printf(" out");
1935 		break;
1936 	}
1937 	if (skw) {
1938 		printf(" wire: ");
1939 		pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1940 		printf(" ");
1941 		pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1942 	}
1943 	if (sks) {
1944 		printf(" stack: ");
1945 		if (sks != skw) {
1946 			pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1947 			printf(" ");
1948 			pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1949 		} else
1950 			printf("-");
1951 	}
1952 	if (s) {
1953 		if (proto == IPPROTO_TCP) {
1954 			printf(" [lo=%u high=%u win=%u modulator=%u",
1955 			    s->src.seqlo, s->src.seqhi,
1956 			    s->src.max_win, s->src.seqdiff);
1957 			if (s->src.wscale && s->dst.wscale)
1958 				printf(" wscale=%u",
1959 				    s->src.wscale & PF_WSCALE_MASK);
1960 			printf("]");
1961 			printf(" [lo=%u high=%u win=%u modulator=%u",
1962 			    s->dst.seqlo, s->dst.seqhi,
1963 			    s->dst.max_win, s->dst.seqdiff);
1964 			if (s->src.wscale && s->dst.wscale)
1965 				printf(" wscale=%u",
1966 				s->dst.wscale & PF_WSCALE_MASK);
1967 			printf("]");
1968 		}
1969 		printf(" %u:%u", s->src.state, s->dst.state);
1970 	}
1971 }
1972 
1973 void
1974 pf_print_flags(u_int8_t f)
1975 {
1976 	if (f)
1977 		printf(" ");
1978 	if (f & TH_FIN)
1979 		printf("F");
1980 	if (f & TH_SYN)
1981 		printf("S");
1982 	if (f & TH_RST)
1983 		printf("R");
1984 	if (f & TH_PUSH)
1985 		printf("P");
1986 	if (f & TH_ACK)
1987 		printf("A");
1988 	if (f & TH_URG)
1989 		printf("U");
1990 	if (f & TH_ECE)
1991 		printf("E");
1992 	if (f & TH_CWR)
1993 		printf("W");
1994 }
1995 
1996 #define	PF_SET_SKIP_STEPS(i)					\
1997 	do {							\
1998 		while (head[i] != cur) {			\
1999 			head[i]->skip[i].ptr = cur;		\
2000 			head[i] = TAILQ_NEXT(head[i], entries);	\
2001 		}						\
2002 	} while (0)
2003 
2004 void
2005 pf_calc_skip_steps(struct pf_rulequeue *rules)
2006 {
2007 	struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
2008 	int i;
2009 
2010 	cur = TAILQ_FIRST(rules);
2011 	prev = cur;
2012 	for (i = 0; i < PF_SKIP_COUNT; ++i)
2013 		head[i] = cur;
2014 	while (cur != NULL) {
2015 
2016 		if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
2017 			PF_SET_SKIP_STEPS(PF_SKIP_IFP);
2018 		if (cur->direction != prev->direction)
2019 			PF_SET_SKIP_STEPS(PF_SKIP_DIR);
2020 		if (cur->af != prev->af)
2021 			PF_SET_SKIP_STEPS(PF_SKIP_AF);
2022 		if (cur->proto != prev->proto)
2023 			PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
2024 		if (cur->src.neg != prev->src.neg ||
2025 		    pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
2026 			PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
2027 		if (cur->src.port[0] != prev->src.port[0] ||
2028 		    cur->src.port[1] != prev->src.port[1] ||
2029 		    cur->src.port_op != prev->src.port_op)
2030 			PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
2031 		if (cur->dst.neg != prev->dst.neg ||
2032 		    pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
2033 			PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
2034 		if (cur->dst.port[0] != prev->dst.port[0] ||
2035 		    cur->dst.port[1] != prev->dst.port[1] ||
2036 		    cur->dst.port_op != prev->dst.port_op)
2037 			PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
2038 
2039 		prev = cur;
2040 		cur = TAILQ_NEXT(cur, entries);
2041 	}
2042 	for (i = 0; i < PF_SKIP_COUNT; ++i)
2043 		PF_SET_SKIP_STEPS(i);
2044 }
2045 
2046 static int
2047 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
2048 {
2049 	if (aw1->type != aw2->type)
2050 		return (1);
2051 	switch (aw1->type) {
2052 	case PF_ADDR_ADDRMASK:
2053 	case PF_ADDR_RANGE:
2054 		if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2055 			return (1);
2056 		if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2057 			return (1);
2058 		return (0);
2059 	case PF_ADDR_DYNIFTL:
2060 		return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2061 	case PF_ADDR_NOROUTE:
2062 	case PF_ADDR_URPFFAILED:
2063 		return (0);
2064 	case PF_ADDR_TABLE:
2065 		return (aw1->p.tbl != aw2->p.tbl);
2066 	default:
2067 		printf("invalid address type: %d\n", aw1->type);
2068 		return (1);
2069 	}
2070 }
2071 
2072 /**
2073  * Checksum updates are a little complicated because the checksum in the TCP/UDP
2074  * header isn't always a full checksum. In some cases (i.e. output) it's a
2075  * pseudo-header checksum, which is a partial checksum over src/dst IP
2076  * addresses, protocol number and length.
2077  *
2078  * That means we have the following cases:
2079  *  * Input or forwarding: we don't have TSO, the checksum fields are full
2080  *  	checksums, we need to update the checksum whenever we change anything.
2081  *  * Output (i.e. the checksum is a pseudo-header checksum):
2082  *  	x The field being updated is src/dst address or affects the length of
2083  *  	the packet. We need to update the pseudo-header checksum (note that this
2084  *  	checksum is not ones' complement).
2085  *  	x Some other field is being modified (e.g. src/dst port numbers): We
2086  *  	don't have to update anything.
2087  **/
2088 u_int16_t
2089 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2090 {
2091 	u_int32_t	l;
2092 
2093 	if (udp && !cksum)
2094 		return (0x0000);
2095 	l = cksum + old - new;
2096 	l = (l >> 16) + (l & 65535);
2097 	l = l & 65535;
2098 	if (udp && !l)
2099 		return (0xFFFF);
2100 	return (l);
2101 }
2102 
2103 u_int16_t
2104 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2105         u_int16_t new, u_int8_t udp)
2106 {
2107 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2108 		return (cksum);
2109 
2110 	return (pf_cksum_fixup(cksum, old, new, udp));
2111 }
2112 
2113 static void
2114 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2115         u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2116         sa_family_t af)
2117 {
2118 	struct pf_addr	ao;
2119 	u_int16_t	po = *p;
2120 
2121 	PF_ACPY(&ao, a, af);
2122 	PF_ACPY(a, an, af);
2123 
2124 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2125 		*pc = ~*pc;
2126 
2127 	*p = pn;
2128 
2129 	switch (af) {
2130 #ifdef INET
2131 	case AF_INET:
2132 		*ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2133 		    ao.addr16[0], an->addr16[0], 0),
2134 		    ao.addr16[1], an->addr16[1], 0);
2135 		*p = pn;
2136 
2137 		*pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2138 		    ao.addr16[0], an->addr16[0], u),
2139 		    ao.addr16[1], an->addr16[1], u);
2140 
2141 		*pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2142 		break;
2143 #endif /* INET */
2144 #ifdef INET6
2145 	case AF_INET6:
2146 		*pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2147 		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2148 		    pf_cksum_fixup(pf_cksum_fixup(*pc,
2149 		    ao.addr16[0], an->addr16[0], u),
2150 		    ao.addr16[1], an->addr16[1], u),
2151 		    ao.addr16[2], an->addr16[2], u),
2152 		    ao.addr16[3], an->addr16[3], u),
2153 		    ao.addr16[4], an->addr16[4], u),
2154 		    ao.addr16[5], an->addr16[5], u),
2155 		    ao.addr16[6], an->addr16[6], u),
2156 		    ao.addr16[7], an->addr16[7], u);
2157 
2158 		*pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2159 		break;
2160 #endif /* INET6 */
2161 	}
2162 
2163 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2164 	    CSUM_DELAY_DATA_IPV6)) {
2165 		*pc = ~*pc;
2166 		if (! *pc)
2167 			*pc = 0xffff;
2168 	}
2169 }
2170 
2171 /* Changes a u_int32_t.  Uses a void * so there are no align restrictions */
2172 void
2173 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2174 {
2175 	u_int32_t	ao;
2176 
2177 	memcpy(&ao, a, sizeof(ao));
2178 	memcpy(a, &an, sizeof(u_int32_t));
2179 	*c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2180 	    ao % 65536, an % 65536, u);
2181 }
2182 
2183 void
2184 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2185 {
2186 	u_int32_t	ao;
2187 
2188 	memcpy(&ao, a, sizeof(ao));
2189 	memcpy(a, &an, sizeof(u_int32_t));
2190 
2191 	*c = pf_proto_cksum_fixup(m,
2192 	    pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2193 	    ao % 65536, an % 65536, udp);
2194 }
2195 
2196 #ifdef INET6
2197 static void
2198 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2199 {
2200 	struct pf_addr	ao;
2201 
2202 	PF_ACPY(&ao, a, AF_INET6);
2203 	PF_ACPY(a, an, AF_INET6);
2204 
2205 	*c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2206 	    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2207 	    pf_cksum_fixup(pf_cksum_fixup(*c,
2208 	    ao.addr16[0], an->addr16[0], u),
2209 	    ao.addr16[1], an->addr16[1], u),
2210 	    ao.addr16[2], an->addr16[2], u),
2211 	    ao.addr16[3], an->addr16[3], u),
2212 	    ao.addr16[4], an->addr16[4], u),
2213 	    ao.addr16[5], an->addr16[5], u),
2214 	    ao.addr16[6], an->addr16[6], u),
2215 	    ao.addr16[7], an->addr16[7], u);
2216 }
2217 #endif /* INET6 */
2218 
2219 static void
2220 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2221     struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2222     u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2223 {
2224 	struct pf_addr	oia, ooa;
2225 
2226 	PF_ACPY(&oia, ia, af);
2227 	if (oa)
2228 		PF_ACPY(&ooa, oa, af);
2229 
2230 	/* Change inner protocol port, fix inner protocol checksum. */
2231 	if (ip != NULL) {
2232 		u_int16_t	oip = *ip;
2233 		u_int32_t	opc;
2234 
2235 		if (pc != NULL)
2236 			opc = *pc;
2237 		*ip = np;
2238 		if (pc != NULL)
2239 			*pc = pf_cksum_fixup(*pc, oip, *ip, u);
2240 		*ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2241 		if (pc != NULL)
2242 			*ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2243 	}
2244 	/* Change inner ip address, fix inner ip and icmp checksums. */
2245 	PF_ACPY(ia, na, af);
2246 	switch (af) {
2247 #ifdef INET
2248 	case AF_INET: {
2249 		u_int32_t	 oh2c = *h2c;
2250 
2251 		*h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2252 		    oia.addr16[0], ia->addr16[0], 0),
2253 		    oia.addr16[1], ia->addr16[1], 0);
2254 		*ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2255 		    oia.addr16[0], ia->addr16[0], 0),
2256 		    oia.addr16[1], ia->addr16[1], 0);
2257 		*ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2258 		break;
2259 	}
2260 #endif /* INET */
2261 #ifdef INET6
2262 	case AF_INET6:
2263 		*ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2264 		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2265 		    pf_cksum_fixup(pf_cksum_fixup(*ic,
2266 		    oia.addr16[0], ia->addr16[0], u),
2267 		    oia.addr16[1], ia->addr16[1], u),
2268 		    oia.addr16[2], ia->addr16[2], u),
2269 		    oia.addr16[3], ia->addr16[3], u),
2270 		    oia.addr16[4], ia->addr16[4], u),
2271 		    oia.addr16[5], ia->addr16[5], u),
2272 		    oia.addr16[6], ia->addr16[6], u),
2273 		    oia.addr16[7], ia->addr16[7], u);
2274 		break;
2275 #endif /* INET6 */
2276 	}
2277 	/* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2278 	if (oa) {
2279 		PF_ACPY(oa, na, af);
2280 		switch (af) {
2281 #ifdef INET
2282 		case AF_INET:
2283 			*hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2284 			    ooa.addr16[0], oa->addr16[0], 0),
2285 			    ooa.addr16[1], oa->addr16[1], 0);
2286 			break;
2287 #endif /* INET */
2288 #ifdef INET6
2289 		case AF_INET6:
2290 			*ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2291 			    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2292 			    pf_cksum_fixup(pf_cksum_fixup(*ic,
2293 			    ooa.addr16[0], oa->addr16[0], u),
2294 			    ooa.addr16[1], oa->addr16[1], u),
2295 			    ooa.addr16[2], oa->addr16[2], u),
2296 			    ooa.addr16[3], oa->addr16[3], u),
2297 			    ooa.addr16[4], oa->addr16[4], u),
2298 			    ooa.addr16[5], oa->addr16[5], u),
2299 			    ooa.addr16[6], oa->addr16[6], u),
2300 			    ooa.addr16[7], oa->addr16[7], u);
2301 			break;
2302 #endif /* INET6 */
2303 		}
2304 	}
2305 }
2306 
2307 
2308 /*
2309  * Need to modulate the sequence numbers in the TCP SACK option
2310  * (credits to Krzysztof Pfaff for report and patch)
2311  */
2312 static int
2313 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2314     struct tcphdr *th, struct pf_state_peer *dst)
2315 {
2316 	int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2317 	u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2318 	int copyback = 0, i, olen;
2319 	struct sackblk sack;
2320 
2321 #define	TCPOLEN_SACKLEN	(TCPOLEN_SACK + 2)
2322 	if (hlen < TCPOLEN_SACKLEN ||
2323 	    !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2324 		return 0;
2325 
2326 	while (hlen >= TCPOLEN_SACKLEN) {
2327 		olen = opt[1];
2328 		switch (*opt) {
2329 		case TCPOPT_EOL:	/* FALLTHROUGH */
2330 		case TCPOPT_NOP:
2331 			opt++;
2332 			hlen--;
2333 			break;
2334 		case TCPOPT_SACK:
2335 			if (olen > hlen)
2336 				olen = hlen;
2337 			if (olen >= TCPOLEN_SACKLEN) {
2338 				for (i = 2; i + TCPOLEN_SACK <= olen;
2339 				    i += TCPOLEN_SACK) {
2340 					memcpy(&sack, &opt[i], sizeof(sack));
2341 					pf_change_proto_a(m, &sack.start, &th->th_sum,
2342 					    htonl(ntohl(sack.start) - dst->seqdiff), 0);
2343 					pf_change_proto_a(m, &sack.end, &th->th_sum,
2344 					    htonl(ntohl(sack.end) - dst->seqdiff), 0);
2345 					memcpy(&opt[i], &sack, sizeof(sack));
2346 				}
2347 				copyback = 1;
2348 			}
2349 			/* FALLTHROUGH */
2350 		default:
2351 			if (olen < 2)
2352 				olen = 2;
2353 			hlen -= olen;
2354 			opt += olen;
2355 		}
2356 	}
2357 
2358 	if (copyback)
2359 		m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2360 	return (copyback);
2361 }
2362 
2363 static void
2364 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2365     const struct pf_addr *saddr, const struct pf_addr *daddr,
2366     u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2367     u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2368     u_int16_t rtag, struct ifnet *ifp)
2369 {
2370 	struct pf_send_entry *pfse;
2371 	struct mbuf	*m;
2372 	int		 len, tlen;
2373 #ifdef INET
2374 	struct ip	*h = NULL;
2375 #endif /* INET */
2376 #ifdef INET6
2377 	struct ip6_hdr	*h6 = NULL;
2378 #endif /* INET6 */
2379 	struct tcphdr	*th;
2380 	char		*opt;
2381 	struct pf_mtag  *pf_mtag;
2382 
2383 	len = 0;
2384 	th = NULL;
2385 
2386 	/* maximum segment size tcp option */
2387 	tlen = sizeof(struct tcphdr);
2388 	if (mss)
2389 		tlen += 4;
2390 
2391 	switch (af) {
2392 #ifdef INET
2393 	case AF_INET:
2394 		len = sizeof(struct ip) + tlen;
2395 		break;
2396 #endif /* INET */
2397 #ifdef INET6
2398 	case AF_INET6:
2399 		len = sizeof(struct ip6_hdr) + tlen;
2400 		break;
2401 #endif /* INET6 */
2402 	default:
2403 		panic("%s: unsupported af %d", __func__, af);
2404 	}
2405 
2406 	/* Allocate outgoing queue entry, mbuf and mbuf tag. */
2407 	pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2408 	if (pfse == NULL)
2409 		return;
2410 	m = m_gethdr(M_NOWAIT, MT_DATA);
2411 	if (m == NULL) {
2412 		free(pfse, M_PFTEMP);
2413 		return;
2414 	}
2415 #ifdef MAC
2416 	mac_netinet_firewall_send(m);
2417 #endif
2418 	if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2419 		free(pfse, M_PFTEMP);
2420 		m_freem(m);
2421 		return;
2422 	}
2423 	if (tag)
2424 		m->m_flags |= M_SKIP_FIREWALL;
2425 	pf_mtag->tag = rtag;
2426 
2427 	if (r != NULL && r->rtableid >= 0)
2428 		M_SETFIB(m, r->rtableid);
2429 
2430 #ifdef ALTQ
2431 	if (r != NULL && r->qid) {
2432 		pf_mtag->qid = r->qid;
2433 
2434 		/* add hints for ecn */
2435 		pf_mtag->hdr = mtod(m, struct ip *);
2436 	}
2437 #endif /* ALTQ */
2438 	m->m_data += max_linkhdr;
2439 	m->m_pkthdr.len = m->m_len = len;
2440 	m->m_pkthdr.rcvif = NULL;
2441 	bzero(m->m_data, len);
2442 	switch (af) {
2443 #ifdef INET
2444 	case AF_INET:
2445 		h = mtod(m, struct ip *);
2446 
2447 		/* IP header fields included in the TCP checksum */
2448 		h->ip_p = IPPROTO_TCP;
2449 		h->ip_len = htons(tlen);
2450 		h->ip_src.s_addr = saddr->v4.s_addr;
2451 		h->ip_dst.s_addr = daddr->v4.s_addr;
2452 
2453 		th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2454 		break;
2455 #endif /* INET */
2456 #ifdef INET6
2457 	case AF_INET6:
2458 		h6 = mtod(m, struct ip6_hdr *);
2459 
2460 		/* IP header fields included in the TCP checksum */
2461 		h6->ip6_nxt = IPPROTO_TCP;
2462 		h6->ip6_plen = htons(tlen);
2463 		memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2464 		memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2465 
2466 		th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2467 		break;
2468 #endif /* INET6 */
2469 	}
2470 
2471 	/* TCP header */
2472 	th->th_sport = sport;
2473 	th->th_dport = dport;
2474 	th->th_seq = htonl(seq);
2475 	th->th_ack = htonl(ack);
2476 	th->th_off = tlen >> 2;
2477 	th->th_flags = flags;
2478 	th->th_win = htons(win);
2479 
2480 	if (mss) {
2481 		opt = (char *)(th + 1);
2482 		opt[0] = TCPOPT_MAXSEG;
2483 		opt[1] = 4;
2484 		HTONS(mss);
2485 		bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2486 	}
2487 
2488 	switch (af) {
2489 #ifdef INET
2490 	case AF_INET:
2491 		/* TCP checksum */
2492 		th->th_sum = in_cksum(m, len);
2493 
2494 		/* Finish the IP header */
2495 		h->ip_v = 4;
2496 		h->ip_hl = sizeof(*h) >> 2;
2497 		h->ip_tos = IPTOS_LOWDELAY;
2498 		h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2499 		h->ip_len = htons(len);
2500 		h->ip_ttl = ttl ? ttl : V_ip_defttl;
2501 		h->ip_sum = 0;
2502 
2503 		pfse->pfse_type = PFSE_IP;
2504 		break;
2505 #endif /* INET */
2506 #ifdef INET6
2507 	case AF_INET6:
2508 		/* TCP checksum */
2509 		th->th_sum = in6_cksum(m, IPPROTO_TCP,
2510 		    sizeof(struct ip6_hdr), tlen);
2511 
2512 		h6->ip6_vfc |= IPV6_VERSION;
2513 		h6->ip6_hlim = IPV6_DEFHLIM;
2514 
2515 		pfse->pfse_type = PFSE_IP6;
2516 		break;
2517 #endif /* INET6 */
2518 	}
2519 	pfse->pfse_m = m;
2520 	pf_send(pfse);
2521 }
2522 
2523 static void
2524 pf_return(struct pf_rule *r, struct pf_rule *nr, struct pf_pdesc *pd,
2525     struct pf_state_key *sk, int off, struct mbuf *m, struct tcphdr *th,
2526     struct pfi_kif *kif, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen,
2527     u_short *reason)
2528 {
2529 	struct pf_addr	* const saddr = pd->src;
2530 	struct pf_addr	* const daddr = pd->dst;
2531 	sa_family_t	 af = pd->af;
2532 
2533 	/* undo NAT changes, if they have taken place */
2534 	if (nr != NULL) {
2535 		PF_ACPY(saddr, &sk->addr[pd->sidx], af);
2536 		PF_ACPY(daddr, &sk->addr[pd->didx], af);
2537 		if (pd->sport)
2538 			*pd->sport = sk->port[pd->sidx];
2539 		if (pd->dport)
2540 			*pd->dport = sk->port[pd->didx];
2541 		if (pd->proto_sum)
2542 			*pd->proto_sum = bproto_sum;
2543 		if (pd->ip_sum)
2544 			*pd->ip_sum = bip_sum;
2545 		m_copyback(m, off, hdrlen, pd->hdr.any);
2546 	}
2547 	if (pd->proto == IPPROTO_TCP &&
2548 	    ((r->rule_flag & PFRULE_RETURNRST) ||
2549 	    (r->rule_flag & PFRULE_RETURN)) &&
2550 	    !(th->th_flags & TH_RST)) {
2551 		u_int32_t	 ack = ntohl(th->th_seq) + pd->p_len;
2552 		int		 len = 0;
2553 #ifdef INET
2554 		struct ip	*h4;
2555 #endif
2556 #ifdef INET6
2557 		struct ip6_hdr	*h6;
2558 #endif
2559 
2560 		switch (af) {
2561 #ifdef INET
2562 		case AF_INET:
2563 			h4 = mtod(m, struct ip *);
2564 			len = ntohs(h4->ip_len) - off;
2565 			break;
2566 #endif
2567 #ifdef INET6
2568 		case AF_INET6:
2569 			h6 = mtod(m, struct ip6_hdr *);
2570 			len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
2571 			break;
2572 #endif
2573 		}
2574 
2575 		if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
2576 			REASON_SET(reason, PFRES_PROTCKSUM);
2577 		else {
2578 			if (th->th_flags & TH_SYN)
2579 				ack++;
2580 			if (th->th_flags & TH_FIN)
2581 				ack++;
2582 			pf_send_tcp(m, r, af, pd->dst,
2583 				pd->src, th->th_dport, th->th_sport,
2584 				ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
2585 				r->return_ttl, 1, 0, kif->pfik_ifp);
2586 		}
2587 	} else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
2588 		r->return_icmp)
2589 		pf_send_icmp(m, r->return_icmp >> 8,
2590 			r->return_icmp & 255, af, r);
2591 	else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
2592 		r->return_icmp6)
2593 		pf_send_icmp(m, r->return_icmp6 >> 8,
2594 			r->return_icmp6 & 255, af, r);
2595 }
2596 
2597 
2598 static int
2599 pf_ieee8021q_setpcp(struct mbuf *m, u_int8_t prio)
2600 {
2601 	struct m_tag *mtag;
2602 
2603 	KASSERT(prio <= PF_PRIO_MAX,
2604 	    ("%s with invalid pcp", __func__));
2605 
2606 	mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_OUT, NULL);
2607 	if (mtag == NULL) {
2608 		mtag = m_tag_alloc(MTAG_8021Q, MTAG_8021Q_PCP_OUT,
2609 		    sizeof(uint8_t), M_NOWAIT);
2610 		if (mtag == NULL)
2611 			return (ENOMEM);
2612 		m_tag_prepend(m, mtag);
2613 	}
2614 
2615 	*(uint8_t *)(mtag + 1) = prio;
2616 	return (0);
2617 }
2618 
2619 static int
2620 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
2621 {
2622 	struct m_tag *mtag;
2623 	u_int8_t mpcp;
2624 
2625 	mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
2626 	if (mtag == NULL)
2627 		return (0);
2628 
2629 	if (prio == PF_PRIO_ZERO)
2630 		prio = 0;
2631 
2632 	mpcp = *(uint8_t *)(mtag + 1);
2633 
2634 	return (mpcp == prio);
2635 }
2636 
2637 static void
2638 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2639     struct pf_rule *r)
2640 {
2641 	struct pf_send_entry *pfse;
2642 	struct mbuf *m0;
2643 	struct pf_mtag *pf_mtag;
2644 
2645 	/* Allocate outgoing queue entry, mbuf and mbuf tag. */
2646 	pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2647 	if (pfse == NULL)
2648 		return;
2649 
2650 	if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2651 		free(pfse, M_PFTEMP);
2652 		return;
2653 	}
2654 
2655 	if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2656 		free(pfse, M_PFTEMP);
2657 		return;
2658 	}
2659 	/* XXX: revisit */
2660 	m0->m_flags |= M_SKIP_FIREWALL;
2661 
2662 	if (r->rtableid >= 0)
2663 		M_SETFIB(m0, r->rtableid);
2664 
2665 #ifdef ALTQ
2666 	if (r->qid) {
2667 		pf_mtag->qid = r->qid;
2668 		/* add hints for ecn */
2669 		pf_mtag->hdr = mtod(m0, struct ip *);
2670 	}
2671 #endif /* ALTQ */
2672 
2673 	switch (af) {
2674 #ifdef INET
2675 	case AF_INET:
2676 		pfse->pfse_type = PFSE_ICMP;
2677 		break;
2678 #endif /* INET */
2679 #ifdef INET6
2680 	case AF_INET6:
2681 		pfse->pfse_type = PFSE_ICMP6;
2682 		break;
2683 #endif /* INET6 */
2684 	}
2685 	pfse->pfse_m = m0;
2686 	pfse->icmpopts.type = type;
2687 	pfse->icmpopts.code = code;
2688 	pf_send(pfse);
2689 }
2690 
2691 /*
2692  * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2693  * If n is 0, they match if they are equal. If n is != 0, they match if they
2694  * are different.
2695  */
2696 int
2697 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2698     struct pf_addr *b, sa_family_t af)
2699 {
2700 	int	match = 0;
2701 
2702 	switch (af) {
2703 #ifdef INET
2704 	case AF_INET:
2705 		if ((a->addr32[0] & m->addr32[0]) ==
2706 		    (b->addr32[0] & m->addr32[0]))
2707 			match++;
2708 		break;
2709 #endif /* INET */
2710 #ifdef INET6
2711 	case AF_INET6:
2712 		if (((a->addr32[0] & m->addr32[0]) ==
2713 		     (b->addr32[0] & m->addr32[0])) &&
2714 		    ((a->addr32[1] & m->addr32[1]) ==
2715 		     (b->addr32[1] & m->addr32[1])) &&
2716 		    ((a->addr32[2] & m->addr32[2]) ==
2717 		     (b->addr32[2] & m->addr32[2])) &&
2718 		    ((a->addr32[3] & m->addr32[3]) ==
2719 		     (b->addr32[3] & m->addr32[3])))
2720 			match++;
2721 		break;
2722 #endif /* INET6 */
2723 	}
2724 	if (match) {
2725 		if (n)
2726 			return (0);
2727 		else
2728 			return (1);
2729 	} else {
2730 		if (n)
2731 			return (1);
2732 		else
2733 			return (0);
2734 	}
2735 }
2736 
2737 /*
2738  * Return 1 if b <= a <= e, otherwise return 0.
2739  */
2740 int
2741 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2742     struct pf_addr *a, sa_family_t af)
2743 {
2744 	switch (af) {
2745 #ifdef INET
2746 	case AF_INET:
2747 		if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2748 		    (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2749 			return (0);
2750 		break;
2751 #endif /* INET */
2752 #ifdef INET6
2753 	case AF_INET6: {
2754 		int	i;
2755 
2756 		/* check a >= b */
2757 		for (i = 0; i < 4; ++i)
2758 			if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2759 				break;
2760 			else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2761 				return (0);
2762 		/* check a <= e */
2763 		for (i = 0; i < 4; ++i)
2764 			if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2765 				break;
2766 			else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2767 				return (0);
2768 		break;
2769 	}
2770 #endif /* INET6 */
2771 	}
2772 	return (1);
2773 }
2774 
2775 static int
2776 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2777 {
2778 	switch (op) {
2779 	case PF_OP_IRG:
2780 		return ((p > a1) && (p < a2));
2781 	case PF_OP_XRG:
2782 		return ((p < a1) || (p > a2));
2783 	case PF_OP_RRG:
2784 		return ((p >= a1) && (p <= a2));
2785 	case PF_OP_EQ:
2786 		return (p == a1);
2787 	case PF_OP_NE:
2788 		return (p != a1);
2789 	case PF_OP_LT:
2790 		return (p < a1);
2791 	case PF_OP_LE:
2792 		return (p <= a1);
2793 	case PF_OP_GT:
2794 		return (p > a1);
2795 	case PF_OP_GE:
2796 		return (p >= a1);
2797 	}
2798 	return (0); /* never reached */
2799 }
2800 
2801 int
2802 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2803 {
2804 	NTOHS(a1);
2805 	NTOHS(a2);
2806 	NTOHS(p);
2807 	return (pf_match(op, a1, a2, p));
2808 }
2809 
2810 static int
2811 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2812 {
2813 	if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2814 		return (0);
2815 	return (pf_match(op, a1, a2, u));
2816 }
2817 
2818 static int
2819 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2820 {
2821 	if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2822 		return (0);
2823 	return (pf_match(op, a1, a2, g));
2824 }
2825 
2826 int
2827 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2828 {
2829 	if (*tag == -1)
2830 		*tag = mtag;
2831 
2832 	return ((!r->match_tag_not && r->match_tag == *tag) ||
2833 	    (r->match_tag_not && r->match_tag != *tag));
2834 }
2835 
2836 int
2837 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2838 {
2839 
2840 	KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2841 
2842 	if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2843 		return (ENOMEM);
2844 
2845 	pd->pf_mtag->tag = tag;
2846 
2847 	return (0);
2848 }
2849 
2850 #define	PF_ANCHOR_STACKSIZE	32
2851 struct pf_anchor_stackframe {
2852 	struct pf_ruleset	*rs;
2853 	struct pf_rule		*r;	/* XXX: + match bit */
2854 	struct pf_anchor	*child;
2855 };
2856 
2857 /*
2858  * XXX: We rely on malloc(9) returning pointer aligned addresses.
2859  */
2860 #define	PF_ANCHORSTACK_MATCH	0x00000001
2861 #define	PF_ANCHORSTACK_MASK	(PF_ANCHORSTACK_MATCH)
2862 
2863 #define	PF_ANCHOR_MATCH(f)	((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2864 #define	PF_ANCHOR_RULE(f)	(struct pf_rule *)			\
2865 				((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2866 #define	PF_ANCHOR_SET_MATCH(f)	do { (f)->r = (void *) 			\
2867 				((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH);  \
2868 } while (0)
2869 
2870 void
2871 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2872     struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2873     int *match)
2874 {
2875 	struct pf_anchor_stackframe	*f;
2876 
2877 	PF_RULES_RASSERT();
2878 
2879 	if (match)
2880 		*match = 0;
2881 	if (*depth >= PF_ANCHOR_STACKSIZE) {
2882 		printf("%s: anchor stack overflow on %s\n",
2883 		    __func__, (*r)->anchor->name);
2884 		*r = TAILQ_NEXT(*r, entries);
2885 		return;
2886 	} else if (*depth == 0 && a != NULL)
2887 		*a = *r;
2888 	f = stack + (*depth)++;
2889 	f->rs = *rs;
2890 	f->r = *r;
2891 	if ((*r)->anchor_wildcard) {
2892 		struct pf_anchor_node *parent = &(*r)->anchor->children;
2893 
2894 		if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2895 			*r = NULL;
2896 			return;
2897 		}
2898 		*rs = &f->child->ruleset;
2899 	} else {
2900 		f->child = NULL;
2901 		*rs = &(*r)->anchor->ruleset;
2902 	}
2903 	*r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2904 }
2905 
2906 int
2907 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2908     struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2909     int *match)
2910 {
2911 	struct pf_anchor_stackframe	*f;
2912 	struct pf_rule *fr;
2913 	int quick = 0;
2914 
2915 	PF_RULES_RASSERT();
2916 
2917 	do {
2918 		if (*depth <= 0)
2919 			break;
2920 		f = stack + *depth - 1;
2921 		fr = PF_ANCHOR_RULE(f);
2922 		if (f->child != NULL) {
2923 			struct pf_anchor_node *parent;
2924 
2925 			/*
2926 			 * This block traverses through
2927 			 * a wildcard anchor.
2928 			 */
2929 			parent = &fr->anchor->children;
2930 			if (match != NULL && *match) {
2931 				/*
2932 				 * If any of "*" matched, then
2933 				 * "foo/ *" matched, mark frame
2934 				 * appropriately.
2935 				 */
2936 				PF_ANCHOR_SET_MATCH(f);
2937 				*match = 0;
2938 			}
2939 			f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2940 			if (f->child != NULL) {
2941 				*rs = &f->child->ruleset;
2942 				*r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2943 				if (*r == NULL)
2944 					continue;
2945 				else
2946 					break;
2947 			}
2948 		}
2949 		(*depth)--;
2950 		if (*depth == 0 && a != NULL)
2951 			*a = NULL;
2952 		*rs = f->rs;
2953 		if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2954 			quick = fr->quick;
2955 		*r = TAILQ_NEXT(fr, entries);
2956 	} while (*r == NULL);
2957 
2958 	return (quick);
2959 }
2960 
2961 #ifdef INET6
2962 void
2963 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2964     struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2965 {
2966 	switch (af) {
2967 #ifdef INET
2968 	case AF_INET:
2969 		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2970 		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2971 		break;
2972 #endif /* INET */
2973 	case AF_INET6:
2974 		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2975 		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2976 		naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2977 		((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2978 		naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2979 		((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2980 		naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2981 		((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2982 		break;
2983 	}
2984 }
2985 
2986 void
2987 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2988 {
2989 	switch (af) {
2990 #ifdef INET
2991 	case AF_INET:
2992 		addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2993 		break;
2994 #endif /* INET */
2995 	case AF_INET6:
2996 		if (addr->addr32[3] == 0xffffffff) {
2997 			addr->addr32[3] = 0;
2998 			if (addr->addr32[2] == 0xffffffff) {
2999 				addr->addr32[2] = 0;
3000 				if (addr->addr32[1] == 0xffffffff) {
3001 					addr->addr32[1] = 0;
3002 					addr->addr32[0] =
3003 					    htonl(ntohl(addr->addr32[0]) + 1);
3004 				} else
3005 					addr->addr32[1] =
3006 					    htonl(ntohl(addr->addr32[1]) + 1);
3007 			} else
3008 				addr->addr32[2] =
3009 				    htonl(ntohl(addr->addr32[2]) + 1);
3010 		} else
3011 			addr->addr32[3] =
3012 			    htonl(ntohl(addr->addr32[3]) + 1);
3013 		break;
3014 	}
3015 }
3016 #endif /* INET6 */
3017 
3018 int
3019 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
3020 {
3021 	struct pf_addr		*saddr, *daddr;
3022 	u_int16_t		 sport, dport;
3023 	struct inpcbinfo	*pi;
3024 	struct inpcb		*inp;
3025 
3026 	pd->lookup.uid = UID_MAX;
3027 	pd->lookup.gid = GID_MAX;
3028 
3029 	switch (pd->proto) {
3030 	case IPPROTO_TCP:
3031 		if (pd->hdr.tcp == NULL)
3032 			return (-1);
3033 		sport = pd->hdr.tcp->th_sport;
3034 		dport = pd->hdr.tcp->th_dport;
3035 		pi = &V_tcbinfo;
3036 		break;
3037 	case IPPROTO_UDP:
3038 		if (pd->hdr.udp == NULL)
3039 			return (-1);
3040 		sport = pd->hdr.udp->uh_sport;
3041 		dport = pd->hdr.udp->uh_dport;
3042 		pi = &V_udbinfo;
3043 		break;
3044 	default:
3045 		return (-1);
3046 	}
3047 	if (direction == PF_IN) {
3048 		saddr = pd->src;
3049 		daddr = pd->dst;
3050 	} else {
3051 		u_int16_t	p;
3052 
3053 		p = sport;
3054 		sport = dport;
3055 		dport = p;
3056 		saddr = pd->dst;
3057 		daddr = pd->src;
3058 	}
3059 	switch (pd->af) {
3060 #ifdef INET
3061 	case AF_INET:
3062 		inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
3063 		    dport, INPLOOKUP_RLOCKPCB, NULL, m);
3064 		if (inp == NULL) {
3065 			inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
3066 			   daddr->v4, dport, INPLOOKUP_WILDCARD |
3067 			   INPLOOKUP_RLOCKPCB, NULL, m);
3068 			if (inp == NULL)
3069 				return (-1);
3070 		}
3071 		break;
3072 #endif /* INET */
3073 #ifdef INET6
3074 	case AF_INET6:
3075 		inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
3076 		    dport, INPLOOKUP_RLOCKPCB, NULL, m);
3077 		if (inp == NULL) {
3078 			inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
3079 			    &daddr->v6, dport, INPLOOKUP_WILDCARD |
3080 			    INPLOOKUP_RLOCKPCB, NULL, m);
3081 			if (inp == NULL)
3082 				return (-1);
3083 		}
3084 		break;
3085 #endif /* INET6 */
3086 
3087 	default:
3088 		return (-1);
3089 	}
3090 	INP_RLOCK_ASSERT(inp);
3091 	pd->lookup.uid = inp->inp_cred->cr_uid;
3092 	pd->lookup.gid = inp->inp_cred->cr_groups[0];
3093 	INP_RUNLOCK(inp);
3094 
3095 	return (1);
3096 }
3097 
3098 static u_int8_t
3099 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3100 {
3101 	int		 hlen;
3102 	u_int8_t	 hdr[60];
3103 	u_int8_t	*opt, optlen;
3104 	u_int8_t	 wscale = 0;
3105 
3106 	hlen = th_off << 2;		/* hlen <= sizeof(hdr) */
3107 	if (hlen <= sizeof(struct tcphdr))
3108 		return (0);
3109 	if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3110 		return (0);
3111 	opt = hdr + sizeof(struct tcphdr);
3112 	hlen -= sizeof(struct tcphdr);
3113 	while (hlen >= 3) {
3114 		switch (*opt) {
3115 		case TCPOPT_EOL:
3116 		case TCPOPT_NOP:
3117 			++opt;
3118 			--hlen;
3119 			break;
3120 		case TCPOPT_WINDOW:
3121 			wscale = opt[2];
3122 			if (wscale > TCP_MAX_WINSHIFT)
3123 				wscale = TCP_MAX_WINSHIFT;
3124 			wscale |= PF_WSCALE_FLAG;
3125 			/* FALLTHROUGH */
3126 		default:
3127 			optlen = opt[1];
3128 			if (optlen < 2)
3129 				optlen = 2;
3130 			hlen -= optlen;
3131 			opt += optlen;
3132 			break;
3133 		}
3134 	}
3135 	return (wscale);
3136 }
3137 
3138 static u_int16_t
3139 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3140 {
3141 	int		 hlen;
3142 	u_int8_t	 hdr[60];
3143 	u_int8_t	*opt, optlen;
3144 	u_int16_t	 mss = V_tcp_mssdflt;
3145 
3146 	hlen = th_off << 2;	/* hlen <= sizeof(hdr) */
3147 	if (hlen <= sizeof(struct tcphdr))
3148 		return (0);
3149 	if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3150 		return (0);
3151 	opt = hdr + sizeof(struct tcphdr);
3152 	hlen -= sizeof(struct tcphdr);
3153 	while (hlen >= TCPOLEN_MAXSEG) {
3154 		switch (*opt) {
3155 		case TCPOPT_EOL:
3156 		case TCPOPT_NOP:
3157 			++opt;
3158 			--hlen;
3159 			break;
3160 		case TCPOPT_MAXSEG:
3161 			bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3162 			NTOHS(mss);
3163 			/* FALLTHROUGH */
3164 		default:
3165 			optlen = opt[1];
3166 			if (optlen < 2)
3167 				optlen = 2;
3168 			hlen -= optlen;
3169 			opt += optlen;
3170 			break;
3171 		}
3172 	}
3173 	return (mss);
3174 }
3175 
3176 static u_int16_t
3177 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3178 {
3179 	struct nhop_object *nh;
3180 #ifdef INET6
3181 	struct in6_addr		dst6;
3182 	uint32_t		scopeid;
3183 #endif /* INET6 */
3184 	int			 hlen = 0;
3185 	uint16_t		 mss = 0;
3186 
3187 	NET_EPOCH_ASSERT();
3188 
3189 	switch (af) {
3190 #ifdef INET
3191 	case AF_INET:
3192 		hlen = sizeof(struct ip);
3193 		nh = fib4_lookup(rtableid, addr->v4, 0, 0, 0);
3194 		if (nh != NULL)
3195 			mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
3196 		break;
3197 #endif /* INET */
3198 #ifdef INET6
3199 	case AF_INET6:
3200 		hlen = sizeof(struct ip6_hdr);
3201 		in6_splitscope(&addr->v6, &dst6, &scopeid);
3202 		nh = fib6_lookup(rtableid, &dst6, scopeid, 0, 0);
3203 		if (nh != NULL)
3204 			mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
3205 		break;
3206 #endif /* INET6 */
3207 	}
3208 
3209 	mss = max(V_tcp_mssdflt, mss);
3210 	mss = min(mss, offer);
3211 	mss = max(mss, 64);		/* sanity - at least max opt space */
3212 	return (mss);
3213 }
3214 
3215 static u_int32_t
3216 pf_tcp_iss(struct pf_pdesc *pd)
3217 {
3218 	MD5_CTX ctx;
3219 	u_int32_t digest[4];
3220 
3221 	if (V_pf_tcp_secret_init == 0) {
3222 		arc4random_buf(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3223 		MD5Init(&V_pf_tcp_secret_ctx);
3224 		MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3225 		    sizeof(V_pf_tcp_secret));
3226 		V_pf_tcp_secret_init = 1;
3227 	}
3228 
3229 	ctx = V_pf_tcp_secret_ctx;
3230 
3231 	MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3232 	MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3233 	if (pd->af == AF_INET6) {
3234 		MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3235 		MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3236 	} else {
3237 		MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3238 		MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3239 	}
3240 	MD5Final((u_char *)digest, &ctx);
3241 	V_pf_tcp_iss_off += 4096;
3242 #define	ISN_RANDOM_INCREMENT (4096 - 1)
3243 	return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3244 	    V_pf_tcp_iss_off);
3245 #undef	ISN_RANDOM_INCREMENT
3246 }
3247 
3248 static int
3249 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3250     struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3251     struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3252 {
3253 	struct pf_rule		*nr = NULL;
3254 	struct pf_addr		* const saddr = pd->src;
3255 	struct pf_addr		* const daddr = pd->dst;
3256 	sa_family_t		 af = pd->af;
3257 	struct pf_rule		*r, *a = NULL;
3258 	struct pf_ruleset	*ruleset = NULL;
3259 	struct pf_src_node	*nsn = NULL;
3260 	struct tcphdr		*th = pd->hdr.tcp;
3261 	struct pf_state_key	*sk = NULL, *nk = NULL;
3262 	u_short			 reason;
3263 	int			 rewrite = 0, hdrlen = 0;
3264 	int			 tag = -1, rtableid = -1;
3265 	int			 asd = 0;
3266 	int			 match = 0;
3267 	int			 state_icmp = 0;
3268 	u_int16_t		 sport = 0, dport = 0;
3269 	u_int16_t		 bproto_sum = 0, bip_sum = 0;
3270 	u_int8_t		 icmptype = 0, icmpcode = 0;
3271 	struct pf_anchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
3272 
3273 	PF_RULES_RASSERT();
3274 
3275 	if (inp != NULL) {
3276 		INP_LOCK_ASSERT(inp);
3277 		pd->lookup.uid = inp->inp_cred->cr_uid;
3278 		pd->lookup.gid = inp->inp_cred->cr_groups[0];
3279 		pd->lookup.done = 1;
3280 	}
3281 
3282 	switch (pd->proto) {
3283 	case IPPROTO_TCP:
3284 		sport = th->th_sport;
3285 		dport = th->th_dport;
3286 		hdrlen = sizeof(*th);
3287 		break;
3288 	case IPPROTO_UDP:
3289 		sport = pd->hdr.udp->uh_sport;
3290 		dport = pd->hdr.udp->uh_dport;
3291 		hdrlen = sizeof(*pd->hdr.udp);
3292 		break;
3293 #ifdef INET
3294 	case IPPROTO_ICMP:
3295 		if (pd->af != AF_INET)
3296 			break;
3297 		sport = dport = pd->hdr.icmp->icmp_id;
3298 		hdrlen = sizeof(*pd->hdr.icmp);
3299 		icmptype = pd->hdr.icmp->icmp_type;
3300 		icmpcode = pd->hdr.icmp->icmp_code;
3301 
3302 		if (icmptype == ICMP_UNREACH ||
3303 		    icmptype == ICMP_SOURCEQUENCH ||
3304 		    icmptype == ICMP_REDIRECT ||
3305 		    icmptype == ICMP_TIMXCEED ||
3306 		    icmptype == ICMP_PARAMPROB)
3307 			state_icmp++;
3308 		break;
3309 #endif /* INET */
3310 #ifdef INET6
3311 	case IPPROTO_ICMPV6:
3312 		if (af != AF_INET6)
3313 			break;
3314 		sport = dport = pd->hdr.icmp6->icmp6_id;
3315 		hdrlen = sizeof(*pd->hdr.icmp6);
3316 		icmptype = pd->hdr.icmp6->icmp6_type;
3317 		icmpcode = pd->hdr.icmp6->icmp6_code;
3318 
3319 		if (icmptype == ICMP6_DST_UNREACH ||
3320 		    icmptype == ICMP6_PACKET_TOO_BIG ||
3321 		    icmptype == ICMP6_TIME_EXCEEDED ||
3322 		    icmptype == ICMP6_PARAM_PROB)
3323 			state_icmp++;
3324 		break;
3325 #endif /* INET6 */
3326 	default:
3327 		sport = dport = hdrlen = 0;
3328 		break;
3329 	}
3330 
3331 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3332 
3333 	/* check packet for BINAT/NAT/RDR */
3334 	if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3335 	    &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3336 		KASSERT(sk != NULL, ("%s: null sk", __func__));
3337 		KASSERT(nk != NULL, ("%s: null nk", __func__));
3338 
3339 		if (pd->ip_sum)
3340 			bip_sum = *pd->ip_sum;
3341 
3342 		switch (pd->proto) {
3343 		case IPPROTO_TCP:
3344 			bproto_sum = th->th_sum;
3345 			pd->proto_sum = &th->th_sum;
3346 
3347 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3348 			    nk->port[pd->sidx] != sport) {
3349 				pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3350 				    &th->th_sum, &nk->addr[pd->sidx],
3351 				    nk->port[pd->sidx], 0, af);
3352 				pd->sport = &th->th_sport;
3353 				sport = th->th_sport;
3354 			}
3355 
3356 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3357 			    nk->port[pd->didx] != dport) {
3358 				pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3359 				    &th->th_sum, &nk->addr[pd->didx],
3360 				    nk->port[pd->didx], 0, af);
3361 				dport = th->th_dport;
3362 				pd->dport = &th->th_dport;
3363 			}
3364 			rewrite++;
3365 			break;
3366 		case IPPROTO_UDP:
3367 			bproto_sum = pd->hdr.udp->uh_sum;
3368 			pd->proto_sum = &pd->hdr.udp->uh_sum;
3369 
3370 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3371 			    nk->port[pd->sidx] != sport) {
3372 				pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3373 				    pd->ip_sum, &pd->hdr.udp->uh_sum,
3374 				    &nk->addr[pd->sidx],
3375 				    nk->port[pd->sidx], 1, af);
3376 				sport = pd->hdr.udp->uh_sport;
3377 				pd->sport = &pd->hdr.udp->uh_sport;
3378 			}
3379 
3380 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3381 			    nk->port[pd->didx] != dport) {
3382 				pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3383 				    pd->ip_sum, &pd->hdr.udp->uh_sum,
3384 				    &nk->addr[pd->didx],
3385 				    nk->port[pd->didx], 1, af);
3386 				dport = pd->hdr.udp->uh_dport;
3387 				pd->dport = &pd->hdr.udp->uh_dport;
3388 			}
3389 			rewrite++;
3390 			break;
3391 #ifdef INET
3392 		case IPPROTO_ICMP:
3393 			nk->port[0] = nk->port[1];
3394 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3395 				pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3396 				    nk->addr[pd->sidx].v4.s_addr, 0);
3397 
3398 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3399 				pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3400 				    nk->addr[pd->didx].v4.s_addr, 0);
3401 
3402 			if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3403 				pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3404 				    pd->hdr.icmp->icmp_cksum, sport,
3405 				    nk->port[1], 0);
3406 				pd->hdr.icmp->icmp_id = nk->port[1];
3407 				pd->sport = &pd->hdr.icmp->icmp_id;
3408 			}
3409 			m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3410 			break;
3411 #endif /* INET */
3412 #ifdef INET6
3413 		case IPPROTO_ICMPV6:
3414 			nk->port[0] = nk->port[1];
3415 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3416 				pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3417 				    &nk->addr[pd->sidx], 0);
3418 
3419 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3420 				pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3421 				    &nk->addr[pd->didx], 0);
3422 			rewrite++;
3423 			break;
3424 #endif /* INET */
3425 		default:
3426 			switch (af) {
3427 #ifdef INET
3428 			case AF_INET:
3429 				if (PF_ANEQ(saddr,
3430 				    &nk->addr[pd->sidx], AF_INET))
3431 					pf_change_a(&saddr->v4.s_addr,
3432 					    pd->ip_sum,
3433 					    nk->addr[pd->sidx].v4.s_addr, 0);
3434 
3435 				if (PF_ANEQ(daddr,
3436 				    &nk->addr[pd->didx], AF_INET))
3437 					pf_change_a(&daddr->v4.s_addr,
3438 					    pd->ip_sum,
3439 					    nk->addr[pd->didx].v4.s_addr, 0);
3440 				break;
3441 #endif /* INET */
3442 #ifdef INET6
3443 			case AF_INET6:
3444 				if (PF_ANEQ(saddr,
3445 				    &nk->addr[pd->sidx], AF_INET6))
3446 					PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3447 
3448 				if (PF_ANEQ(daddr,
3449 				    &nk->addr[pd->didx], AF_INET6))
3450 					PF_ACPY(daddr, &nk->addr[pd->didx], af);
3451 				break;
3452 #endif /* INET */
3453 			}
3454 			break;
3455 		}
3456 		if (nr->natpass)
3457 			r = NULL;
3458 		pd->nat_rule = nr;
3459 	}
3460 
3461 	while (r != NULL) {
3462 		r->evaluations++;
3463 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
3464 			r = r->skip[PF_SKIP_IFP].ptr;
3465 		else if (r->direction && r->direction != direction)
3466 			r = r->skip[PF_SKIP_DIR].ptr;
3467 		else if (r->af && r->af != af)
3468 			r = r->skip[PF_SKIP_AF].ptr;
3469 		else if (r->proto && r->proto != pd->proto)
3470 			r = r->skip[PF_SKIP_PROTO].ptr;
3471 		else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3472 		    r->src.neg, kif, M_GETFIB(m)))
3473 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3474 		/* tcp/udp only. port_op always 0 in other cases */
3475 		else if (r->src.port_op && !pf_match_port(r->src.port_op,
3476 		    r->src.port[0], r->src.port[1], sport))
3477 			r = r->skip[PF_SKIP_SRC_PORT].ptr;
3478 		else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3479 		    r->dst.neg, NULL, M_GETFIB(m)))
3480 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
3481 		/* tcp/udp only. port_op always 0 in other cases */
3482 		else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3483 		    r->dst.port[0], r->dst.port[1], dport))
3484 			r = r->skip[PF_SKIP_DST_PORT].ptr;
3485 		/* icmp only. type always 0 in other cases */
3486 		else if (r->type && r->type != icmptype + 1)
3487 			r = TAILQ_NEXT(r, entries);
3488 		/* icmp only. type always 0 in other cases */
3489 		else if (r->code && r->code != icmpcode + 1)
3490 			r = TAILQ_NEXT(r, entries);
3491 		else if (r->tos && !(r->tos == pd->tos))
3492 			r = TAILQ_NEXT(r, entries);
3493 		else if (r->rule_flag & PFRULE_FRAGMENT)
3494 			r = TAILQ_NEXT(r, entries);
3495 		else if (pd->proto == IPPROTO_TCP &&
3496 		    (r->flagset & th->th_flags) != r->flags)
3497 			r = TAILQ_NEXT(r, entries);
3498 		/* tcp/udp only. uid.op always 0 in other cases */
3499 		else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3500 		    pf_socket_lookup(direction, pd, m), 1)) &&
3501 		    !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3502 		    pd->lookup.uid))
3503 			r = TAILQ_NEXT(r, entries);
3504 		/* tcp/udp only. gid.op always 0 in other cases */
3505 		else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3506 		    pf_socket_lookup(direction, pd, m), 1)) &&
3507 		    !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3508 		    pd->lookup.gid))
3509 			r = TAILQ_NEXT(r, entries);
3510 		else if (r->prio &&
3511 		    !pf_match_ieee8021q_pcp(r->prio, m))
3512 			r = TAILQ_NEXT(r, entries);
3513 		else if (r->prob &&
3514 		    r->prob <= arc4random())
3515 			r = TAILQ_NEXT(r, entries);
3516 		else if (r->match_tag && !pf_match_tag(m, r, &tag,
3517 		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
3518 			r = TAILQ_NEXT(r, entries);
3519 		else if (r->os_fingerprint != PF_OSFP_ANY &&
3520 		    (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3521 		    pf_osfp_fingerprint(pd, m, off, th),
3522 		    r->os_fingerprint)))
3523 			r = TAILQ_NEXT(r, entries);
3524 		else {
3525 			if (r->tag)
3526 				tag = r->tag;
3527 			if (r->rtableid >= 0)
3528 				rtableid = r->rtableid;
3529 			if (r->anchor == NULL) {
3530 				match = 1;
3531 				*rm = r;
3532 				*am = a;
3533 				*rsm = ruleset;
3534 				if ((*rm)->quick)
3535 					break;
3536 				r = TAILQ_NEXT(r, entries);
3537 			} else
3538 				pf_step_into_anchor(anchor_stack, &asd,
3539 				    &ruleset, PF_RULESET_FILTER, &r, &a,
3540 				    &match);
3541 		}
3542 		if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3543 		    &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3544 			break;
3545 	}
3546 	r = *rm;
3547 	a = *am;
3548 	ruleset = *rsm;
3549 
3550 	REASON_SET(&reason, PFRES_MATCH);
3551 
3552 	if (r->log || (nr != NULL && nr->log)) {
3553 		if (rewrite)
3554 			m_copyback(m, off, hdrlen, pd->hdr.any);
3555 		PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3556 		    ruleset, pd, 1);
3557 	}
3558 
3559 	if ((r->action == PF_DROP) &&
3560 	    ((r->rule_flag & PFRULE_RETURNRST) ||
3561 	    (r->rule_flag & PFRULE_RETURNICMP) ||
3562 	    (r->rule_flag & PFRULE_RETURN))) {
3563 		pf_return(r, nr, pd, sk, off, m, th, kif, bproto_sum,
3564 		    bip_sum, hdrlen, &reason);
3565 	}
3566 
3567 	if (r->action == PF_DROP)
3568 		goto cleanup;
3569 
3570 	if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3571 		REASON_SET(&reason, PFRES_MEMORY);
3572 		goto cleanup;
3573 	}
3574 	if (rtableid >= 0)
3575 		M_SETFIB(m, rtableid);
3576 
3577 	if (!state_icmp && (r->keep_state || nr != NULL ||
3578 	    (pd->flags & PFDESC_TCP_NORM))) {
3579 		int action;
3580 		action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3581 		    sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3582 		    hdrlen);
3583 		if (action != PF_PASS) {
3584 			if (action == PF_DROP &&
3585 			    (r->rule_flag & PFRULE_RETURN))
3586 				pf_return(r, nr, pd, sk, off, m, th, kif,
3587 				    bproto_sum, bip_sum, hdrlen, &reason);
3588 			return (action);
3589 		}
3590 	} else {
3591 		if (sk != NULL)
3592 			uma_zfree(V_pf_state_key_z, sk);
3593 		if (nk != NULL)
3594 			uma_zfree(V_pf_state_key_z, nk);
3595 	}
3596 
3597 	/* copy back packet headers if we performed NAT operations */
3598 	if (rewrite)
3599 		m_copyback(m, off, hdrlen, pd->hdr.any);
3600 
3601 	if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3602 	    direction == PF_OUT &&
3603 	    V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, m))
3604 		/*
3605 		 * We want the state created, but we dont
3606 		 * want to send this in case a partner
3607 		 * firewall has to know about it to allow
3608 		 * replies through it.
3609 		 */
3610 		return (PF_DEFER);
3611 
3612 	return (PF_PASS);
3613 
3614 cleanup:
3615 	if (sk != NULL)
3616 		uma_zfree(V_pf_state_key_z, sk);
3617 	if (nk != NULL)
3618 		uma_zfree(V_pf_state_key_z, nk);
3619 	return (PF_DROP);
3620 }
3621 
3622 static int
3623 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3624     struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3625     struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3626     u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3627     int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3628 {
3629 	struct pf_state		*s = NULL;
3630 	struct pf_src_node	*sn = NULL;
3631 	struct tcphdr		*th = pd->hdr.tcp;
3632 	u_int16_t		 mss = V_tcp_mssdflt;
3633 	u_short			 reason;
3634 
3635 	/* check maximums */
3636 	if (r->max_states &&
3637 	    (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3638 		counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3639 		REASON_SET(&reason, PFRES_MAXSTATES);
3640 		goto csfailed;
3641 	}
3642 	/* src node for filter rule */
3643 	if ((r->rule_flag & PFRULE_SRCTRACK ||
3644 	    r->rpool.opts & PF_POOL_STICKYADDR) &&
3645 	    pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3646 		REASON_SET(&reason, PFRES_SRCLIMIT);
3647 		goto csfailed;
3648 	}
3649 	/* src node for translation rule */
3650 	if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3651 	    pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3652 		REASON_SET(&reason, PFRES_SRCLIMIT);
3653 		goto csfailed;
3654 	}
3655 	s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3656 	if (s == NULL) {
3657 		REASON_SET(&reason, PFRES_MEMORY);
3658 		goto csfailed;
3659 	}
3660 	s->rule.ptr = r;
3661 	s->nat_rule.ptr = nr;
3662 	s->anchor.ptr = a;
3663 	STATE_INC_COUNTERS(s);
3664 	if (r->allow_opts)
3665 		s->state_flags |= PFSTATE_ALLOWOPTS;
3666 	if (r->rule_flag & PFRULE_STATESLOPPY)
3667 		s->state_flags |= PFSTATE_SLOPPY;
3668 	s->log = r->log & PF_LOG_ALL;
3669 	s->sync_state = PFSYNC_S_NONE;
3670 	if (nr != NULL)
3671 		s->log |= nr->log & PF_LOG_ALL;
3672 	switch (pd->proto) {
3673 	case IPPROTO_TCP:
3674 		s->src.seqlo = ntohl(th->th_seq);
3675 		s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3676 		if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3677 		    r->keep_state == PF_STATE_MODULATE) {
3678 			/* Generate sequence number modulator */
3679 			if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3680 			    0)
3681 				s->src.seqdiff = 1;
3682 			pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3683 			    htonl(s->src.seqlo + s->src.seqdiff), 0);
3684 			*rewrite = 1;
3685 		} else
3686 			s->src.seqdiff = 0;
3687 		if (th->th_flags & TH_SYN) {
3688 			s->src.seqhi++;
3689 			s->src.wscale = pf_get_wscale(m, off,
3690 			    th->th_off, pd->af);
3691 		}
3692 		s->src.max_win = MAX(ntohs(th->th_win), 1);
3693 		if (s->src.wscale & PF_WSCALE_MASK) {
3694 			/* Remove scale factor from initial window */
3695 			int win = s->src.max_win;
3696 			win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3697 			s->src.max_win = (win - 1) >>
3698 			    (s->src.wscale & PF_WSCALE_MASK);
3699 		}
3700 		if (th->th_flags & TH_FIN)
3701 			s->src.seqhi++;
3702 		s->dst.seqhi = 1;
3703 		s->dst.max_win = 1;
3704 		s->src.state = TCPS_SYN_SENT;
3705 		s->dst.state = TCPS_CLOSED;
3706 		s->timeout = PFTM_TCP_FIRST_PACKET;
3707 		break;
3708 	case IPPROTO_UDP:
3709 		s->src.state = PFUDPS_SINGLE;
3710 		s->dst.state = PFUDPS_NO_TRAFFIC;
3711 		s->timeout = PFTM_UDP_FIRST_PACKET;
3712 		break;
3713 	case IPPROTO_ICMP:
3714 #ifdef INET6
3715 	case IPPROTO_ICMPV6:
3716 #endif
3717 		s->timeout = PFTM_ICMP_FIRST_PACKET;
3718 		break;
3719 	default:
3720 		s->src.state = PFOTHERS_SINGLE;
3721 		s->dst.state = PFOTHERS_NO_TRAFFIC;
3722 		s->timeout = PFTM_OTHER_FIRST_PACKET;
3723 	}
3724 
3725 	if (r->rt) {
3726 		if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3727 			REASON_SET(&reason, PFRES_MAPFAILED);
3728 			pf_src_tree_remove_state(s);
3729 			STATE_DEC_COUNTERS(s);
3730 			uma_zfree(V_pf_state_z, s);
3731 			goto csfailed;
3732 		}
3733 		s->rt_kif = r->rpool.cur->kif;
3734 	}
3735 
3736 	s->creation = time_uptime;
3737 	s->expire = time_uptime;
3738 
3739 	if (sn != NULL)
3740 		s->src_node = sn;
3741 	if (nsn != NULL) {
3742 		/* XXX We only modify one side for now. */
3743 		PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3744 		s->nat_src_node = nsn;
3745 	}
3746 	if (pd->proto == IPPROTO_TCP) {
3747 		if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3748 		    off, pd, th, &s->src, &s->dst)) {
3749 			REASON_SET(&reason, PFRES_MEMORY);
3750 			pf_src_tree_remove_state(s);
3751 			STATE_DEC_COUNTERS(s);
3752 			uma_zfree(V_pf_state_z, s);
3753 			return (PF_DROP);
3754 		}
3755 		if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3756 		    pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3757 		    &s->src, &s->dst, rewrite)) {
3758 			/* This really shouldn't happen!!! */
3759 			DPFPRINTF(PF_DEBUG_URGENT,
3760 			    ("pf_normalize_tcp_stateful failed on first "
3761 			     "pkt\n"));
3762 			pf_normalize_tcp_cleanup(s);
3763 			pf_src_tree_remove_state(s);
3764 			STATE_DEC_COUNTERS(s);
3765 			uma_zfree(V_pf_state_z, s);
3766 			return (PF_DROP);
3767 		}
3768 	}
3769 	s->direction = pd->dir;
3770 
3771 	/*
3772 	 * sk/nk could already been setup by pf_get_translation().
3773 	 */
3774 	if (nr == NULL) {
3775 		KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3776 		    __func__, nr, sk, nk));
3777 		sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3778 		if (sk == NULL)
3779 			goto csfailed;
3780 		nk = sk;
3781 	} else
3782 		KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3783 		    __func__, nr, sk, nk));
3784 
3785 	/* Swap sk/nk for PF_OUT. */
3786 	if (pf_state_insert(BOUND_IFACE(r, kif),
3787 	    (pd->dir == PF_IN) ? sk : nk,
3788 	    (pd->dir == PF_IN) ? nk : sk, s)) {
3789 		if (pd->proto == IPPROTO_TCP)
3790 			pf_normalize_tcp_cleanup(s);
3791 		REASON_SET(&reason, PFRES_STATEINS);
3792 		pf_src_tree_remove_state(s);
3793 		STATE_DEC_COUNTERS(s);
3794 		uma_zfree(V_pf_state_z, s);
3795 		return (PF_DROP);
3796 	} else
3797 		*sm = s;
3798 
3799 	if (tag > 0)
3800 		s->tag = tag;
3801 	if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3802 	    TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3803 		s->src.state = PF_TCPS_PROXY_SRC;
3804 		/* undo NAT changes, if they have taken place */
3805 		if (nr != NULL) {
3806 			struct pf_state_key *skt = s->key[PF_SK_WIRE];
3807 			if (pd->dir == PF_OUT)
3808 				skt = s->key[PF_SK_STACK];
3809 			PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3810 			PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3811 			if (pd->sport)
3812 				*pd->sport = skt->port[pd->sidx];
3813 			if (pd->dport)
3814 				*pd->dport = skt->port[pd->didx];
3815 			if (pd->proto_sum)
3816 				*pd->proto_sum = bproto_sum;
3817 			if (pd->ip_sum)
3818 				*pd->ip_sum = bip_sum;
3819 			m_copyback(m, off, hdrlen, pd->hdr.any);
3820 		}
3821 		s->src.seqhi = htonl(arc4random());
3822 		/* Find mss option */
3823 		int rtid = M_GETFIB(m);
3824 		mss = pf_get_mss(m, off, th->th_off, pd->af);
3825 		mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3826 		mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3827 		s->src.mss = mss;
3828 		pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3829 		    th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3830 		    TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3831 		REASON_SET(&reason, PFRES_SYNPROXY);
3832 		return (PF_SYNPROXY_DROP);
3833 	}
3834 
3835 	return (PF_PASS);
3836 
3837 csfailed:
3838 	if (sk != NULL)
3839 		uma_zfree(V_pf_state_key_z, sk);
3840 	if (nk != NULL)
3841 		uma_zfree(V_pf_state_key_z, nk);
3842 
3843 	if (sn != NULL) {
3844 		struct pf_srchash *sh;
3845 
3846 		sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3847 		PF_HASHROW_LOCK(sh);
3848 		if (--sn->states == 0 && sn->expire == 0) {
3849 			pf_unlink_src_node(sn);
3850 			uma_zfree(V_pf_sources_z, sn);
3851 			counter_u64_add(
3852 			    V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3853 		}
3854 		PF_HASHROW_UNLOCK(sh);
3855 	}
3856 
3857 	if (nsn != sn && nsn != NULL) {
3858 		struct pf_srchash *sh;
3859 
3860 		sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3861 		PF_HASHROW_LOCK(sh);
3862 		if (--nsn->states == 0 && nsn->expire == 0) {
3863 			pf_unlink_src_node(nsn);
3864 			uma_zfree(V_pf_sources_z, nsn);
3865 			counter_u64_add(
3866 			    V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3867 		}
3868 		PF_HASHROW_UNLOCK(sh);
3869 	}
3870 
3871 	return (PF_DROP);
3872 }
3873 
3874 static int
3875 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3876     struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3877     struct pf_ruleset **rsm)
3878 {
3879 	struct pf_rule		*r, *a = NULL;
3880 	struct pf_ruleset	*ruleset = NULL;
3881 	sa_family_t		 af = pd->af;
3882 	u_short			 reason;
3883 	int			 tag = -1;
3884 	int			 asd = 0;
3885 	int			 match = 0;
3886 	struct pf_anchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
3887 
3888 	PF_RULES_RASSERT();
3889 
3890 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3891 	while (r != NULL) {
3892 		r->evaluations++;
3893 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
3894 			r = r->skip[PF_SKIP_IFP].ptr;
3895 		else if (r->direction && r->direction != direction)
3896 			r = r->skip[PF_SKIP_DIR].ptr;
3897 		else if (r->af && r->af != af)
3898 			r = r->skip[PF_SKIP_AF].ptr;
3899 		else if (r->proto && r->proto != pd->proto)
3900 			r = r->skip[PF_SKIP_PROTO].ptr;
3901 		else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3902 		    r->src.neg, kif, M_GETFIB(m)))
3903 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3904 		else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3905 		    r->dst.neg, NULL, M_GETFIB(m)))
3906 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
3907 		else if (r->tos && !(r->tos == pd->tos))
3908 			r = TAILQ_NEXT(r, entries);
3909 		else if (r->os_fingerprint != PF_OSFP_ANY)
3910 			r = TAILQ_NEXT(r, entries);
3911 		else if (pd->proto == IPPROTO_UDP &&
3912 		    (r->src.port_op || r->dst.port_op))
3913 			r = TAILQ_NEXT(r, entries);
3914 		else if (pd->proto == IPPROTO_TCP &&
3915 		    (r->src.port_op || r->dst.port_op || r->flagset))
3916 			r = TAILQ_NEXT(r, entries);
3917 		else if ((pd->proto == IPPROTO_ICMP ||
3918 		    pd->proto == IPPROTO_ICMPV6) &&
3919 		    (r->type || r->code))
3920 			r = TAILQ_NEXT(r, entries);
3921 		else if (r->prio &&
3922 		    !pf_match_ieee8021q_pcp(r->prio, m))
3923 			r = TAILQ_NEXT(r, entries);
3924 		else if (r->prob && r->prob <=
3925 		    (arc4random() % (UINT_MAX - 1) + 1))
3926 			r = TAILQ_NEXT(r, entries);
3927 		else if (r->match_tag && !pf_match_tag(m, r, &tag,
3928 		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
3929 			r = TAILQ_NEXT(r, entries);
3930 		else {
3931 			if (r->anchor == NULL) {
3932 				match = 1;
3933 				*rm = r;
3934 				*am = a;
3935 				*rsm = ruleset;
3936 				if ((*rm)->quick)
3937 					break;
3938 				r = TAILQ_NEXT(r, entries);
3939 			} else
3940 				pf_step_into_anchor(anchor_stack, &asd,
3941 				    &ruleset, PF_RULESET_FILTER, &r, &a,
3942 				    &match);
3943 		}
3944 		if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3945 		    &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3946 			break;
3947 	}
3948 	r = *rm;
3949 	a = *am;
3950 	ruleset = *rsm;
3951 
3952 	REASON_SET(&reason, PFRES_MATCH);
3953 
3954 	if (r->log)
3955 		PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3956 		    1);
3957 
3958 	if (r->action != PF_PASS)
3959 		return (PF_DROP);
3960 
3961 	if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3962 		REASON_SET(&reason, PFRES_MEMORY);
3963 		return (PF_DROP);
3964 	}
3965 
3966 	return (PF_PASS);
3967 }
3968 
3969 static int
3970 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3971 	struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3972 	struct pf_pdesc *pd, u_short *reason, int *copyback)
3973 {
3974 	struct tcphdr		*th = pd->hdr.tcp;
3975 	u_int16_t		 win = ntohs(th->th_win);
3976 	u_int32_t		 ack, end, seq, orig_seq;
3977 	u_int8_t		 sws, dws;
3978 	int			 ackskew;
3979 
3980 	if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3981 		sws = src->wscale & PF_WSCALE_MASK;
3982 		dws = dst->wscale & PF_WSCALE_MASK;
3983 	} else
3984 		sws = dws = 0;
3985 
3986 	/*
3987 	 * Sequence tracking algorithm from Guido van Rooij's paper:
3988 	 *   http://www.madison-gurkha.com/publications/tcp_filtering/
3989 	 *	tcp_filtering.ps
3990 	 */
3991 
3992 	orig_seq = seq = ntohl(th->th_seq);
3993 	if (src->seqlo == 0) {
3994 		/* First packet from this end. Set its state */
3995 
3996 		if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3997 		    src->scrub == NULL) {
3998 			if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3999 				REASON_SET(reason, PFRES_MEMORY);
4000 				return (PF_DROP);
4001 			}
4002 		}
4003 
4004 		/* Deferred generation of sequence number modulator */
4005 		if (dst->seqdiff && !src->seqdiff) {
4006 			/* use random iss for the TCP server */
4007 			while ((src->seqdiff = arc4random() - seq) == 0)
4008 				;
4009 			ack = ntohl(th->th_ack) - dst->seqdiff;
4010 			pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4011 			    src->seqdiff), 0);
4012 			pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4013 			*copyback = 1;
4014 		} else {
4015 			ack = ntohl(th->th_ack);
4016 		}
4017 
4018 		end = seq + pd->p_len;
4019 		if (th->th_flags & TH_SYN) {
4020 			end++;
4021 			if (dst->wscale & PF_WSCALE_FLAG) {
4022 				src->wscale = pf_get_wscale(m, off, th->th_off,
4023 				    pd->af);
4024 				if (src->wscale & PF_WSCALE_FLAG) {
4025 					/* Remove scale factor from initial
4026 					 * window */
4027 					sws = src->wscale & PF_WSCALE_MASK;
4028 					win = ((u_int32_t)win + (1 << sws) - 1)
4029 					    >> sws;
4030 					dws = dst->wscale & PF_WSCALE_MASK;
4031 				} else {
4032 					/* fixup other window */
4033 					dst->max_win <<= dst->wscale &
4034 					    PF_WSCALE_MASK;
4035 					/* in case of a retrans SYN|ACK */
4036 					dst->wscale = 0;
4037 				}
4038 			}
4039 		}
4040 		if (th->th_flags & TH_FIN)
4041 			end++;
4042 
4043 		src->seqlo = seq;
4044 		if (src->state < TCPS_SYN_SENT)
4045 			src->state = TCPS_SYN_SENT;
4046 
4047 		/*
4048 		 * May need to slide the window (seqhi may have been set by
4049 		 * the crappy stack check or if we picked up the connection
4050 		 * after establishment)
4051 		 */
4052 		if (src->seqhi == 1 ||
4053 		    SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4054 			src->seqhi = end + MAX(1, dst->max_win << dws);
4055 		if (win > src->max_win)
4056 			src->max_win = win;
4057 
4058 	} else {
4059 		ack = ntohl(th->th_ack) - dst->seqdiff;
4060 		if (src->seqdiff) {
4061 			/* Modulate sequence numbers */
4062 			pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4063 			    src->seqdiff), 0);
4064 			pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4065 			*copyback = 1;
4066 		}
4067 		end = seq + pd->p_len;
4068 		if (th->th_flags & TH_SYN)
4069 			end++;
4070 		if (th->th_flags & TH_FIN)
4071 			end++;
4072 	}
4073 
4074 	if ((th->th_flags & TH_ACK) == 0) {
4075 		/* Let it pass through the ack skew check */
4076 		ack = dst->seqlo;
4077 	} else if ((ack == 0 &&
4078 	    (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4079 	    /* broken tcp stacks do not set ack */
4080 	    (dst->state < TCPS_SYN_SENT)) {
4081 		/*
4082 		 * Many stacks (ours included) will set the ACK number in an
4083 		 * FIN|ACK if the SYN times out -- no sequence to ACK.
4084 		 */
4085 		ack = dst->seqlo;
4086 	}
4087 
4088 	if (seq == end) {
4089 		/* Ease sequencing restrictions on no data packets */
4090 		seq = src->seqlo;
4091 		end = seq;
4092 	}
4093 
4094 	ackskew = dst->seqlo - ack;
4095 
4096 
4097 	/*
4098 	 * Need to demodulate the sequence numbers in any TCP SACK options
4099 	 * (Selective ACK). We could optionally validate the SACK values
4100 	 * against the current ACK window, either forwards or backwards, but
4101 	 * I'm not confident that SACK has been implemented properly
4102 	 * everywhere. It wouldn't surprise me if several stacks accidentally
4103 	 * SACK too far backwards of previously ACKed data. There really aren't
4104 	 * any security implications of bad SACKing unless the target stack
4105 	 * doesn't validate the option length correctly. Someone trying to
4106 	 * spoof into a TCP connection won't bother blindly sending SACK
4107 	 * options anyway.
4108 	 */
4109 	if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4110 		if (pf_modulate_sack(m, off, pd, th, dst))
4111 			*copyback = 1;
4112 	}
4113 
4114 
4115 #define	MAXACKWINDOW (0xffff + 1500)	/* 1500 is an arbitrary fudge factor */
4116 	if (SEQ_GEQ(src->seqhi, end) &&
4117 	    /* Last octet inside other's window space */
4118 	    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4119 	    /* Retrans: not more than one window back */
4120 	    (ackskew >= -MAXACKWINDOW) &&
4121 	    /* Acking not more than one reassembled fragment backwards */
4122 	    (ackskew <= (MAXACKWINDOW << sws)) &&
4123 	    /* Acking not more than one window forward */
4124 	    ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4125 	    (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4126 	    (pd->flags & PFDESC_IP_REAS) == 0)) {
4127 	    /* Require an exact/+1 sequence match on resets when possible */
4128 
4129 		if (dst->scrub || src->scrub) {
4130 			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4131 			    *state, src, dst, copyback))
4132 				return (PF_DROP);
4133 		}
4134 
4135 		/* update max window */
4136 		if (src->max_win < win)
4137 			src->max_win = win;
4138 		/* synchronize sequencing */
4139 		if (SEQ_GT(end, src->seqlo))
4140 			src->seqlo = end;
4141 		/* slide the window of what the other end can send */
4142 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4143 			dst->seqhi = ack + MAX((win << sws), 1);
4144 
4145 
4146 		/* update states */
4147 		if (th->th_flags & TH_SYN)
4148 			if (src->state < TCPS_SYN_SENT)
4149 				src->state = TCPS_SYN_SENT;
4150 		if (th->th_flags & TH_FIN)
4151 			if (src->state < TCPS_CLOSING)
4152 				src->state = TCPS_CLOSING;
4153 		if (th->th_flags & TH_ACK) {
4154 			if (dst->state == TCPS_SYN_SENT) {
4155 				dst->state = TCPS_ESTABLISHED;
4156 				if (src->state == TCPS_ESTABLISHED &&
4157 				    (*state)->src_node != NULL &&
4158 				    pf_src_connlimit(state)) {
4159 					REASON_SET(reason, PFRES_SRCLIMIT);
4160 					return (PF_DROP);
4161 				}
4162 			} else if (dst->state == TCPS_CLOSING)
4163 				dst->state = TCPS_FIN_WAIT_2;
4164 		}
4165 		if (th->th_flags & TH_RST)
4166 			src->state = dst->state = TCPS_TIME_WAIT;
4167 
4168 		/* update expire time */
4169 		(*state)->expire = time_uptime;
4170 		if (src->state >= TCPS_FIN_WAIT_2 &&
4171 		    dst->state >= TCPS_FIN_WAIT_2)
4172 			(*state)->timeout = PFTM_TCP_CLOSED;
4173 		else if (src->state >= TCPS_CLOSING &&
4174 		    dst->state >= TCPS_CLOSING)
4175 			(*state)->timeout = PFTM_TCP_FIN_WAIT;
4176 		else if (src->state < TCPS_ESTABLISHED ||
4177 		    dst->state < TCPS_ESTABLISHED)
4178 			(*state)->timeout = PFTM_TCP_OPENING;
4179 		else if (src->state >= TCPS_CLOSING ||
4180 		    dst->state >= TCPS_CLOSING)
4181 			(*state)->timeout = PFTM_TCP_CLOSING;
4182 		else
4183 			(*state)->timeout = PFTM_TCP_ESTABLISHED;
4184 
4185 		/* Fall through to PASS packet */
4186 
4187 	} else if ((dst->state < TCPS_SYN_SENT ||
4188 		dst->state >= TCPS_FIN_WAIT_2 ||
4189 		src->state >= TCPS_FIN_WAIT_2) &&
4190 	    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4191 	    /* Within a window forward of the originating packet */
4192 	    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4193 	    /* Within a window backward of the originating packet */
4194 
4195 		/*
4196 		 * This currently handles three situations:
4197 		 *  1) Stupid stacks will shotgun SYNs before their peer
4198 		 *     replies.
4199 		 *  2) When PF catches an already established stream (the
4200 		 *     firewall rebooted, the state table was flushed, routes
4201 		 *     changed...)
4202 		 *  3) Packets get funky immediately after the connection
4203 		 *     closes (this should catch Solaris spurious ACK|FINs
4204 		 *     that web servers like to spew after a close)
4205 		 *
4206 		 * This must be a little more careful than the above code
4207 		 * since packet floods will also be caught here. We don't
4208 		 * update the TTL here to mitigate the damage of a packet
4209 		 * flood and so the same code can handle awkward establishment
4210 		 * and a loosened connection close.
4211 		 * In the establishment case, a correct peer response will
4212 		 * validate the connection, go through the normal state code
4213 		 * and keep updating the state TTL.
4214 		 */
4215 
4216 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
4217 			printf("pf: loose state match: ");
4218 			pf_print_state(*state);
4219 			pf_print_flags(th->th_flags);
4220 			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4221 			    "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4222 			    pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4223 			    (unsigned long long)(*state)->packets[1],
4224 			    pd->dir == PF_IN ? "in" : "out",
4225 			    pd->dir == (*state)->direction ? "fwd" : "rev");
4226 		}
4227 
4228 		if (dst->scrub || src->scrub) {
4229 			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4230 			    *state, src, dst, copyback))
4231 				return (PF_DROP);
4232 		}
4233 
4234 		/* update max window */
4235 		if (src->max_win < win)
4236 			src->max_win = win;
4237 		/* synchronize sequencing */
4238 		if (SEQ_GT(end, src->seqlo))
4239 			src->seqlo = end;
4240 		/* slide the window of what the other end can send */
4241 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4242 			dst->seqhi = ack + MAX((win << sws), 1);
4243 
4244 		/*
4245 		 * Cannot set dst->seqhi here since this could be a shotgunned
4246 		 * SYN and not an already established connection.
4247 		 */
4248 
4249 		if (th->th_flags & TH_FIN)
4250 			if (src->state < TCPS_CLOSING)
4251 				src->state = TCPS_CLOSING;
4252 		if (th->th_flags & TH_RST)
4253 			src->state = dst->state = TCPS_TIME_WAIT;
4254 
4255 		/* Fall through to PASS packet */
4256 
4257 	} else {
4258 		if ((*state)->dst.state == TCPS_SYN_SENT &&
4259 		    (*state)->src.state == TCPS_SYN_SENT) {
4260 			/* Send RST for state mismatches during handshake */
4261 			if (!(th->th_flags & TH_RST))
4262 				pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4263 				    pd->dst, pd->src, th->th_dport,
4264 				    th->th_sport, ntohl(th->th_ack), 0,
4265 				    TH_RST, 0, 0,
4266 				    (*state)->rule.ptr->return_ttl, 1, 0,
4267 				    kif->pfik_ifp);
4268 			src->seqlo = 0;
4269 			src->seqhi = 1;
4270 			src->max_win = 1;
4271 		} else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4272 			printf("pf: BAD state: ");
4273 			pf_print_state(*state);
4274 			pf_print_flags(th->th_flags);
4275 			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4276 			    "pkts=%llu:%llu dir=%s,%s\n",
4277 			    seq, orig_seq, ack, pd->p_len, ackskew,
4278 			    (unsigned long long)(*state)->packets[0],
4279 			    (unsigned long long)(*state)->packets[1],
4280 			    pd->dir == PF_IN ? "in" : "out",
4281 			    pd->dir == (*state)->direction ? "fwd" : "rev");
4282 			printf("pf: State failure on: %c %c %c %c | %c %c\n",
4283 			    SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4284 			    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4285 			    ' ': '2',
4286 			    (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4287 			    (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4288 			    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4289 			    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4290 		}
4291 		REASON_SET(reason, PFRES_BADSTATE);
4292 		return (PF_DROP);
4293 	}
4294 
4295 	return (PF_PASS);
4296 }
4297 
4298 static int
4299 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4300 	struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4301 {
4302 	struct tcphdr		*th = pd->hdr.tcp;
4303 
4304 	if (th->th_flags & TH_SYN)
4305 		if (src->state < TCPS_SYN_SENT)
4306 			src->state = TCPS_SYN_SENT;
4307 	if (th->th_flags & TH_FIN)
4308 		if (src->state < TCPS_CLOSING)
4309 			src->state = TCPS_CLOSING;
4310 	if (th->th_flags & TH_ACK) {
4311 		if (dst->state == TCPS_SYN_SENT) {
4312 			dst->state = TCPS_ESTABLISHED;
4313 			if (src->state == TCPS_ESTABLISHED &&
4314 			    (*state)->src_node != NULL &&
4315 			    pf_src_connlimit(state)) {
4316 				REASON_SET(reason, PFRES_SRCLIMIT);
4317 				return (PF_DROP);
4318 			}
4319 		} else if (dst->state == TCPS_CLOSING) {
4320 			dst->state = TCPS_FIN_WAIT_2;
4321 		} else if (src->state == TCPS_SYN_SENT &&
4322 		    dst->state < TCPS_SYN_SENT) {
4323 			/*
4324 			 * Handle a special sloppy case where we only see one
4325 			 * half of the connection. If there is a ACK after
4326 			 * the initial SYN without ever seeing a packet from
4327 			 * the destination, set the connection to established.
4328 			 */
4329 			dst->state = src->state = TCPS_ESTABLISHED;
4330 			if ((*state)->src_node != NULL &&
4331 			    pf_src_connlimit(state)) {
4332 				REASON_SET(reason, PFRES_SRCLIMIT);
4333 				return (PF_DROP);
4334 			}
4335 		} else if (src->state == TCPS_CLOSING &&
4336 		    dst->state == TCPS_ESTABLISHED &&
4337 		    dst->seqlo == 0) {
4338 			/*
4339 			 * Handle the closing of half connections where we
4340 			 * don't see the full bidirectional FIN/ACK+ACK
4341 			 * handshake.
4342 			 */
4343 			dst->state = TCPS_CLOSING;
4344 		}
4345 	}
4346 	if (th->th_flags & TH_RST)
4347 		src->state = dst->state = TCPS_TIME_WAIT;
4348 
4349 	/* update expire time */
4350 	(*state)->expire = time_uptime;
4351 	if (src->state >= TCPS_FIN_WAIT_2 &&
4352 	    dst->state >= TCPS_FIN_WAIT_2)
4353 		(*state)->timeout = PFTM_TCP_CLOSED;
4354 	else if (src->state >= TCPS_CLOSING &&
4355 	    dst->state >= TCPS_CLOSING)
4356 		(*state)->timeout = PFTM_TCP_FIN_WAIT;
4357 	else if (src->state < TCPS_ESTABLISHED ||
4358 	    dst->state < TCPS_ESTABLISHED)
4359 		(*state)->timeout = PFTM_TCP_OPENING;
4360 	else if (src->state >= TCPS_CLOSING ||
4361 	    dst->state >= TCPS_CLOSING)
4362 		(*state)->timeout = PFTM_TCP_CLOSING;
4363 	else
4364 		(*state)->timeout = PFTM_TCP_ESTABLISHED;
4365 
4366 	return (PF_PASS);
4367 }
4368 
4369 static int
4370 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4371     struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4372     u_short *reason)
4373 {
4374 	struct pf_state_key_cmp	 key;
4375 	struct tcphdr		*th = pd->hdr.tcp;
4376 	int			 copyback = 0;
4377 	struct pf_state_peer	*src, *dst;
4378 	struct pf_state_key	*sk;
4379 
4380 	bzero(&key, sizeof(key));
4381 	key.af = pd->af;
4382 	key.proto = IPPROTO_TCP;
4383 	if (direction == PF_IN)	{	/* wire side, straight */
4384 		PF_ACPY(&key.addr[0], pd->src, key.af);
4385 		PF_ACPY(&key.addr[1], pd->dst, key.af);
4386 		key.port[0] = th->th_sport;
4387 		key.port[1] = th->th_dport;
4388 	} else {			/* stack side, reverse */
4389 		PF_ACPY(&key.addr[1], pd->src, key.af);
4390 		PF_ACPY(&key.addr[0], pd->dst, key.af);
4391 		key.port[1] = th->th_sport;
4392 		key.port[0] = th->th_dport;
4393 	}
4394 
4395 	STATE_LOOKUP(kif, &key, direction, *state, pd);
4396 
4397 	if (direction == (*state)->direction) {
4398 		src = &(*state)->src;
4399 		dst = &(*state)->dst;
4400 	} else {
4401 		src = &(*state)->dst;
4402 		dst = &(*state)->src;
4403 	}
4404 
4405 	sk = (*state)->key[pd->didx];
4406 
4407 	if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4408 		if (direction != (*state)->direction) {
4409 			REASON_SET(reason, PFRES_SYNPROXY);
4410 			return (PF_SYNPROXY_DROP);
4411 		}
4412 		if (th->th_flags & TH_SYN) {
4413 			if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4414 				REASON_SET(reason, PFRES_SYNPROXY);
4415 				return (PF_DROP);
4416 			}
4417 			pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4418 			    pd->src, th->th_dport, th->th_sport,
4419 			    (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4420 			    TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4421 			REASON_SET(reason, PFRES_SYNPROXY);
4422 			return (PF_SYNPROXY_DROP);
4423 		} else if ((th->th_flags & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
4424 		    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4425 		    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4426 			REASON_SET(reason, PFRES_SYNPROXY);
4427 			return (PF_DROP);
4428 		} else if ((*state)->src_node != NULL &&
4429 		    pf_src_connlimit(state)) {
4430 			REASON_SET(reason, PFRES_SRCLIMIT);
4431 			return (PF_DROP);
4432 		} else
4433 			(*state)->src.state = PF_TCPS_PROXY_DST;
4434 	}
4435 	if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4436 		if (direction == (*state)->direction) {
4437 			if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4438 			    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4439 			    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4440 				REASON_SET(reason, PFRES_SYNPROXY);
4441 				return (PF_DROP);
4442 			}
4443 			(*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4444 			if ((*state)->dst.seqhi == 1)
4445 				(*state)->dst.seqhi = htonl(arc4random());
4446 			pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4447 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
4448 			    sk->port[pd->sidx], sk->port[pd->didx],
4449 			    (*state)->dst.seqhi, 0, TH_SYN, 0,
4450 			    (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4451 			REASON_SET(reason, PFRES_SYNPROXY);
4452 			return (PF_SYNPROXY_DROP);
4453 		} else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4454 		    (TH_SYN|TH_ACK)) ||
4455 		    (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4456 			REASON_SET(reason, PFRES_SYNPROXY);
4457 			return (PF_DROP);
4458 		} else {
4459 			(*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4460 			(*state)->dst.seqlo = ntohl(th->th_seq);
4461 			pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4462 			    pd->src, th->th_dport, th->th_sport,
4463 			    ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4464 			    TH_ACK, (*state)->src.max_win, 0, 0, 0,
4465 			    (*state)->tag, NULL);
4466 			pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4467 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
4468 			    sk->port[pd->sidx], sk->port[pd->didx],
4469 			    (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4470 			    TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4471 			(*state)->src.seqdiff = (*state)->dst.seqhi -
4472 			    (*state)->src.seqlo;
4473 			(*state)->dst.seqdiff = (*state)->src.seqhi -
4474 			    (*state)->dst.seqlo;
4475 			(*state)->src.seqhi = (*state)->src.seqlo +
4476 			    (*state)->dst.max_win;
4477 			(*state)->dst.seqhi = (*state)->dst.seqlo +
4478 			    (*state)->src.max_win;
4479 			(*state)->src.wscale = (*state)->dst.wscale = 0;
4480 			(*state)->src.state = (*state)->dst.state =
4481 			    TCPS_ESTABLISHED;
4482 			REASON_SET(reason, PFRES_SYNPROXY);
4483 			return (PF_SYNPROXY_DROP);
4484 		}
4485 	}
4486 
4487 	if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4488 	    dst->state >= TCPS_FIN_WAIT_2 &&
4489 	    src->state >= TCPS_FIN_WAIT_2) {
4490 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
4491 			printf("pf: state reuse ");
4492 			pf_print_state(*state);
4493 			pf_print_flags(th->th_flags);
4494 			printf("\n");
4495 		}
4496 		/* XXX make sure it's the same direction ?? */
4497 		(*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4498 		pf_unlink_state(*state, PF_ENTER_LOCKED);
4499 		*state = NULL;
4500 		return (PF_DROP);
4501 	}
4502 
4503 	if ((*state)->state_flags & PFSTATE_SLOPPY) {
4504 		if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4505 			return (PF_DROP);
4506 	} else {
4507 		if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4508 		    &copyback) == PF_DROP)
4509 			return (PF_DROP);
4510 	}
4511 
4512 	/* translate source/destination address, if necessary */
4513 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4514 		struct pf_state_key *nk = (*state)->key[pd->didx];
4515 
4516 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4517 		    nk->port[pd->sidx] != th->th_sport)
4518 			pf_change_ap(m, pd->src, &th->th_sport,
4519 			    pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4520 			    nk->port[pd->sidx], 0, pd->af);
4521 
4522 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4523 		    nk->port[pd->didx] != th->th_dport)
4524 			pf_change_ap(m, pd->dst, &th->th_dport,
4525 			    pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4526 			    nk->port[pd->didx], 0, pd->af);
4527 		copyback = 1;
4528 	}
4529 
4530 	/* Copyback sequence modulation or stateful scrub changes if needed */
4531 	if (copyback)
4532 		m_copyback(m, off, sizeof(*th), (caddr_t)th);
4533 
4534 	return (PF_PASS);
4535 }
4536 
4537 static int
4538 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4539     struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4540 {
4541 	struct pf_state_peer	*src, *dst;
4542 	struct pf_state_key_cmp	 key;
4543 	struct udphdr		*uh = pd->hdr.udp;
4544 
4545 	bzero(&key, sizeof(key));
4546 	key.af = pd->af;
4547 	key.proto = IPPROTO_UDP;
4548 	if (direction == PF_IN)	{	/* wire side, straight */
4549 		PF_ACPY(&key.addr[0], pd->src, key.af);
4550 		PF_ACPY(&key.addr[1], pd->dst, key.af);
4551 		key.port[0] = uh->uh_sport;
4552 		key.port[1] = uh->uh_dport;
4553 	} else {			/* stack side, reverse */
4554 		PF_ACPY(&key.addr[1], pd->src, key.af);
4555 		PF_ACPY(&key.addr[0], pd->dst, key.af);
4556 		key.port[1] = uh->uh_sport;
4557 		key.port[0] = uh->uh_dport;
4558 	}
4559 
4560 	STATE_LOOKUP(kif, &key, direction, *state, pd);
4561 
4562 	if (direction == (*state)->direction) {
4563 		src = &(*state)->src;
4564 		dst = &(*state)->dst;
4565 	} else {
4566 		src = &(*state)->dst;
4567 		dst = &(*state)->src;
4568 	}
4569 
4570 	/* update states */
4571 	if (src->state < PFUDPS_SINGLE)
4572 		src->state = PFUDPS_SINGLE;
4573 	if (dst->state == PFUDPS_SINGLE)
4574 		dst->state = PFUDPS_MULTIPLE;
4575 
4576 	/* update expire time */
4577 	(*state)->expire = time_uptime;
4578 	if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4579 		(*state)->timeout = PFTM_UDP_MULTIPLE;
4580 	else
4581 		(*state)->timeout = PFTM_UDP_SINGLE;
4582 
4583 	/* translate source/destination address, if necessary */
4584 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4585 		struct pf_state_key *nk = (*state)->key[pd->didx];
4586 
4587 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4588 		    nk->port[pd->sidx] != uh->uh_sport)
4589 			pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4590 			    &uh->uh_sum, &nk->addr[pd->sidx],
4591 			    nk->port[pd->sidx], 1, pd->af);
4592 
4593 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4594 		    nk->port[pd->didx] != uh->uh_dport)
4595 			pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4596 			    &uh->uh_sum, &nk->addr[pd->didx],
4597 			    nk->port[pd->didx], 1, pd->af);
4598 		m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4599 	}
4600 
4601 	return (PF_PASS);
4602 }
4603 
4604 static int
4605 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4606     struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4607 {
4608 	struct pf_addr  *saddr = pd->src, *daddr = pd->dst;
4609 	u_int16_t	 icmpid = 0, *icmpsum;
4610 	u_int8_t	 icmptype, icmpcode;
4611 	int		 state_icmp = 0;
4612 	struct pf_state_key_cmp key;
4613 
4614 	bzero(&key, sizeof(key));
4615 	switch (pd->proto) {
4616 #ifdef INET
4617 	case IPPROTO_ICMP:
4618 		icmptype = pd->hdr.icmp->icmp_type;
4619 		icmpcode = pd->hdr.icmp->icmp_code;
4620 		icmpid = pd->hdr.icmp->icmp_id;
4621 		icmpsum = &pd->hdr.icmp->icmp_cksum;
4622 
4623 		if (icmptype == ICMP_UNREACH ||
4624 		    icmptype == ICMP_SOURCEQUENCH ||
4625 		    icmptype == ICMP_REDIRECT ||
4626 		    icmptype == ICMP_TIMXCEED ||
4627 		    icmptype == ICMP_PARAMPROB)
4628 			state_icmp++;
4629 		break;
4630 #endif /* INET */
4631 #ifdef INET6
4632 	case IPPROTO_ICMPV6:
4633 		icmptype = pd->hdr.icmp6->icmp6_type;
4634 		icmpcode = pd->hdr.icmp6->icmp6_code;
4635 		icmpid = pd->hdr.icmp6->icmp6_id;
4636 		icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4637 
4638 		if (icmptype == ICMP6_DST_UNREACH ||
4639 		    icmptype == ICMP6_PACKET_TOO_BIG ||
4640 		    icmptype == ICMP6_TIME_EXCEEDED ||
4641 		    icmptype == ICMP6_PARAM_PROB)
4642 			state_icmp++;
4643 		break;
4644 #endif /* INET6 */
4645 	}
4646 
4647 	if (!state_icmp) {
4648 
4649 		/*
4650 		 * ICMP query/reply message not related to a TCP/UDP packet.
4651 		 * Search for an ICMP state.
4652 		 */
4653 		key.af = pd->af;
4654 		key.proto = pd->proto;
4655 		key.port[0] = key.port[1] = icmpid;
4656 		if (direction == PF_IN)	{	/* wire side, straight */
4657 			PF_ACPY(&key.addr[0], pd->src, key.af);
4658 			PF_ACPY(&key.addr[1], pd->dst, key.af);
4659 		} else {			/* stack side, reverse */
4660 			PF_ACPY(&key.addr[1], pd->src, key.af);
4661 			PF_ACPY(&key.addr[0], pd->dst, key.af);
4662 		}
4663 
4664 		STATE_LOOKUP(kif, &key, direction, *state, pd);
4665 
4666 		(*state)->expire = time_uptime;
4667 		(*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4668 
4669 		/* translate source/destination address, if necessary */
4670 		if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4671 			struct pf_state_key *nk = (*state)->key[pd->didx];
4672 
4673 			switch (pd->af) {
4674 #ifdef INET
4675 			case AF_INET:
4676 				if (PF_ANEQ(pd->src,
4677 				    &nk->addr[pd->sidx], AF_INET))
4678 					pf_change_a(&saddr->v4.s_addr,
4679 					    pd->ip_sum,
4680 					    nk->addr[pd->sidx].v4.s_addr, 0);
4681 
4682 				if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4683 				    AF_INET))
4684 					pf_change_a(&daddr->v4.s_addr,
4685 					    pd->ip_sum,
4686 					    nk->addr[pd->didx].v4.s_addr, 0);
4687 
4688 				if (nk->port[0] !=
4689 				    pd->hdr.icmp->icmp_id) {
4690 					pd->hdr.icmp->icmp_cksum =
4691 					    pf_cksum_fixup(
4692 					    pd->hdr.icmp->icmp_cksum, icmpid,
4693 					    nk->port[pd->sidx], 0);
4694 					pd->hdr.icmp->icmp_id =
4695 					    nk->port[pd->sidx];
4696 				}
4697 
4698 				m_copyback(m, off, ICMP_MINLEN,
4699 				    (caddr_t )pd->hdr.icmp);
4700 				break;
4701 #endif /* INET */
4702 #ifdef INET6
4703 			case AF_INET6:
4704 				if (PF_ANEQ(pd->src,
4705 				    &nk->addr[pd->sidx], AF_INET6))
4706 					pf_change_a6(saddr,
4707 					    &pd->hdr.icmp6->icmp6_cksum,
4708 					    &nk->addr[pd->sidx], 0);
4709 
4710 				if (PF_ANEQ(pd->dst,
4711 				    &nk->addr[pd->didx], AF_INET6))
4712 					pf_change_a6(daddr,
4713 					    &pd->hdr.icmp6->icmp6_cksum,
4714 					    &nk->addr[pd->didx], 0);
4715 
4716 				m_copyback(m, off, sizeof(struct icmp6_hdr),
4717 				    (caddr_t )pd->hdr.icmp6);
4718 				break;
4719 #endif /* INET6 */
4720 			}
4721 		}
4722 		return (PF_PASS);
4723 
4724 	} else {
4725 		/*
4726 		 * ICMP error message in response to a TCP/UDP packet.
4727 		 * Extract the inner TCP/UDP header and search for that state.
4728 		 */
4729 
4730 		struct pf_pdesc	pd2;
4731 		bzero(&pd2, sizeof pd2);
4732 #ifdef INET
4733 		struct ip	h2;
4734 #endif /* INET */
4735 #ifdef INET6
4736 		struct ip6_hdr	h2_6;
4737 		int		terminal = 0;
4738 #endif /* INET6 */
4739 		int		ipoff2 = 0;
4740 		int		off2 = 0;
4741 
4742 		pd2.af = pd->af;
4743 		/* Payload packet is from the opposite direction. */
4744 		pd2.sidx = (direction == PF_IN) ? 1 : 0;
4745 		pd2.didx = (direction == PF_IN) ? 0 : 1;
4746 		switch (pd->af) {
4747 #ifdef INET
4748 		case AF_INET:
4749 			/* offset of h2 in mbuf chain */
4750 			ipoff2 = off + ICMP_MINLEN;
4751 
4752 			if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4753 			    NULL, reason, pd2.af)) {
4754 				DPFPRINTF(PF_DEBUG_MISC,
4755 				    ("pf: ICMP error message too short "
4756 				    "(ip)\n"));
4757 				return (PF_DROP);
4758 			}
4759 			/*
4760 			 * ICMP error messages don't refer to non-first
4761 			 * fragments
4762 			 */
4763 			if (h2.ip_off & htons(IP_OFFMASK)) {
4764 				REASON_SET(reason, PFRES_FRAG);
4765 				return (PF_DROP);
4766 			}
4767 
4768 			/* offset of protocol header that follows h2 */
4769 			off2 = ipoff2 + (h2.ip_hl << 2);
4770 
4771 			pd2.proto = h2.ip_p;
4772 			pd2.src = (struct pf_addr *)&h2.ip_src;
4773 			pd2.dst = (struct pf_addr *)&h2.ip_dst;
4774 			pd2.ip_sum = &h2.ip_sum;
4775 			break;
4776 #endif /* INET */
4777 #ifdef INET6
4778 		case AF_INET6:
4779 			ipoff2 = off + sizeof(struct icmp6_hdr);
4780 
4781 			if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4782 			    NULL, reason, pd2.af)) {
4783 				DPFPRINTF(PF_DEBUG_MISC,
4784 				    ("pf: ICMP error message too short "
4785 				    "(ip6)\n"));
4786 				return (PF_DROP);
4787 			}
4788 			pd2.proto = h2_6.ip6_nxt;
4789 			pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4790 			pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4791 			pd2.ip_sum = NULL;
4792 			off2 = ipoff2 + sizeof(h2_6);
4793 			do {
4794 				switch (pd2.proto) {
4795 				case IPPROTO_FRAGMENT:
4796 					/*
4797 					 * ICMPv6 error messages for
4798 					 * non-first fragments
4799 					 */
4800 					REASON_SET(reason, PFRES_FRAG);
4801 					return (PF_DROP);
4802 				case IPPROTO_AH:
4803 				case IPPROTO_HOPOPTS:
4804 				case IPPROTO_ROUTING:
4805 				case IPPROTO_DSTOPTS: {
4806 					/* get next header and header length */
4807 					struct ip6_ext opt6;
4808 
4809 					if (!pf_pull_hdr(m, off2, &opt6,
4810 					    sizeof(opt6), NULL, reason,
4811 					    pd2.af)) {
4812 						DPFPRINTF(PF_DEBUG_MISC,
4813 						    ("pf: ICMPv6 short opt\n"));
4814 						return (PF_DROP);
4815 					}
4816 					if (pd2.proto == IPPROTO_AH)
4817 						off2 += (opt6.ip6e_len + 2) * 4;
4818 					else
4819 						off2 += (opt6.ip6e_len + 1) * 8;
4820 					pd2.proto = opt6.ip6e_nxt;
4821 					/* goto the next header */
4822 					break;
4823 				}
4824 				default:
4825 					terminal++;
4826 					break;
4827 				}
4828 			} while (!terminal);
4829 			break;
4830 #endif /* INET6 */
4831 		}
4832 
4833 		if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
4834 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
4835 				printf("pf: BAD ICMP %d:%d outer dst: ",
4836 				    icmptype, icmpcode);
4837 				pf_print_host(pd->src, 0, pd->af);
4838 				printf(" -> ");
4839 				pf_print_host(pd->dst, 0, pd->af);
4840 				printf(" inner src: ");
4841 				pf_print_host(pd2.src, 0, pd2.af);
4842 				printf(" -> ");
4843 				pf_print_host(pd2.dst, 0, pd2.af);
4844 				printf("\n");
4845 			}
4846 			REASON_SET(reason, PFRES_BADSTATE);
4847 			return (PF_DROP);
4848 		}
4849 
4850 		switch (pd2.proto) {
4851 		case IPPROTO_TCP: {
4852 			struct tcphdr		 th;
4853 			u_int32_t		 seq;
4854 			struct pf_state_peer	*src, *dst;
4855 			u_int8_t		 dws;
4856 			int			 copyback = 0;
4857 
4858 			/*
4859 			 * Only the first 8 bytes of the TCP header can be
4860 			 * expected. Don't access any TCP header fields after
4861 			 * th_seq, an ackskew test is not possible.
4862 			 */
4863 			if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4864 			    pd2.af)) {
4865 				DPFPRINTF(PF_DEBUG_MISC,
4866 				    ("pf: ICMP error message too short "
4867 				    "(tcp)\n"));
4868 				return (PF_DROP);
4869 			}
4870 
4871 			key.af = pd2.af;
4872 			key.proto = IPPROTO_TCP;
4873 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4874 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4875 			key.port[pd2.sidx] = th.th_sport;
4876 			key.port[pd2.didx] = th.th_dport;
4877 
4878 			STATE_LOOKUP(kif, &key, direction, *state, pd);
4879 
4880 			if (direction == (*state)->direction) {
4881 				src = &(*state)->dst;
4882 				dst = &(*state)->src;
4883 			} else {
4884 				src = &(*state)->src;
4885 				dst = &(*state)->dst;
4886 			}
4887 
4888 			if (src->wscale && dst->wscale)
4889 				dws = dst->wscale & PF_WSCALE_MASK;
4890 			else
4891 				dws = 0;
4892 
4893 			/* Demodulate sequence number */
4894 			seq = ntohl(th.th_seq) - src->seqdiff;
4895 			if (src->seqdiff) {
4896 				pf_change_a(&th.th_seq, icmpsum,
4897 				    htonl(seq), 0);
4898 				copyback = 1;
4899 			}
4900 
4901 			if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4902 			    (!SEQ_GEQ(src->seqhi, seq) ||
4903 			    !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4904 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
4905 					printf("pf: BAD ICMP %d:%d ",
4906 					    icmptype, icmpcode);
4907 					pf_print_host(pd->src, 0, pd->af);
4908 					printf(" -> ");
4909 					pf_print_host(pd->dst, 0, pd->af);
4910 					printf(" state: ");
4911 					pf_print_state(*state);
4912 					printf(" seq=%u\n", seq);
4913 				}
4914 				REASON_SET(reason, PFRES_BADSTATE);
4915 				return (PF_DROP);
4916 			} else {
4917 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
4918 					printf("pf: OK ICMP %d:%d ",
4919 					    icmptype, icmpcode);
4920 					pf_print_host(pd->src, 0, pd->af);
4921 					printf(" -> ");
4922 					pf_print_host(pd->dst, 0, pd->af);
4923 					printf(" state: ");
4924 					pf_print_state(*state);
4925 					printf(" seq=%u\n", seq);
4926 				}
4927 			}
4928 
4929 			/* translate source/destination address, if necessary */
4930 			if ((*state)->key[PF_SK_WIRE] !=
4931 			    (*state)->key[PF_SK_STACK]) {
4932 				struct pf_state_key *nk =
4933 				    (*state)->key[pd->didx];
4934 
4935 				if (PF_ANEQ(pd2.src,
4936 				    &nk->addr[pd2.sidx], pd2.af) ||
4937 				    nk->port[pd2.sidx] != th.th_sport)
4938 					pf_change_icmp(pd2.src, &th.th_sport,
4939 					    daddr, &nk->addr[pd2.sidx],
4940 					    nk->port[pd2.sidx], NULL,
4941 					    pd2.ip_sum, icmpsum,
4942 					    pd->ip_sum, 0, pd2.af);
4943 
4944 				if (PF_ANEQ(pd2.dst,
4945 				    &nk->addr[pd2.didx], pd2.af) ||
4946 				    nk->port[pd2.didx] != th.th_dport)
4947 					pf_change_icmp(pd2.dst, &th.th_dport,
4948 					    saddr, &nk->addr[pd2.didx],
4949 					    nk->port[pd2.didx], NULL,
4950 					    pd2.ip_sum, icmpsum,
4951 					    pd->ip_sum, 0, pd2.af);
4952 				copyback = 1;
4953 			}
4954 
4955 			if (copyback) {
4956 				switch (pd2.af) {
4957 #ifdef INET
4958 				case AF_INET:
4959 					m_copyback(m, off, ICMP_MINLEN,
4960 					    (caddr_t )pd->hdr.icmp);
4961 					m_copyback(m, ipoff2, sizeof(h2),
4962 					    (caddr_t )&h2);
4963 					break;
4964 #endif /* INET */
4965 #ifdef INET6
4966 				case AF_INET6:
4967 					m_copyback(m, off,
4968 					    sizeof(struct icmp6_hdr),
4969 					    (caddr_t )pd->hdr.icmp6);
4970 					m_copyback(m, ipoff2, sizeof(h2_6),
4971 					    (caddr_t )&h2_6);
4972 					break;
4973 #endif /* INET6 */
4974 				}
4975 				m_copyback(m, off2, 8, (caddr_t)&th);
4976 			}
4977 
4978 			return (PF_PASS);
4979 			break;
4980 		}
4981 		case IPPROTO_UDP: {
4982 			struct udphdr		uh;
4983 
4984 			if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4985 			    NULL, reason, pd2.af)) {
4986 				DPFPRINTF(PF_DEBUG_MISC,
4987 				    ("pf: ICMP error message too short "
4988 				    "(udp)\n"));
4989 				return (PF_DROP);
4990 			}
4991 
4992 			key.af = pd2.af;
4993 			key.proto = IPPROTO_UDP;
4994 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4995 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4996 			key.port[pd2.sidx] = uh.uh_sport;
4997 			key.port[pd2.didx] = uh.uh_dport;
4998 
4999 			STATE_LOOKUP(kif, &key, direction, *state, pd);
5000 
5001 			/* translate source/destination address, if necessary */
5002 			if ((*state)->key[PF_SK_WIRE] !=
5003 			    (*state)->key[PF_SK_STACK]) {
5004 				struct pf_state_key *nk =
5005 				    (*state)->key[pd->didx];
5006 
5007 				if (PF_ANEQ(pd2.src,
5008 				    &nk->addr[pd2.sidx], pd2.af) ||
5009 				    nk->port[pd2.sidx] != uh.uh_sport)
5010 					pf_change_icmp(pd2.src, &uh.uh_sport,
5011 					    daddr, &nk->addr[pd2.sidx],
5012 					    nk->port[pd2.sidx], &uh.uh_sum,
5013 					    pd2.ip_sum, icmpsum,
5014 					    pd->ip_sum, 1, pd2.af);
5015 
5016 				if (PF_ANEQ(pd2.dst,
5017 				    &nk->addr[pd2.didx], pd2.af) ||
5018 				    nk->port[pd2.didx] != uh.uh_dport)
5019 					pf_change_icmp(pd2.dst, &uh.uh_dport,
5020 					    saddr, &nk->addr[pd2.didx],
5021 					    nk->port[pd2.didx], &uh.uh_sum,
5022 					    pd2.ip_sum, icmpsum,
5023 					    pd->ip_sum, 1, pd2.af);
5024 
5025 				switch (pd2.af) {
5026 #ifdef INET
5027 				case AF_INET:
5028 					m_copyback(m, off, ICMP_MINLEN,
5029 					    (caddr_t )pd->hdr.icmp);
5030 					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5031 					break;
5032 #endif /* INET */
5033 #ifdef INET6
5034 				case AF_INET6:
5035 					m_copyback(m, off,
5036 					    sizeof(struct icmp6_hdr),
5037 					    (caddr_t )pd->hdr.icmp6);
5038 					m_copyback(m, ipoff2, sizeof(h2_6),
5039 					    (caddr_t )&h2_6);
5040 					break;
5041 #endif /* INET6 */
5042 				}
5043 				m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5044 			}
5045 			return (PF_PASS);
5046 			break;
5047 		}
5048 #ifdef INET
5049 		case IPPROTO_ICMP: {
5050 			struct icmp		iih;
5051 
5052 			if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5053 			    NULL, reason, pd2.af)) {
5054 				DPFPRINTF(PF_DEBUG_MISC,
5055 				    ("pf: ICMP error message too short i"
5056 				    "(icmp)\n"));
5057 				return (PF_DROP);
5058 			}
5059 
5060 			key.af = pd2.af;
5061 			key.proto = IPPROTO_ICMP;
5062 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5063 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5064 			key.port[0] = key.port[1] = iih.icmp_id;
5065 
5066 			STATE_LOOKUP(kif, &key, direction, *state, pd);
5067 
5068 			/* translate source/destination address, if necessary */
5069 			if ((*state)->key[PF_SK_WIRE] !=
5070 			    (*state)->key[PF_SK_STACK]) {
5071 				struct pf_state_key *nk =
5072 				    (*state)->key[pd->didx];
5073 
5074 				if (PF_ANEQ(pd2.src,
5075 				    &nk->addr[pd2.sidx], pd2.af) ||
5076 				    nk->port[pd2.sidx] != iih.icmp_id)
5077 					pf_change_icmp(pd2.src, &iih.icmp_id,
5078 					    daddr, &nk->addr[pd2.sidx],
5079 					    nk->port[pd2.sidx], NULL,
5080 					    pd2.ip_sum, icmpsum,
5081 					    pd->ip_sum, 0, AF_INET);
5082 
5083 				if (PF_ANEQ(pd2.dst,
5084 				    &nk->addr[pd2.didx], pd2.af) ||
5085 				    nk->port[pd2.didx] != iih.icmp_id)
5086 					pf_change_icmp(pd2.dst, &iih.icmp_id,
5087 					    saddr, &nk->addr[pd2.didx],
5088 					    nk->port[pd2.didx], NULL,
5089 					    pd2.ip_sum, icmpsum,
5090 					    pd->ip_sum, 0, AF_INET);
5091 
5092 				m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5093 				m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5094 				m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5095 			}
5096 			return (PF_PASS);
5097 			break;
5098 		}
5099 #endif /* INET */
5100 #ifdef INET6
5101 		case IPPROTO_ICMPV6: {
5102 			struct icmp6_hdr	iih;
5103 
5104 			if (!pf_pull_hdr(m, off2, &iih,
5105 			    sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5106 				DPFPRINTF(PF_DEBUG_MISC,
5107 				    ("pf: ICMP error message too short "
5108 				    "(icmp6)\n"));
5109 				return (PF_DROP);
5110 			}
5111 
5112 			key.af = pd2.af;
5113 			key.proto = IPPROTO_ICMPV6;
5114 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5115 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5116 			key.port[0] = key.port[1] = iih.icmp6_id;
5117 
5118 			STATE_LOOKUP(kif, &key, direction, *state, pd);
5119 
5120 			/* translate source/destination address, if necessary */
5121 			if ((*state)->key[PF_SK_WIRE] !=
5122 			    (*state)->key[PF_SK_STACK]) {
5123 				struct pf_state_key *nk =
5124 				    (*state)->key[pd->didx];
5125 
5126 				if (PF_ANEQ(pd2.src,
5127 				    &nk->addr[pd2.sidx], pd2.af) ||
5128 				    nk->port[pd2.sidx] != iih.icmp6_id)
5129 					pf_change_icmp(pd2.src, &iih.icmp6_id,
5130 					    daddr, &nk->addr[pd2.sidx],
5131 					    nk->port[pd2.sidx], NULL,
5132 					    pd2.ip_sum, icmpsum,
5133 					    pd->ip_sum, 0, AF_INET6);
5134 
5135 				if (PF_ANEQ(pd2.dst,
5136 				    &nk->addr[pd2.didx], pd2.af) ||
5137 				    nk->port[pd2.didx] != iih.icmp6_id)
5138 					pf_change_icmp(pd2.dst, &iih.icmp6_id,
5139 					    saddr, &nk->addr[pd2.didx],
5140 					    nk->port[pd2.didx], NULL,
5141 					    pd2.ip_sum, icmpsum,
5142 					    pd->ip_sum, 0, AF_INET6);
5143 
5144 				m_copyback(m, off, sizeof(struct icmp6_hdr),
5145 				    (caddr_t)pd->hdr.icmp6);
5146 				m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5147 				m_copyback(m, off2, sizeof(struct icmp6_hdr),
5148 				    (caddr_t)&iih);
5149 			}
5150 			return (PF_PASS);
5151 			break;
5152 		}
5153 #endif /* INET6 */
5154 		default: {
5155 			key.af = pd2.af;
5156 			key.proto = pd2.proto;
5157 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5158 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5159 			key.port[0] = key.port[1] = 0;
5160 
5161 			STATE_LOOKUP(kif, &key, direction, *state, pd);
5162 
5163 			/* translate source/destination address, if necessary */
5164 			if ((*state)->key[PF_SK_WIRE] !=
5165 			    (*state)->key[PF_SK_STACK]) {
5166 				struct pf_state_key *nk =
5167 				    (*state)->key[pd->didx];
5168 
5169 				if (PF_ANEQ(pd2.src,
5170 				    &nk->addr[pd2.sidx], pd2.af))
5171 					pf_change_icmp(pd2.src, NULL, daddr,
5172 					    &nk->addr[pd2.sidx], 0, NULL,
5173 					    pd2.ip_sum, icmpsum,
5174 					    pd->ip_sum, 0, pd2.af);
5175 
5176 				if (PF_ANEQ(pd2.dst,
5177 				    &nk->addr[pd2.didx], pd2.af))
5178 					pf_change_icmp(pd2.dst, NULL, saddr,
5179 					    &nk->addr[pd2.didx], 0, NULL,
5180 					    pd2.ip_sum, icmpsum,
5181 					    pd->ip_sum, 0, pd2.af);
5182 
5183 				switch (pd2.af) {
5184 #ifdef INET
5185 				case AF_INET:
5186 					m_copyback(m, off, ICMP_MINLEN,
5187 					    (caddr_t)pd->hdr.icmp);
5188 					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5189 					break;
5190 #endif /* INET */
5191 #ifdef INET6
5192 				case AF_INET6:
5193 					m_copyback(m, off,
5194 					    sizeof(struct icmp6_hdr),
5195 					    (caddr_t )pd->hdr.icmp6);
5196 					m_copyback(m, ipoff2, sizeof(h2_6),
5197 					    (caddr_t )&h2_6);
5198 					break;
5199 #endif /* INET6 */
5200 				}
5201 			}
5202 			return (PF_PASS);
5203 			break;
5204 		}
5205 		}
5206 	}
5207 }
5208 
5209 static int
5210 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5211     struct mbuf *m, struct pf_pdesc *pd)
5212 {
5213 	struct pf_state_peer	*src, *dst;
5214 	struct pf_state_key_cmp	 key;
5215 
5216 	bzero(&key, sizeof(key));
5217 	key.af = pd->af;
5218 	key.proto = pd->proto;
5219 	if (direction == PF_IN)	{
5220 		PF_ACPY(&key.addr[0], pd->src, key.af);
5221 		PF_ACPY(&key.addr[1], pd->dst, key.af);
5222 		key.port[0] = key.port[1] = 0;
5223 	} else {
5224 		PF_ACPY(&key.addr[1], pd->src, key.af);
5225 		PF_ACPY(&key.addr[0], pd->dst, key.af);
5226 		key.port[1] = key.port[0] = 0;
5227 	}
5228 
5229 	STATE_LOOKUP(kif, &key, direction, *state, pd);
5230 
5231 	if (direction == (*state)->direction) {
5232 		src = &(*state)->src;
5233 		dst = &(*state)->dst;
5234 	} else {
5235 		src = &(*state)->dst;
5236 		dst = &(*state)->src;
5237 	}
5238 
5239 	/* update states */
5240 	if (src->state < PFOTHERS_SINGLE)
5241 		src->state = PFOTHERS_SINGLE;
5242 	if (dst->state == PFOTHERS_SINGLE)
5243 		dst->state = PFOTHERS_MULTIPLE;
5244 
5245 	/* update expire time */
5246 	(*state)->expire = time_uptime;
5247 	if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5248 		(*state)->timeout = PFTM_OTHER_MULTIPLE;
5249 	else
5250 		(*state)->timeout = PFTM_OTHER_SINGLE;
5251 
5252 	/* translate source/destination address, if necessary */
5253 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5254 		struct pf_state_key *nk = (*state)->key[pd->didx];
5255 
5256 		KASSERT(nk, ("%s: nk is null", __func__));
5257 		KASSERT(pd, ("%s: pd is null", __func__));
5258 		KASSERT(pd->src, ("%s: pd->src is null", __func__));
5259 		KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5260 		switch (pd->af) {
5261 #ifdef INET
5262 		case AF_INET:
5263 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5264 				pf_change_a(&pd->src->v4.s_addr,
5265 				    pd->ip_sum,
5266 				    nk->addr[pd->sidx].v4.s_addr,
5267 				    0);
5268 
5269 
5270 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5271 				pf_change_a(&pd->dst->v4.s_addr,
5272 				    pd->ip_sum,
5273 				    nk->addr[pd->didx].v4.s_addr,
5274 				    0);
5275 
5276 			break;
5277 #endif /* INET */
5278 #ifdef INET6
5279 		case AF_INET6:
5280 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5281 				PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5282 
5283 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5284 				PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5285 #endif /* INET6 */
5286 		}
5287 	}
5288 	return (PF_PASS);
5289 }
5290 
5291 /*
5292  * ipoff and off are measured from the start of the mbuf chain.
5293  * h must be at "ipoff" on the mbuf chain.
5294  */
5295 void *
5296 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5297     u_short *actionp, u_short *reasonp, sa_family_t af)
5298 {
5299 	switch (af) {
5300 #ifdef INET
5301 	case AF_INET: {
5302 		struct ip	*h = mtod(m, struct ip *);
5303 		u_int16_t	 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5304 
5305 		if (fragoff) {
5306 			if (fragoff >= len)
5307 				ACTION_SET(actionp, PF_PASS);
5308 			else {
5309 				ACTION_SET(actionp, PF_DROP);
5310 				REASON_SET(reasonp, PFRES_FRAG);
5311 			}
5312 			return (NULL);
5313 		}
5314 		if (m->m_pkthdr.len < off + len ||
5315 		    ntohs(h->ip_len) < off + len) {
5316 			ACTION_SET(actionp, PF_DROP);
5317 			REASON_SET(reasonp, PFRES_SHORT);
5318 			return (NULL);
5319 		}
5320 		break;
5321 	}
5322 #endif /* INET */
5323 #ifdef INET6
5324 	case AF_INET6: {
5325 		struct ip6_hdr	*h = mtod(m, struct ip6_hdr *);
5326 
5327 		if (m->m_pkthdr.len < off + len ||
5328 		    (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5329 		    (unsigned)(off + len)) {
5330 			ACTION_SET(actionp, PF_DROP);
5331 			REASON_SET(reasonp, PFRES_SHORT);
5332 			return (NULL);
5333 		}
5334 		break;
5335 	}
5336 #endif /* INET6 */
5337 	}
5338 	m_copydata(m, off, len, p);
5339 	return (p);
5340 }
5341 
5342 int
5343 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5344     int rtableid)
5345 {
5346 	struct ifnet		*ifp;
5347 
5348 	/*
5349 	 * Skip check for addresses with embedded interface scope,
5350 	 * as they would always match anyway.
5351 	 */
5352 	if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
5353 		return (1);
5354 
5355 	if (af != AF_INET && af != AF_INET6)
5356 		return (0);
5357 
5358 	/* Skip checks for ipsec interfaces */
5359 	if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5360 		return (1);
5361 
5362 	ifp = (kif != NULL) ? kif->pfik_ifp : NULL;
5363 
5364 	switch (af) {
5365 #ifdef INET6
5366 	case AF_INET6:
5367 		return (fib6_check_urpf(rtableid, &addr->v6, 0, NHR_NONE,
5368 		    ifp));
5369 #endif
5370 #ifdef INET
5371 	case AF_INET:
5372 		return (fib4_check_urpf(rtableid, addr->v4, 0, NHR_NONE,
5373 		    ifp));
5374 #endif
5375 	}
5376 
5377 	return (0);
5378 }
5379 
5380 #ifdef INET
5381 static void
5382 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5383     struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5384 {
5385 	struct mbuf		*m0, *m1;
5386 	struct sockaddr_in	dst;
5387 	struct ip		*ip;
5388 	struct ifnet		*ifp = NULL;
5389 	struct pf_addr		 naddr;
5390 	struct pf_src_node	*sn = NULL;
5391 	int			 error = 0;
5392 	uint16_t		 ip_len, ip_off;
5393 
5394 	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5395 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5396 	    __func__));
5397 
5398 	if ((pd->pf_mtag == NULL &&
5399 	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5400 	    pd->pf_mtag->routed++ > 3) {
5401 		m0 = *m;
5402 		*m = NULL;
5403 		goto bad_locked;
5404 	}
5405 
5406 	if (r->rt == PF_DUPTO) {
5407 		if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5408 			if (s)
5409 				PF_STATE_UNLOCK(s);
5410 			return;
5411 		}
5412 	} else {
5413 		if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5414 			if (s)
5415 				PF_STATE_UNLOCK(s);
5416 			return;
5417 		}
5418 		m0 = *m;
5419 	}
5420 
5421 	ip = mtod(m0, struct ip *);
5422 
5423 	bzero(&dst, sizeof(dst));
5424 	dst.sin_family = AF_INET;
5425 	dst.sin_len = sizeof(dst);
5426 	dst.sin_addr = ip->ip_dst;
5427 
5428 	bzero(&naddr, sizeof(naddr));
5429 
5430 	if (TAILQ_EMPTY(&r->rpool.list)) {
5431 		DPFPRINTF(PF_DEBUG_URGENT,
5432 		    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5433 		goto bad_locked;
5434 	}
5435 	if (s == NULL) {
5436 		pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5437 		    &naddr, NULL, &sn);
5438 		if (!PF_AZERO(&naddr, AF_INET))
5439 			dst.sin_addr.s_addr = naddr.v4.s_addr;
5440 		ifp = r->rpool.cur->kif ?
5441 		    r->rpool.cur->kif->pfik_ifp : NULL;
5442 	} else {
5443 		if (!PF_AZERO(&s->rt_addr, AF_INET))
5444 			dst.sin_addr.s_addr =
5445 			    s->rt_addr.v4.s_addr;
5446 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5447 		PF_STATE_UNLOCK(s);
5448 	}
5449 	if (ifp == NULL)
5450 		goto bad;
5451 
5452 	if (oifp != ifp) {
5453 		if (pf_test(PF_OUT, 0, ifp, &m0, inp) != PF_PASS)
5454 			goto bad;
5455 		else if (m0 == NULL)
5456 			goto done;
5457 		if (m0->m_len < sizeof(struct ip)) {
5458 			DPFPRINTF(PF_DEBUG_URGENT,
5459 			    ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5460 			goto bad;
5461 		}
5462 		ip = mtod(m0, struct ip *);
5463 	}
5464 
5465 	if (ifp->if_flags & IFF_LOOPBACK)
5466 		m0->m_flags |= M_SKIP_FIREWALL;
5467 
5468 	ip_len = ntohs(ip->ip_len);
5469 	ip_off = ntohs(ip->ip_off);
5470 
5471 	/* Copied from FreeBSD 10.0-CURRENT ip_output. */
5472 	m0->m_pkthdr.csum_flags |= CSUM_IP;
5473 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5474 		in_delayed_cksum(m0);
5475 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5476 	}
5477 #if defined(SCTP) || defined(SCTP_SUPPORT)
5478 	if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5479 		sctp_delayed_cksum(m0, (uint32_t)(ip->ip_hl << 2));
5480 		m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5481 	}
5482 #endif
5483 
5484 	/*
5485 	 * If small enough for interface, or the interface will take
5486 	 * care of the fragmentation for us, we can just send directly.
5487 	 */
5488 	if (ip_len <= ifp->if_mtu ||
5489 	    (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
5490 		ip->ip_sum = 0;
5491 		if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5492 			ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5493 			m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5494 		}
5495 		m_clrprotoflags(m0);	/* Avoid confusing lower layers. */
5496 		error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5497 		goto done;
5498 	}
5499 
5500 	/* Balk when DF bit is set or the interface didn't support TSO. */
5501 	if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5502 		error = EMSGSIZE;
5503 		KMOD_IPSTAT_INC(ips_cantfrag);
5504 		if (r->rt != PF_DUPTO) {
5505 			icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5506 			    ifp->if_mtu);
5507 			goto done;
5508 		} else
5509 			goto bad;
5510 	}
5511 
5512 	error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5513 	if (error)
5514 		goto bad;
5515 
5516 	for (; m0; m0 = m1) {
5517 		m1 = m0->m_nextpkt;
5518 		m0->m_nextpkt = NULL;
5519 		if (error == 0) {
5520 			m_clrprotoflags(m0);
5521 			error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5522 		} else
5523 			m_freem(m0);
5524 	}
5525 
5526 	if (error == 0)
5527 		KMOD_IPSTAT_INC(ips_fragmented);
5528 
5529 done:
5530 	if (r->rt != PF_DUPTO)
5531 		*m = NULL;
5532 	return;
5533 
5534 bad_locked:
5535 	if (s)
5536 		PF_STATE_UNLOCK(s);
5537 bad:
5538 	m_freem(m0);
5539 	goto done;
5540 }
5541 #endif /* INET */
5542 
5543 #ifdef INET6
5544 static void
5545 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5546     struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5547 {
5548 	struct mbuf		*m0;
5549 	struct sockaddr_in6	dst;
5550 	struct ip6_hdr		*ip6;
5551 	struct ifnet		*ifp = NULL;
5552 	struct pf_addr		 naddr;
5553 	struct pf_src_node	*sn = NULL;
5554 
5555 	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5556 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5557 	    __func__));
5558 
5559 	if ((pd->pf_mtag == NULL &&
5560 	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5561 	    pd->pf_mtag->routed++ > 3) {
5562 		m0 = *m;
5563 		*m = NULL;
5564 		goto bad_locked;
5565 	}
5566 
5567 	if (r->rt == PF_DUPTO) {
5568 		if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5569 			if (s)
5570 				PF_STATE_UNLOCK(s);
5571 			return;
5572 		}
5573 	} else {
5574 		if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5575 			if (s)
5576 				PF_STATE_UNLOCK(s);
5577 			return;
5578 		}
5579 		m0 = *m;
5580 	}
5581 
5582 	ip6 = mtod(m0, struct ip6_hdr *);
5583 
5584 	bzero(&dst, sizeof(dst));
5585 	dst.sin6_family = AF_INET6;
5586 	dst.sin6_len = sizeof(dst);
5587 	dst.sin6_addr = ip6->ip6_dst;
5588 
5589 	bzero(&naddr, sizeof(naddr));
5590 
5591 	if (TAILQ_EMPTY(&r->rpool.list)) {
5592 		DPFPRINTF(PF_DEBUG_URGENT,
5593 		    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5594 		goto bad_locked;
5595 	}
5596 	if (s == NULL) {
5597 		pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5598 		    &naddr, NULL, &sn);
5599 		if (!PF_AZERO(&naddr, AF_INET6))
5600 			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5601 			    &naddr, AF_INET6);
5602 		ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5603 	} else {
5604 		if (!PF_AZERO(&s->rt_addr, AF_INET6))
5605 			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5606 			    &s->rt_addr, AF_INET6);
5607 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5608 	}
5609 
5610 	if (s)
5611 		PF_STATE_UNLOCK(s);
5612 
5613 	if (ifp == NULL)
5614 		goto bad;
5615 
5616 	if (oifp != ifp) {
5617 		if (pf_test6(PF_OUT, PFIL_FWD, ifp, &m0, inp) != PF_PASS)
5618 			goto bad;
5619 		else if (m0 == NULL)
5620 			goto done;
5621 		if (m0->m_len < sizeof(struct ip6_hdr)) {
5622 			DPFPRINTF(PF_DEBUG_URGENT,
5623 			    ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5624 			    __func__));
5625 			goto bad;
5626 		}
5627 		ip6 = mtod(m0, struct ip6_hdr *);
5628 	}
5629 
5630 	if (ifp->if_flags & IFF_LOOPBACK)
5631 		m0->m_flags |= M_SKIP_FIREWALL;
5632 
5633 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5634 	    ~ifp->if_hwassist) {
5635 		uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5636 		in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5637 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5638 	}
5639 
5640 	/*
5641 	 * If the packet is too large for the outgoing interface,
5642 	 * send back an icmp6 error.
5643 	 */
5644 	if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5645 		dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5646 	if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5647 		nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
5648 	else {
5649 		in6_ifstat_inc(ifp, ifs6_in_toobig);
5650 		if (r->rt != PF_DUPTO)
5651 			icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5652 		else
5653 			goto bad;
5654 	}
5655 
5656 done:
5657 	if (r->rt != PF_DUPTO)
5658 		*m = NULL;
5659 	return;
5660 
5661 bad_locked:
5662 	if (s)
5663 		PF_STATE_UNLOCK(s);
5664 bad:
5665 	m_freem(m0);
5666 	goto done;
5667 }
5668 #endif /* INET6 */
5669 
5670 /*
5671  * FreeBSD supports cksum offloads for the following drivers.
5672  *  em(4), fxp(4), lge(4), ndis(4), nge(4), re(4), ti(4), txp(4), xl(4)
5673  *
5674  * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5675  *  network driver performed cksum including pseudo header, need to verify
5676  *   csum_data
5677  * CSUM_DATA_VALID :
5678  *  network driver performed cksum, needs to additional pseudo header
5679  *  cksum computation with partial csum_data(i.e. lack of H/W support for
5680  *  pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5681  *
5682  * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5683  * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5684  * TCP/UDP layer.
5685  * Also, set csum_data to 0xffff to force cksum validation.
5686  */
5687 static int
5688 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5689 {
5690 	u_int16_t sum = 0;
5691 	int hw_assist = 0;
5692 	struct ip *ip;
5693 
5694 	if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5695 		return (1);
5696 	if (m->m_pkthdr.len < off + len)
5697 		return (1);
5698 
5699 	switch (p) {
5700 	case IPPROTO_TCP:
5701 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5702 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5703 				sum = m->m_pkthdr.csum_data;
5704 			} else {
5705 				ip = mtod(m, struct ip *);
5706 				sum = in_pseudo(ip->ip_src.s_addr,
5707 				ip->ip_dst.s_addr, htonl((u_short)len +
5708 				m->m_pkthdr.csum_data + IPPROTO_TCP));
5709 			}
5710 			sum ^= 0xffff;
5711 			++hw_assist;
5712 		}
5713 		break;
5714 	case IPPROTO_UDP:
5715 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5716 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5717 				sum = m->m_pkthdr.csum_data;
5718 			} else {
5719 				ip = mtod(m, struct ip *);
5720 				sum = in_pseudo(ip->ip_src.s_addr,
5721 				ip->ip_dst.s_addr, htonl((u_short)len +
5722 				m->m_pkthdr.csum_data + IPPROTO_UDP));
5723 			}
5724 			sum ^= 0xffff;
5725 			++hw_assist;
5726 		}
5727 		break;
5728 	case IPPROTO_ICMP:
5729 #ifdef INET6
5730 	case IPPROTO_ICMPV6:
5731 #endif /* INET6 */
5732 		break;
5733 	default:
5734 		return (1);
5735 	}
5736 
5737 	if (!hw_assist) {
5738 		switch (af) {
5739 		case AF_INET:
5740 			if (p == IPPROTO_ICMP) {
5741 				if (m->m_len < off)
5742 					return (1);
5743 				m->m_data += off;
5744 				m->m_len -= off;
5745 				sum = in_cksum(m, len);
5746 				m->m_data -= off;
5747 				m->m_len += off;
5748 			} else {
5749 				if (m->m_len < sizeof(struct ip))
5750 					return (1);
5751 				sum = in4_cksum(m, p, off, len);
5752 			}
5753 			break;
5754 #ifdef INET6
5755 		case AF_INET6:
5756 			if (m->m_len < sizeof(struct ip6_hdr))
5757 				return (1);
5758 			sum = in6_cksum(m, p, off, len);
5759 			break;
5760 #endif /* INET6 */
5761 		default:
5762 			return (1);
5763 		}
5764 	}
5765 	if (sum) {
5766 		switch (p) {
5767 		case IPPROTO_TCP:
5768 		    {
5769 			KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5770 			break;
5771 		    }
5772 		case IPPROTO_UDP:
5773 		    {
5774 			KMOD_UDPSTAT_INC(udps_badsum);
5775 			break;
5776 		    }
5777 #ifdef INET
5778 		case IPPROTO_ICMP:
5779 		    {
5780 			KMOD_ICMPSTAT_INC(icps_checksum);
5781 			break;
5782 		    }
5783 #endif
5784 #ifdef INET6
5785 		case IPPROTO_ICMPV6:
5786 		    {
5787 			KMOD_ICMP6STAT_INC(icp6s_checksum);
5788 			break;
5789 		    }
5790 #endif /* INET6 */
5791 		}
5792 		return (1);
5793 	} else {
5794 		if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5795 			m->m_pkthdr.csum_flags |=
5796 			    (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5797 			m->m_pkthdr.csum_data = 0xffff;
5798 		}
5799 	}
5800 	return (0);
5801 }
5802 
5803 
5804 #ifdef INET
5805 int
5806 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5807 {
5808 	struct pfi_kif		*kif;
5809 	u_short			 action, reason = 0, log = 0;
5810 	struct mbuf		*m = *m0;
5811 	struct ip		*h = NULL;
5812 	struct m_tag		*ipfwtag;
5813 	struct pf_rule		*a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5814 	struct pf_state		*s = NULL;
5815 	struct pf_ruleset	*ruleset = NULL;
5816 	struct pf_pdesc		 pd;
5817 	int			 off, dirndx, pqid = 0;
5818 
5819 	PF_RULES_RLOCK_TRACKER;
5820 
5821 	M_ASSERTPKTHDR(m);
5822 
5823 	if (!V_pf_status.running)
5824 		return (PF_PASS);
5825 
5826 	memset(&pd, 0, sizeof(pd));
5827 
5828 	kif = (struct pfi_kif *)ifp->if_pf_kif;
5829 
5830 	if (kif == NULL) {
5831 		DPFPRINTF(PF_DEBUG_URGENT,
5832 		    ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5833 		return (PF_DROP);
5834 	}
5835 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
5836 		return (PF_PASS);
5837 
5838 	if (m->m_flags & M_SKIP_FIREWALL)
5839 		return (PF_PASS);
5840 
5841 	pd.pf_mtag = pf_find_mtag(m);
5842 
5843 	PF_RULES_RLOCK();
5844 
5845 	if (ip_divert_ptr != NULL &&
5846 	    ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5847 		struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5848 		if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5849 			if (pd.pf_mtag == NULL &&
5850 			    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5851 				action = PF_DROP;
5852 				goto done;
5853 			}
5854 			pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5855 			m_tag_delete(m, ipfwtag);
5856 		}
5857 		if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5858 			m->m_flags |= M_FASTFWD_OURS;
5859 			pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5860 		}
5861 	} else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5862 		/* We do IP header normalization and packet reassembly here */
5863 		action = PF_DROP;
5864 		goto done;
5865 	}
5866 	m = *m0;	/* pf_normalize messes with m0 */
5867 	h = mtod(m, struct ip *);
5868 
5869 	off = h->ip_hl << 2;
5870 	if (off < (int)sizeof(struct ip)) {
5871 		action = PF_DROP;
5872 		REASON_SET(&reason, PFRES_SHORT);
5873 		log = 1;
5874 		goto done;
5875 	}
5876 
5877 	pd.src = (struct pf_addr *)&h->ip_src;
5878 	pd.dst = (struct pf_addr *)&h->ip_dst;
5879 	pd.sport = pd.dport = NULL;
5880 	pd.ip_sum = &h->ip_sum;
5881 	pd.proto_sum = NULL;
5882 	pd.proto = h->ip_p;
5883 	pd.dir = dir;
5884 	pd.sidx = (dir == PF_IN) ? 0 : 1;
5885 	pd.didx = (dir == PF_IN) ? 1 : 0;
5886 	pd.af = AF_INET;
5887 	pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
5888 	pd.tot_len = ntohs(h->ip_len);
5889 
5890 	/* handle fragments that didn't get reassembled by normalization */
5891 	if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5892 		action = pf_test_fragment(&r, dir, kif, m, h,
5893 		    &pd, &a, &ruleset);
5894 		goto done;
5895 	}
5896 
5897 	switch (h->ip_p) {
5898 
5899 	case IPPROTO_TCP: {
5900 		struct tcphdr	th;
5901 
5902 		pd.hdr.tcp = &th;
5903 		if (!pf_pull_hdr(m, off, &th, sizeof(th),
5904 		    &action, &reason, AF_INET)) {
5905 			log = action != PF_PASS;
5906 			goto done;
5907 		}
5908 		pd.p_len = pd.tot_len - off - (th.th_off << 2);
5909 		if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5910 			pqid = 1;
5911 		action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5912 		if (action == PF_DROP)
5913 			goto done;
5914 		action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5915 		    &reason);
5916 		if (action == PF_PASS) {
5917 			if (V_pfsync_update_state_ptr != NULL)
5918 				V_pfsync_update_state_ptr(s);
5919 			r = s->rule.ptr;
5920 			a = s->anchor.ptr;
5921 			log = s->log;
5922 		} else if (s == NULL)
5923 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5924 			    &a, &ruleset, inp);
5925 		break;
5926 	}
5927 
5928 	case IPPROTO_UDP: {
5929 		struct udphdr	uh;
5930 
5931 		pd.hdr.udp = &uh;
5932 		if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5933 		    &action, &reason, AF_INET)) {
5934 			log = action != PF_PASS;
5935 			goto done;
5936 		}
5937 		if (uh.uh_dport == 0 ||
5938 		    ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5939 		    ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5940 			action = PF_DROP;
5941 			REASON_SET(&reason, PFRES_SHORT);
5942 			goto done;
5943 		}
5944 		action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5945 		if (action == PF_PASS) {
5946 			if (V_pfsync_update_state_ptr != NULL)
5947 				V_pfsync_update_state_ptr(s);
5948 			r = s->rule.ptr;
5949 			a = s->anchor.ptr;
5950 			log = s->log;
5951 		} else if (s == NULL)
5952 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5953 			    &a, &ruleset, inp);
5954 		break;
5955 	}
5956 
5957 	case IPPROTO_ICMP: {
5958 		struct icmp	ih;
5959 
5960 		pd.hdr.icmp = &ih;
5961 		if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5962 		    &action, &reason, AF_INET)) {
5963 			log = action != PF_PASS;
5964 			goto done;
5965 		}
5966 		action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5967 		    &reason);
5968 		if (action == PF_PASS) {
5969 			if (V_pfsync_update_state_ptr != NULL)
5970 				V_pfsync_update_state_ptr(s);
5971 			r = s->rule.ptr;
5972 			a = s->anchor.ptr;
5973 			log = s->log;
5974 		} else if (s == NULL)
5975 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5976 			    &a, &ruleset, inp);
5977 		break;
5978 	}
5979 
5980 #ifdef INET6
5981 	case IPPROTO_ICMPV6: {
5982 		action = PF_DROP;
5983 		DPFPRINTF(PF_DEBUG_MISC,
5984 		    ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
5985 		goto done;
5986 	}
5987 #endif
5988 
5989 	default:
5990 		action = pf_test_state_other(&s, dir, kif, m, &pd);
5991 		if (action == PF_PASS) {
5992 			if (V_pfsync_update_state_ptr != NULL)
5993 				V_pfsync_update_state_ptr(s);
5994 			r = s->rule.ptr;
5995 			a = s->anchor.ptr;
5996 			log = s->log;
5997 		} else if (s == NULL)
5998 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5999 			    &a, &ruleset, inp);
6000 		break;
6001 	}
6002 
6003 done:
6004 	PF_RULES_RUNLOCK();
6005 	if (action == PF_PASS && h->ip_hl > 5 &&
6006 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6007 		action = PF_DROP;
6008 		REASON_SET(&reason, PFRES_IPOPTIONS);
6009 		log = r->log;
6010 		DPFPRINTF(PF_DEBUG_MISC,
6011 		    ("pf: dropping packet with ip options\n"));
6012 	}
6013 
6014 	if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6015 		action = PF_DROP;
6016 		REASON_SET(&reason, PFRES_MEMORY);
6017 	}
6018 	if (r->rtableid >= 0)
6019 		M_SETFIB(m, r->rtableid);
6020 
6021 	if (r->scrub_flags & PFSTATE_SETPRIO) {
6022 		if (pd.tos & IPTOS_LOWDELAY)
6023 			pqid = 1;
6024 		if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6025 			action = PF_DROP;
6026 			REASON_SET(&reason, PFRES_MEMORY);
6027 			log = 1;
6028 			DPFPRINTF(PF_DEBUG_MISC,
6029 			    ("pf: failed to allocate 802.1q mtag\n"));
6030 		}
6031 	}
6032 
6033 #ifdef ALTQ
6034 	if (action == PF_PASS && r->qid) {
6035 		if (pd.pf_mtag == NULL &&
6036 		    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6037 			action = PF_DROP;
6038 			REASON_SET(&reason, PFRES_MEMORY);
6039 		} else {
6040 			if (s != NULL)
6041 				pd.pf_mtag->qid_hash = pf_state_hash(s);
6042 			if (pqid || (pd.tos & IPTOS_LOWDELAY))
6043 				pd.pf_mtag->qid = r->pqid;
6044 			else
6045 				pd.pf_mtag->qid = r->qid;
6046 			/* Add hints for ecn. */
6047 			pd.pf_mtag->hdr = h;
6048 		}
6049 
6050 	}
6051 #endif /* ALTQ */
6052 
6053 	/*
6054 	 * connections redirected to loopback should not match sockets
6055 	 * bound specifically to loopback due to security implications,
6056 	 * see tcp_input() and in_pcblookup_listen().
6057 	 */
6058 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6059 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6060 	    (s->nat_rule.ptr->action == PF_RDR ||
6061 	    s->nat_rule.ptr->action == PF_BINAT) &&
6062 	    IN_LOOPBACK(ntohl(pd.dst->v4.s_addr)))
6063 		m->m_flags |= M_SKIP_FIREWALL;
6064 
6065 	if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6066 	    !PACKET_LOOPED(&pd)) {
6067 
6068 		ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6069 		    sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6070 		if (ipfwtag != NULL) {
6071 			((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6072 			    ntohs(r->divert.port);
6073 			((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6074 
6075 			if (s)
6076 				PF_STATE_UNLOCK(s);
6077 
6078 			m_tag_prepend(m, ipfwtag);
6079 			if (m->m_flags & M_FASTFWD_OURS) {
6080 				if (pd.pf_mtag == NULL &&
6081 				    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6082 					action = PF_DROP;
6083 					REASON_SET(&reason, PFRES_MEMORY);
6084 					log = 1;
6085 					DPFPRINTF(PF_DEBUG_MISC,
6086 					    ("pf: failed to allocate tag\n"));
6087 				} else {
6088 					pd.pf_mtag->flags |=
6089 					    PF_FASTFWD_OURS_PRESENT;
6090 					m->m_flags &= ~M_FASTFWD_OURS;
6091 				}
6092 			}
6093 			ip_divert_ptr(*m0, dir == PF_IN);
6094 			*m0 = NULL;
6095 
6096 			return (action);
6097 		} else {
6098 			/* XXX: ipfw has the same behaviour! */
6099 			action = PF_DROP;
6100 			REASON_SET(&reason, PFRES_MEMORY);
6101 			log = 1;
6102 			DPFPRINTF(PF_DEBUG_MISC,
6103 			    ("pf: failed to allocate divert tag\n"));
6104 		}
6105 	}
6106 
6107 	if (log) {
6108 		struct pf_rule *lr;
6109 
6110 		if (s != NULL && s->nat_rule.ptr != NULL &&
6111 		    s->nat_rule.ptr->log & PF_LOG_ALL)
6112 			lr = s->nat_rule.ptr;
6113 		else
6114 			lr = r;
6115 		PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6116 		    (s == NULL));
6117 	}
6118 
6119 	kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6120 	kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6121 
6122 	if (action == PF_PASS || r->action == PF_DROP) {
6123 		dirndx = (dir == PF_OUT);
6124 		r->packets[dirndx]++;
6125 		r->bytes[dirndx] += pd.tot_len;
6126 		if (a != NULL) {
6127 			a->packets[dirndx]++;
6128 			a->bytes[dirndx] += pd.tot_len;
6129 		}
6130 		if (s != NULL) {
6131 			if (s->nat_rule.ptr != NULL) {
6132 				s->nat_rule.ptr->packets[dirndx]++;
6133 				s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6134 			}
6135 			if (s->src_node != NULL) {
6136 				s->src_node->packets[dirndx]++;
6137 				s->src_node->bytes[dirndx] += pd.tot_len;
6138 			}
6139 			if (s->nat_src_node != NULL) {
6140 				s->nat_src_node->packets[dirndx]++;
6141 				s->nat_src_node->bytes[dirndx] += pd.tot_len;
6142 			}
6143 			dirndx = (dir == s->direction) ? 0 : 1;
6144 			s->packets[dirndx]++;
6145 			s->bytes[dirndx] += pd.tot_len;
6146 		}
6147 		tr = r;
6148 		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6149 		if (nr != NULL && r == &V_pf_default_rule)
6150 			tr = nr;
6151 		if (tr->src.addr.type == PF_ADDR_TABLE)
6152 			pfr_update_stats(tr->src.addr.p.tbl,
6153 			    (s == NULL) ? pd.src :
6154 			    &s->key[(s->direction == PF_IN)]->
6155 				addr[(s->direction == PF_OUT)],
6156 			    pd.af, pd.tot_len, dir == PF_OUT,
6157 			    r->action == PF_PASS, tr->src.neg);
6158 		if (tr->dst.addr.type == PF_ADDR_TABLE)
6159 			pfr_update_stats(tr->dst.addr.p.tbl,
6160 			    (s == NULL) ? pd.dst :
6161 			    &s->key[(s->direction == PF_IN)]->
6162 				addr[(s->direction == PF_IN)],
6163 			    pd.af, pd.tot_len, dir == PF_OUT,
6164 			    r->action == PF_PASS, tr->dst.neg);
6165 	}
6166 
6167 	switch (action) {
6168 	case PF_SYNPROXY_DROP:
6169 		m_freem(*m0);
6170 	case PF_DEFER:
6171 		*m0 = NULL;
6172 		action = PF_PASS;
6173 		break;
6174 	case PF_DROP:
6175 		m_freem(*m0);
6176 		*m0 = NULL;
6177 		break;
6178 	default:
6179 		/* pf_route() returns unlocked. */
6180 		if (r->rt) {
6181 			pf_route(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6182 			return (action);
6183 		}
6184 		break;
6185 	}
6186 	if (s)
6187 		PF_STATE_UNLOCK(s);
6188 
6189 	return (action);
6190 }
6191 #endif /* INET */
6192 
6193 #ifdef INET6
6194 int
6195 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6196 {
6197 	struct pfi_kif		*kif;
6198 	u_short			 action, reason = 0, log = 0;
6199 	struct mbuf		*m = *m0, *n = NULL;
6200 	struct m_tag		*mtag;
6201 	struct ip6_hdr		*h = NULL;
6202 	struct pf_rule		*a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6203 	struct pf_state		*s = NULL;
6204 	struct pf_ruleset	*ruleset = NULL;
6205 	struct pf_pdesc		 pd;
6206 	int			 off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
6207 
6208 	PF_RULES_RLOCK_TRACKER;
6209 	M_ASSERTPKTHDR(m);
6210 
6211 	if (!V_pf_status.running)
6212 		return (PF_PASS);
6213 
6214 	memset(&pd, 0, sizeof(pd));
6215 	pd.pf_mtag = pf_find_mtag(m);
6216 
6217 	if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6218 		return (PF_PASS);
6219 
6220 	kif = (struct pfi_kif *)ifp->if_pf_kif;
6221 	if (kif == NULL) {
6222 		DPFPRINTF(PF_DEBUG_URGENT,
6223 		    ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6224 		return (PF_DROP);
6225 	}
6226 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
6227 		return (PF_PASS);
6228 
6229 	if (m->m_flags & M_SKIP_FIREWALL)
6230 		return (PF_PASS);
6231 
6232 	PF_RULES_RLOCK();
6233 
6234 	/* We do IP header normalization and packet reassembly here */
6235 	if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6236 		action = PF_DROP;
6237 		goto done;
6238 	}
6239 	m = *m0;	/* pf_normalize messes with m0 */
6240 	h = mtod(m, struct ip6_hdr *);
6241 
6242 	/*
6243 	 * we do not support jumbogram.  if we keep going, zero ip6_plen
6244 	 * will do something bad, so drop the packet for now.
6245 	 */
6246 	if (htons(h->ip6_plen) == 0) {
6247 		action = PF_DROP;
6248 		REASON_SET(&reason, PFRES_NORM);	/*XXX*/
6249 		goto done;
6250 	}
6251 
6252 	pd.src = (struct pf_addr *)&h->ip6_src;
6253 	pd.dst = (struct pf_addr *)&h->ip6_dst;
6254 	pd.sport = pd.dport = NULL;
6255 	pd.ip_sum = NULL;
6256 	pd.proto_sum = NULL;
6257 	pd.dir = dir;
6258 	pd.sidx = (dir == PF_IN) ? 0 : 1;
6259 	pd.didx = (dir == PF_IN) ? 1 : 0;
6260 	pd.af = AF_INET6;
6261 	pd.tos = 0;
6262 	pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6263 
6264 	off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6265 	pd.proto = h->ip6_nxt;
6266 	do {
6267 		switch (pd.proto) {
6268 		case IPPROTO_FRAGMENT:
6269 			action = pf_test_fragment(&r, dir, kif, m, h,
6270 			    &pd, &a, &ruleset);
6271 			if (action == PF_DROP)
6272 				REASON_SET(&reason, PFRES_FRAG);
6273 			goto done;
6274 		case IPPROTO_ROUTING: {
6275 			struct ip6_rthdr rthdr;
6276 
6277 			if (rh_cnt++) {
6278 				DPFPRINTF(PF_DEBUG_MISC,
6279 				    ("pf: IPv6 more than one rthdr\n"));
6280 				action = PF_DROP;
6281 				REASON_SET(&reason, PFRES_IPOPTIONS);
6282 				log = 1;
6283 				goto done;
6284 			}
6285 			if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6286 			    &reason, pd.af)) {
6287 				DPFPRINTF(PF_DEBUG_MISC,
6288 				    ("pf: IPv6 short rthdr\n"));
6289 				action = PF_DROP;
6290 				REASON_SET(&reason, PFRES_SHORT);
6291 				log = 1;
6292 				goto done;
6293 			}
6294 			if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6295 				DPFPRINTF(PF_DEBUG_MISC,
6296 				    ("pf: IPv6 rthdr0\n"));
6297 				action = PF_DROP;
6298 				REASON_SET(&reason, PFRES_IPOPTIONS);
6299 				log = 1;
6300 				goto done;
6301 			}
6302 			/* FALLTHROUGH */
6303 		}
6304 		case IPPROTO_AH:
6305 		case IPPROTO_HOPOPTS:
6306 		case IPPROTO_DSTOPTS: {
6307 			/* get next header and header length */
6308 			struct ip6_ext	opt6;
6309 
6310 			if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6311 			    NULL, &reason, pd.af)) {
6312 				DPFPRINTF(PF_DEBUG_MISC,
6313 				    ("pf: IPv6 short opt\n"));
6314 				action = PF_DROP;
6315 				log = 1;
6316 				goto done;
6317 			}
6318 			if (pd.proto == IPPROTO_AH)
6319 				off += (opt6.ip6e_len + 2) * 4;
6320 			else
6321 				off += (opt6.ip6e_len + 1) * 8;
6322 			pd.proto = opt6.ip6e_nxt;
6323 			/* goto the next header */
6324 			break;
6325 		}
6326 		default:
6327 			terminal++;
6328 			break;
6329 		}
6330 	} while (!terminal);
6331 
6332 	/* if there's no routing header, use unmodified mbuf for checksumming */
6333 	if (!n)
6334 		n = m;
6335 
6336 	switch (pd.proto) {
6337 
6338 	case IPPROTO_TCP: {
6339 		struct tcphdr	th;
6340 
6341 		pd.hdr.tcp = &th;
6342 		if (!pf_pull_hdr(m, off, &th, sizeof(th),
6343 		    &action, &reason, AF_INET6)) {
6344 			log = action != PF_PASS;
6345 			goto done;
6346 		}
6347 		pd.p_len = pd.tot_len - off - (th.th_off << 2);
6348 		action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6349 		if (action == PF_DROP)
6350 			goto done;
6351 		action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6352 		    &reason);
6353 		if (action == PF_PASS) {
6354 			if (V_pfsync_update_state_ptr != NULL)
6355 				V_pfsync_update_state_ptr(s);
6356 			r = s->rule.ptr;
6357 			a = s->anchor.ptr;
6358 			log = s->log;
6359 		} else if (s == NULL)
6360 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6361 			    &a, &ruleset, inp);
6362 		break;
6363 	}
6364 
6365 	case IPPROTO_UDP: {
6366 		struct udphdr	uh;
6367 
6368 		pd.hdr.udp = &uh;
6369 		if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6370 		    &action, &reason, AF_INET6)) {
6371 			log = action != PF_PASS;
6372 			goto done;
6373 		}
6374 		if (uh.uh_dport == 0 ||
6375 		    ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6376 		    ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6377 			action = PF_DROP;
6378 			REASON_SET(&reason, PFRES_SHORT);
6379 			goto done;
6380 		}
6381 		action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6382 		if (action == PF_PASS) {
6383 			if (V_pfsync_update_state_ptr != NULL)
6384 				V_pfsync_update_state_ptr(s);
6385 			r = s->rule.ptr;
6386 			a = s->anchor.ptr;
6387 			log = s->log;
6388 		} else if (s == NULL)
6389 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6390 			    &a, &ruleset, inp);
6391 		break;
6392 	}
6393 
6394 	case IPPROTO_ICMP: {
6395 		action = PF_DROP;
6396 		DPFPRINTF(PF_DEBUG_MISC,
6397 		    ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6398 		goto done;
6399 	}
6400 
6401 	case IPPROTO_ICMPV6: {
6402 		struct icmp6_hdr	ih;
6403 
6404 		pd.hdr.icmp6 = &ih;
6405 		if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6406 		    &action, &reason, AF_INET6)) {
6407 			log = action != PF_PASS;
6408 			goto done;
6409 		}
6410 		action = pf_test_state_icmp(&s, dir, kif,
6411 		    m, off, h, &pd, &reason);
6412 		if (action == PF_PASS) {
6413 			if (V_pfsync_update_state_ptr != NULL)
6414 				V_pfsync_update_state_ptr(s);
6415 			r = s->rule.ptr;
6416 			a = s->anchor.ptr;
6417 			log = s->log;
6418 		} else if (s == NULL)
6419 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6420 			    &a, &ruleset, inp);
6421 		break;
6422 	}
6423 
6424 	default:
6425 		action = pf_test_state_other(&s, dir, kif, m, &pd);
6426 		if (action == PF_PASS) {
6427 			if (V_pfsync_update_state_ptr != NULL)
6428 				V_pfsync_update_state_ptr(s);
6429 			r = s->rule.ptr;
6430 			a = s->anchor.ptr;
6431 			log = s->log;
6432 		} else if (s == NULL)
6433 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6434 			    &a, &ruleset, inp);
6435 		break;
6436 	}
6437 
6438 done:
6439 	PF_RULES_RUNLOCK();
6440 	if (n != m) {
6441 		m_freem(n);
6442 		n = NULL;
6443 	}
6444 
6445 	/* handle dangerous IPv6 extension headers. */
6446 	if (action == PF_PASS && rh_cnt &&
6447 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6448 		action = PF_DROP;
6449 		REASON_SET(&reason, PFRES_IPOPTIONS);
6450 		log = r->log;
6451 		DPFPRINTF(PF_DEBUG_MISC,
6452 		    ("pf: dropping packet with dangerous v6 headers\n"));
6453 	}
6454 
6455 	if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6456 		action = PF_DROP;
6457 		REASON_SET(&reason, PFRES_MEMORY);
6458 	}
6459 	if (r->rtableid >= 0)
6460 		M_SETFIB(m, r->rtableid);
6461 
6462 	if (r->scrub_flags & PFSTATE_SETPRIO) {
6463 		if (pd.tos & IPTOS_LOWDELAY)
6464 			pqid = 1;
6465 		if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6466 			action = PF_DROP;
6467 			REASON_SET(&reason, PFRES_MEMORY);
6468 			log = 1;
6469 			DPFPRINTF(PF_DEBUG_MISC,
6470 			    ("pf: failed to allocate 802.1q mtag\n"));
6471 		}
6472 	}
6473 
6474 #ifdef ALTQ
6475 	if (action == PF_PASS && r->qid) {
6476 		if (pd.pf_mtag == NULL &&
6477 		    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6478 			action = PF_DROP;
6479 			REASON_SET(&reason, PFRES_MEMORY);
6480 		} else {
6481 			if (s != NULL)
6482 				pd.pf_mtag->qid_hash = pf_state_hash(s);
6483 			if (pd.tos & IPTOS_LOWDELAY)
6484 				pd.pf_mtag->qid = r->pqid;
6485 			else
6486 				pd.pf_mtag->qid = r->qid;
6487 			/* Add hints for ecn. */
6488 			pd.pf_mtag->hdr = h;
6489 		}
6490 	}
6491 #endif /* ALTQ */
6492 
6493 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6494 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6495 	    (s->nat_rule.ptr->action == PF_RDR ||
6496 	    s->nat_rule.ptr->action == PF_BINAT) &&
6497 	    IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6498 		m->m_flags |= M_SKIP_FIREWALL;
6499 
6500 	/* XXX: Anybody working on it?! */
6501 	if (r->divert.port)
6502 		printf("pf: divert(9) is not supported for IPv6\n");
6503 
6504 	if (log) {
6505 		struct pf_rule *lr;
6506 
6507 		if (s != NULL && s->nat_rule.ptr != NULL &&
6508 		    s->nat_rule.ptr->log & PF_LOG_ALL)
6509 			lr = s->nat_rule.ptr;
6510 		else
6511 			lr = r;
6512 		PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6513 		    &pd, (s == NULL));
6514 	}
6515 
6516 	kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6517 	kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6518 
6519 	if (action == PF_PASS || r->action == PF_DROP) {
6520 		dirndx = (dir == PF_OUT);
6521 		r->packets[dirndx]++;
6522 		r->bytes[dirndx] += pd.tot_len;
6523 		if (a != NULL) {
6524 			a->packets[dirndx]++;
6525 			a->bytes[dirndx] += pd.tot_len;
6526 		}
6527 		if (s != NULL) {
6528 			if (s->nat_rule.ptr != NULL) {
6529 				s->nat_rule.ptr->packets[dirndx]++;
6530 				s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6531 			}
6532 			if (s->src_node != NULL) {
6533 				s->src_node->packets[dirndx]++;
6534 				s->src_node->bytes[dirndx] += pd.tot_len;
6535 			}
6536 			if (s->nat_src_node != NULL) {
6537 				s->nat_src_node->packets[dirndx]++;
6538 				s->nat_src_node->bytes[dirndx] += pd.tot_len;
6539 			}
6540 			dirndx = (dir == s->direction) ? 0 : 1;
6541 			s->packets[dirndx]++;
6542 			s->bytes[dirndx] += pd.tot_len;
6543 		}
6544 		tr = r;
6545 		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6546 		if (nr != NULL && r == &V_pf_default_rule)
6547 			tr = nr;
6548 		if (tr->src.addr.type == PF_ADDR_TABLE)
6549 			pfr_update_stats(tr->src.addr.p.tbl,
6550 			    (s == NULL) ? pd.src :
6551 			    &s->key[(s->direction == PF_IN)]->addr[0],
6552 			    pd.af, pd.tot_len, dir == PF_OUT,
6553 			    r->action == PF_PASS, tr->src.neg);
6554 		if (tr->dst.addr.type == PF_ADDR_TABLE)
6555 			pfr_update_stats(tr->dst.addr.p.tbl,
6556 			    (s == NULL) ? pd.dst :
6557 			    &s->key[(s->direction == PF_IN)]->addr[1],
6558 			    pd.af, pd.tot_len, dir == PF_OUT,
6559 			    r->action == PF_PASS, tr->dst.neg);
6560 	}
6561 
6562 	switch (action) {
6563 	case PF_SYNPROXY_DROP:
6564 		m_freem(*m0);
6565 	case PF_DEFER:
6566 		*m0 = NULL;
6567 		action = PF_PASS;
6568 		break;
6569 	case PF_DROP:
6570 		m_freem(*m0);
6571 		*m0 = NULL;
6572 		break;
6573 	default:
6574 		/* pf_route6() returns unlocked. */
6575 		if (r->rt) {
6576 			pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6577 			return (action);
6578 		}
6579 		break;
6580 	}
6581 
6582 	if (s)
6583 		PF_STATE_UNLOCK(s);
6584 
6585 	/* If reassembled packet passed, create new fragments. */
6586 	if (action == PF_PASS && *m0 && (pflags & PFIL_FWD) &&
6587 	    (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6588 		action = pf_refragment6(ifp, m0, mtag);
6589 
6590 	return (action);
6591 }
6592 #endif /* INET6 */
6593