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