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