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