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