xref: /freebsd/sys/netpfil/pf/pf.c (revision 6fe0a6c80a1aff14236924eb33e4013aa8c14f91)
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 int
3052 pf_icmp_to_bandlim(uint8_t type)
3053 {
3054 	switch (type) {
3055 		case ICMP_ECHO:
3056 		case ICMP_ECHOREPLY:
3057 			return (BANDLIM_ICMP_ECHO);
3058 		case ICMP_TSTAMP:
3059 		case ICMP_TSTAMPREPLY:
3060 			return (BANDLIM_ICMP_TSTAMP);
3061 		case ICMP_UNREACH:
3062 		default:
3063 			return (BANDLIM_ICMP_UNREACH);
3064 	}
3065 }
3066 
3067 static void
3068 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
3069     struct pf_krule *r)
3070 {
3071 	struct pf_send_entry *pfse;
3072 	struct mbuf *m0;
3073 	struct pf_mtag *pf_mtag;
3074 
3075 	/* ICMP packet rate limitation. */
3076 #ifdef INET6
3077 	if (af == AF_INET6) {
3078 		if (icmp6_ratelimit(NULL, type, code))
3079 			return;
3080 	}
3081 #endif
3082 #ifdef INET
3083 	if (af == AF_INET) {
3084 		if (badport_bandlim(pf_icmp_to_bandlim(type)) != 0)
3085 			return;
3086 	}
3087 #endif
3088 
3089 	/* Allocate outgoing queue entry, mbuf and mbuf tag. */
3090 	pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
3091 	if (pfse == NULL)
3092 		return;
3093 
3094 	if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
3095 		free(pfse, M_PFTEMP);
3096 		return;
3097 	}
3098 
3099 	if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
3100 		free(pfse, M_PFTEMP);
3101 		return;
3102 	}
3103 	/* XXX: revisit */
3104 	m0->m_flags |= M_SKIP_FIREWALL;
3105 
3106 	if (r->rtableid >= 0)
3107 		M_SETFIB(m0, r->rtableid);
3108 
3109 #ifdef ALTQ
3110 	if (r->qid) {
3111 		pf_mtag->qid = r->qid;
3112 		/* add hints for ecn */
3113 		pf_mtag->hdr = mtod(m0, struct ip *);
3114 	}
3115 #endif /* ALTQ */
3116 
3117 	switch (af) {
3118 #ifdef INET
3119 	case AF_INET:
3120 		pfse->pfse_type = PFSE_ICMP;
3121 		break;
3122 #endif /* INET */
3123 #ifdef INET6
3124 	case AF_INET6:
3125 		pfse->pfse_type = PFSE_ICMP6;
3126 		break;
3127 #endif /* INET6 */
3128 	}
3129 	pfse->pfse_m = m0;
3130 	pfse->icmpopts.type = type;
3131 	pfse->icmpopts.code = code;
3132 	pf_send(pfse);
3133 }
3134 
3135 /*
3136  * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
3137  * If n is 0, they match if they are equal. If n is != 0, they match if they
3138  * are different.
3139  */
3140 int
3141 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
3142     struct pf_addr *b, sa_family_t af)
3143 {
3144 	int	match = 0;
3145 
3146 	switch (af) {
3147 #ifdef INET
3148 	case AF_INET:
3149 		if ((a->addr32[0] & m->addr32[0]) ==
3150 		    (b->addr32[0] & m->addr32[0]))
3151 			match++;
3152 		break;
3153 #endif /* INET */
3154 #ifdef INET6
3155 	case AF_INET6:
3156 		if (((a->addr32[0] & m->addr32[0]) ==
3157 		     (b->addr32[0] & m->addr32[0])) &&
3158 		    ((a->addr32[1] & m->addr32[1]) ==
3159 		     (b->addr32[1] & m->addr32[1])) &&
3160 		    ((a->addr32[2] & m->addr32[2]) ==
3161 		     (b->addr32[2] & m->addr32[2])) &&
3162 		    ((a->addr32[3] & m->addr32[3]) ==
3163 		     (b->addr32[3] & m->addr32[3])))
3164 			match++;
3165 		break;
3166 #endif /* INET6 */
3167 	}
3168 	if (match) {
3169 		if (n)
3170 			return (0);
3171 		else
3172 			return (1);
3173 	} else {
3174 		if (n)
3175 			return (1);
3176 		else
3177 			return (0);
3178 	}
3179 }
3180 
3181 /*
3182  * Return 1 if b <= a <= e, otherwise return 0.
3183  */
3184 int
3185 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
3186     struct pf_addr *a, sa_family_t af)
3187 {
3188 	switch (af) {
3189 #ifdef INET
3190 	case AF_INET:
3191 		if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
3192 		    (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
3193 			return (0);
3194 		break;
3195 #endif /* INET */
3196 #ifdef INET6
3197 	case AF_INET6: {
3198 		int	i;
3199 
3200 		/* check a >= b */
3201 		for (i = 0; i < 4; ++i)
3202 			if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
3203 				break;
3204 			else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
3205 				return (0);
3206 		/* check a <= e */
3207 		for (i = 0; i < 4; ++i)
3208 			if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
3209 				break;
3210 			else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
3211 				return (0);
3212 		break;
3213 	}
3214 #endif /* INET6 */
3215 	}
3216 	return (1);
3217 }
3218 
3219 static int
3220 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
3221 {
3222 	switch (op) {
3223 	case PF_OP_IRG:
3224 		return ((p > a1) && (p < a2));
3225 	case PF_OP_XRG:
3226 		return ((p < a1) || (p > a2));
3227 	case PF_OP_RRG:
3228 		return ((p >= a1) && (p <= a2));
3229 	case PF_OP_EQ:
3230 		return (p == a1);
3231 	case PF_OP_NE:
3232 		return (p != a1);
3233 	case PF_OP_LT:
3234 		return (p < a1);
3235 	case PF_OP_LE:
3236 		return (p <= a1);
3237 	case PF_OP_GT:
3238 		return (p > a1);
3239 	case PF_OP_GE:
3240 		return (p >= a1);
3241 	}
3242 	return (0); /* never reached */
3243 }
3244 
3245 int
3246 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
3247 {
3248 	NTOHS(a1);
3249 	NTOHS(a2);
3250 	NTOHS(p);
3251 	return (pf_match(op, a1, a2, p));
3252 }
3253 
3254 static int
3255 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
3256 {
3257 	if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
3258 		return (0);
3259 	return (pf_match(op, a1, a2, u));
3260 }
3261 
3262 static int
3263 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
3264 {
3265 	if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
3266 		return (0);
3267 	return (pf_match(op, a1, a2, g));
3268 }
3269 
3270 int
3271 pf_match_tag(struct mbuf *m, struct pf_krule *r, int *tag, int mtag)
3272 {
3273 	if (*tag == -1)
3274 		*tag = mtag;
3275 
3276 	return ((!r->match_tag_not && r->match_tag == *tag) ||
3277 	    (r->match_tag_not && r->match_tag != *tag));
3278 }
3279 
3280 int
3281 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
3282 {
3283 
3284 	KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
3285 
3286 	if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
3287 		return (ENOMEM);
3288 
3289 	pd->pf_mtag->tag = tag;
3290 
3291 	return (0);
3292 }
3293 
3294 #define	PF_ANCHOR_STACKSIZE	32
3295 struct pf_kanchor_stackframe {
3296 	struct pf_kruleset	*rs;
3297 	struct pf_krule		*r;	/* XXX: + match bit */
3298 	struct pf_kanchor	*child;
3299 };
3300 
3301 /*
3302  * XXX: We rely on malloc(9) returning pointer aligned addresses.
3303  */
3304 #define	PF_ANCHORSTACK_MATCH	0x00000001
3305 #define	PF_ANCHORSTACK_MASK	(PF_ANCHORSTACK_MATCH)
3306 
3307 #define	PF_ANCHOR_MATCH(f)	((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
3308 #define	PF_ANCHOR_RULE(f)	(struct pf_krule *)			\
3309 				((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
3310 #define	PF_ANCHOR_SET_MATCH(f)	do { (f)->r = (void *) 			\
3311 				((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH);  \
3312 } while (0)
3313 
3314 void
3315 pf_step_into_anchor(struct pf_kanchor_stackframe *stack, int *depth,
3316     struct pf_kruleset **rs, int n, struct pf_krule **r, struct pf_krule **a,
3317     int *match)
3318 {
3319 	struct pf_kanchor_stackframe	*f;
3320 
3321 	PF_RULES_RASSERT();
3322 
3323 	if (match)
3324 		*match = 0;
3325 	if (*depth >= PF_ANCHOR_STACKSIZE) {
3326 		printf("%s: anchor stack overflow on %s\n",
3327 		    __func__, (*r)->anchor->name);
3328 		*r = TAILQ_NEXT(*r, entries);
3329 		return;
3330 	} else if (*depth == 0 && a != NULL)
3331 		*a = *r;
3332 	f = stack + (*depth)++;
3333 	f->rs = *rs;
3334 	f->r = *r;
3335 	if ((*r)->anchor_wildcard) {
3336 		struct pf_kanchor_node *parent = &(*r)->anchor->children;
3337 
3338 		if ((f->child = RB_MIN(pf_kanchor_node, parent)) == NULL) {
3339 			*r = NULL;
3340 			return;
3341 		}
3342 		*rs = &f->child->ruleset;
3343 	} else {
3344 		f->child = NULL;
3345 		*rs = &(*r)->anchor->ruleset;
3346 	}
3347 	*r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
3348 }
3349 
3350 int
3351 pf_step_out_of_anchor(struct pf_kanchor_stackframe *stack, int *depth,
3352     struct pf_kruleset **rs, int n, struct pf_krule **r, struct pf_krule **a,
3353     int *match)
3354 {
3355 	struct pf_kanchor_stackframe	*f;
3356 	struct pf_krule *fr;
3357 	int quick = 0;
3358 
3359 	PF_RULES_RASSERT();
3360 
3361 	do {
3362 		if (*depth <= 0)
3363 			break;
3364 		f = stack + *depth - 1;
3365 		fr = PF_ANCHOR_RULE(f);
3366 		if (f->child != NULL) {
3367 			/*
3368 			 * This block traverses through
3369 			 * a wildcard anchor.
3370 			 */
3371 			if (match != NULL && *match) {
3372 				/*
3373 				 * If any of "*" matched, then
3374 				 * "foo/ *" matched, mark frame
3375 				 * appropriately.
3376 				 */
3377 				PF_ANCHOR_SET_MATCH(f);
3378 				*match = 0;
3379 			}
3380 			f->child = RB_NEXT(pf_kanchor_node,
3381 			    &fr->anchor->children, f->child);
3382 			if (f->child != NULL) {
3383 				*rs = &f->child->ruleset;
3384 				*r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
3385 				if (*r == NULL)
3386 					continue;
3387 				else
3388 					break;
3389 			}
3390 		}
3391 		(*depth)--;
3392 		if (*depth == 0 && a != NULL)
3393 			*a = NULL;
3394 		*rs = f->rs;
3395 		if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
3396 			quick = fr->quick;
3397 		*r = TAILQ_NEXT(fr, entries);
3398 	} while (*r == NULL);
3399 
3400 	return (quick);
3401 }
3402 
3403 struct pf_keth_anchor_stackframe {
3404 	struct pf_keth_ruleset	*rs;
3405 	struct pf_keth_rule	*r;	/* XXX: + match bit */
3406 	struct pf_keth_anchor	*child;
3407 };
3408 
3409 #define	PF_ETH_ANCHOR_MATCH(f)	((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
3410 #define	PF_ETH_ANCHOR_RULE(f)	(struct pf_keth_rule *)			\
3411 				((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
3412 #define	PF_ETH_ANCHOR_SET_MATCH(f)	do { (f)->r = (void *) 		\
3413 				((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH);  \
3414 } while (0)
3415 
3416 void
3417 pf_step_into_keth_anchor(struct pf_keth_anchor_stackframe *stack, int *depth,
3418     struct pf_keth_ruleset **rs, struct pf_keth_rule **r,
3419     struct pf_keth_rule **a, int *match)
3420 {
3421 	struct pf_keth_anchor_stackframe	*f;
3422 
3423 	NET_EPOCH_ASSERT();
3424 
3425 	if (match)
3426 		*match = 0;
3427 	if (*depth >= PF_ANCHOR_STACKSIZE) {
3428 		printf("%s: anchor stack overflow on %s\n",
3429 		    __func__, (*r)->anchor->name);
3430 		*r = TAILQ_NEXT(*r, entries);
3431 		return;
3432 	} else if (*depth == 0 && a != NULL)
3433 		*a = *r;
3434 	f = stack + (*depth)++;
3435 	f->rs = *rs;
3436 	f->r = *r;
3437 	if ((*r)->anchor_wildcard) {
3438 		struct pf_keth_anchor_node *parent = &(*r)->anchor->children;
3439 
3440 		if ((f->child = RB_MIN(pf_keth_anchor_node, parent)) == NULL) {
3441 			*r = NULL;
3442 			return;
3443 		}
3444 		*rs = &f->child->ruleset;
3445 	} else {
3446 		f->child = NULL;
3447 		*rs = &(*r)->anchor->ruleset;
3448 	}
3449 	*r = TAILQ_FIRST((*rs)->active.rules);
3450 }
3451 
3452 int
3453 pf_step_out_of_keth_anchor(struct pf_keth_anchor_stackframe *stack, int *depth,
3454     struct pf_keth_ruleset **rs, struct pf_keth_rule **r,
3455     struct pf_keth_rule **a, int *match)
3456 {
3457 	struct pf_keth_anchor_stackframe	*f;
3458 	struct pf_keth_rule *fr;
3459 	int quick = 0;
3460 
3461 	NET_EPOCH_ASSERT();
3462 
3463 	do {
3464 		if (*depth <= 0)
3465 			break;
3466 		f = stack + *depth - 1;
3467 		fr = PF_ETH_ANCHOR_RULE(f);
3468 		if (f->child != NULL) {
3469 			/*
3470 			 * This block traverses through
3471 			 * a wildcard anchor.
3472 			 */
3473 			if (match != NULL && *match) {
3474 				/*
3475 				 * If any of "*" matched, then
3476 				 * "foo/ *" matched, mark frame
3477 				 * appropriately.
3478 				 */
3479 				PF_ETH_ANCHOR_SET_MATCH(f);
3480 				*match = 0;
3481 			}
3482 			f->child = RB_NEXT(pf_keth_anchor_node,
3483 			    &fr->anchor->children, f->child);
3484 			if (f->child != NULL) {
3485 				*rs = &f->child->ruleset;
3486 				*r = TAILQ_FIRST((*rs)->active.rules);
3487 				if (*r == NULL)
3488 					continue;
3489 				else
3490 					break;
3491 			}
3492 		}
3493 		(*depth)--;
3494 		if (*depth == 0 && a != NULL)
3495 			*a = NULL;
3496 		*rs = f->rs;
3497 		if (PF_ETH_ANCHOR_MATCH(f) || (match != NULL && *match))
3498 			quick = fr->quick;
3499 		*r = TAILQ_NEXT(fr, entries);
3500 	} while (*r == NULL);
3501 
3502 	return (quick);
3503 }
3504 
3505 #ifdef INET6
3506 void
3507 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
3508     struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
3509 {
3510 	switch (af) {
3511 #ifdef INET
3512 	case AF_INET:
3513 		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
3514 		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
3515 		break;
3516 #endif /* INET */
3517 	case AF_INET6:
3518 		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
3519 		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
3520 		naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
3521 		((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
3522 		naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
3523 		((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
3524 		naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
3525 		((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
3526 		break;
3527 	}
3528 }
3529 
3530 void
3531 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
3532 {
3533 	switch (af) {
3534 #ifdef INET
3535 	case AF_INET:
3536 		addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
3537 		break;
3538 #endif /* INET */
3539 	case AF_INET6:
3540 		if (addr->addr32[3] == 0xffffffff) {
3541 			addr->addr32[3] = 0;
3542 			if (addr->addr32[2] == 0xffffffff) {
3543 				addr->addr32[2] = 0;
3544 				if (addr->addr32[1] == 0xffffffff) {
3545 					addr->addr32[1] = 0;
3546 					addr->addr32[0] =
3547 					    htonl(ntohl(addr->addr32[0]) + 1);
3548 				} else
3549 					addr->addr32[1] =
3550 					    htonl(ntohl(addr->addr32[1]) + 1);
3551 			} else
3552 				addr->addr32[2] =
3553 				    htonl(ntohl(addr->addr32[2]) + 1);
3554 		} else
3555 			addr->addr32[3] =
3556 			    htonl(ntohl(addr->addr32[3]) + 1);
3557 		break;
3558 	}
3559 }
3560 #endif /* INET6 */
3561 
3562 void
3563 pf_rule_to_actions(struct pf_krule *r, struct pf_rule_actions *a)
3564 {
3565 	if (r->qid)
3566 		a->qid = r->qid;
3567 	if (r->pqid)
3568 		a->pqid = r->pqid;
3569 	if (r->dnpipe)
3570 		a->dnpipe = r->dnpipe;
3571 	if (r->dnrpipe)
3572 		a->dnrpipe = r->dnrpipe;
3573 	if (r->dnpipe || r->dnrpipe) {
3574 		if (r->free_flags & PFRULE_DN_IS_PIPE)
3575 			a->flags |= PFRULE_DN_IS_PIPE;
3576 		else
3577 			a->flags &= ~PFRULE_DN_IS_PIPE;
3578 	}
3579 }
3580 
3581 int
3582 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
3583 {
3584 	struct pf_addr		*saddr, *daddr;
3585 	u_int16_t		 sport, dport;
3586 	struct inpcbinfo	*pi;
3587 	struct inpcb		*inp;
3588 
3589 	pd->lookup.uid = UID_MAX;
3590 	pd->lookup.gid = GID_MAX;
3591 
3592 	switch (pd->proto) {
3593 	case IPPROTO_TCP:
3594 		sport = pd->hdr.tcp.th_sport;
3595 		dport = pd->hdr.tcp.th_dport;
3596 		pi = &V_tcbinfo;
3597 		break;
3598 	case IPPROTO_UDP:
3599 		sport = pd->hdr.udp.uh_sport;
3600 		dport = pd->hdr.udp.uh_dport;
3601 		pi = &V_udbinfo;
3602 		break;
3603 	default:
3604 		return (-1);
3605 	}
3606 	if (direction == PF_IN) {
3607 		saddr = pd->src;
3608 		daddr = pd->dst;
3609 	} else {
3610 		u_int16_t	p;
3611 
3612 		p = sport;
3613 		sport = dport;
3614 		dport = p;
3615 		saddr = pd->dst;
3616 		daddr = pd->src;
3617 	}
3618 	switch (pd->af) {
3619 #ifdef INET
3620 	case AF_INET:
3621 		inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
3622 		    dport, INPLOOKUP_RLOCKPCB, NULL, m);
3623 		if (inp == NULL) {
3624 			inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
3625 			   daddr->v4, dport, INPLOOKUP_WILDCARD |
3626 			   INPLOOKUP_RLOCKPCB, NULL, m);
3627 			if (inp == NULL)
3628 				return (-1);
3629 		}
3630 		break;
3631 #endif /* INET */
3632 #ifdef INET6
3633 	case AF_INET6:
3634 		inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
3635 		    dport, INPLOOKUP_RLOCKPCB, NULL, m);
3636 		if (inp == NULL) {
3637 			inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
3638 			    &daddr->v6, dport, INPLOOKUP_WILDCARD |
3639 			    INPLOOKUP_RLOCKPCB, NULL, m);
3640 			if (inp == NULL)
3641 				return (-1);
3642 		}
3643 		break;
3644 #endif /* INET6 */
3645 
3646 	default:
3647 		return (-1);
3648 	}
3649 	INP_RLOCK_ASSERT(inp);
3650 	pd->lookup.uid = inp->inp_cred->cr_uid;
3651 	pd->lookup.gid = inp->inp_cred->cr_groups[0];
3652 	INP_RUNLOCK(inp);
3653 
3654 	return (1);
3655 }
3656 
3657 u_int8_t
3658 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3659 {
3660 	int		 hlen;
3661 	u_int8_t	 hdr[60];
3662 	u_int8_t	*opt, optlen;
3663 	u_int8_t	 wscale = 0;
3664 
3665 	hlen = th_off << 2;		/* hlen <= sizeof(hdr) */
3666 	if (hlen <= sizeof(struct tcphdr))
3667 		return (0);
3668 	if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3669 		return (0);
3670 	opt = hdr + sizeof(struct tcphdr);
3671 	hlen -= sizeof(struct tcphdr);
3672 	while (hlen >= 3) {
3673 		switch (*opt) {
3674 		case TCPOPT_EOL:
3675 		case TCPOPT_NOP:
3676 			++opt;
3677 			--hlen;
3678 			break;
3679 		case TCPOPT_WINDOW:
3680 			wscale = opt[2];
3681 			if (wscale > TCP_MAX_WINSHIFT)
3682 				wscale = TCP_MAX_WINSHIFT;
3683 			wscale |= PF_WSCALE_FLAG;
3684 			/* FALLTHROUGH */
3685 		default:
3686 			optlen = opt[1];
3687 			if (optlen < 2)
3688 				optlen = 2;
3689 			hlen -= optlen;
3690 			opt += optlen;
3691 			break;
3692 		}
3693 	}
3694 	return (wscale);
3695 }
3696 
3697 u_int16_t
3698 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3699 {
3700 	int		 hlen;
3701 	u_int8_t	 hdr[60];
3702 	u_int8_t	*opt, optlen;
3703 	u_int16_t	 mss = V_tcp_mssdflt;
3704 
3705 	hlen = th_off << 2;	/* hlen <= sizeof(hdr) */
3706 	if (hlen <= sizeof(struct tcphdr))
3707 		return (0);
3708 	if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3709 		return (0);
3710 	opt = hdr + sizeof(struct tcphdr);
3711 	hlen -= sizeof(struct tcphdr);
3712 	while (hlen >= TCPOLEN_MAXSEG) {
3713 		switch (*opt) {
3714 		case TCPOPT_EOL:
3715 		case TCPOPT_NOP:
3716 			++opt;
3717 			--hlen;
3718 			break;
3719 		case TCPOPT_MAXSEG:
3720 			bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3721 			NTOHS(mss);
3722 			/* FALLTHROUGH */
3723 		default:
3724 			optlen = opt[1];
3725 			if (optlen < 2)
3726 				optlen = 2;
3727 			hlen -= optlen;
3728 			opt += optlen;
3729 			break;
3730 		}
3731 	}
3732 	return (mss);
3733 }
3734 
3735 static u_int16_t
3736 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3737 {
3738 	struct nhop_object *nh;
3739 #ifdef INET6
3740 	struct in6_addr		dst6;
3741 	uint32_t		scopeid;
3742 #endif /* INET6 */
3743 	int			 hlen = 0;
3744 	uint16_t		 mss = 0;
3745 
3746 	NET_EPOCH_ASSERT();
3747 
3748 	switch (af) {
3749 #ifdef INET
3750 	case AF_INET:
3751 		hlen = sizeof(struct ip);
3752 		nh = fib4_lookup(rtableid, addr->v4, 0, 0, 0);
3753 		if (nh != NULL)
3754 			mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
3755 		break;
3756 #endif /* INET */
3757 #ifdef INET6
3758 	case AF_INET6:
3759 		hlen = sizeof(struct ip6_hdr);
3760 		in6_splitscope(&addr->v6, &dst6, &scopeid);
3761 		nh = fib6_lookup(rtableid, &dst6, scopeid, 0, 0);
3762 		if (nh != NULL)
3763 			mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
3764 		break;
3765 #endif /* INET6 */
3766 	}
3767 
3768 	mss = max(V_tcp_mssdflt, mss);
3769 	mss = min(mss, offer);
3770 	mss = max(mss, 64);		/* sanity - at least max opt space */
3771 	return (mss);
3772 }
3773 
3774 static u_int32_t
3775 pf_tcp_iss(struct pf_pdesc *pd)
3776 {
3777 	MD5_CTX ctx;
3778 	u_int32_t digest[4];
3779 
3780 	if (V_pf_tcp_secret_init == 0) {
3781 		arc4random_buf(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3782 		MD5Init(&V_pf_tcp_secret_ctx);
3783 		MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3784 		    sizeof(V_pf_tcp_secret));
3785 		V_pf_tcp_secret_init = 1;
3786 	}
3787 
3788 	ctx = V_pf_tcp_secret_ctx;
3789 
3790 	MD5Update(&ctx, (char *)&pd->hdr.tcp.th_sport, sizeof(u_short));
3791 	MD5Update(&ctx, (char *)&pd->hdr.tcp.th_dport, sizeof(u_short));
3792 	if (pd->af == AF_INET6) {
3793 		MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3794 		MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3795 	} else {
3796 		MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3797 		MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3798 	}
3799 	MD5Final((u_char *)digest, &ctx);
3800 	V_pf_tcp_iss_off += 4096;
3801 #define	ISN_RANDOM_INCREMENT (4096 - 1)
3802 	return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3803 	    V_pf_tcp_iss_off);
3804 #undef	ISN_RANDOM_INCREMENT
3805 }
3806 
3807 static bool
3808 pf_match_eth_addr(const uint8_t *a, const struct pf_keth_rule_addr *r)
3809 {
3810 	bool match = true;
3811 
3812 	/* Always matches if not set */
3813 	if (! r->isset)
3814 		return (!r->neg);
3815 
3816 	for (int i = 0; i < ETHER_ADDR_LEN; i++) {
3817 		if ((a[i] & r->mask[i]) != (r->addr[i] & r->mask[i])) {
3818 			match = false;
3819 			break;
3820 		}
3821 	}
3822 
3823 	return (match ^ r->neg);
3824 }
3825 
3826 static int
3827 pf_match_eth_tag(struct mbuf *m, struct pf_keth_rule *r, int *tag, int mtag)
3828 {
3829 	if (*tag == -1)
3830 		*tag = mtag;
3831 
3832 	return ((!r->match_tag_not && r->match_tag == *tag) ||
3833 	    (r->match_tag_not && r->match_tag != *tag));
3834 }
3835 
3836 static int
3837 pf_test_eth_rule(int dir, struct pfi_kkif *kif, struct mbuf **m0)
3838 {
3839 #ifdef INET
3840 	struct ip ip;
3841 #endif
3842 #ifdef INET6
3843 	struct ip6_hdr ip6;
3844 #endif
3845 	struct mbuf *m = *m0;
3846 	struct ether_header *e;
3847 	struct pf_keth_rule *r, *rm, *a = NULL;
3848 	struct pf_keth_ruleset *ruleset = NULL;
3849 	struct pf_mtag *mtag;
3850 	struct pf_keth_ruleq *rules;
3851 	struct pf_addr *src = NULL, *dst = NULL;
3852 	sa_family_t af = 0;
3853 	uint16_t proto;
3854 	int asd = 0, match = 0;
3855 	int tag = -1;
3856 	uint8_t action;
3857 	struct pf_keth_anchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
3858 
3859 	MPASS(kif->pfik_ifp->if_vnet == curvnet);
3860 	NET_EPOCH_ASSERT();
3861 
3862 	PF_RULES_RLOCK_TRACKER;
3863 
3864 	SDT_PROBE3(pf, eth, test_rule, entry, dir, kif->pfik_ifp, m);
3865 
3866 	mtag = pf_find_mtag(m);
3867 	if (mtag != NULL && mtag->flags & PF_TAG_DUMMYNET) {
3868 		/* Dummynet re-injects packets after they've
3869 		 * completed their delay. We've already
3870 		 * processed them, so pass unconditionally. */
3871 
3872 		/* But only once. We may see the packet multiple times (e.g.
3873 		 * PFIL_IN/PFIL_OUT). */
3874 		mtag->flags &= ~PF_TAG_DUMMYNET;
3875 
3876 		return (PF_PASS);
3877 	}
3878 
3879 	ruleset = V_pf_keth;
3880 	rules = ck_pr_load_ptr(&ruleset->active.rules);
3881 	r = TAILQ_FIRST(rules);
3882 	rm = NULL;
3883 
3884 	e = mtod(m, struct ether_header *);
3885 	proto = ntohs(e->ether_type);
3886 
3887 	switch (proto) {
3888 #ifdef INET
3889 	case ETHERTYPE_IP: {
3890 		if (m_length(m, NULL) < (sizeof(struct ether_header) +
3891 		    sizeof(ip)))
3892 			return (PF_DROP);
3893 
3894 		af = AF_INET;
3895 		m_copydata(m, sizeof(struct ether_header), sizeof(ip),
3896 		    (caddr_t)&ip);
3897 		src = (struct pf_addr *)&ip.ip_src;
3898 		dst = (struct pf_addr *)&ip.ip_dst;
3899 		break;
3900 	}
3901 #endif /* INET */
3902 #ifdef INET6
3903 	case ETHERTYPE_IPV6: {
3904 		if (m_length(m, NULL) < (sizeof(struct ether_header) +
3905 		    sizeof(ip6)))
3906 			return (PF_DROP);
3907 
3908 		af = AF_INET6;
3909 		m_copydata(m, sizeof(struct ether_header), sizeof(ip6),
3910 		    (caddr_t)&ip6);
3911 		src = (struct pf_addr *)&ip6.ip6_src;
3912 		dst = (struct pf_addr *)&ip6.ip6_dst;
3913 		break;
3914 	}
3915 #endif /* INET6 */
3916 	}
3917 
3918 	PF_RULES_RLOCK();
3919 
3920 	while (r != NULL) {
3921 		counter_u64_add(r->evaluations, 1);
3922 		SDT_PROBE2(pf, eth, test_rule, test, r->nr, r);
3923 
3924 		if (pfi_kkif_match(r->kif, kif) == r->ifnot) {
3925 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
3926 			    "kif");
3927 			r = r->skip[PFE_SKIP_IFP].ptr;
3928 		}
3929 		else if (r->direction && r->direction != dir) {
3930 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
3931 			    "dir");
3932 			r = r->skip[PFE_SKIP_DIR].ptr;
3933 		}
3934 		else if (r->proto && r->proto != proto) {
3935 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
3936 			    "proto");
3937 			r = r->skip[PFE_SKIP_PROTO].ptr;
3938 		}
3939 		else if (! pf_match_eth_addr(e->ether_shost, &r->src)) {
3940 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
3941 			    "src");
3942 			r = r->skip[PFE_SKIP_SRC_ADDR].ptr;
3943 		}
3944 		else if (! pf_match_eth_addr(e->ether_dhost, &r->dst)) {
3945 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
3946 			    "dst");
3947 			r = TAILQ_NEXT(r, entries);
3948 		}
3949 		else if (src != NULL && PF_MISMATCHAW(&r->ipsrc.addr, src, af,
3950 		    r->ipsrc.neg, kif, M_GETFIB(m))) {
3951 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
3952 			    "ip_src");
3953 			r = TAILQ_NEXT(r, entries);
3954 		}
3955 		else if (dst != NULL && PF_MISMATCHAW(&r->ipdst.addr, dst, af,
3956 		    r->ipdst.neg, kif, M_GETFIB(m))) {
3957 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
3958 			    "ip_dst");
3959 			r = TAILQ_NEXT(r, entries);
3960 		}
3961 		else if (r->match_tag && !pf_match_eth_tag(m, r, &tag,
3962 		    mtag ? mtag->tag : 0)) {
3963 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
3964 			    "match_tag");
3965 			r = TAILQ_NEXT(r, entries);
3966 		}
3967 		else {
3968 			if (r->tag)
3969 				tag = r->tag;
3970 			if (r->anchor == NULL) {
3971 				/* Rule matches */
3972 				rm = r;
3973 
3974 				SDT_PROBE2(pf, eth, test_rule, match, r->nr, r);
3975 
3976 				if (r->quick)
3977 					break;
3978 
3979 				r = TAILQ_NEXT(r, entries);
3980 			} else {
3981 				pf_step_into_keth_anchor(anchor_stack, &asd,
3982 				    &ruleset, &r, &a, &match);
3983 			}
3984 		}
3985 		if (r == NULL && pf_step_out_of_keth_anchor(anchor_stack, &asd,
3986 		    &ruleset, &r, &a, &match))
3987 			break;
3988 	}
3989 
3990 	r = rm;
3991 
3992 	SDT_PROBE2(pf, eth, test_rule, final_match, (r != NULL ? r->nr : -1), r);
3993 
3994 	/* Default to pass. */
3995 	if (r == NULL) {
3996 		PF_RULES_RUNLOCK();
3997 		return (PF_PASS);
3998 	}
3999 
4000 	/* Execute action. */
4001 	counter_u64_add(r->packets[dir == PF_OUT], 1);
4002 	counter_u64_add(r->bytes[dir == PF_OUT], m_length(m, NULL));
4003 	pf_update_timestamp(r);
4004 
4005 	/* Shortcut. Don't tag if we're just going to drop anyway. */
4006 	if (r->action == PF_DROP) {
4007 		PF_RULES_RUNLOCK();
4008 		return (PF_DROP);
4009 	}
4010 
4011 	if (tag > 0) {
4012 		if (mtag == NULL)
4013 			mtag = pf_get_mtag(m);
4014 		if (mtag == NULL) {
4015 			PF_RULES_RUNLOCK();
4016 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4017 			return (PF_DROP);
4018 		}
4019 		mtag->tag = tag;
4020 	}
4021 
4022 	if (r->qid != 0) {
4023 		if (mtag == NULL)
4024 			mtag = pf_get_mtag(m);
4025 		if (mtag == NULL) {
4026 			PF_RULES_RUNLOCK();
4027 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4028 			return (PF_DROP);
4029 		}
4030 		mtag->qid = r->qid;
4031 	}
4032 
4033 	/* Dummynet */
4034 	if (r->dnpipe) {
4035 		struct ip_fw_args dnflow;
4036 
4037 		/* Drop packet if dummynet is not loaded. */
4038 		if (ip_dn_io_ptr == NULL) {
4039 			PF_RULES_RUNLOCK();
4040 			m_freem(m);
4041 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4042 			return (PF_DROP);
4043 		}
4044 		if (mtag == NULL)
4045 			mtag = pf_get_mtag(m);
4046 		if (mtag == NULL) {
4047 			PF_RULES_RUNLOCK();
4048 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4049 			return (PF_DROP);
4050 		}
4051 
4052 		bzero(&dnflow, sizeof(dnflow));
4053 
4054 		/* We don't have port numbers here, so we set 0.  That means
4055 		 * that we'll be somewhat limited in distinguishing flows (i.e.
4056 		 * only based on IP addresses, not based on port numbers), but
4057 		 * it's better than nothing. */
4058 		dnflow.f_id.dst_port = 0;
4059 		dnflow.f_id.src_port = 0;
4060 		dnflow.f_id.proto = 0;
4061 
4062 		dnflow.rule.info = r->dnpipe;
4063 		dnflow.rule.info |= IPFW_IS_DUMMYNET;
4064 		if (r->dnflags & PFRULE_DN_IS_PIPE)
4065 			dnflow.rule.info |= IPFW_IS_PIPE;
4066 
4067 		dnflow.f_id.extra = dnflow.rule.info;
4068 
4069 		dnflow.flags = dir == PF_IN ? IPFW_ARGS_IN : IPFW_ARGS_OUT;
4070 		dnflow.flags |= IPFW_ARGS_ETHER;
4071 		dnflow.ifp = kif->pfik_ifp;
4072 
4073 		switch (af) {
4074 		case AF_INET:
4075 			dnflow.f_id.addr_type = 4;
4076 			dnflow.f_id.src_ip = src->v4.s_addr;
4077 			dnflow.f_id.dst_ip = dst->v4.s_addr;
4078 			break;
4079 		case AF_INET6:
4080 			dnflow.flags |= IPFW_ARGS_IP6;
4081 			dnflow.f_id.addr_type = 6;
4082 			dnflow.f_id.src_ip6 = src->v6;
4083 			dnflow.f_id.dst_ip6 = dst->v6;
4084 			break;
4085 		}
4086 
4087 		mtag->flags |= PF_TAG_DUMMYNET;
4088 		ip_dn_io_ptr(m0, &dnflow);
4089 		if (*m0 != NULL)
4090 			mtag->flags &= ~PF_TAG_DUMMYNET;
4091 	}
4092 
4093 	action = r->action;
4094 
4095 	PF_RULES_RUNLOCK();
4096 
4097 	return (action);
4098 }
4099 
4100 static int
4101 pf_test_rule(struct pf_krule **rm, struct pf_kstate **sm, int direction,
4102     struct pfi_kkif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
4103     struct pf_krule **am, struct pf_kruleset **rsm, struct inpcb *inp)
4104 {
4105 	struct pf_krule		*nr = NULL;
4106 	struct pf_addr		* const saddr = pd->src;
4107 	struct pf_addr		* const daddr = pd->dst;
4108 	sa_family_t		 af = pd->af;
4109 	struct pf_krule		*r, *a = NULL;
4110 	struct pf_kruleset	*ruleset = NULL;
4111 	struct pf_ksrc_node	*nsn = NULL;
4112 	struct tcphdr		*th = &pd->hdr.tcp;
4113 	struct pf_state_key	*sk = NULL, *nk = NULL;
4114 	u_short			 reason;
4115 	int			 rewrite = 0, hdrlen = 0;
4116 	int			 tag = -1, rtableid = -1;
4117 	int			 asd = 0;
4118 	int			 match = 0;
4119 	int			 state_icmp = 0;
4120 	u_int16_t		 sport = 0, dport = 0;
4121 	u_int16_t		 bproto_sum = 0, bip_sum = 0;
4122 	u_int8_t		 icmptype = 0, icmpcode = 0;
4123 	struct pf_kanchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
4124 
4125 	PF_RULES_RASSERT();
4126 
4127 	if (inp != NULL) {
4128 		INP_LOCK_ASSERT(inp);
4129 		pd->lookup.uid = inp->inp_cred->cr_uid;
4130 		pd->lookup.gid = inp->inp_cred->cr_groups[0];
4131 		pd->lookup.done = 1;
4132 	}
4133 
4134 	switch (pd->proto) {
4135 	case IPPROTO_TCP:
4136 		sport = th->th_sport;
4137 		dport = th->th_dport;
4138 		hdrlen = sizeof(*th);
4139 		break;
4140 	case IPPROTO_UDP:
4141 		sport = pd->hdr.udp.uh_sport;
4142 		dport = pd->hdr.udp.uh_dport;
4143 		hdrlen = sizeof(pd->hdr.udp);
4144 		break;
4145 #ifdef INET
4146 	case IPPROTO_ICMP:
4147 		if (pd->af != AF_INET)
4148 			break;
4149 		sport = dport = pd->hdr.icmp.icmp_id;
4150 		hdrlen = sizeof(pd->hdr.icmp);
4151 		icmptype = pd->hdr.icmp.icmp_type;
4152 		icmpcode = pd->hdr.icmp.icmp_code;
4153 
4154 		if (icmptype == ICMP_UNREACH ||
4155 		    icmptype == ICMP_SOURCEQUENCH ||
4156 		    icmptype == ICMP_REDIRECT ||
4157 		    icmptype == ICMP_TIMXCEED ||
4158 		    icmptype == ICMP_PARAMPROB)
4159 			state_icmp++;
4160 		break;
4161 #endif /* INET */
4162 #ifdef INET6
4163 	case IPPROTO_ICMPV6:
4164 		if (af != AF_INET6)
4165 			break;
4166 		sport = dport = pd->hdr.icmp6.icmp6_id;
4167 		hdrlen = sizeof(pd->hdr.icmp6);
4168 		icmptype = pd->hdr.icmp6.icmp6_type;
4169 		icmpcode = pd->hdr.icmp6.icmp6_code;
4170 
4171 		if (icmptype == ICMP6_DST_UNREACH ||
4172 		    icmptype == ICMP6_PACKET_TOO_BIG ||
4173 		    icmptype == ICMP6_TIME_EXCEEDED ||
4174 		    icmptype == ICMP6_PARAM_PROB)
4175 			state_icmp++;
4176 		break;
4177 #endif /* INET6 */
4178 	default:
4179 		sport = dport = hdrlen = 0;
4180 		break;
4181 	}
4182 
4183 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
4184 
4185 	/* check packet for BINAT/NAT/RDR */
4186 	if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
4187 	    &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
4188 		KASSERT(sk != NULL, ("%s: null sk", __func__));
4189 		KASSERT(nk != NULL, ("%s: null nk", __func__));
4190 
4191 		if (nr->log) {
4192 			PFLOG_PACKET(kif, m, af, direction, PFRES_MATCH, nr, a,
4193 			    ruleset, pd, 1);
4194 		}
4195 
4196 		if (pd->ip_sum)
4197 			bip_sum = *pd->ip_sum;
4198 
4199 		switch (pd->proto) {
4200 		case IPPROTO_TCP:
4201 			bproto_sum = th->th_sum;
4202 			pd->proto_sum = &th->th_sum;
4203 
4204 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
4205 			    nk->port[pd->sidx] != sport) {
4206 				pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
4207 				    &th->th_sum, &nk->addr[pd->sidx],
4208 				    nk->port[pd->sidx], 0, af);
4209 				pd->sport = &th->th_sport;
4210 				sport = th->th_sport;
4211 			}
4212 
4213 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
4214 			    nk->port[pd->didx] != dport) {
4215 				pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
4216 				    &th->th_sum, &nk->addr[pd->didx],
4217 				    nk->port[pd->didx], 0, af);
4218 				dport = th->th_dport;
4219 				pd->dport = &th->th_dport;
4220 			}
4221 			rewrite++;
4222 			break;
4223 		case IPPROTO_UDP:
4224 			bproto_sum = pd->hdr.udp.uh_sum;
4225 			pd->proto_sum = &pd->hdr.udp.uh_sum;
4226 
4227 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
4228 			    nk->port[pd->sidx] != sport) {
4229 				pf_change_ap(m, saddr, &pd->hdr.udp.uh_sport,
4230 				    pd->ip_sum, &pd->hdr.udp.uh_sum,
4231 				    &nk->addr[pd->sidx],
4232 				    nk->port[pd->sidx], 1, af);
4233 				sport = pd->hdr.udp.uh_sport;
4234 				pd->sport = &pd->hdr.udp.uh_sport;
4235 			}
4236 
4237 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
4238 			    nk->port[pd->didx] != dport) {
4239 				pf_change_ap(m, daddr, &pd->hdr.udp.uh_dport,
4240 				    pd->ip_sum, &pd->hdr.udp.uh_sum,
4241 				    &nk->addr[pd->didx],
4242 				    nk->port[pd->didx], 1, af);
4243 				dport = pd->hdr.udp.uh_dport;
4244 				pd->dport = &pd->hdr.udp.uh_dport;
4245 			}
4246 			rewrite++;
4247 			break;
4248 #ifdef INET
4249 		case IPPROTO_ICMP:
4250 			nk->port[0] = nk->port[1];
4251 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
4252 				pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
4253 				    nk->addr[pd->sidx].v4.s_addr, 0);
4254 
4255 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
4256 				pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
4257 				    nk->addr[pd->didx].v4.s_addr, 0);
4258 
4259 			if (nk->port[1] != pd->hdr.icmp.icmp_id) {
4260 				pd->hdr.icmp.icmp_cksum = pf_cksum_fixup(
4261 				    pd->hdr.icmp.icmp_cksum, sport,
4262 				    nk->port[1], 0);
4263 				pd->hdr.icmp.icmp_id = nk->port[1];
4264 				pd->sport = &pd->hdr.icmp.icmp_id;
4265 			}
4266 			m_copyback(m, off, ICMP_MINLEN, (caddr_t)&pd->hdr.icmp);
4267 			break;
4268 #endif /* INET */
4269 #ifdef INET6
4270 		case IPPROTO_ICMPV6:
4271 			nk->port[0] = nk->port[1];
4272 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
4273 				pf_change_a6(saddr, &pd->hdr.icmp6.icmp6_cksum,
4274 				    &nk->addr[pd->sidx], 0);
4275 
4276 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
4277 				pf_change_a6(daddr, &pd->hdr.icmp6.icmp6_cksum,
4278 				    &nk->addr[pd->didx], 0);
4279 			rewrite++;
4280 			break;
4281 #endif /* INET */
4282 		default:
4283 			switch (af) {
4284 #ifdef INET
4285 			case AF_INET:
4286 				if (PF_ANEQ(saddr,
4287 				    &nk->addr[pd->sidx], AF_INET))
4288 					pf_change_a(&saddr->v4.s_addr,
4289 					    pd->ip_sum,
4290 					    nk->addr[pd->sidx].v4.s_addr, 0);
4291 
4292 				if (PF_ANEQ(daddr,
4293 				    &nk->addr[pd->didx], AF_INET))
4294 					pf_change_a(&daddr->v4.s_addr,
4295 					    pd->ip_sum,
4296 					    nk->addr[pd->didx].v4.s_addr, 0);
4297 				break;
4298 #endif /* INET */
4299 #ifdef INET6
4300 			case AF_INET6:
4301 				if (PF_ANEQ(saddr,
4302 				    &nk->addr[pd->sidx], AF_INET6))
4303 					PF_ACPY(saddr, &nk->addr[pd->sidx], af);
4304 
4305 				if (PF_ANEQ(daddr,
4306 				    &nk->addr[pd->didx], AF_INET6))
4307 					PF_ACPY(daddr, &nk->addr[pd->didx], af);
4308 				break;
4309 #endif /* INET */
4310 			}
4311 			break;
4312 		}
4313 		if (nr->natpass)
4314 			r = NULL;
4315 		pd->nat_rule = nr;
4316 	}
4317 
4318 	while (r != NULL) {
4319 		pf_counter_u64_add(&r->evaluations, 1);
4320 		if (pfi_kkif_match(r->kif, kif) == r->ifnot)
4321 			r = r->skip[PF_SKIP_IFP].ptr;
4322 		else if (r->direction && r->direction != direction)
4323 			r = r->skip[PF_SKIP_DIR].ptr;
4324 		else if (r->af && r->af != af)
4325 			r = r->skip[PF_SKIP_AF].ptr;
4326 		else if (r->proto && r->proto != pd->proto)
4327 			r = r->skip[PF_SKIP_PROTO].ptr;
4328 		else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
4329 		    r->src.neg, kif, M_GETFIB(m)))
4330 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
4331 		/* tcp/udp only. port_op always 0 in other cases */
4332 		else if (r->src.port_op && !pf_match_port(r->src.port_op,
4333 		    r->src.port[0], r->src.port[1], sport))
4334 			r = r->skip[PF_SKIP_SRC_PORT].ptr;
4335 		else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
4336 		    r->dst.neg, NULL, M_GETFIB(m)))
4337 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
4338 		/* tcp/udp only. port_op always 0 in other cases */
4339 		else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
4340 		    r->dst.port[0], r->dst.port[1], dport))
4341 			r = r->skip[PF_SKIP_DST_PORT].ptr;
4342 		/* icmp only. type always 0 in other cases */
4343 		else if (r->type && r->type != icmptype + 1)
4344 			r = TAILQ_NEXT(r, entries);
4345 		/* icmp only. type always 0 in other cases */
4346 		else if (r->code && r->code != icmpcode + 1)
4347 			r = TAILQ_NEXT(r, entries);
4348 		else if (r->tos && !(r->tos == pd->tos))
4349 			r = TAILQ_NEXT(r, entries);
4350 		else if (r->rule_flag & PFRULE_FRAGMENT)
4351 			r = TAILQ_NEXT(r, entries);
4352 		else if (pd->proto == IPPROTO_TCP &&
4353 		    (r->flagset & th->th_flags) != r->flags)
4354 			r = TAILQ_NEXT(r, entries);
4355 		/* tcp/udp only. uid.op always 0 in other cases */
4356 		else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
4357 		    pf_socket_lookup(direction, pd, m), 1)) &&
4358 		    !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
4359 		    pd->lookup.uid))
4360 			r = TAILQ_NEXT(r, entries);
4361 		/* tcp/udp only. gid.op always 0 in other cases */
4362 		else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
4363 		    pf_socket_lookup(direction, pd, m), 1)) &&
4364 		    !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
4365 		    pd->lookup.gid))
4366 			r = TAILQ_NEXT(r, entries);
4367 		else if (r->prio &&
4368 		    !pf_match_ieee8021q_pcp(r->prio, m))
4369 			r = TAILQ_NEXT(r, entries);
4370 		else if (r->prob &&
4371 		    r->prob <= arc4random())
4372 			r = TAILQ_NEXT(r, entries);
4373 		else if (r->match_tag && !pf_match_tag(m, r, &tag,
4374 		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
4375 			r = TAILQ_NEXT(r, entries);
4376 		else if (r->os_fingerprint != PF_OSFP_ANY &&
4377 		    (pd->proto != IPPROTO_TCP || !pf_osfp_match(
4378 		    pf_osfp_fingerprint(pd, m, off, th),
4379 		    r->os_fingerprint)))
4380 			r = TAILQ_NEXT(r, entries);
4381 		else {
4382 			if (r->tag)
4383 				tag = r->tag;
4384 			if (r->rtableid >= 0)
4385 				rtableid = r->rtableid;
4386 			if (r->anchor == NULL) {
4387 				if (r->action == PF_MATCH) {
4388 					pf_counter_u64_critical_enter();
4389 					pf_counter_u64_add_protected(&r->packets[direction == PF_OUT], 1);
4390 					pf_counter_u64_add_protected(&r->bytes[direction == PF_OUT], pd->tot_len);
4391 					pf_counter_u64_critical_exit();
4392 					pf_rule_to_actions(r, &pd->act);
4393 					if (r->log)
4394 						PFLOG_PACKET(kif, m, af,
4395 						    direction, PFRES_MATCH, r,
4396 						    a, ruleset, pd, 1);
4397 				} else {
4398 					match = 1;
4399 					*rm = r;
4400 					*am = a;
4401 					*rsm = ruleset;
4402 				}
4403 				if ((*rm)->quick)
4404 					break;
4405 				r = TAILQ_NEXT(r, entries);
4406 			} else
4407 				pf_step_into_anchor(anchor_stack, &asd,
4408 				    &ruleset, PF_RULESET_FILTER, &r, &a,
4409 				    &match);
4410 		}
4411 		if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
4412 		    &ruleset, PF_RULESET_FILTER, &r, &a, &match))
4413 			break;
4414 	}
4415 	r = *rm;
4416 	a = *am;
4417 	ruleset = *rsm;
4418 
4419 	REASON_SET(&reason, PFRES_MATCH);
4420 
4421 	/* apply actions for last matching pass/block rule */
4422 	pf_rule_to_actions(r, &pd->act);
4423 
4424 	if (r->log) {
4425 		if (rewrite)
4426 			m_copyback(m, off, hdrlen, pd->hdr.any);
4427 		PFLOG_PACKET(kif, m, af, direction, reason, r, a,
4428 		    ruleset, pd, 1);
4429 	}
4430 
4431 	if ((r->action == PF_DROP) &&
4432 	    ((r->rule_flag & PFRULE_RETURNRST) ||
4433 	    (r->rule_flag & PFRULE_RETURNICMP) ||
4434 	    (r->rule_flag & PFRULE_RETURN))) {
4435 		pf_return(r, nr, pd, sk, off, m, th, kif, bproto_sum,
4436 		    bip_sum, hdrlen, &reason);
4437 	}
4438 
4439 	if (r->action == PF_DROP)
4440 		goto cleanup;
4441 
4442 	if (tag > 0 && pf_tag_packet(m, pd, tag)) {
4443 		REASON_SET(&reason, PFRES_MEMORY);
4444 		goto cleanup;
4445 	}
4446 	if (rtableid >= 0)
4447 		M_SETFIB(m, rtableid);
4448 
4449 	if (!state_icmp && (r->keep_state || nr != NULL ||
4450 	    (pd->flags & PFDESC_TCP_NORM))) {
4451 		int action;
4452 		action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
4453 		    sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
4454 		    hdrlen);
4455 		if (action != PF_PASS) {
4456 			if (action == PF_DROP &&
4457 			    (r->rule_flag & PFRULE_RETURN))
4458 				pf_return(r, nr, pd, sk, off, m, th, kif,
4459 				    bproto_sum, bip_sum, hdrlen, &reason);
4460 			return (action);
4461 		}
4462 	} else {
4463 		if (sk != NULL)
4464 			uma_zfree(V_pf_state_key_z, sk);
4465 		if (nk != NULL)
4466 			uma_zfree(V_pf_state_key_z, nk);
4467 	}
4468 
4469 	/* copy back packet headers if we performed NAT operations */
4470 	if (rewrite)
4471 		m_copyback(m, off, hdrlen, pd->hdr.any);
4472 
4473 	if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
4474 	    direction == PF_OUT &&
4475 	    V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, m))
4476 		/*
4477 		 * We want the state created, but we dont
4478 		 * want to send this in case a partner
4479 		 * firewall has to know about it to allow
4480 		 * replies through it.
4481 		 */
4482 		return (PF_DEFER);
4483 
4484 	return (PF_PASS);
4485 
4486 cleanup:
4487 	if (sk != NULL)
4488 		uma_zfree(V_pf_state_key_z, sk);
4489 	if (nk != NULL)
4490 		uma_zfree(V_pf_state_key_z, nk);
4491 	return (PF_DROP);
4492 }
4493 
4494 static int
4495 pf_create_state(struct pf_krule *r, struct pf_krule *nr, struct pf_krule *a,
4496     struct pf_pdesc *pd, struct pf_ksrc_node *nsn, struct pf_state_key *nk,
4497     struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
4498     u_int16_t dport, int *rewrite, struct pfi_kkif *kif, struct pf_kstate **sm,
4499     int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
4500 {
4501 	struct pf_kstate	*s = NULL;
4502 	struct pf_ksrc_node	*sn = NULL;
4503 	struct tcphdr		*th = &pd->hdr.tcp;
4504 	u_int16_t		 mss = V_tcp_mssdflt;
4505 	u_short			 reason;
4506 
4507 	/* check maximums */
4508 	if (r->max_states &&
4509 	    (counter_u64_fetch(r->states_cur) >= r->max_states)) {
4510 		counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
4511 		REASON_SET(&reason, PFRES_MAXSTATES);
4512 		goto csfailed;
4513 	}
4514 	/* src node for filter rule */
4515 	if ((r->rule_flag & PFRULE_SRCTRACK ||
4516 	    r->rpool.opts & PF_POOL_STICKYADDR) &&
4517 	    pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
4518 		REASON_SET(&reason, PFRES_SRCLIMIT);
4519 		goto csfailed;
4520 	}
4521 	/* src node for translation rule */
4522 	if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
4523 	    pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
4524 		REASON_SET(&reason, PFRES_SRCLIMIT);
4525 		goto csfailed;
4526 	}
4527 	s = pf_alloc_state(M_NOWAIT);
4528 	if (s == NULL) {
4529 		REASON_SET(&reason, PFRES_MEMORY);
4530 		goto csfailed;
4531 	}
4532 	s->rule.ptr = r;
4533 	s->nat_rule.ptr = nr;
4534 	s->anchor.ptr = a;
4535 	STATE_INC_COUNTERS(s);
4536 	if (r->allow_opts)
4537 		s->state_flags |= PFSTATE_ALLOWOPTS;
4538 	if (r->rule_flag & PFRULE_STATESLOPPY)
4539 		s->state_flags |= PFSTATE_SLOPPY;
4540 	s->log = r->log & PF_LOG_ALL;
4541 	s->sync_state = PFSYNC_S_NONE;
4542 	s->qid = pd->act.qid;
4543 	s->pqid = pd->act.pqid;
4544 	s->dnpipe = pd->act.dnpipe;
4545 	s->dnrpipe = pd->act.dnrpipe;
4546 	s->state_flags |= pd->act.flags;
4547 	if (nr != NULL)
4548 		s->log |= nr->log & PF_LOG_ALL;
4549 	switch (pd->proto) {
4550 	case IPPROTO_TCP:
4551 		s->src.seqlo = ntohl(th->th_seq);
4552 		s->src.seqhi = s->src.seqlo + pd->p_len + 1;
4553 		if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
4554 		    r->keep_state == PF_STATE_MODULATE) {
4555 			/* Generate sequence number modulator */
4556 			if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
4557 			    0)
4558 				s->src.seqdiff = 1;
4559 			pf_change_proto_a(m, &th->th_seq, &th->th_sum,
4560 			    htonl(s->src.seqlo + s->src.seqdiff), 0);
4561 			*rewrite = 1;
4562 		} else
4563 			s->src.seqdiff = 0;
4564 		if (th->th_flags & TH_SYN) {
4565 			s->src.seqhi++;
4566 			s->src.wscale = pf_get_wscale(m, off,
4567 			    th->th_off, pd->af);
4568 		}
4569 		s->src.max_win = MAX(ntohs(th->th_win), 1);
4570 		if (s->src.wscale & PF_WSCALE_MASK) {
4571 			/* Remove scale factor from initial window */
4572 			int win = s->src.max_win;
4573 			win += 1 << (s->src.wscale & PF_WSCALE_MASK);
4574 			s->src.max_win = (win - 1) >>
4575 			    (s->src.wscale & PF_WSCALE_MASK);
4576 		}
4577 		if (th->th_flags & TH_FIN)
4578 			s->src.seqhi++;
4579 		s->dst.seqhi = 1;
4580 		s->dst.max_win = 1;
4581 		pf_set_protostate(s, PF_PEER_SRC, TCPS_SYN_SENT);
4582 		pf_set_protostate(s, PF_PEER_DST, TCPS_CLOSED);
4583 		s->timeout = PFTM_TCP_FIRST_PACKET;
4584 		atomic_add_32(&V_pf_status.states_halfopen, 1);
4585 		break;
4586 	case IPPROTO_UDP:
4587 		pf_set_protostate(s, PF_PEER_SRC, PFUDPS_SINGLE);
4588 		pf_set_protostate(s, PF_PEER_DST, PFUDPS_NO_TRAFFIC);
4589 		s->timeout = PFTM_UDP_FIRST_PACKET;
4590 		break;
4591 	case IPPROTO_ICMP:
4592 #ifdef INET6
4593 	case IPPROTO_ICMPV6:
4594 #endif
4595 		s->timeout = PFTM_ICMP_FIRST_PACKET;
4596 		break;
4597 	default:
4598 		pf_set_protostate(s, PF_PEER_SRC, PFOTHERS_SINGLE);
4599 		pf_set_protostate(s, PF_PEER_DST, PFOTHERS_NO_TRAFFIC);
4600 		s->timeout = PFTM_OTHER_FIRST_PACKET;
4601 	}
4602 
4603 	if (r->rt) {
4604 		if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
4605 			REASON_SET(&reason, PFRES_MAPFAILED);
4606 			pf_src_tree_remove_state(s);
4607 			s->timeout = PFTM_UNLINKED;
4608 			STATE_DEC_COUNTERS(s);
4609 			pf_free_state(s);
4610 			goto csfailed;
4611 		}
4612 		s->rt_kif = r->rpool.cur->kif;
4613 	}
4614 
4615 	s->creation = time_uptime;
4616 	s->expire = time_uptime;
4617 
4618 	if (sn != NULL)
4619 		s->src_node = sn;
4620 	if (nsn != NULL) {
4621 		/* XXX We only modify one side for now. */
4622 		PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
4623 		s->nat_src_node = nsn;
4624 	}
4625 	if (pd->proto == IPPROTO_TCP) {
4626 		if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
4627 		    off, pd, th, &s->src, &s->dst)) {
4628 			REASON_SET(&reason, PFRES_MEMORY);
4629 			pf_src_tree_remove_state(s);
4630 			s->timeout = PFTM_UNLINKED;
4631 			STATE_DEC_COUNTERS(s);
4632 			pf_free_state(s);
4633 			return (PF_DROP);
4634 		}
4635 		if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
4636 		    pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
4637 		    &s->src, &s->dst, rewrite)) {
4638 			/* This really shouldn't happen!!! */
4639 			DPFPRINTF(PF_DEBUG_URGENT,
4640 			    ("pf_normalize_tcp_stateful failed on first "
4641 			     "pkt\n"));
4642 			pf_src_tree_remove_state(s);
4643 			s->timeout = PFTM_UNLINKED;
4644 			STATE_DEC_COUNTERS(s);
4645 			pf_free_state(s);
4646 			return (PF_DROP);
4647 		}
4648 	}
4649 	s->direction = pd->dir;
4650 
4651 	/*
4652 	 * sk/nk could already been setup by pf_get_translation().
4653 	 */
4654 	if (nr == NULL) {
4655 		KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
4656 		    __func__, nr, sk, nk));
4657 		sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
4658 		if (sk == NULL)
4659 			goto csfailed;
4660 		nk = sk;
4661 	} else
4662 		KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
4663 		    __func__, nr, sk, nk));
4664 
4665 	/* Swap sk/nk for PF_OUT. */
4666 	if (pf_state_insert(BOUND_IFACE(r, kif), kif,
4667 	    (pd->dir == PF_IN) ? sk : nk,
4668 	    (pd->dir == PF_IN) ? nk : sk, s)) {
4669 		REASON_SET(&reason, PFRES_STATEINS);
4670 		pf_src_tree_remove_state(s);
4671 		s->timeout = PFTM_UNLINKED;
4672 		STATE_DEC_COUNTERS(s);
4673 		pf_free_state(s);
4674 		return (PF_DROP);
4675 	} else
4676 		*sm = s;
4677 
4678 	if (tag > 0)
4679 		s->tag = tag;
4680 	if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
4681 	    TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
4682 		pf_set_protostate(s, PF_PEER_SRC, PF_TCPS_PROXY_SRC);
4683 		/* undo NAT changes, if they have taken place */
4684 		if (nr != NULL) {
4685 			struct pf_state_key *skt = s->key[PF_SK_WIRE];
4686 			if (pd->dir == PF_OUT)
4687 				skt = s->key[PF_SK_STACK];
4688 			PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
4689 			PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
4690 			if (pd->sport)
4691 				*pd->sport = skt->port[pd->sidx];
4692 			if (pd->dport)
4693 				*pd->dport = skt->port[pd->didx];
4694 			if (pd->proto_sum)
4695 				*pd->proto_sum = bproto_sum;
4696 			if (pd->ip_sum)
4697 				*pd->ip_sum = bip_sum;
4698 			m_copyback(m, off, hdrlen, pd->hdr.any);
4699 		}
4700 		s->src.seqhi = htonl(arc4random());
4701 		/* Find mss option */
4702 		int rtid = M_GETFIB(m);
4703 		mss = pf_get_mss(m, off, th->th_off, pd->af);
4704 		mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
4705 		mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
4706 		s->src.mss = mss;
4707 		pf_send_tcp(r, pd->af, pd->dst, pd->src, th->th_dport,
4708 		    th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
4709 		    TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0);
4710 		REASON_SET(&reason, PFRES_SYNPROXY);
4711 		return (PF_SYNPROXY_DROP);
4712 	}
4713 
4714 	return (PF_PASS);
4715 
4716 csfailed:
4717 	if (sk != NULL)
4718 		uma_zfree(V_pf_state_key_z, sk);
4719 	if (nk != NULL)
4720 		uma_zfree(V_pf_state_key_z, nk);
4721 
4722 	if (sn != NULL) {
4723 		struct pf_srchash *sh;
4724 
4725 		sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
4726 		PF_HASHROW_LOCK(sh);
4727 		if (--sn->states == 0 && sn->expire == 0) {
4728 			pf_unlink_src_node(sn);
4729 			uma_zfree(V_pf_sources_z, sn);
4730 			counter_u64_add(
4731 			    V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
4732 		}
4733 		PF_HASHROW_UNLOCK(sh);
4734 	}
4735 
4736 	if (nsn != sn && nsn != NULL) {
4737 		struct pf_srchash *sh;
4738 
4739 		sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
4740 		PF_HASHROW_LOCK(sh);
4741 		if (--nsn->states == 0 && nsn->expire == 0) {
4742 			pf_unlink_src_node(nsn);
4743 			uma_zfree(V_pf_sources_z, nsn);
4744 			counter_u64_add(
4745 			    V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
4746 		}
4747 		PF_HASHROW_UNLOCK(sh);
4748 	}
4749 
4750 	return (PF_DROP);
4751 }
4752 
4753 static int
4754 pf_test_fragment(struct pf_krule **rm, int direction, struct pfi_kkif *kif,
4755     struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_krule **am,
4756     struct pf_kruleset **rsm)
4757 {
4758 	struct pf_krule		*r, *a = NULL;
4759 	struct pf_kruleset	*ruleset = NULL;
4760 	sa_family_t		 af = pd->af;
4761 	u_short			 reason;
4762 	int			 tag = -1;
4763 	int			 asd = 0;
4764 	int			 match = 0;
4765 	struct pf_kanchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
4766 
4767 	PF_RULES_RASSERT();
4768 
4769 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
4770 	while (r != NULL) {
4771 		pf_counter_u64_add(&r->evaluations, 1);
4772 		if (pfi_kkif_match(r->kif, kif) == r->ifnot)
4773 			r = r->skip[PF_SKIP_IFP].ptr;
4774 		else if (r->direction && r->direction != direction)
4775 			r = r->skip[PF_SKIP_DIR].ptr;
4776 		else if (r->af && r->af != af)
4777 			r = r->skip[PF_SKIP_AF].ptr;
4778 		else if (r->proto && r->proto != pd->proto)
4779 			r = r->skip[PF_SKIP_PROTO].ptr;
4780 		else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
4781 		    r->src.neg, kif, M_GETFIB(m)))
4782 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
4783 		else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
4784 		    r->dst.neg, NULL, M_GETFIB(m)))
4785 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
4786 		else if (r->tos && !(r->tos == pd->tos))
4787 			r = TAILQ_NEXT(r, entries);
4788 		else if (r->os_fingerprint != PF_OSFP_ANY)
4789 			r = TAILQ_NEXT(r, entries);
4790 		else if (pd->proto == IPPROTO_UDP &&
4791 		    (r->src.port_op || r->dst.port_op))
4792 			r = TAILQ_NEXT(r, entries);
4793 		else if (pd->proto == IPPROTO_TCP &&
4794 		    (r->src.port_op || r->dst.port_op || r->flagset))
4795 			r = TAILQ_NEXT(r, entries);
4796 		else if ((pd->proto == IPPROTO_ICMP ||
4797 		    pd->proto == IPPROTO_ICMPV6) &&
4798 		    (r->type || r->code))
4799 			r = TAILQ_NEXT(r, entries);
4800 		else if (r->prio &&
4801 		    !pf_match_ieee8021q_pcp(r->prio, m))
4802 			r = TAILQ_NEXT(r, entries);
4803 		else if (r->prob && r->prob <=
4804 		    (arc4random() % (UINT_MAX - 1) + 1))
4805 			r = TAILQ_NEXT(r, entries);
4806 		else if (r->match_tag && !pf_match_tag(m, r, &tag,
4807 		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
4808 			r = TAILQ_NEXT(r, entries);
4809 		else {
4810 			if (r->anchor == NULL) {
4811 				if (r->action == PF_MATCH) {
4812 					pf_counter_u64_critical_enter();
4813 					pf_counter_u64_add_protected(&r->packets[direction == PF_OUT], 1);
4814 					pf_counter_u64_add_protected(&r->bytes[direction == PF_OUT], pd->tot_len);
4815 					pf_counter_u64_critical_exit();
4816 					pf_rule_to_actions(r, &pd->act);
4817 					if (r->log)
4818 						PFLOG_PACKET(kif, m, af,
4819 						    direction, PFRES_MATCH, r,
4820 						    a, ruleset, pd, 1);
4821 				} else {
4822 					match = 1;
4823 					*rm = r;
4824 					*am = a;
4825 					*rsm = ruleset;
4826 				}
4827 				if ((*rm)->quick)
4828 					break;
4829 				r = TAILQ_NEXT(r, entries);
4830 			} else
4831 				pf_step_into_anchor(anchor_stack, &asd,
4832 				    &ruleset, PF_RULESET_FILTER, &r, &a,
4833 				    &match);
4834 		}
4835 		if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
4836 		    &ruleset, PF_RULESET_FILTER, &r, &a, &match))
4837 			break;
4838 	}
4839 	r = *rm;
4840 	a = *am;
4841 	ruleset = *rsm;
4842 
4843 	REASON_SET(&reason, PFRES_MATCH);
4844 
4845 	/* apply actions for last matching pass/block rule */
4846 	pf_rule_to_actions(r, &pd->act);
4847 
4848 	if (r->log)
4849 		PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
4850 		    1);
4851 
4852 	if (r->action != PF_PASS)
4853 		return (PF_DROP);
4854 
4855 	if (tag > 0 && pf_tag_packet(m, pd, tag)) {
4856 		REASON_SET(&reason, PFRES_MEMORY);
4857 		return (PF_DROP);
4858 	}
4859 
4860 	return (PF_PASS);
4861 }
4862 
4863 static int
4864 pf_tcp_track_full(struct pf_kstate **state, struct pfi_kkif *kif,
4865     struct mbuf *m, int off, struct pf_pdesc *pd, u_short *reason,
4866     int *copyback)
4867 {
4868 	struct tcphdr		*th = &pd->hdr.tcp;
4869 	struct pf_state_peer	*src, *dst;
4870 	u_int16_t		 win = ntohs(th->th_win);
4871 	u_int32_t		 ack, end, seq, orig_seq;
4872 	u_int8_t		 sws, dws, psrc, pdst;
4873 	int			 ackskew;
4874 
4875 	if (pd->dir == (*state)->direction) {
4876 		src = &(*state)->src;
4877 		dst = &(*state)->dst;
4878 		psrc = PF_PEER_SRC;
4879 		pdst = PF_PEER_DST;
4880 	} else {
4881 		src = &(*state)->dst;
4882 		dst = &(*state)->src;
4883 		psrc = PF_PEER_DST;
4884 		pdst = PF_PEER_SRC;
4885 	}
4886 
4887 	if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
4888 		sws = src->wscale & PF_WSCALE_MASK;
4889 		dws = dst->wscale & PF_WSCALE_MASK;
4890 	} else
4891 		sws = dws = 0;
4892 
4893 	/*
4894 	 * Sequence tracking algorithm from Guido van Rooij's paper:
4895 	 *   http://www.madison-gurkha.com/publications/tcp_filtering/
4896 	 *	tcp_filtering.ps
4897 	 */
4898 
4899 	orig_seq = seq = ntohl(th->th_seq);
4900 	if (src->seqlo == 0) {
4901 		/* First packet from this end. Set its state */
4902 
4903 		if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
4904 		    src->scrub == NULL) {
4905 			if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
4906 				REASON_SET(reason, PFRES_MEMORY);
4907 				return (PF_DROP);
4908 			}
4909 		}
4910 
4911 		/* Deferred generation of sequence number modulator */
4912 		if (dst->seqdiff && !src->seqdiff) {
4913 			/* use random iss for the TCP server */
4914 			while ((src->seqdiff = arc4random() - seq) == 0)
4915 				;
4916 			ack = ntohl(th->th_ack) - dst->seqdiff;
4917 			pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4918 			    src->seqdiff), 0);
4919 			pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4920 			*copyback = 1;
4921 		} else {
4922 			ack = ntohl(th->th_ack);
4923 		}
4924 
4925 		end = seq + pd->p_len;
4926 		if (th->th_flags & TH_SYN) {
4927 			end++;
4928 			if (dst->wscale & PF_WSCALE_FLAG) {
4929 				src->wscale = pf_get_wscale(m, off, th->th_off,
4930 				    pd->af);
4931 				if (src->wscale & PF_WSCALE_FLAG) {
4932 					/* Remove scale factor from initial
4933 					 * window */
4934 					sws = src->wscale & PF_WSCALE_MASK;
4935 					win = ((u_int32_t)win + (1 << sws) - 1)
4936 					    >> sws;
4937 					dws = dst->wscale & PF_WSCALE_MASK;
4938 				} else {
4939 					/* fixup other window */
4940 					dst->max_win <<= dst->wscale &
4941 					    PF_WSCALE_MASK;
4942 					/* in case of a retrans SYN|ACK */
4943 					dst->wscale = 0;
4944 				}
4945 			}
4946 		}
4947 		if (th->th_flags & TH_FIN)
4948 			end++;
4949 
4950 		src->seqlo = seq;
4951 		if (src->state < TCPS_SYN_SENT)
4952 			pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
4953 
4954 		/*
4955 		 * May need to slide the window (seqhi may have been set by
4956 		 * the crappy stack check or if we picked up the connection
4957 		 * after establishment)
4958 		 */
4959 		if (src->seqhi == 1 ||
4960 		    SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4961 			src->seqhi = end + MAX(1, dst->max_win << dws);
4962 		if (win > src->max_win)
4963 			src->max_win = win;
4964 
4965 	} else {
4966 		ack = ntohl(th->th_ack) - dst->seqdiff;
4967 		if (src->seqdiff) {
4968 			/* Modulate sequence numbers */
4969 			pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4970 			    src->seqdiff), 0);
4971 			pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4972 			*copyback = 1;
4973 		}
4974 		end = seq + pd->p_len;
4975 		if (th->th_flags & TH_SYN)
4976 			end++;
4977 		if (th->th_flags & TH_FIN)
4978 			end++;
4979 	}
4980 
4981 	if ((th->th_flags & TH_ACK) == 0) {
4982 		/* Let it pass through the ack skew check */
4983 		ack = dst->seqlo;
4984 	} else if ((ack == 0 &&
4985 	    (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4986 	    /* broken tcp stacks do not set ack */
4987 	    (dst->state < TCPS_SYN_SENT)) {
4988 		/*
4989 		 * Many stacks (ours included) will set the ACK number in an
4990 		 * FIN|ACK if the SYN times out -- no sequence to ACK.
4991 		 */
4992 		ack = dst->seqlo;
4993 	}
4994 
4995 	if (seq == end) {
4996 		/* Ease sequencing restrictions on no data packets */
4997 		seq = src->seqlo;
4998 		end = seq;
4999 	}
5000 
5001 	ackskew = dst->seqlo - ack;
5002 
5003 	/*
5004 	 * Need to demodulate the sequence numbers in any TCP SACK options
5005 	 * (Selective ACK). We could optionally validate the SACK values
5006 	 * against the current ACK window, either forwards or backwards, but
5007 	 * I'm not confident that SACK has been implemented properly
5008 	 * everywhere. It wouldn't surprise me if several stacks accidentally
5009 	 * SACK too far backwards of previously ACKed data. There really aren't
5010 	 * any security implications of bad SACKing unless the target stack
5011 	 * doesn't validate the option length correctly. Someone trying to
5012 	 * spoof into a TCP connection won't bother blindly sending SACK
5013 	 * options anyway.
5014 	 */
5015 	if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
5016 		if (pf_modulate_sack(m, off, pd, th, dst))
5017 			*copyback = 1;
5018 	}
5019 
5020 #define	MAXACKWINDOW (0xffff + 1500)	/* 1500 is an arbitrary fudge factor */
5021 	if (SEQ_GEQ(src->seqhi, end) &&
5022 	    /* Last octet inside other's window space */
5023 	    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
5024 	    /* Retrans: not more than one window back */
5025 	    (ackskew >= -MAXACKWINDOW) &&
5026 	    /* Acking not more than one reassembled fragment backwards */
5027 	    (ackskew <= (MAXACKWINDOW << sws)) &&
5028 	    /* Acking not more than one window forward */
5029 	    ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
5030 	    (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
5031 	    (pd->flags & PFDESC_IP_REAS) == 0)) {
5032 	    /* Require an exact/+1 sequence match on resets when possible */
5033 
5034 		if (dst->scrub || src->scrub) {
5035 			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
5036 			    *state, src, dst, copyback))
5037 				return (PF_DROP);
5038 		}
5039 
5040 		/* update max window */
5041 		if (src->max_win < win)
5042 			src->max_win = win;
5043 		/* synchronize sequencing */
5044 		if (SEQ_GT(end, src->seqlo))
5045 			src->seqlo = end;
5046 		/* slide the window of what the other end can send */
5047 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
5048 			dst->seqhi = ack + MAX((win << sws), 1);
5049 
5050 		/* update states */
5051 		if (th->th_flags & TH_SYN)
5052 			if (src->state < TCPS_SYN_SENT)
5053 				pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
5054 		if (th->th_flags & TH_FIN)
5055 			if (src->state < TCPS_CLOSING)
5056 				pf_set_protostate(*state, psrc, TCPS_CLOSING);
5057 		if (th->th_flags & TH_ACK) {
5058 			if (dst->state == TCPS_SYN_SENT) {
5059 				pf_set_protostate(*state, pdst,
5060 				    TCPS_ESTABLISHED);
5061 				if (src->state == TCPS_ESTABLISHED &&
5062 				    (*state)->src_node != NULL &&
5063 				    pf_src_connlimit(state)) {
5064 					REASON_SET(reason, PFRES_SRCLIMIT);
5065 					return (PF_DROP);
5066 				}
5067 			} else if (dst->state == TCPS_CLOSING)
5068 				pf_set_protostate(*state, pdst,
5069 				    TCPS_FIN_WAIT_2);
5070 		}
5071 		if (th->th_flags & TH_RST)
5072 			pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
5073 
5074 		/* update expire time */
5075 		(*state)->expire = time_uptime;
5076 		if (src->state >= TCPS_FIN_WAIT_2 &&
5077 		    dst->state >= TCPS_FIN_WAIT_2)
5078 			(*state)->timeout = PFTM_TCP_CLOSED;
5079 		else if (src->state >= TCPS_CLOSING &&
5080 		    dst->state >= TCPS_CLOSING)
5081 			(*state)->timeout = PFTM_TCP_FIN_WAIT;
5082 		else if (src->state < TCPS_ESTABLISHED ||
5083 		    dst->state < TCPS_ESTABLISHED)
5084 			(*state)->timeout = PFTM_TCP_OPENING;
5085 		else if (src->state >= TCPS_CLOSING ||
5086 		    dst->state >= TCPS_CLOSING)
5087 			(*state)->timeout = PFTM_TCP_CLOSING;
5088 		else
5089 			(*state)->timeout = PFTM_TCP_ESTABLISHED;
5090 
5091 		/* Fall through to PASS packet */
5092 
5093 	} else if ((dst->state < TCPS_SYN_SENT ||
5094 		dst->state >= TCPS_FIN_WAIT_2 ||
5095 		src->state >= TCPS_FIN_WAIT_2) &&
5096 	    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
5097 	    /* Within a window forward of the originating packet */
5098 	    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
5099 	    /* Within a window backward of the originating packet */
5100 
5101 		/*
5102 		 * This currently handles three situations:
5103 		 *  1) Stupid stacks will shotgun SYNs before their peer
5104 		 *     replies.
5105 		 *  2) When PF catches an already established stream (the
5106 		 *     firewall rebooted, the state table was flushed, routes
5107 		 *     changed...)
5108 		 *  3) Packets get funky immediately after the connection
5109 		 *     closes (this should catch Solaris spurious ACK|FINs
5110 		 *     that web servers like to spew after a close)
5111 		 *
5112 		 * This must be a little more careful than the above code
5113 		 * since packet floods will also be caught here. We don't
5114 		 * update the TTL here to mitigate the damage of a packet
5115 		 * flood and so the same code can handle awkward establishment
5116 		 * and a loosened connection close.
5117 		 * In the establishment case, a correct peer response will
5118 		 * validate the connection, go through the normal state code
5119 		 * and keep updating the state TTL.
5120 		 */
5121 
5122 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
5123 			printf("pf: loose state match: ");
5124 			pf_print_state(*state);
5125 			pf_print_flags(th->th_flags);
5126 			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
5127 			    "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
5128 			    pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
5129 			    (unsigned long long)(*state)->packets[1],
5130 			    pd->dir == PF_IN ? "in" : "out",
5131 			    pd->dir == (*state)->direction ? "fwd" : "rev");
5132 		}
5133 
5134 		if (dst->scrub || src->scrub) {
5135 			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
5136 			    *state, src, dst, copyback))
5137 				return (PF_DROP);
5138 		}
5139 
5140 		/* update max window */
5141 		if (src->max_win < win)
5142 			src->max_win = win;
5143 		/* synchronize sequencing */
5144 		if (SEQ_GT(end, src->seqlo))
5145 			src->seqlo = end;
5146 		/* slide the window of what the other end can send */
5147 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
5148 			dst->seqhi = ack + MAX((win << sws), 1);
5149 
5150 		/*
5151 		 * Cannot set dst->seqhi here since this could be a shotgunned
5152 		 * SYN and not an already established connection.
5153 		 */
5154 
5155 		if (th->th_flags & TH_FIN)
5156 			if (src->state < TCPS_CLOSING)
5157 				pf_set_protostate(*state, psrc, TCPS_CLOSING);
5158 		if (th->th_flags & TH_RST)
5159 			pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
5160 
5161 		/* Fall through to PASS packet */
5162 
5163 	} else {
5164 		if ((*state)->dst.state == TCPS_SYN_SENT &&
5165 		    (*state)->src.state == TCPS_SYN_SENT) {
5166 			/* Send RST for state mismatches during handshake */
5167 			if (!(th->th_flags & TH_RST))
5168 				pf_send_tcp((*state)->rule.ptr, pd->af,
5169 				    pd->dst, pd->src, th->th_dport,
5170 				    th->th_sport, ntohl(th->th_ack), 0,
5171 				    TH_RST, 0, 0,
5172 				    (*state)->rule.ptr->return_ttl, 1, 0);
5173 			src->seqlo = 0;
5174 			src->seqhi = 1;
5175 			src->max_win = 1;
5176 		} else if (V_pf_status.debug >= PF_DEBUG_MISC) {
5177 			printf("pf: BAD state: ");
5178 			pf_print_state(*state);
5179 			pf_print_flags(th->th_flags);
5180 			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
5181 			    "pkts=%llu:%llu dir=%s,%s\n",
5182 			    seq, orig_seq, ack, pd->p_len, ackskew,
5183 			    (unsigned long long)(*state)->packets[0],
5184 			    (unsigned long long)(*state)->packets[1],
5185 			    pd->dir == PF_IN ? "in" : "out",
5186 			    pd->dir == (*state)->direction ? "fwd" : "rev");
5187 			printf("pf: State failure on: %c %c %c %c | %c %c\n",
5188 			    SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
5189 			    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
5190 			    ' ': '2',
5191 			    (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
5192 			    (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
5193 			    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
5194 			    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
5195 		}
5196 		REASON_SET(reason, PFRES_BADSTATE);
5197 		return (PF_DROP);
5198 	}
5199 
5200 	return (PF_PASS);
5201 }
5202 
5203 static int
5204 pf_tcp_track_sloppy(struct pf_kstate **state, struct pf_pdesc *pd, u_short *reason)
5205 {
5206 	struct tcphdr		*th = &pd->hdr.tcp;
5207 	struct pf_state_peer	*src, *dst;
5208 	u_int8_t		 psrc, pdst;
5209 
5210 	if (pd->dir == (*state)->direction) {
5211 		src = &(*state)->src;
5212 		dst = &(*state)->dst;
5213 		psrc = PF_PEER_SRC;
5214 		pdst = PF_PEER_DST;
5215 	} else {
5216 		src = &(*state)->dst;
5217 		dst = &(*state)->src;
5218 		psrc = PF_PEER_DST;
5219 		pdst = PF_PEER_SRC;
5220 	}
5221 
5222 	if (th->th_flags & TH_SYN)
5223 		if (src->state < TCPS_SYN_SENT)
5224 			pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
5225 	if (th->th_flags & TH_FIN)
5226 		if (src->state < TCPS_CLOSING)
5227 			pf_set_protostate(*state, psrc, TCPS_CLOSING);
5228 	if (th->th_flags & TH_ACK) {
5229 		if (dst->state == TCPS_SYN_SENT) {
5230 			pf_set_protostate(*state, pdst, TCPS_ESTABLISHED);
5231 			if (src->state == TCPS_ESTABLISHED &&
5232 			    (*state)->src_node != NULL &&
5233 			    pf_src_connlimit(state)) {
5234 				REASON_SET(reason, PFRES_SRCLIMIT);
5235 				return (PF_DROP);
5236 			}
5237 		} else if (dst->state == TCPS_CLOSING) {
5238 			pf_set_protostate(*state, pdst, TCPS_FIN_WAIT_2);
5239 		} else if (src->state == TCPS_SYN_SENT &&
5240 		    dst->state < TCPS_SYN_SENT) {
5241 			/*
5242 			 * Handle a special sloppy case where we only see one
5243 			 * half of the connection. If there is a ACK after
5244 			 * the initial SYN without ever seeing a packet from
5245 			 * the destination, set the connection to established.
5246 			 */
5247 			pf_set_protostate(*state, PF_PEER_BOTH,
5248 			    TCPS_ESTABLISHED);
5249 			dst->state = src->state = TCPS_ESTABLISHED;
5250 			if ((*state)->src_node != NULL &&
5251 			    pf_src_connlimit(state)) {
5252 				REASON_SET(reason, PFRES_SRCLIMIT);
5253 				return (PF_DROP);
5254 			}
5255 		} else if (src->state == TCPS_CLOSING &&
5256 		    dst->state == TCPS_ESTABLISHED &&
5257 		    dst->seqlo == 0) {
5258 			/*
5259 			 * Handle the closing of half connections where we
5260 			 * don't see the full bidirectional FIN/ACK+ACK
5261 			 * handshake.
5262 			 */
5263 			pf_set_protostate(*state, pdst, TCPS_CLOSING);
5264 		}
5265 	}
5266 	if (th->th_flags & TH_RST)
5267 		pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
5268 
5269 	/* update expire time */
5270 	(*state)->expire = time_uptime;
5271 	if (src->state >= TCPS_FIN_WAIT_2 &&
5272 	    dst->state >= TCPS_FIN_WAIT_2)
5273 		(*state)->timeout = PFTM_TCP_CLOSED;
5274 	else if (src->state >= TCPS_CLOSING &&
5275 	    dst->state >= TCPS_CLOSING)
5276 		(*state)->timeout = PFTM_TCP_FIN_WAIT;
5277 	else if (src->state < TCPS_ESTABLISHED ||
5278 	    dst->state < TCPS_ESTABLISHED)
5279 		(*state)->timeout = PFTM_TCP_OPENING;
5280 	else if (src->state >= TCPS_CLOSING ||
5281 	    dst->state >= TCPS_CLOSING)
5282 		(*state)->timeout = PFTM_TCP_CLOSING;
5283 	else
5284 		(*state)->timeout = PFTM_TCP_ESTABLISHED;
5285 
5286 	return (PF_PASS);
5287 }
5288 
5289 static int
5290 pf_synproxy(struct pf_pdesc *pd, struct pf_kstate **state, u_short *reason)
5291 {
5292 	struct pf_state_key	*sk = (*state)->key[pd->didx];
5293 	struct tcphdr		*th = &pd->hdr.tcp;
5294 
5295 	if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
5296 		if (pd->dir != (*state)->direction) {
5297 			REASON_SET(reason, PFRES_SYNPROXY);
5298 			return (PF_SYNPROXY_DROP);
5299 		}
5300 		if (th->th_flags & TH_SYN) {
5301 			if (ntohl(th->th_seq) != (*state)->src.seqlo) {
5302 				REASON_SET(reason, PFRES_SYNPROXY);
5303 				return (PF_DROP);
5304 			}
5305 			pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
5306 			    pd->src, th->th_dport, th->th_sport,
5307 			    (*state)->src.seqhi, ntohl(th->th_seq) + 1,
5308 			    TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0);
5309 			REASON_SET(reason, PFRES_SYNPROXY);
5310 			return (PF_SYNPROXY_DROP);
5311 		} else if ((th->th_flags & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
5312 		    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
5313 		    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
5314 			REASON_SET(reason, PFRES_SYNPROXY);
5315 			return (PF_DROP);
5316 		} else if ((*state)->src_node != NULL &&
5317 		    pf_src_connlimit(state)) {
5318 			REASON_SET(reason, PFRES_SRCLIMIT);
5319 			return (PF_DROP);
5320 		} else
5321 			pf_set_protostate(*state, PF_PEER_SRC,
5322 			    PF_TCPS_PROXY_DST);
5323 	}
5324 	if ((*state)->src.state == PF_TCPS_PROXY_DST) {
5325 		if (pd->dir == (*state)->direction) {
5326 			if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
5327 			    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
5328 			    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
5329 				REASON_SET(reason, PFRES_SYNPROXY);
5330 				return (PF_DROP);
5331 			}
5332 			(*state)->src.max_win = MAX(ntohs(th->th_win), 1);
5333 			if ((*state)->dst.seqhi == 1)
5334 				(*state)->dst.seqhi = htonl(arc4random());
5335 			pf_send_tcp((*state)->rule.ptr, pd->af,
5336 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
5337 			    sk->port[pd->sidx], sk->port[pd->didx],
5338 			    (*state)->dst.seqhi, 0, TH_SYN, 0,
5339 			    (*state)->src.mss, 0, 0, (*state)->tag);
5340 			REASON_SET(reason, PFRES_SYNPROXY);
5341 			return (PF_SYNPROXY_DROP);
5342 		} else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
5343 		    (TH_SYN|TH_ACK)) ||
5344 		    (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
5345 			REASON_SET(reason, PFRES_SYNPROXY);
5346 			return (PF_DROP);
5347 		} else {
5348 			(*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
5349 			(*state)->dst.seqlo = ntohl(th->th_seq);
5350 			pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
5351 			    pd->src, th->th_dport, th->th_sport,
5352 			    ntohl(th->th_ack), ntohl(th->th_seq) + 1,
5353 			    TH_ACK, (*state)->src.max_win, 0, 0, 0,
5354 			    (*state)->tag);
5355 			pf_send_tcp((*state)->rule.ptr, pd->af,
5356 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
5357 			    sk->port[pd->sidx], sk->port[pd->didx],
5358 			    (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
5359 			    TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0);
5360 			(*state)->src.seqdiff = (*state)->dst.seqhi -
5361 			    (*state)->src.seqlo;
5362 			(*state)->dst.seqdiff = (*state)->src.seqhi -
5363 			    (*state)->dst.seqlo;
5364 			(*state)->src.seqhi = (*state)->src.seqlo +
5365 			    (*state)->dst.max_win;
5366 			(*state)->dst.seqhi = (*state)->dst.seqlo +
5367 			    (*state)->src.max_win;
5368 			(*state)->src.wscale = (*state)->dst.wscale = 0;
5369 			pf_set_protostate(*state, PF_PEER_BOTH,
5370 			    TCPS_ESTABLISHED);
5371 			REASON_SET(reason, PFRES_SYNPROXY);
5372 			return (PF_SYNPROXY_DROP);
5373 		}
5374 	}
5375 
5376 	return (PF_PASS);
5377 }
5378 
5379 static int
5380 pf_test_state_tcp(struct pf_kstate **state, int direction, struct pfi_kkif *kif,
5381     struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
5382     u_short *reason)
5383 {
5384 	struct pf_state_key_cmp	 key;
5385 	struct tcphdr		*th = &pd->hdr.tcp;
5386 	int			 copyback = 0;
5387 	int			 action;
5388 	struct pf_state_peer	*src, *dst;
5389 
5390 	bzero(&key, sizeof(key));
5391 	key.af = pd->af;
5392 	key.proto = IPPROTO_TCP;
5393 	if (direction == PF_IN)	{	/* wire side, straight */
5394 		PF_ACPY(&key.addr[0], pd->src, key.af);
5395 		PF_ACPY(&key.addr[1], pd->dst, key.af);
5396 		key.port[0] = th->th_sport;
5397 		key.port[1] = th->th_dport;
5398 	} else {			/* stack side, reverse */
5399 		PF_ACPY(&key.addr[1], pd->src, key.af);
5400 		PF_ACPY(&key.addr[0], pd->dst, key.af);
5401 		key.port[1] = th->th_sport;
5402 		key.port[0] = th->th_dport;
5403 	}
5404 
5405 	STATE_LOOKUP(kif, &key, direction, *state, pd);
5406 
5407 	if (direction == (*state)->direction) {
5408 		src = &(*state)->src;
5409 		dst = &(*state)->dst;
5410 	} else {
5411 		src = &(*state)->dst;
5412 		dst = &(*state)->src;
5413 	}
5414 
5415 	if ((action = pf_synproxy(pd, state, reason)) != PF_PASS)
5416 		return (action);
5417 
5418 	if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
5419 	    dst->state >= TCPS_FIN_WAIT_2 &&
5420 	    src->state >= TCPS_FIN_WAIT_2) {
5421 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
5422 			printf("pf: state reuse ");
5423 			pf_print_state(*state);
5424 			pf_print_flags(th->th_flags);
5425 			printf("\n");
5426 		}
5427 		/* XXX make sure it's the same direction ?? */
5428 		pf_set_protostate(*state, PF_PEER_BOTH, TCPS_CLOSED);
5429 		pf_unlink_state(*state);
5430 		*state = NULL;
5431 		return (PF_DROP);
5432 	}
5433 
5434 	if ((*state)->state_flags & PFSTATE_SLOPPY) {
5435 		if (pf_tcp_track_sloppy(state, pd, reason) == PF_DROP)
5436 			return (PF_DROP);
5437 	} else {
5438 		if (pf_tcp_track_full(state, kif, m, off, pd, reason,
5439 		    &copyback) == PF_DROP)
5440 			return (PF_DROP);
5441 	}
5442 
5443 	/* translate source/destination address, if necessary */
5444 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5445 		struct pf_state_key *nk = (*state)->key[pd->didx];
5446 
5447 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
5448 		    nk->port[pd->sidx] != th->th_sport)
5449 			pf_change_ap(m, pd->src, &th->th_sport,
5450 			    pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
5451 			    nk->port[pd->sidx], 0, pd->af);
5452 
5453 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
5454 		    nk->port[pd->didx] != th->th_dport)
5455 			pf_change_ap(m, pd->dst, &th->th_dport,
5456 			    pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
5457 			    nk->port[pd->didx], 0, pd->af);
5458 		copyback = 1;
5459 	}
5460 
5461 	/* Copyback sequence modulation or stateful scrub changes if needed */
5462 	if (copyback)
5463 		m_copyback(m, off, sizeof(*th), (caddr_t)th);
5464 
5465 	return (PF_PASS);
5466 }
5467 
5468 static int
5469 pf_test_state_udp(struct pf_kstate **state, int direction, struct pfi_kkif *kif,
5470     struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
5471 {
5472 	struct pf_state_peer	*src, *dst;
5473 	struct pf_state_key_cmp	 key;
5474 	struct udphdr		*uh = &pd->hdr.udp;
5475 	uint8_t			 psrc, pdst;
5476 
5477 	bzero(&key, sizeof(key));
5478 	key.af = pd->af;
5479 	key.proto = IPPROTO_UDP;
5480 	if (direction == PF_IN)	{	/* wire side, straight */
5481 		PF_ACPY(&key.addr[0], pd->src, key.af);
5482 		PF_ACPY(&key.addr[1], pd->dst, key.af);
5483 		key.port[0] = uh->uh_sport;
5484 		key.port[1] = uh->uh_dport;
5485 	} else {			/* stack side, reverse */
5486 		PF_ACPY(&key.addr[1], pd->src, key.af);
5487 		PF_ACPY(&key.addr[0], pd->dst, key.af);
5488 		key.port[1] = uh->uh_sport;
5489 		key.port[0] = uh->uh_dport;
5490 	}
5491 
5492 	STATE_LOOKUP(kif, &key, direction, *state, pd);
5493 
5494 	if (direction == (*state)->direction) {
5495 		src = &(*state)->src;
5496 		dst = &(*state)->dst;
5497 		psrc = PF_PEER_SRC;
5498 		pdst = PF_PEER_DST;
5499 	} else {
5500 		src = &(*state)->dst;
5501 		dst = &(*state)->src;
5502 		psrc = PF_PEER_DST;
5503 		pdst = PF_PEER_SRC;
5504 	}
5505 
5506 	/* update states */
5507 	if (src->state < PFUDPS_SINGLE)
5508 		pf_set_protostate(*state, psrc, PFUDPS_SINGLE);
5509 	if (dst->state == PFUDPS_SINGLE)
5510 		pf_set_protostate(*state, pdst, PFUDPS_MULTIPLE);
5511 
5512 	/* update expire time */
5513 	(*state)->expire = time_uptime;
5514 	if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
5515 		(*state)->timeout = PFTM_UDP_MULTIPLE;
5516 	else
5517 		(*state)->timeout = PFTM_UDP_SINGLE;
5518 
5519 	/* translate source/destination address, if necessary */
5520 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5521 		struct pf_state_key *nk = (*state)->key[pd->didx];
5522 
5523 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
5524 		    nk->port[pd->sidx] != uh->uh_sport)
5525 			pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
5526 			    &uh->uh_sum, &nk->addr[pd->sidx],
5527 			    nk->port[pd->sidx], 1, pd->af);
5528 
5529 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
5530 		    nk->port[pd->didx] != uh->uh_dport)
5531 			pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
5532 			    &uh->uh_sum, &nk->addr[pd->didx],
5533 			    nk->port[pd->didx], 1, pd->af);
5534 		m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
5535 	}
5536 
5537 	return (PF_PASS);
5538 }
5539 
5540 static int
5541 pf_test_state_icmp(struct pf_kstate **state, int direction, struct pfi_kkif *kif,
5542     struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
5543 {
5544 	struct pf_addr  *saddr = pd->src, *daddr = pd->dst;
5545 	u_int16_t	 icmpid = 0, *icmpsum;
5546 	u_int8_t	 icmptype, icmpcode;
5547 	int		 state_icmp = 0;
5548 	struct pf_state_key_cmp key;
5549 
5550 	bzero(&key, sizeof(key));
5551 	switch (pd->proto) {
5552 #ifdef INET
5553 	case IPPROTO_ICMP:
5554 		icmptype = pd->hdr.icmp.icmp_type;
5555 		icmpcode = pd->hdr.icmp.icmp_code;
5556 		icmpid = pd->hdr.icmp.icmp_id;
5557 		icmpsum = &pd->hdr.icmp.icmp_cksum;
5558 
5559 		if (icmptype == ICMP_UNREACH ||
5560 		    icmptype == ICMP_SOURCEQUENCH ||
5561 		    icmptype == ICMP_REDIRECT ||
5562 		    icmptype == ICMP_TIMXCEED ||
5563 		    icmptype == ICMP_PARAMPROB)
5564 			state_icmp++;
5565 		break;
5566 #endif /* INET */
5567 #ifdef INET6
5568 	case IPPROTO_ICMPV6:
5569 		icmptype = pd->hdr.icmp6.icmp6_type;
5570 		icmpcode = pd->hdr.icmp6.icmp6_code;
5571 		icmpid = pd->hdr.icmp6.icmp6_id;
5572 		icmpsum = &pd->hdr.icmp6.icmp6_cksum;
5573 
5574 		if (icmptype == ICMP6_DST_UNREACH ||
5575 		    icmptype == ICMP6_PACKET_TOO_BIG ||
5576 		    icmptype == ICMP6_TIME_EXCEEDED ||
5577 		    icmptype == ICMP6_PARAM_PROB)
5578 			state_icmp++;
5579 		break;
5580 #endif /* INET6 */
5581 	}
5582 
5583 	if (!state_icmp) {
5584 		/*
5585 		 * ICMP query/reply message not related to a TCP/UDP packet.
5586 		 * Search for an ICMP state.
5587 		 */
5588 		key.af = pd->af;
5589 		key.proto = pd->proto;
5590 		key.port[0] = key.port[1] = icmpid;
5591 		if (direction == PF_IN)	{	/* wire side, straight */
5592 			PF_ACPY(&key.addr[0], pd->src, key.af);
5593 			PF_ACPY(&key.addr[1], pd->dst, key.af);
5594 		} else {			/* stack side, reverse */
5595 			PF_ACPY(&key.addr[1], pd->src, key.af);
5596 			PF_ACPY(&key.addr[0], pd->dst, key.af);
5597 		}
5598 
5599 		STATE_LOOKUP(kif, &key, direction, *state, pd);
5600 
5601 		(*state)->expire = time_uptime;
5602 		(*state)->timeout = PFTM_ICMP_ERROR_REPLY;
5603 
5604 		/* translate source/destination address, if necessary */
5605 		if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5606 			struct pf_state_key *nk = (*state)->key[pd->didx];
5607 
5608 			switch (pd->af) {
5609 #ifdef INET
5610 			case AF_INET:
5611 				if (PF_ANEQ(pd->src,
5612 				    &nk->addr[pd->sidx], AF_INET))
5613 					pf_change_a(&saddr->v4.s_addr,
5614 					    pd->ip_sum,
5615 					    nk->addr[pd->sidx].v4.s_addr, 0);
5616 
5617 				if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
5618 				    AF_INET))
5619 					pf_change_a(&daddr->v4.s_addr,
5620 					    pd->ip_sum,
5621 					    nk->addr[pd->didx].v4.s_addr, 0);
5622 
5623 				if (nk->port[0] !=
5624 				    pd->hdr.icmp.icmp_id) {
5625 					pd->hdr.icmp.icmp_cksum =
5626 					    pf_cksum_fixup(
5627 					    pd->hdr.icmp.icmp_cksum, icmpid,
5628 					    nk->port[pd->sidx], 0);
5629 					pd->hdr.icmp.icmp_id =
5630 					    nk->port[pd->sidx];
5631 				}
5632 
5633 				m_copyback(m, off, ICMP_MINLEN,
5634 				    (caddr_t )&pd->hdr.icmp);
5635 				break;
5636 #endif /* INET */
5637 #ifdef INET6
5638 			case AF_INET6:
5639 				if (PF_ANEQ(pd->src,
5640 				    &nk->addr[pd->sidx], AF_INET6))
5641 					pf_change_a6(saddr,
5642 					    &pd->hdr.icmp6.icmp6_cksum,
5643 					    &nk->addr[pd->sidx], 0);
5644 
5645 				if (PF_ANEQ(pd->dst,
5646 				    &nk->addr[pd->didx], AF_INET6))
5647 					pf_change_a6(daddr,
5648 					    &pd->hdr.icmp6.icmp6_cksum,
5649 					    &nk->addr[pd->didx], 0);
5650 
5651 				m_copyback(m, off, sizeof(struct icmp6_hdr),
5652 				    (caddr_t )&pd->hdr.icmp6);
5653 				break;
5654 #endif /* INET6 */
5655 			}
5656 		}
5657 		return (PF_PASS);
5658 
5659 	} else {
5660 		/*
5661 		 * ICMP error message in response to a TCP/UDP packet.
5662 		 * Extract the inner TCP/UDP header and search for that state.
5663 		 */
5664 
5665 		struct pf_pdesc	pd2;
5666 		bzero(&pd2, sizeof pd2);
5667 #ifdef INET
5668 		struct ip	h2;
5669 #endif /* INET */
5670 #ifdef INET6
5671 		struct ip6_hdr	h2_6;
5672 		int		terminal = 0;
5673 #endif /* INET6 */
5674 		int		ipoff2 = 0;
5675 		int		off2 = 0;
5676 
5677 		pd2.af = pd->af;
5678 		/* Payload packet is from the opposite direction. */
5679 		pd2.sidx = (direction == PF_IN) ? 1 : 0;
5680 		pd2.didx = (direction == PF_IN) ? 0 : 1;
5681 		switch (pd->af) {
5682 #ifdef INET
5683 		case AF_INET:
5684 			/* offset of h2 in mbuf chain */
5685 			ipoff2 = off + ICMP_MINLEN;
5686 
5687 			if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
5688 			    NULL, reason, pd2.af)) {
5689 				DPFPRINTF(PF_DEBUG_MISC,
5690 				    ("pf: ICMP error message too short "
5691 				    "(ip)\n"));
5692 				return (PF_DROP);
5693 			}
5694 			/*
5695 			 * ICMP error messages don't refer to non-first
5696 			 * fragments
5697 			 */
5698 			if (h2.ip_off & htons(IP_OFFMASK)) {
5699 				REASON_SET(reason, PFRES_FRAG);
5700 				return (PF_DROP);
5701 			}
5702 
5703 			/* offset of protocol header that follows h2 */
5704 			off2 = ipoff2 + (h2.ip_hl << 2);
5705 
5706 			pd2.proto = h2.ip_p;
5707 			pd2.src = (struct pf_addr *)&h2.ip_src;
5708 			pd2.dst = (struct pf_addr *)&h2.ip_dst;
5709 			pd2.ip_sum = &h2.ip_sum;
5710 			break;
5711 #endif /* INET */
5712 #ifdef INET6
5713 		case AF_INET6:
5714 			ipoff2 = off + sizeof(struct icmp6_hdr);
5715 
5716 			if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
5717 			    NULL, reason, pd2.af)) {
5718 				DPFPRINTF(PF_DEBUG_MISC,
5719 				    ("pf: ICMP error message too short "
5720 				    "(ip6)\n"));
5721 				return (PF_DROP);
5722 			}
5723 			pd2.proto = h2_6.ip6_nxt;
5724 			pd2.src = (struct pf_addr *)&h2_6.ip6_src;
5725 			pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
5726 			pd2.ip_sum = NULL;
5727 			off2 = ipoff2 + sizeof(h2_6);
5728 			do {
5729 				switch (pd2.proto) {
5730 				case IPPROTO_FRAGMENT:
5731 					/*
5732 					 * ICMPv6 error messages for
5733 					 * non-first fragments
5734 					 */
5735 					REASON_SET(reason, PFRES_FRAG);
5736 					return (PF_DROP);
5737 				case IPPROTO_AH:
5738 				case IPPROTO_HOPOPTS:
5739 				case IPPROTO_ROUTING:
5740 				case IPPROTO_DSTOPTS: {
5741 					/* get next header and header length */
5742 					struct ip6_ext opt6;
5743 
5744 					if (!pf_pull_hdr(m, off2, &opt6,
5745 					    sizeof(opt6), NULL, reason,
5746 					    pd2.af)) {
5747 						DPFPRINTF(PF_DEBUG_MISC,
5748 						    ("pf: ICMPv6 short opt\n"));
5749 						return (PF_DROP);
5750 					}
5751 					if (pd2.proto == IPPROTO_AH)
5752 						off2 += (opt6.ip6e_len + 2) * 4;
5753 					else
5754 						off2 += (opt6.ip6e_len + 1) * 8;
5755 					pd2.proto = opt6.ip6e_nxt;
5756 					/* goto the next header */
5757 					break;
5758 				}
5759 				default:
5760 					terminal++;
5761 					break;
5762 				}
5763 			} while (!terminal);
5764 			break;
5765 #endif /* INET6 */
5766 		}
5767 
5768 		if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
5769 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
5770 				printf("pf: BAD ICMP %d:%d outer dst: ",
5771 				    icmptype, icmpcode);
5772 				pf_print_host(pd->src, 0, pd->af);
5773 				printf(" -> ");
5774 				pf_print_host(pd->dst, 0, pd->af);
5775 				printf(" inner src: ");
5776 				pf_print_host(pd2.src, 0, pd2.af);
5777 				printf(" -> ");
5778 				pf_print_host(pd2.dst, 0, pd2.af);
5779 				printf("\n");
5780 			}
5781 			REASON_SET(reason, PFRES_BADSTATE);
5782 			return (PF_DROP);
5783 		}
5784 
5785 		switch (pd2.proto) {
5786 		case IPPROTO_TCP: {
5787 			struct tcphdr		 th;
5788 			u_int32_t		 seq;
5789 			struct pf_state_peer	*src, *dst;
5790 			u_int8_t		 dws;
5791 			int			 copyback = 0;
5792 
5793 			/*
5794 			 * Only the first 8 bytes of the TCP header can be
5795 			 * expected. Don't access any TCP header fields after
5796 			 * th_seq, an ackskew test is not possible.
5797 			 */
5798 			if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
5799 			    pd2.af)) {
5800 				DPFPRINTF(PF_DEBUG_MISC,
5801 				    ("pf: ICMP error message too short "
5802 				    "(tcp)\n"));
5803 				return (PF_DROP);
5804 			}
5805 
5806 			key.af = pd2.af;
5807 			key.proto = IPPROTO_TCP;
5808 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5809 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5810 			key.port[pd2.sidx] = th.th_sport;
5811 			key.port[pd2.didx] = th.th_dport;
5812 
5813 			STATE_LOOKUP(kif, &key, direction, *state, pd);
5814 
5815 			if (direction == (*state)->direction) {
5816 				src = &(*state)->dst;
5817 				dst = &(*state)->src;
5818 			} else {
5819 				src = &(*state)->src;
5820 				dst = &(*state)->dst;
5821 			}
5822 
5823 			if (src->wscale && dst->wscale)
5824 				dws = dst->wscale & PF_WSCALE_MASK;
5825 			else
5826 				dws = 0;
5827 
5828 			/* Demodulate sequence number */
5829 			seq = ntohl(th.th_seq) - src->seqdiff;
5830 			if (src->seqdiff) {
5831 				pf_change_a(&th.th_seq, icmpsum,
5832 				    htonl(seq), 0);
5833 				copyback = 1;
5834 			}
5835 
5836 			if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
5837 			    (!SEQ_GEQ(src->seqhi, seq) ||
5838 			    !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
5839 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
5840 					printf("pf: BAD ICMP %d:%d ",
5841 					    icmptype, icmpcode);
5842 					pf_print_host(pd->src, 0, pd->af);
5843 					printf(" -> ");
5844 					pf_print_host(pd->dst, 0, pd->af);
5845 					printf(" state: ");
5846 					pf_print_state(*state);
5847 					printf(" seq=%u\n", seq);
5848 				}
5849 				REASON_SET(reason, PFRES_BADSTATE);
5850 				return (PF_DROP);
5851 			} else {
5852 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
5853 					printf("pf: OK ICMP %d:%d ",
5854 					    icmptype, icmpcode);
5855 					pf_print_host(pd->src, 0, pd->af);
5856 					printf(" -> ");
5857 					pf_print_host(pd->dst, 0, pd->af);
5858 					printf(" state: ");
5859 					pf_print_state(*state);
5860 					printf(" seq=%u\n", seq);
5861 				}
5862 			}
5863 
5864 			/* translate source/destination address, if necessary */
5865 			if ((*state)->key[PF_SK_WIRE] !=
5866 			    (*state)->key[PF_SK_STACK]) {
5867 				struct pf_state_key *nk =
5868 				    (*state)->key[pd->didx];
5869 
5870 				if (PF_ANEQ(pd2.src,
5871 				    &nk->addr[pd2.sidx], pd2.af) ||
5872 				    nk->port[pd2.sidx] != th.th_sport)
5873 					pf_change_icmp(pd2.src, &th.th_sport,
5874 					    daddr, &nk->addr[pd2.sidx],
5875 					    nk->port[pd2.sidx], NULL,
5876 					    pd2.ip_sum, icmpsum,
5877 					    pd->ip_sum, 0, pd2.af);
5878 
5879 				if (PF_ANEQ(pd2.dst,
5880 				    &nk->addr[pd2.didx], pd2.af) ||
5881 				    nk->port[pd2.didx] != th.th_dport)
5882 					pf_change_icmp(pd2.dst, &th.th_dport,
5883 					    saddr, &nk->addr[pd2.didx],
5884 					    nk->port[pd2.didx], NULL,
5885 					    pd2.ip_sum, icmpsum,
5886 					    pd->ip_sum, 0, pd2.af);
5887 				copyback = 1;
5888 			}
5889 
5890 			if (copyback) {
5891 				switch (pd2.af) {
5892 #ifdef INET
5893 				case AF_INET:
5894 					m_copyback(m, off, ICMP_MINLEN,
5895 					    (caddr_t )&pd->hdr.icmp);
5896 					m_copyback(m, ipoff2, sizeof(h2),
5897 					    (caddr_t )&h2);
5898 					break;
5899 #endif /* INET */
5900 #ifdef INET6
5901 				case AF_INET6:
5902 					m_copyback(m, off,
5903 					    sizeof(struct icmp6_hdr),
5904 					    (caddr_t )&pd->hdr.icmp6);
5905 					m_copyback(m, ipoff2, sizeof(h2_6),
5906 					    (caddr_t )&h2_6);
5907 					break;
5908 #endif /* INET6 */
5909 				}
5910 				m_copyback(m, off2, 8, (caddr_t)&th);
5911 			}
5912 
5913 			return (PF_PASS);
5914 			break;
5915 		}
5916 		case IPPROTO_UDP: {
5917 			struct udphdr		uh;
5918 
5919 			if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
5920 			    NULL, reason, pd2.af)) {
5921 				DPFPRINTF(PF_DEBUG_MISC,
5922 				    ("pf: ICMP error message too short "
5923 				    "(udp)\n"));
5924 				return (PF_DROP);
5925 			}
5926 
5927 			key.af = pd2.af;
5928 			key.proto = IPPROTO_UDP;
5929 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5930 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5931 			key.port[pd2.sidx] = uh.uh_sport;
5932 			key.port[pd2.didx] = uh.uh_dport;
5933 
5934 			STATE_LOOKUP(kif, &key, direction, *state, pd);
5935 
5936 			/* translate source/destination address, if necessary */
5937 			if ((*state)->key[PF_SK_WIRE] !=
5938 			    (*state)->key[PF_SK_STACK]) {
5939 				struct pf_state_key *nk =
5940 				    (*state)->key[pd->didx];
5941 
5942 				if (PF_ANEQ(pd2.src,
5943 				    &nk->addr[pd2.sidx], pd2.af) ||
5944 				    nk->port[pd2.sidx] != uh.uh_sport)
5945 					pf_change_icmp(pd2.src, &uh.uh_sport,
5946 					    daddr, &nk->addr[pd2.sidx],
5947 					    nk->port[pd2.sidx], &uh.uh_sum,
5948 					    pd2.ip_sum, icmpsum,
5949 					    pd->ip_sum, 1, pd2.af);
5950 
5951 				if (PF_ANEQ(pd2.dst,
5952 				    &nk->addr[pd2.didx], pd2.af) ||
5953 				    nk->port[pd2.didx] != uh.uh_dport)
5954 					pf_change_icmp(pd2.dst, &uh.uh_dport,
5955 					    saddr, &nk->addr[pd2.didx],
5956 					    nk->port[pd2.didx], &uh.uh_sum,
5957 					    pd2.ip_sum, icmpsum,
5958 					    pd->ip_sum, 1, pd2.af);
5959 
5960 				switch (pd2.af) {
5961 #ifdef INET
5962 				case AF_INET:
5963 					m_copyback(m, off, ICMP_MINLEN,
5964 					    (caddr_t )&pd->hdr.icmp);
5965 					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5966 					break;
5967 #endif /* INET */
5968 #ifdef INET6
5969 				case AF_INET6:
5970 					m_copyback(m, off,
5971 					    sizeof(struct icmp6_hdr),
5972 					    (caddr_t )&pd->hdr.icmp6);
5973 					m_copyback(m, ipoff2, sizeof(h2_6),
5974 					    (caddr_t )&h2_6);
5975 					break;
5976 #endif /* INET6 */
5977 				}
5978 				m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5979 			}
5980 			return (PF_PASS);
5981 			break;
5982 		}
5983 #ifdef INET
5984 		case IPPROTO_ICMP: {
5985 			struct icmp		iih;
5986 
5987 			if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5988 			    NULL, reason, pd2.af)) {
5989 				DPFPRINTF(PF_DEBUG_MISC,
5990 				    ("pf: ICMP error message too short i"
5991 				    "(icmp)\n"));
5992 				return (PF_DROP);
5993 			}
5994 
5995 			key.af = pd2.af;
5996 			key.proto = IPPROTO_ICMP;
5997 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5998 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5999 			key.port[0] = key.port[1] = iih.icmp_id;
6000 
6001 			STATE_LOOKUP(kif, &key, direction, *state, pd);
6002 
6003 			/* translate source/destination address, if necessary */
6004 			if ((*state)->key[PF_SK_WIRE] !=
6005 			    (*state)->key[PF_SK_STACK]) {
6006 				struct pf_state_key *nk =
6007 				    (*state)->key[pd->didx];
6008 
6009 				if (PF_ANEQ(pd2.src,
6010 				    &nk->addr[pd2.sidx], pd2.af) ||
6011 				    nk->port[pd2.sidx] != iih.icmp_id)
6012 					pf_change_icmp(pd2.src, &iih.icmp_id,
6013 					    daddr, &nk->addr[pd2.sidx],
6014 					    nk->port[pd2.sidx], NULL,
6015 					    pd2.ip_sum, icmpsum,
6016 					    pd->ip_sum, 0, AF_INET);
6017 
6018 				if (PF_ANEQ(pd2.dst,
6019 				    &nk->addr[pd2.didx], pd2.af) ||
6020 				    nk->port[pd2.didx] != iih.icmp_id)
6021 					pf_change_icmp(pd2.dst, &iih.icmp_id,
6022 					    saddr, &nk->addr[pd2.didx],
6023 					    nk->port[pd2.didx], NULL,
6024 					    pd2.ip_sum, icmpsum,
6025 					    pd->ip_sum, 0, AF_INET);
6026 
6027 				m_copyback(m, off, ICMP_MINLEN, (caddr_t)&pd->hdr.icmp);
6028 				m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
6029 				m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
6030 			}
6031 			return (PF_PASS);
6032 			break;
6033 		}
6034 #endif /* INET */
6035 #ifdef INET6
6036 		case IPPROTO_ICMPV6: {
6037 			struct icmp6_hdr	iih;
6038 
6039 			if (!pf_pull_hdr(m, off2, &iih,
6040 			    sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
6041 				DPFPRINTF(PF_DEBUG_MISC,
6042 				    ("pf: ICMP error message too short "
6043 				    "(icmp6)\n"));
6044 				return (PF_DROP);
6045 			}
6046 
6047 			key.af = pd2.af;
6048 			key.proto = IPPROTO_ICMPV6;
6049 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
6050 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
6051 			key.port[0] = key.port[1] = iih.icmp6_id;
6052 
6053 			STATE_LOOKUP(kif, &key, direction, *state, pd);
6054 
6055 			/* translate source/destination address, if necessary */
6056 			if ((*state)->key[PF_SK_WIRE] !=
6057 			    (*state)->key[PF_SK_STACK]) {
6058 				struct pf_state_key *nk =
6059 				    (*state)->key[pd->didx];
6060 
6061 				if (PF_ANEQ(pd2.src,
6062 				    &nk->addr[pd2.sidx], pd2.af) ||
6063 				    nk->port[pd2.sidx] != iih.icmp6_id)
6064 					pf_change_icmp(pd2.src, &iih.icmp6_id,
6065 					    daddr, &nk->addr[pd2.sidx],
6066 					    nk->port[pd2.sidx], NULL,
6067 					    pd2.ip_sum, icmpsum,
6068 					    pd->ip_sum, 0, AF_INET6);
6069 
6070 				if (PF_ANEQ(pd2.dst,
6071 				    &nk->addr[pd2.didx], pd2.af) ||
6072 				    nk->port[pd2.didx] != iih.icmp6_id)
6073 					pf_change_icmp(pd2.dst, &iih.icmp6_id,
6074 					    saddr, &nk->addr[pd2.didx],
6075 					    nk->port[pd2.didx], NULL,
6076 					    pd2.ip_sum, icmpsum,
6077 					    pd->ip_sum, 0, AF_INET6);
6078 
6079 				m_copyback(m, off, sizeof(struct icmp6_hdr),
6080 				    (caddr_t)&pd->hdr.icmp6);
6081 				m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
6082 				m_copyback(m, off2, sizeof(struct icmp6_hdr),
6083 				    (caddr_t)&iih);
6084 			}
6085 			return (PF_PASS);
6086 			break;
6087 		}
6088 #endif /* INET6 */
6089 		default: {
6090 			key.af = pd2.af;
6091 			key.proto = pd2.proto;
6092 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
6093 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
6094 			key.port[0] = key.port[1] = 0;
6095 
6096 			STATE_LOOKUP(kif, &key, direction, *state, pd);
6097 
6098 			/* translate source/destination address, if necessary */
6099 			if ((*state)->key[PF_SK_WIRE] !=
6100 			    (*state)->key[PF_SK_STACK]) {
6101 				struct pf_state_key *nk =
6102 				    (*state)->key[pd->didx];
6103 
6104 				if (PF_ANEQ(pd2.src,
6105 				    &nk->addr[pd2.sidx], pd2.af))
6106 					pf_change_icmp(pd2.src, NULL, daddr,
6107 					    &nk->addr[pd2.sidx], 0, NULL,
6108 					    pd2.ip_sum, icmpsum,
6109 					    pd->ip_sum, 0, pd2.af);
6110 
6111 				if (PF_ANEQ(pd2.dst,
6112 				    &nk->addr[pd2.didx], pd2.af))
6113 					pf_change_icmp(pd2.dst, NULL, saddr,
6114 					    &nk->addr[pd2.didx], 0, NULL,
6115 					    pd2.ip_sum, icmpsum,
6116 					    pd->ip_sum, 0, pd2.af);
6117 
6118 				switch (pd2.af) {
6119 #ifdef INET
6120 				case AF_INET:
6121 					m_copyback(m, off, ICMP_MINLEN,
6122 					    (caddr_t)&pd->hdr.icmp);
6123 					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
6124 					break;
6125 #endif /* INET */
6126 #ifdef INET6
6127 				case AF_INET6:
6128 					m_copyback(m, off,
6129 					    sizeof(struct icmp6_hdr),
6130 					    (caddr_t )&pd->hdr.icmp6);
6131 					m_copyback(m, ipoff2, sizeof(h2_6),
6132 					    (caddr_t )&h2_6);
6133 					break;
6134 #endif /* INET6 */
6135 				}
6136 			}
6137 			return (PF_PASS);
6138 			break;
6139 		}
6140 		}
6141 	}
6142 }
6143 
6144 static int
6145 pf_test_state_other(struct pf_kstate **state, int direction, struct pfi_kkif *kif,
6146     struct mbuf *m, struct pf_pdesc *pd)
6147 {
6148 	struct pf_state_peer	*src, *dst;
6149 	struct pf_state_key_cmp	 key;
6150 	uint8_t			 psrc, pdst;
6151 
6152 	bzero(&key, sizeof(key));
6153 	key.af = pd->af;
6154 	key.proto = pd->proto;
6155 	if (direction == PF_IN)	{
6156 		PF_ACPY(&key.addr[0], pd->src, key.af);
6157 		PF_ACPY(&key.addr[1], pd->dst, key.af);
6158 		key.port[0] = key.port[1] = 0;
6159 	} else {
6160 		PF_ACPY(&key.addr[1], pd->src, key.af);
6161 		PF_ACPY(&key.addr[0], pd->dst, key.af);
6162 		key.port[1] = key.port[0] = 0;
6163 	}
6164 
6165 	STATE_LOOKUP(kif, &key, direction, *state, pd);
6166 
6167 	if (direction == (*state)->direction) {
6168 		src = &(*state)->src;
6169 		dst = &(*state)->dst;
6170 		psrc = PF_PEER_SRC;
6171 		pdst = PF_PEER_DST;
6172 	} else {
6173 		src = &(*state)->dst;
6174 		dst = &(*state)->src;
6175 		psrc = PF_PEER_DST;
6176 		pdst = PF_PEER_SRC;
6177 	}
6178 
6179 	/* update states */
6180 	if (src->state < PFOTHERS_SINGLE)
6181 		pf_set_protostate(*state, psrc, PFOTHERS_SINGLE);
6182 	if (dst->state == PFOTHERS_SINGLE)
6183 		pf_set_protostate(*state, pdst, PFOTHERS_MULTIPLE);
6184 
6185 	/* update expire time */
6186 	(*state)->expire = time_uptime;
6187 	if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
6188 		(*state)->timeout = PFTM_OTHER_MULTIPLE;
6189 	else
6190 		(*state)->timeout = PFTM_OTHER_SINGLE;
6191 
6192 	/* translate source/destination address, if necessary */
6193 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
6194 		struct pf_state_key *nk = (*state)->key[pd->didx];
6195 
6196 		KASSERT(nk, ("%s: nk is null", __func__));
6197 		KASSERT(pd, ("%s: pd is null", __func__));
6198 		KASSERT(pd->src, ("%s: pd->src is null", __func__));
6199 		KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
6200 		switch (pd->af) {
6201 #ifdef INET
6202 		case AF_INET:
6203 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
6204 				pf_change_a(&pd->src->v4.s_addr,
6205 				    pd->ip_sum,
6206 				    nk->addr[pd->sidx].v4.s_addr,
6207 				    0);
6208 
6209 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
6210 				pf_change_a(&pd->dst->v4.s_addr,
6211 				    pd->ip_sum,
6212 				    nk->addr[pd->didx].v4.s_addr,
6213 				    0);
6214 
6215 			break;
6216 #endif /* INET */
6217 #ifdef INET6
6218 		case AF_INET6:
6219 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
6220 				PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
6221 
6222 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
6223 				PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
6224 #endif /* INET6 */
6225 		}
6226 	}
6227 	return (PF_PASS);
6228 }
6229 
6230 /*
6231  * ipoff and off are measured from the start of the mbuf chain.
6232  * h must be at "ipoff" on the mbuf chain.
6233  */
6234 void *
6235 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
6236     u_short *actionp, u_short *reasonp, sa_family_t af)
6237 {
6238 	switch (af) {
6239 #ifdef INET
6240 	case AF_INET: {
6241 		struct ip	*h = mtod(m, struct ip *);
6242 		u_int16_t	 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
6243 
6244 		if (fragoff) {
6245 			if (fragoff >= len)
6246 				ACTION_SET(actionp, PF_PASS);
6247 			else {
6248 				ACTION_SET(actionp, PF_DROP);
6249 				REASON_SET(reasonp, PFRES_FRAG);
6250 			}
6251 			return (NULL);
6252 		}
6253 		if (m->m_pkthdr.len < off + len ||
6254 		    ntohs(h->ip_len) < off + len) {
6255 			ACTION_SET(actionp, PF_DROP);
6256 			REASON_SET(reasonp, PFRES_SHORT);
6257 			return (NULL);
6258 		}
6259 		break;
6260 	}
6261 #endif /* INET */
6262 #ifdef INET6
6263 	case AF_INET6: {
6264 		struct ip6_hdr	*h = mtod(m, struct ip6_hdr *);
6265 
6266 		if (m->m_pkthdr.len < off + len ||
6267 		    (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
6268 		    (unsigned)(off + len)) {
6269 			ACTION_SET(actionp, PF_DROP);
6270 			REASON_SET(reasonp, PFRES_SHORT);
6271 			return (NULL);
6272 		}
6273 		break;
6274 	}
6275 #endif /* INET6 */
6276 	}
6277 	m_copydata(m, off, len, p);
6278 	return (p);
6279 }
6280 
6281 int
6282 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kkif *kif,
6283     int rtableid)
6284 {
6285 	struct ifnet		*ifp;
6286 
6287 	/*
6288 	 * Skip check for addresses with embedded interface scope,
6289 	 * as they would always match anyway.
6290 	 */
6291 	if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
6292 		return (1);
6293 
6294 	if (af != AF_INET && af != AF_INET6)
6295 		return (0);
6296 
6297 	/* Skip checks for ipsec interfaces */
6298 	if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
6299 		return (1);
6300 
6301 	ifp = (kif != NULL) ? kif->pfik_ifp : NULL;
6302 
6303 	switch (af) {
6304 #ifdef INET6
6305 	case AF_INET6:
6306 		return (fib6_check_urpf(rtableid, &addr->v6, 0, NHR_NONE,
6307 		    ifp));
6308 #endif
6309 #ifdef INET
6310 	case AF_INET:
6311 		return (fib4_check_urpf(rtableid, addr->v4, 0, NHR_NONE,
6312 		    ifp));
6313 #endif
6314 	}
6315 
6316 	return (0);
6317 }
6318 
6319 #ifdef INET
6320 static void
6321 pf_route(struct mbuf **m, struct pf_krule *r, int dir, struct ifnet *oifp,
6322     struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
6323 {
6324 	struct mbuf		*m0, *m1, *md;
6325 	struct sockaddr_in	dst;
6326 	struct ip		*ip;
6327 	struct ifnet		*ifp = NULL;
6328 	struct pf_addr		 naddr;
6329 	struct pf_ksrc_node	*sn = NULL;
6330 	int			 error = 0;
6331 	uint16_t		 ip_len, ip_off;
6332 
6333 	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
6334 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
6335 	    __func__));
6336 
6337 	if ((pd->pf_mtag == NULL &&
6338 	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
6339 	    pd->pf_mtag->routed++ > 3) {
6340 		m0 = *m;
6341 		*m = NULL;
6342 		goto bad_locked;
6343 	}
6344 
6345 	if (r->rt == PF_DUPTO) {
6346 		if ((pd->pf_mtag->flags & PF_DUPLICATED)) {
6347 			if (s == NULL) {
6348 				ifp = r->rpool.cur->kif ?
6349 				    r->rpool.cur->kif->pfik_ifp : NULL;
6350 			} else {
6351 				ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
6352 				/* If pfsync'd */
6353 				if (ifp == NULL)
6354 					ifp = r->rpool.cur->kif ?
6355 					    r->rpool.cur->kif->pfik_ifp : NULL;
6356 				PF_STATE_UNLOCK(s);
6357 			}
6358 			if (ifp == oifp) {
6359 				/* When the 2nd interface is not skipped */
6360 				return;
6361 			} else {
6362 				m0 = *m;
6363 				*m = NULL;
6364 				goto bad;
6365 			}
6366 		} else {
6367 			pd->pf_mtag->flags |= PF_DUPLICATED;
6368 			if (((m0 = m_dup(*m, M_NOWAIT)) == NULL)) {
6369 				if (s)
6370 					PF_STATE_UNLOCK(s);
6371 				return;
6372 			}
6373 		}
6374 	} else {
6375 		if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
6376 			pf_dummynet(pd, dir, s, r, m);
6377 			if (s)
6378 				PF_STATE_UNLOCK(s);
6379 			return;
6380 		}
6381 		m0 = *m;
6382 	}
6383 
6384 	ip = mtod(m0, struct ip *);
6385 
6386 	bzero(&dst, sizeof(dst));
6387 	dst.sin_family = AF_INET;
6388 	dst.sin_len = sizeof(dst);
6389 	dst.sin_addr = ip->ip_dst;
6390 
6391 	bzero(&naddr, sizeof(naddr));
6392 
6393 	if (s == NULL) {
6394 		if (TAILQ_EMPTY(&r->rpool.list)) {
6395 			DPFPRINTF(PF_DEBUG_URGENT,
6396 			    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
6397 			goto bad_locked;
6398 		}
6399 		pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
6400 		    &naddr, NULL, &sn);
6401 		if (!PF_AZERO(&naddr, AF_INET))
6402 			dst.sin_addr.s_addr = naddr.v4.s_addr;
6403 		ifp = r->rpool.cur->kif ?
6404 		    r->rpool.cur->kif->pfik_ifp : NULL;
6405 	} else {
6406 		if (!PF_AZERO(&s->rt_addr, AF_INET))
6407 			dst.sin_addr.s_addr =
6408 			    s->rt_addr.v4.s_addr;
6409 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
6410 		PF_STATE_UNLOCK(s);
6411 	}
6412 	/* If pfsync'd */
6413 	if (ifp == NULL)
6414 		ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
6415 	if (ifp == NULL)
6416 		goto bad;
6417 
6418 	if (dir == PF_IN) {
6419 		if (pf_test(PF_OUT, 0, ifp, &m0, inp) != PF_PASS)
6420 			goto bad;
6421 		else if (m0 == NULL)
6422 			goto done;
6423 		if (m0->m_len < sizeof(struct ip)) {
6424 			DPFPRINTF(PF_DEBUG_URGENT,
6425 			    ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
6426 			goto bad;
6427 		}
6428 		ip = mtod(m0, struct ip *);
6429 	}
6430 
6431 	if (ifp->if_flags & IFF_LOOPBACK)
6432 		m0->m_flags |= M_SKIP_FIREWALL;
6433 
6434 	ip_len = ntohs(ip->ip_len);
6435 	ip_off = ntohs(ip->ip_off);
6436 
6437 	/* Copied from FreeBSD 10.0-CURRENT ip_output. */
6438 	m0->m_pkthdr.csum_flags |= CSUM_IP;
6439 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
6440 		in_delayed_cksum(m0);
6441 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
6442 	}
6443 #if defined(SCTP) || defined(SCTP_SUPPORT)
6444 	if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
6445 		sctp_delayed_cksum(m0, (uint32_t)(ip->ip_hl << 2));
6446 		m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
6447 	}
6448 #endif
6449 
6450 	/*
6451 	 * If small enough for interface, or the interface will take
6452 	 * care of the fragmentation for us, we can just send directly.
6453 	 */
6454 	if (ip_len <= ifp->if_mtu ||
6455 	    (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
6456 		ip->ip_sum = 0;
6457 		if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
6458 			ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
6459 			m0->m_pkthdr.csum_flags &= ~CSUM_IP;
6460 		}
6461 		m_clrprotoflags(m0);	/* Avoid confusing lower layers. */
6462 
6463 		md = m0;
6464 		error = pf_dummynet_route(pd, dir, s, r, ifp, sintosa(&dst), &md);
6465 		if (md != NULL)
6466 			error = (*ifp->if_output)(ifp, md, sintosa(&dst), NULL);
6467 		goto done;
6468 	}
6469 
6470 	/* Balk when DF bit is set or the interface didn't support TSO. */
6471 	if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
6472 		error = EMSGSIZE;
6473 		KMOD_IPSTAT_INC(ips_cantfrag);
6474 		if (r->rt != PF_DUPTO) {
6475 			if (s && pd->nat_rule != NULL)
6476 				PACKET_UNDO_NAT(m0, pd,
6477 				    (ip->ip_hl << 2) + (ip_off & IP_OFFMASK),
6478 				    s, dir);
6479 
6480 			icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
6481 			    ifp->if_mtu);
6482 			goto done;
6483 		} else
6484 			goto bad;
6485 	}
6486 
6487 	error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
6488 	if (error)
6489 		goto bad;
6490 
6491 	for (; m0; m0 = m1) {
6492 		m1 = m0->m_nextpkt;
6493 		m0->m_nextpkt = NULL;
6494 		if (error == 0) {
6495 			m_clrprotoflags(m0);
6496 			md = m0;
6497 			error = pf_dummynet_route(pd, dir, s, r, ifp,
6498 			    sintosa(&dst), &md);
6499 			if (md != NULL)
6500 				error = (*ifp->if_output)(ifp, md,
6501 				    sintosa(&dst), NULL);
6502 		} else
6503 			m_freem(m0);
6504 	}
6505 
6506 	if (error == 0)
6507 		KMOD_IPSTAT_INC(ips_fragmented);
6508 
6509 done:
6510 	if (r->rt != PF_DUPTO)
6511 		*m = NULL;
6512 	return;
6513 
6514 bad_locked:
6515 	if (s)
6516 		PF_STATE_UNLOCK(s);
6517 bad:
6518 	m_freem(m0);
6519 	goto done;
6520 }
6521 #endif /* INET */
6522 
6523 #ifdef INET6
6524 static void
6525 pf_route6(struct mbuf **m, struct pf_krule *r, int dir, struct ifnet *oifp,
6526     struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
6527 {
6528 	struct mbuf		*m0, *md;
6529 	struct sockaddr_in6	dst;
6530 	struct ip6_hdr		*ip6;
6531 	struct ifnet		*ifp = NULL;
6532 	struct pf_addr		 naddr;
6533 	struct pf_ksrc_node	*sn = NULL;
6534 
6535 	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
6536 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
6537 	    __func__));
6538 
6539 	if ((pd->pf_mtag == NULL &&
6540 	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
6541 	    pd->pf_mtag->routed++ > 3) {
6542 		m0 = *m;
6543 		*m = NULL;
6544 		goto bad_locked;
6545 	}
6546 
6547 	if (r->rt == PF_DUPTO) {
6548 		if ((pd->pf_mtag->flags & PF_DUPLICATED)) {
6549 			if (s == NULL) {
6550 				ifp = r->rpool.cur->kif ?
6551 				    r->rpool.cur->kif->pfik_ifp : NULL;
6552 			} else {
6553 				ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
6554 				/* If pfsync'd */
6555 				if (ifp == NULL)
6556 					ifp = r->rpool.cur->kif ?
6557 					    r->rpool.cur->kif->pfik_ifp : NULL;
6558 				PF_STATE_UNLOCK(s);
6559 			}
6560 			if (ifp == oifp) {
6561 				/* When the 2nd interface is not skipped */
6562 				return;
6563 			} else {
6564 				m0 = *m;
6565 				*m = NULL;
6566 				goto bad;
6567 			}
6568 		} else {
6569 			pd->pf_mtag->flags |= PF_DUPLICATED;
6570 			if (((m0 = m_dup(*m, M_NOWAIT)) == NULL)) {
6571 				if (s)
6572 					PF_STATE_UNLOCK(s);
6573 				return;
6574 			}
6575 		}
6576 	} else {
6577 		if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
6578 			pf_dummynet(pd, dir, s, r, m);
6579 			if (s)
6580 				PF_STATE_UNLOCK(s);
6581 			return;
6582 		}
6583 		m0 = *m;
6584 	}
6585 
6586 	ip6 = mtod(m0, struct ip6_hdr *);
6587 
6588 	bzero(&dst, sizeof(dst));
6589 	dst.sin6_family = AF_INET6;
6590 	dst.sin6_len = sizeof(dst);
6591 	dst.sin6_addr = ip6->ip6_dst;
6592 
6593 	bzero(&naddr, sizeof(naddr));
6594 
6595 	if (s == NULL) {
6596 		if (TAILQ_EMPTY(&r->rpool.list)) {
6597 			DPFPRINTF(PF_DEBUG_URGENT,
6598 			    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
6599 			goto bad_locked;
6600 		}
6601 		pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
6602 		    &naddr, NULL, &sn);
6603 		if (!PF_AZERO(&naddr, AF_INET6))
6604 			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
6605 			    &naddr, AF_INET6);
6606 		ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
6607 	} else {
6608 		if (!PF_AZERO(&s->rt_addr, AF_INET6))
6609 			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
6610 			    &s->rt_addr, AF_INET6);
6611 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
6612 	}
6613 
6614 	if (s)
6615 		PF_STATE_UNLOCK(s);
6616 
6617 	/* If pfsync'd */
6618 	if (ifp == NULL)
6619 		ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
6620 	if (ifp == NULL)
6621 		goto bad;
6622 
6623 	if (dir == PF_IN) {
6624 		if (pf_test6(PF_OUT, 0, ifp, &m0, inp) != PF_PASS)
6625 			goto bad;
6626 		else if (m0 == NULL)
6627 			goto done;
6628 		if (m0->m_len < sizeof(struct ip6_hdr)) {
6629 			DPFPRINTF(PF_DEBUG_URGENT,
6630 			    ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
6631 			    __func__));
6632 			goto bad;
6633 		}
6634 		ip6 = mtod(m0, struct ip6_hdr *);
6635 	}
6636 
6637 	if (ifp->if_flags & IFF_LOOPBACK)
6638 		m0->m_flags |= M_SKIP_FIREWALL;
6639 
6640 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
6641 	    ~ifp->if_hwassist) {
6642 		uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
6643 		in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
6644 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
6645 	}
6646 
6647 	/*
6648 	 * If the packet is too large for the outgoing interface,
6649 	 * send back an icmp6 error.
6650 	 */
6651 	if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
6652 		dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
6653 	if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu) {
6654 		md = m0;
6655 		pf_dummynet_route(pd, dir, s, r, ifp, sintosa(&dst), &md);
6656 		if (md != NULL)
6657 			nd6_output_ifp(ifp, ifp, md, &dst, NULL);
6658 	}
6659 	else {
6660 		in6_ifstat_inc(ifp, ifs6_in_toobig);
6661 		if (r->rt != PF_DUPTO) {
6662 			if (s && pd->nat_rule != NULL)
6663 				PACKET_UNDO_NAT(m0, pd,
6664 				    ((caddr_t)ip6 - m0->m_data) +
6665 				    sizeof(struct ip6_hdr), s, dir);
6666 
6667 			icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
6668 		} else
6669 			goto bad;
6670 	}
6671 
6672 done:
6673 	if (r->rt != PF_DUPTO)
6674 		*m = NULL;
6675 	return;
6676 
6677 bad_locked:
6678 	if (s)
6679 		PF_STATE_UNLOCK(s);
6680 bad:
6681 	m_freem(m0);
6682 	goto done;
6683 }
6684 #endif /* INET6 */
6685 
6686 /*
6687  * FreeBSD supports cksum offloads for the following drivers.
6688  *  em(4), fxp(4), lge(4), nge(4), re(4), ti(4), txp(4), xl(4)
6689  *
6690  * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
6691  *  network driver performed cksum including pseudo header, need to verify
6692  *   csum_data
6693  * CSUM_DATA_VALID :
6694  *  network driver performed cksum, needs to additional pseudo header
6695  *  cksum computation with partial csum_data(i.e. lack of H/W support for
6696  *  pseudo header, for instance sk(4) and possibly gem(4))
6697  *
6698  * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
6699  * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
6700  * TCP/UDP layer.
6701  * Also, set csum_data to 0xffff to force cksum validation.
6702  */
6703 static int
6704 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
6705 {
6706 	u_int16_t sum = 0;
6707 	int hw_assist = 0;
6708 	struct ip *ip;
6709 
6710 	if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
6711 		return (1);
6712 	if (m->m_pkthdr.len < off + len)
6713 		return (1);
6714 
6715 	switch (p) {
6716 	case IPPROTO_TCP:
6717 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
6718 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
6719 				sum = m->m_pkthdr.csum_data;
6720 			} else {
6721 				ip = mtod(m, struct ip *);
6722 				sum = in_pseudo(ip->ip_src.s_addr,
6723 				ip->ip_dst.s_addr, htonl((u_short)len +
6724 				m->m_pkthdr.csum_data + IPPROTO_TCP));
6725 			}
6726 			sum ^= 0xffff;
6727 			++hw_assist;
6728 		}
6729 		break;
6730 	case IPPROTO_UDP:
6731 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
6732 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
6733 				sum = m->m_pkthdr.csum_data;
6734 			} else {
6735 				ip = mtod(m, struct ip *);
6736 				sum = in_pseudo(ip->ip_src.s_addr,
6737 				ip->ip_dst.s_addr, htonl((u_short)len +
6738 				m->m_pkthdr.csum_data + IPPROTO_UDP));
6739 			}
6740 			sum ^= 0xffff;
6741 			++hw_assist;
6742 		}
6743 		break;
6744 	case IPPROTO_ICMP:
6745 #ifdef INET6
6746 	case IPPROTO_ICMPV6:
6747 #endif /* INET6 */
6748 		break;
6749 	default:
6750 		return (1);
6751 	}
6752 
6753 	if (!hw_assist) {
6754 		switch (af) {
6755 		case AF_INET:
6756 			if (p == IPPROTO_ICMP) {
6757 				if (m->m_len < off)
6758 					return (1);
6759 				m->m_data += off;
6760 				m->m_len -= off;
6761 				sum = in_cksum(m, len);
6762 				m->m_data -= off;
6763 				m->m_len += off;
6764 			} else {
6765 				if (m->m_len < sizeof(struct ip))
6766 					return (1);
6767 				sum = in4_cksum(m, p, off, len);
6768 			}
6769 			break;
6770 #ifdef INET6
6771 		case AF_INET6:
6772 			if (m->m_len < sizeof(struct ip6_hdr))
6773 				return (1);
6774 			sum = in6_cksum(m, p, off, len);
6775 			break;
6776 #endif /* INET6 */
6777 		default:
6778 			return (1);
6779 		}
6780 	}
6781 	if (sum) {
6782 		switch (p) {
6783 		case IPPROTO_TCP:
6784 		    {
6785 			KMOD_TCPSTAT_INC(tcps_rcvbadsum);
6786 			break;
6787 		    }
6788 		case IPPROTO_UDP:
6789 		    {
6790 			KMOD_UDPSTAT_INC(udps_badsum);
6791 			break;
6792 		    }
6793 #ifdef INET
6794 		case IPPROTO_ICMP:
6795 		    {
6796 			KMOD_ICMPSTAT_INC(icps_checksum);
6797 			break;
6798 		    }
6799 #endif
6800 #ifdef INET6
6801 		case IPPROTO_ICMPV6:
6802 		    {
6803 			KMOD_ICMP6STAT_INC(icp6s_checksum);
6804 			break;
6805 		    }
6806 #endif /* INET6 */
6807 		}
6808 		return (1);
6809 	} else {
6810 		if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
6811 			m->m_pkthdr.csum_flags |=
6812 			    (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
6813 			m->m_pkthdr.csum_data = 0xffff;
6814 		}
6815 	}
6816 	return (0);
6817 }
6818 
6819 static bool
6820 pf_pdesc_to_dnflow(int dir, const struct pf_pdesc *pd,
6821     const struct pf_krule *r, const struct pf_kstate *s,
6822     struct ip_fw_args *dnflow)
6823 {
6824 	int dndir = r->direction;
6825 
6826 	if (s && dndir == PF_INOUT) {
6827 		dndir = s->direction;
6828 	} else if (dndir == PF_INOUT) {
6829 		/* Assume primary direction. Happens when we've set dnpipe in
6830 		 * the ethernet level code. */
6831 		dndir = dir;
6832 	}
6833 
6834 	memset(dnflow, 0, sizeof(*dnflow));
6835 
6836 	if (pd->dport != NULL)
6837 		dnflow->f_id.dst_port = ntohs(*pd->dport);
6838 	if (pd->sport != NULL)
6839 		dnflow->f_id.src_port = ntohs(*pd->sport);
6840 
6841 	if (dir == PF_IN)
6842 		dnflow->flags |= IPFW_ARGS_IN;
6843 	else
6844 		dnflow->flags |= IPFW_ARGS_OUT;
6845 
6846 	if (dir != dndir && pd->act.dnrpipe) {
6847 		dnflow->rule.info = pd->act.dnrpipe;
6848 	}
6849 	else if (dir == dndir && pd->act.dnpipe) {
6850 		dnflow->rule.info = pd->act.dnpipe;
6851 	}
6852 	else {
6853 		return (false);
6854 	}
6855 
6856 	dnflow->rule.info |= IPFW_IS_DUMMYNET;
6857 	if (r->free_flags & PFRULE_DN_IS_PIPE || pd->act.flags & PFRULE_DN_IS_PIPE)
6858 		dnflow->rule.info |= IPFW_IS_PIPE;
6859 
6860 	dnflow->f_id.proto = pd->proto;
6861 	dnflow->f_id.extra = dnflow->rule.info;
6862 	switch (pd->af) {
6863 	case AF_INET:
6864 		dnflow->f_id.addr_type = 4;
6865 		dnflow->f_id.src_ip = ntohl(pd->src->v4.s_addr);
6866 		dnflow->f_id.dst_ip = ntohl(pd->dst->v4.s_addr);
6867 		break;
6868 	case AF_INET6:
6869 		dnflow->flags |= IPFW_ARGS_IP6;
6870 		dnflow->f_id.addr_type = 6;
6871 		dnflow->f_id.src_ip6 = pd->src->v6;
6872 		dnflow->f_id.dst_ip6 = pd->dst->v6;
6873 		break;
6874 	default:
6875 		panic("Invalid AF");
6876 		break;
6877 	}
6878 
6879 	return (true);
6880 }
6881 
6882 int
6883 pf_test_eth(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0,
6884     struct inpcb *inp)
6885 {
6886 	struct pfi_kkif		*kif;
6887 	struct mbuf		*m = *m0;
6888 
6889 	M_ASSERTPKTHDR(m);
6890 	MPASS(ifp->if_vnet == curvnet);
6891 	NET_EPOCH_ASSERT();
6892 
6893 	if (!V_pf_status.running)
6894 		return (PF_PASS);
6895 
6896 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
6897 
6898 	if (kif == NULL) {
6899 		DPFPRINTF(PF_DEBUG_URGENT,
6900 		    ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
6901 		return (PF_DROP);
6902 	}
6903 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
6904 		return (PF_PASS);
6905 
6906 	if (m->m_flags & M_SKIP_FIREWALL)
6907 		return (PF_PASS);
6908 
6909 	/* Stateless! */
6910 	return (pf_test_eth_rule(dir, kif, m0));
6911 }
6912 
6913 static int
6914 pf_dummynet(struct pf_pdesc *pd, int dir, struct pf_kstate *s,
6915     struct pf_krule *r, struct mbuf **m0)
6916 {
6917 	return (pf_dummynet_route(pd, dir, s, r, NULL, NULL, m0));
6918 }
6919 
6920 static int
6921 pf_dummynet_route(struct pf_pdesc *pd, int dir, struct pf_kstate *s,
6922     struct pf_krule *r, struct ifnet *ifp, struct sockaddr *sa,
6923     struct mbuf **m0)
6924 {
6925 	NET_EPOCH_ASSERT();
6926 
6927 	if (s && (s->dnpipe || s->dnrpipe)) {
6928 		pd->act.dnpipe = s->dnpipe;
6929 		pd->act.dnrpipe = s->dnrpipe;
6930 		pd->act.flags = s->state_flags;
6931 	} else if (r->dnpipe || r->dnrpipe) {
6932 		pd->act.dnpipe = r->dnpipe;
6933 		pd->act.dnrpipe = r->dnrpipe;
6934 		pd->act.flags = r->free_flags;
6935 	}
6936 	if (pd->act.dnpipe || pd->act.dnrpipe) {
6937 		struct ip_fw_args dnflow;
6938 		if (ip_dn_io_ptr == NULL) {
6939 			m_freem(*m0);
6940 			*m0 = NULL;
6941 			return (ENOMEM);
6942 		}
6943 
6944 		if (pd->pf_mtag == NULL &&
6945 		    ((pd->pf_mtag = pf_get_mtag(*m0)) == NULL)) {
6946 			m_freem(*m0);
6947 			*m0 = NULL;
6948 			return (ENOMEM);
6949 		}
6950 
6951 		if (ifp != NULL) {
6952 			pd->pf_mtag->flags |= PF_TAG_ROUTE_TO;
6953 
6954 			pd->pf_mtag->if_index = ifp->if_index;
6955 			pd->pf_mtag->if_idxgen = ifp->if_idxgen;
6956 
6957 			MPASS(sa != NULL);
6958 
6959 			if (pd->af == AF_INET)
6960 				memcpy(&pd->pf_mtag->dst, sa,
6961 				    sizeof(struct sockaddr_in));
6962 			else
6963 				memcpy(&pd->pf_mtag->dst, sa,
6964 				    sizeof(struct sockaddr_in6));
6965 		}
6966 
6967 		if (pf_pdesc_to_dnflow(dir, pd, r, s, &dnflow)) {
6968 			pd->pf_mtag->flags |= PF_TAG_DUMMYNET;
6969 			ip_dn_io_ptr(m0, &dnflow);
6970 			if (*m0 != NULL)
6971 				pd->pf_mtag->flags &= ~PF_TAG_DUMMYNET;
6972 		}
6973 	}
6974 
6975 	return (0);
6976 }
6977 
6978 #ifdef INET
6979 int
6980 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6981 {
6982 	struct pfi_kkif		*kif;
6983 	u_short			 action, reason = 0, log = 0;
6984 	struct mbuf		*m = *m0;
6985 	struct ip		*h = NULL;
6986 	struct m_tag		*ipfwtag;
6987 	struct pf_krule		*a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6988 	struct pf_kstate	*s = NULL;
6989 	struct pf_kruleset	*ruleset = NULL;
6990 	struct pf_pdesc		 pd;
6991 	int			 off, dirndx, pqid = 0;
6992 
6993 	PF_RULES_RLOCK_TRACKER;
6994 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: bad direction %d\n", __func__, dir));
6995 	M_ASSERTPKTHDR(m);
6996 
6997 	if (!V_pf_status.running)
6998 		return (PF_PASS);
6999 
7000 	PF_RULES_RLOCK();
7001 
7002 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
7003 
7004 	if (__predict_false(kif == NULL)) {
7005 		DPFPRINTF(PF_DEBUG_URGENT,
7006 		    ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
7007 		PF_RULES_RUNLOCK();
7008 		return (PF_DROP);
7009 	}
7010 	if (kif->pfik_flags & PFI_IFLAG_SKIP) {
7011 		PF_RULES_RUNLOCK();
7012 		return (PF_PASS);
7013 	}
7014 
7015 	if (m->m_flags & M_SKIP_FIREWALL) {
7016 		PF_RULES_RUNLOCK();
7017 		return (PF_PASS);
7018 	}
7019 
7020 	memset(&pd, 0, sizeof(pd));
7021 	pd.pf_mtag = pf_find_mtag(m);
7022 
7023 	if (pd.pf_mtag != NULL && (pd.pf_mtag->flags & PF_TAG_ROUTE_TO)) {
7024 		pd.pf_mtag->flags &= ~PF_TAG_ROUTE_TO;
7025 
7026 		ifp = ifnet_byindexgen(pd.pf_mtag->if_index,
7027 		    pd.pf_mtag->if_idxgen);
7028 		if (ifp == NULL || ifp->if_flags & IFF_DYING) {
7029 			PF_RULES_RUNLOCK();
7030 			m_freem(*m0);
7031 			*m0 = NULL;
7032 			return (PF_PASS);
7033 		}
7034 		PF_RULES_RUNLOCK();
7035 		(ifp->if_output)(ifp, m, sintosa(&pd.pf_mtag->dst), NULL);
7036 		*m0 = NULL;
7037 		return (PF_PASS);
7038 	}
7039 
7040 	if (pd.pf_mtag && pd.pf_mtag->dnpipe) {
7041 		pd.act.dnpipe = pd.pf_mtag->dnpipe;
7042 		pd.act.flags = pd.pf_mtag->dnflags;
7043 	}
7044 
7045 	if (ip_dn_io_ptr != NULL && pd.pf_mtag != NULL &&
7046 	    pd.pf_mtag->flags & PF_TAG_DUMMYNET) {
7047 		/* Dummynet re-injects packets after they've
7048 		 * completed their delay. We've already
7049 		 * processed them, so pass unconditionally. */
7050 
7051 		/* But only once. We may see the packet multiple times (e.g.
7052 		 * PFIL_IN/PFIL_OUT). */
7053 		pd.pf_mtag->flags &= ~PF_TAG_DUMMYNET;
7054 		PF_RULES_RUNLOCK();
7055 
7056 		return (PF_PASS);
7057 	}
7058 
7059 	if (__predict_false(ip_divert_ptr != NULL) &&
7060 	    ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
7061 		struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
7062 		if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
7063 			if (pd.pf_mtag == NULL &&
7064 			    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
7065 				action = PF_DROP;
7066 				goto done;
7067 			}
7068 			pd.pf_mtag->flags |= PF_PACKET_LOOPED;
7069 			m_tag_delete(m, ipfwtag);
7070 		}
7071 		if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
7072 			m->m_flags |= M_FASTFWD_OURS;
7073 			pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
7074 		}
7075 	} else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
7076 		/* We do IP header normalization and packet reassembly here */
7077 		action = PF_DROP;
7078 		goto done;
7079 	}
7080 	m = *m0;	/* pf_normalize messes with m0 */
7081 	h = mtod(m, struct ip *);
7082 
7083 	off = h->ip_hl << 2;
7084 	if (off < (int)sizeof(struct ip)) {
7085 		action = PF_DROP;
7086 		REASON_SET(&reason, PFRES_SHORT);
7087 		log = 1;
7088 		goto done;
7089 	}
7090 
7091 	pd.src = (struct pf_addr *)&h->ip_src;
7092 	pd.dst = (struct pf_addr *)&h->ip_dst;
7093 	pd.sport = pd.dport = NULL;
7094 	pd.ip_sum = &h->ip_sum;
7095 	pd.proto_sum = NULL;
7096 	pd.proto = h->ip_p;
7097 	pd.dir = dir;
7098 	pd.sidx = (dir == PF_IN) ? 0 : 1;
7099 	pd.didx = (dir == PF_IN) ? 1 : 0;
7100 	pd.af = AF_INET;
7101 	pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
7102 	pd.tot_len = ntohs(h->ip_len);
7103 
7104 	/* handle fragments that didn't get reassembled by normalization */
7105 	if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
7106 		action = pf_test_fragment(&r, dir, kif, m, h,
7107 		    &pd, &a, &ruleset);
7108 		goto done;
7109 	}
7110 
7111 	switch (h->ip_p) {
7112 	case IPPROTO_TCP: {
7113 		if (!pf_pull_hdr(m, off, &pd.hdr.tcp, sizeof(pd.hdr.tcp),
7114 		    &action, &reason, AF_INET)) {
7115 			log = action != PF_PASS;
7116 			goto done;
7117 		}
7118 		pd.p_len = pd.tot_len - off - (pd.hdr.tcp.th_off << 2);
7119 
7120 		pd.sport = &pd.hdr.tcp.th_sport;
7121 		pd.dport = &pd.hdr.tcp.th_dport;
7122 
7123 		/* Respond to SYN with a syncookie. */
7124 		if ((pd.hdr.tcp.th_flags & (TH_SYN|TH_ACK|TH_RST)) == TH_SYN &&
7125 		    pd.dir == PF_IN && pf_synflood_check(&pd)) {
7126 			pf_syncookie_send(m, off, &pd);
7127 			action = PF_DROP;
7128 			break;
7129 		}
7130 
7131 		if ((pd.hdr.tcp.th_flags & TH_ACK) && pd.p_len == 0)
7132 			pqid = 1;
7133 		action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
7134 		if (action == PF_DROP)
7135 			goto done;
7136 		action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
7137 		    &reason);
7138 		if (action == PF_PASS) {
7139 			if (V_pfsync_update_state_ptr != NULL)
7140 				V_pfsync_update_state_ptr(s);
7141 			r = s->rule.ptr;
7142 			a = s->anchor.ptr;
7143 			log = s->log;
7144 		} else if (s == NULL) {
7145 			/* Validate remote SYN|ACK, re-create original SYN if
7146 			 * valid. */
7147 			if ((pd.hdr.tcp.th_flags & (TH_SYN|TH_ACK|TH_RST)) ==
7148 			    TH_ACK && pf_syncookie_validate(&pd) &&
7149 			    pd.dir == PF_IN) {
7150 				struct mbuf *msyn;
7151 
7152 				msyn = pf_syncookie_recreate_syn(h->ip_ttl,
7153 				    off,&pd);
7154 				if (msyn == NULL) {
7155 					action = PF_DROP;
7156 					break;
7157 				}
7158 
7159 				action = pf_test(dir, pflags, ifp, &msyn, inp);
7160 				m_freem(msyn);
7161 
7162 				if (action == PF_PASS) {
7163 					action = pf_test_state_tcp(&s, dir,
7164 					    kif, m, off, h, &pd, &reason);
7165 					if (action != PF_PASS || s == NULL) {
7166 						action = PF_DROP;
7167 						break;
7168 					}
7169 
7170 					s->src.seqhi = ntohl(pd.hdr.tcp.th_ack)
7171 					    - 1;
7172 					s->src.seqlo = ntohl(pd.hdr.tcp.th_seq)
7173 					    - 1;
7174 					pf_set_protostate(s, PF_PEER_SRC,
7175 					    PF_TCPS_PROXY_DST);
7176 
7177 					action = pf_synproxy(&pd, &s, &reason);
7178 					if (action != PF_PASS)
7179 						break;
7180 				}
7181 				break;
7182 			}
7183 			else {
7184 				action = pf_test_rule(&r, &s, dir, kif, m, off,
7185 				    &pd, &a, &ruleset, inp);
7186 			}
7187 		}
7188 		break;
7189 	}
7190 
7191 	case IPPROTO_UDP: {
7192 		if (!pf_pull_hdr(m, off, &pd.hdr.udp, sizeof(pd.hdr.udp),
7193 		    &action, &reason, AF_INET)) {
7194 			log = action != PF_PASS;
7195 			goto done;
7196 		}
7197 		pd.sport = &pd.hdr.udp.uh_sport;
7198 		pd.dport = &pd.hdr.udp.uh_dport;
7199 		if (pd.hdr.udp.uh_dport == 0 ||
7200 		    ntohs(pd.hdr.udp.uh_ulen) > m->m_pkthdr.len - off ||
7201 		    ntohs(pd.hdr.udp.uh_ulen) < sizeof(struct udphdr)) {
7202 			action = PF_DROP;
7203 			REASON_SET(&reason, PFRES_SHORT);
7204 			goto done;
7205 		}
7206 		action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
7207 		if (action == PF_PASS) {
7208 			if (V_pfsync_update_state_ptr != NULL)
7209 				V_pfsync_update_state_ptr(s);
7210 			r = s->rule.ptr;
7211 			a = s->anchor.ptr;
7212 			log = s->log;
7213 		} else if (s == NULL)
7214 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7215 			    &a, &ruleset, inp);
7216 		break;
7217 	}
7218 
7219 	case IPPROTO_ICMP: {
7220 		if (!pf_pull_hdr(m, off, &pd.hdr.icmp, ICMP_MINLEN,
7221 		    &action, &reason, AF_INET)) {
7222 			log = action != PF_PASS;
7223 			goto done;
7224 		}
7225 		action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
7226 		    &reason);
7227 		if (action == PF_PASS) {
7228 			if (V_pfsync_update_state_ptr != NULL)
7229 				V_pfsync_update_state_ptr(s);
7230 			r = s->rule.ptr;
7231 			a = s->anchor.ptr;
7232 			log = s->log;
7233 		} else if (s == NULL)
7234 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7235 			    &a, &ruleset, inp);
7236 		break;
7237 	}
7238 
7239 #ifdef INET6
7240 	case IPPROTO_ICMPV6: {
7241 		action = PF_DROP;
7242 		DPFPRINTF(PF_DEBUG_MISC,
7243 		    ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
7244 		goto done;
7245 	}
7246 #endif
7247 
7248 	default:
7249 		action = pf_test_state_other(&s, dir, kif, m, &pd);
7250 		if (action == PF_PASS) {
7251 			if (V_pfsync_update_state_ptr != NULL)
7252 				V_pfsync_update_state_ptr(s);
7253 			r = s->rule.ptr;
7254 			a = s->anchor.ptr;
7255 			log = s->log;
7256 		} else if (s == NULL)
7257 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7258 			    &a, &ruleset, inp);
7259 		break;
7260 	}
7261 
7262 done:
7263 	PF_RULES_RUNLOCK();
7264 	if (action == PF_PASS && h->ip_hl > 5 &&
7265 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
7266 		action = PF_DROP;
7267 		REASON_SET(&reason, PFRES_IPOPTIONS);
7268 		log = r->log;
7269 		DPFPRINTF(PF_DEBUG_MISC,
7270 		    ("pf: dropping packet with ip options\n"));
7271 	}
7272 
7273 	if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
7274 		action = PF_DROP;
7275 		REASON_SET(&reason, PFRES_MEMORY);
7276 	}
7277 	if (r->rtableid >= 0)
7278 		M_SETFIB(m, r->rtableid);
7279 
7280 	if (r->scrub_flags & PFSTATE_SETPRIO) {
7281 		if (pd.tos & IPTOS_LOWDELAY)
7282 			pqid = 1;
7283 		if (vlan_set_pcp(m, r->set_prio[pqid])) {
7284 			action = PF_DROP;
7285 			REASON_SET(&reason, PFRES_MEMORY);
7286 			log = 1;
7287 			DPFPRINTF(PF_DEBUG_MISC,
7288 			    ("pf: failed to allocate 802.1q mtag\n"));
7289 		}
7290 	}
7291 
7292 #ifdef ALTQ
7293 	if (s && s->qid) {
7294 		pd.act.pqid = s->pqid;
7295 		pd.act.qid = s->qid;
7296 	} else if (r->qid) {
7297 		pd.act.pqid = r->pqid;
7298 		pd.act.qid = r->qid;
7299 	}
7300 	if (action == PF_PASS && pd.act.qid) {
7301 		if (pd.pf_mtag == NULL &&
7302 		    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
7303 			action = PF_DROP;
7304 			REASON_SET(&reason, PFRES_MEMORY);
7305 		} else {
7306 			if (s != NULL)
7307 				pd.pf_mtag->qid_hash = pf_state_hash(s);
7308 			if (pqid || (pd.tos & IPTOS_LOWDELAY))
7309 				pd.pf_mtag->qid = pd.act.pqid;
7310 			else
7311 				pd.pf_mtag->qid = pd.act.qid;
7312 			/* Add hints for ecn. */
7313 			pd.pf_mtag->hdr = h;
7314 		}
7315 	}
7316 #endif /* ALTQ */
7317 
7318 	/*
7319 	 * connections redirected to loopback should not match sockets
7320 	 * bound specifically to loopback due to security implications,
7321 	 * see tcp_input() and in_pcblookup_listen().
7322 	 */
7323 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
7324 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
7325 	    (s->nat_rule.ptr->action == PF_RDR ||
7326 	    s->nat_rule.ptr->action == PF_BINAT) &&
7327 	    IN_LOOPBACK(ntohl(pd.dst->v4.s_addr)))
7328 		m->m_flags |= M_SKIP_FIREWALL;
7329 
7330 	if (__predict_false(ip_divert_ptr != NULL) && action == PF_PASS &&
7331 	    r->divert.port && !PACKET_LOOPED(&pd)) {
7332 		ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
7333 		    sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
7334 		if (ipfwtag != NULL) {
7335 			((struct ipfw_rule_ref *)(ipfwtag+1))->info =
7336 			    ntohs(r->divert.port);
7337 			((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
7338 
7339 			if (s)
7340 				PF_STATE_UNLOCK(s);
7341 
7342 			m_tag_prepend(m, ipfwtag);
7343 			if (m->m_flags & M_FASTFWD_OURS) {
7344 				if (pd.pf_mtag == NULL &&
7345 				    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
7346 					action = PF_DROP;
7347 					REASON_SET(&reason, PFRES_MEMORY);
7348 					log = 1;
7349 					DPFPRINTF(PF_DEBUG_MISC,
7350 					    ("pf: failed to allocate tag\n"));
7351 				} else {
7352 					pd.pf_mtag->flags |=
7353 					    PF_FASTFWD_OURS_PRESENT;
7354 					m->m_flags &= ~M_FASTFWD_OURS;
7355 				}
7356 			}
7357 			ip_divert_ptr(*m0, dir == PF_IN);
7358 			*m0 = NULL;
7359 
7360 			return (action);
7361 		} else {
7362 			/* XXX: ipfw has the same behaviour! */
7363 			action = PF_DROP;
7364 			REASON_SET(&reason, PFRES_MEMORY);
7365 			log = 1;
7366 			DPFPRINTF(PF_DEBUG_MISC,
7367 			    ("pf: failed to allocate divert tag\n"));
7368 		}
7369 	}
7370 
7371 	if (log) {
7372 		struct pf_krule *lr;
7373 
7374 		if (s != NULL && s->nat_rule.ptr != NULL &&
7375 		    s->nat_rule.ptr->log & PF_LOG_ALL)
7376 			lr = s->nat_rule.ptr;
7377 		else
7378 			lr = r;
7379 		PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
7380 		    (s == NULL));
7381 	}
7382 
7383 	pf_counter_u64_critical_enter();
7384 	pf_counter_u64_add_protected(&kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS],
7385 	    pd.tot_len);
7386 	pf_counter_u64_add_protected(&kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS],
7387 	    1);
7388 
7389 	if (action == PF_PASS || r->action == PF_DROP) {
7390 		dirndx = (dir == PF_OUT);
7391 		pf_counter_u64_add_protected(&r->packets[dirndx], 1);
7392 		pf_counter_u64_add_protected(&r->bytes[dirndx], pd.tot_len);
7393 		pf_update_timestamp(r);
7394 
7395 		if (a != NULL) {
7396 			pf_counter_u64_add_protected(&a->packets[dirndx], 1);
7397 			pf_counter_u64_add_protected(&a->bytes[dirndx], pd.tot_len);
7398 		}
7399 		if (s != NULL) {
7400 			if (s->nat_rule.ptr != NULL) {
7401 				pf_counter_u64_add_protected(&s->nat_rule.ptr->packets[dirndx],
7402 				    1);
7403 				pf_counter_u64_add_protected(&s->nat_rule.ptr->bytes[dirndx],
7404 				    pd.tot_len);
7405 			}
7406 			if (s->src_node != NULL) {
7407 				counter_u64_add(s->src_node->packets[dirndx],
7408 				    1);
7409 				counter_u64_add(s->src_node->bytes[dirndx],
7410 				    pd.tot_len);
7411 			}
7412 			if (s->nat_src_node != NULL) {
7413 				counter_u64_add(s->nat_src_node->packets[dirndx],
7414 				    1);
7415 				counter_u64_add(s->nat_src_node->bytes[dirndx],
7416 				    pd.tot_len);
7417 			}
7418 			dirndx = (dir == s->direction) ? 0 : 1;
7419 			s->packets[dirndx]++;
7420 			s->bytes[dirndx] += pd.tot_len;
7421 		}
7422 		tr = r;
7423 		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
7424 		if (nr != NULL && r == &V_pf_default_rule)
7425 			tr = nr;
7426 		if (tr->src.addr.type == PF_ADDR_TABLE)
7427 			pfr_update_stats(tr->src.addr.p.tbl,
7428 			    (s == NULL) ? pd.src :
7429 			    &s->key[(s->direction == PF_IN)]->
7430 				addr[(s->direction == PF_OUT)],
7431 			    pd.af, pd.tot_len, dir == PF_OUT,
7432 			    r->action == PF_PASS, tr->src.neg);
7433 		if (tr->dst.addr.type == PF_ADDR_TABLE)
7434 			pfr_update_stats(tr->dst.addr.p.tbl,
7435 			    (s == NULL) ? pd.dst :
7436 			    &s->key[(s->direction == PF_IN)]->
7437 				addr[(s->direction == PF_IN)],
7438 			    pd.af, pd.tot_len, dir == PF_OUT,
7439 			    r->action == PF_PASS, tr->dst.neg);
7440 	}
7441 	pf_counter_u64_critical_exit();
7442 
7443 	switch (action) {
7444 	case PF_SYNPROXY_DROP:
7445 		m_freem(*m0);
7446 	case PF_DEFER:
7447 		*m0 = NULL;
7448 		action = PF_PASS;
7449 		break;
7450 	case PF_DROP:
7451 		m_freem(*m0);
7452 		*m0 = NULL;
7453 		break;
7454 	default:
7455 		/* pf_route() returns unlocked. */
7456 		if (r->rt) {
7457 			pf_route(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
7458 			return (action);
7459 		}
7460 		if (pf_dummynet(&pd, dir, s, r, m0) != 0) {
7461 			action = PF_DROP;
7462 			REASON_SET(&reason, PFRES_MEMORY);
7463 		}
7464 		break;
7465 	}
7466 
7467 	SDT_PROBE4(pf, ip, test, done, action, reason, r, s);
7468 
7469 	if (s)
7470 		PF_STATE_UNLOCK(s);
7471 
7472 	return (action);
7473 }
7474 #endif /* INET */
7475 
7476 #ifdef INET6
7477 int
7478 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
7479 {
7480 	struct pfi_kkif		*kif;
7481 	u_short			 action, reason = 0, log = 0;
7482 	struct mbuf		*m = *m0, *n = NULL;
7483 	struct m_tag		*mtag;
7484 	struct ip6_hdr		*h = NULL;
7485 	struct pf_krule		*a = NULL, *r = &V_pf_default_rule, *tr, *nr;
7486 	struct pf_kstate	*s = NULL;
7487 	struct pf_kruleset	*ruleset = NULL;
7488 	struct pf_pdesc		 pd;
7489 	int			 off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
7490 
7491 	PF_RULES_RLOCK_TRACKER;
7492 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: bad direction %d\n", __func__, dir));
7493 	M_ASSERTPKTHDR(m);
7494 
7495 	if (!V_pf_status.running)
7496 		return (PF_PASS);
7497 
7498 	PF_RULES_RLOCK();
7499 
7500 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
7501 	if (__predict_false(kif == NULL)) {
7502 		DPFPRINTF(PF_DEBUG_URGENT,
7503 		    ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
7504 		PF_RULES_RUNLOCK();
7505 		return (PF_DROP);
7506 	}
7507 	if (kif->pfik_flags & PFI_IFLAG_SKIP) {
7508 		PF_RULES_RUNLOCK();
7509 		return (PF_PASS);
7510 	}
7511 
7512 	if (m->m_flags & M_SKIP_FIREWALL) {
7513 		PF_RULES_RUNLOCK();
7514 		return (PF_PASS);
7515 	}
7516 
7517 	memset(&pd, 0, sizeof(pd));
7518 	pd.pf_mtag = pf_find_mtag(m);
7519 
7520 	if (pd.pf_mtag != NULL && (pd.pf_mtag->flags & PF_TAG_ROUTE_TO)) {
7521 		pd.pf_mtag->flags &= ~PF_TAG_ROUTE_TO;
7522 
7523 		ifp = ifnet_byindexgen(pd.pf_mtag->if_index,
7524 		    pd.pf_mtag->if_idxgen);
7525 		if (ifp == NULL || ifp->if_flags & IFF_DYING) {
7526 			PF_RULES_RUNLOCK();
7527 			m_freem(*m0);
7528 			*m0 = NULL;
7529 			return (PF_PASS);
7530 		}
7531 		PF_RULES_RUNLOCK();
7532 		nd6_output_ifp(ifp, ifp, m,
7533                     (struct sockaddr_in6 *)&pd.pf_mtag->dst, NULL);
7534 		*m0 = NULL;
7535 		return (PF_PASS);
7536 	}
7537 
7538 	if (pd.pf_mtag && pd.pf_mtag->dnpipe) {
7539 		pd.act.dnpipe = pd.pf_mtag->dnpipe;
7540 		pd.act.flags = pd.pf_mtag->dnflags;
7541 	}
7542 
7543 	if (ip_dn_io_ptr != NULL && pd.pf_mtag != NULL &&
7544 	    pd.pf_mtag->flags & PF_TAG_DUMMYNET) {
7545 		pd.pf_mtag->flags &= ~PF_TAG_DUMMYNET;
7546 		/* Dummynet re-injects packets after they've
7547 		 * completed their delay. We've already
7548 		 * processed them, so pass unconditionally. */
7549 		PF_RULES_RUNLOCK();
7550 		return (PF_PASS);
7551 	}
7552 
7553 	/* We do IP header normalization and packet reassembly here */
7554 	if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
7555 		action = PF_DROP;
7556 		goto done;
7557 	}
7558 	m = *m0;	/* pf_normalize messes with m0 */
7559 	h = mtod(m, struct ip6_hdr *);
7560 
7561 	/*
7562 	 * we do not support jumbogram.  if we keep going, zero ip6_plen
7563 	 * will do something bad, so drop the packet for now.
7564 	 */
7565 	if (htons(h->ip6_plen) == 0) {
7566 		action = PF_DROP;
7567 		REASON_SET(&reason, PFRES_NORM);	/*XXX*/
7568 		goto done;
7569 	}
7570 
7571 	pd.src = (struct pf_addr *)&h->ip6_src;
7572 	pd.dst = (struct pf_addr *)&h->ip6_dst;
7573 	pd.sport = pd.dport = NULL;
7574 	pd.ip_sum = NULL;
7575 	pd.proto_sum = NULL;
7576 	pd.dir = dir;
7577 	pd.sidx = (dir == PF_IN) ? 0 : 1;
7578 	pd.didx = (dir == PF_IN) ? 1 : 0;
7579 	pd.af = AF_INET6;
7580 	pd.tos = IPV6_DSCP(h);
7581 	pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
7582 
7583 	off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
7584 	pd.proto = h->ip6_nxt;
7585 	do {
7586 		switch (pd.proto) {
7587 		case IPPROTO_FRAGMENT:
7588 			action = pf_test_fragment(&r, dir, kif, m, h,
7589 			    &pd, &a, &ruleset);
7590 			if (action == PF_DROP)
7591 				REASON_SET(&reason, PFRES_FRAG);
7592 			goto done;
7593 		case IPPROTO_ROUTING: {
7594 			struct ip6_rthdr rthdr;
7595 
7596 			if (rh_cnt++) {
7597 				DPFPRINTF(PF_DEBUG_MISC,
7598 				    ("pf: IPv6 more than one rthdr\n"));
7599 				action = PF_DROP;
7600 				REASON_SET(&reason, PFRES_IPOPTIONS);
7601 				log = 1;
7602 				goto done;
7603 			}
7604 			if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
7605 			    &reason, pd.af)) {
7606 				DPFPRINTF(PF_DEBUG_MISC,
7607 				    ("pf: IPv6 short rthdr\n"));
7608 				action = PF_DROP;
7609 				REASON_SET(&reason, PFRES_SHORT);
7610 				log = 1;
7611 				goto done;
7612 			}
7613 			if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
7614 				DPFPRINTF(PF_DEBUG_MISC,
7615 				    ("pf: IPv6 rthdr0\n"));
7616 				action = PF_DROP;
7617 				REASON_SET(&reason, PFRES_IPOPTIONS);
7618 				log = 1;
7619 				goto done;
7620 			}
7621 			/* FALLTHROUGH */
7622 		}
7623 		case IPPROTO_AH:
7624 		case IPPROTO_HOPOPTS:
7625 		case IPPROTO_DSTOPTS: {
7626 			/* get next header and header length */
7627 			struct ip6_ext	opt6;
7628 
7629 			if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
7630 			    NULL, &reason, pd.af)) {
7631 				DPFPRINTF(PF_DEBUG_MISC,
7632 				    ("pf: IPv6 short opt\n"));
7633 				action = PF_DROP;
7634 				log = 1;
7635 				goto done;
7636 			}
7637 			if (pd.proto == IPPROTO_AH)
7638 				off += (opt6.ip6e_len + 2) * 4;
7639 			else
7640 				off += (opt6.ip6e_len + 1) * 8;
7641 			pd.proto = opt6.ip6e_nxt;
7642 			/* goto the next header */
7643 			break;
7644 		}
7645 		default:
7646 			terminal++;
7647 			break;
7648 		}
7649 	} while (!terminal);
7650 
7651 	/* if there's no routing header, use unmodified mbuf for checksumming */
7652 	if (!n)
7653 		n = m;
7654 
7655 	switch (pd.proto) {
7656 	case IPPROTO_TCP: {
7657 		if (!pf_pull_hdr(m, off, &pd.hdr.tcp, sizeof(pd.hdr.tcp),
7658 		    &action, &reason, AF_INET6)) {
7659 			log = action != PF_PASS;
7660 			goto done;
7661 		}
7662 		pd.p_len = pd.tot_len - off - (pd.hdr.tcp.th_off << 2);
7663 		pd.sport = &pd.hdr.tcp.th_sport;
7664 		pd.dport = &pd.hdr.tcp.th_dport;
7665 		action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
7666 		if (action == PF_DROP)
7667 			goto done;
7668 		action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
7669 		    &reason);
7670 		if (action == PF_PASS) {
7671 			if (V_pfsync_update_state_ptr != NULL)
7672 				V_pfsync_update_state_ptr(s);
7673 			r = s->rule.ptr;
7674 			a = s->anchor.ptr;
7675 			log = s->log;
7676 		} else if (s == NULL)
7677 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7678 			    &a, &ruleset, inp);
7679 		break;
7680 	}
7681 
7682 	case IPPROTO_UDP: {
7683 		if (!pf_pull_hdr(m, off, &pd.hdr.udp, sizeof(pd.hdr.udp),
7684 		    &action, &reason, AF_INET6)) {
7685 			log = action != PF_PASS;
7686 			goto done;
7687 		}
7688 		pd.sport = &pd.hdr.udp.uh_sport;
7689 		pd.dport = &pd.hdr.udp.uh_dport;
7690 		if (pd.hdr.udp.uh_dport == 0 ||
7691 		    ntohs(pd.hdr.udp.uh_ulen) > m->m_pkthdr.len - off ||
7692 		    ntohs(pd.hdr.udp.uh_ulen) < sizeof(struct udphdr)) {
7693 			action = PF_DROP;
7694 			REASON_SET(&reason, PFRES_SHORT);
7695 			goto done;
7696 		}
7697 		action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
7698 		if (action == PF_PASS) {
7699 			if (V_pfsync_update_state_ptr != NULL)
7700 				V_pfsync_update_state_ptr(s);
7701 			r = s->rule.ptr;
7702 			a = s->anchor.ptr;
7703 			log = s->log;
7704 		} else if (s == NULL)
7705 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7706 			    &a, &ruleset, inp);
7707 		break;
7708 	}
7709 
7710 	case IPPROTO_ICMP: {
7711 		action = PF_DROP;
7712 		DPFPRINTF(PF_DEBUG_MISC,
7713 		    ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
7714 		goto done;
7715 	}
7716 
7717 	case IPPROTO_ICMPV6: {
7718 		if (!pf_pull_hdr(m, off, &pd.hdr.icmp6, sizeof(pd.hdr.icmp6),
7719 		    &action, &reason, AF_INET6)) {
7720 			log = action != PF_PASS;
7721 			goto done;
7722 		}
7723 		action = pf_test_state_icmp(&s, dir, kif,
7724 		    m, off, h, &pd, &reason);
7725 		if (action == PF_PASS) {
7726 			if (V_pfsync_update_state_ptr != NULL)
7727 				V_pfsync_update_state_ptr(s);
7728 			r = s->rule.ptr;
7729 			a = s->anchor.ptr;
7730 			log = s->log;
7731 		} else if (s == NULL)
7732 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7733 			    &a, &ruleset, inp);
7734 		break;
7735 	}
7736 
7737 	default:
7738 		action = pf_test_state_other(&s, dir, kif, m, &pd);
7739 		if (action == PF_PASS) {
7740 			if (V_pfsync_update_state_ptr != NULL)
7741 				V_pfsync_update_state_ptr(s);
7742 			r = s->rule.ptr;
7743 			a = s->anchor.ptr;
7744 			log = s->log;
7745 		} else if (s == NULL)
7746 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7747 			    &a, &ruleset, inp);
7748 		break;
7749 	}
7750 
7751 done:
7752 	PF_RULES_RUNLOCK();
7753 	if (n != m) {
7754 		m_freem(n);
7755 		n = NULL;
7756 	}
7757 
7758 	/* handle dangerous IPv6 extension headers. */
7759 	if (action == PF_PASS && rh_cnt &&
7760 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
7761 		action = PF_DROP;
7762 		REASON_SET(&reason, PFRES_IPOPTIONS);
7763 		log = r->log;
7764 		DPFPRINTF(PF_DEBUG_MISC,
7765 		    ("pf: dropping packet with dangerous v6 headers\n"));
7766 	}
7767 
7768 	if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
7769 		action = PF_DROP;
7770 		REASON_SET(&reason, PFRES_MEMORY);
7771 	}
7772 	if (r->rtableid >= 0)
7773 		M_SETFIB(m, r->rtableid);
7774 
7775 	if (r->scrub_flags & PFSTATE_SETPRIO) {
7776 		if (pd.tos & IPTOS_LOWDELAY)
7777 			pqid = 1;
7778 		if (vlan_set_pcp(m, r->set_prio[pqid])) {
7779 			action = PF_DROP;
7780 			REASON_SET(&reason, PFRES_MEMORY);
7781 			log = 1;
7782 			DPFPRINTF(PF_DEBUG_MISC,
7783 			    ("pf: failed to allocate 802.1q mtag\n"));
7784 		}
7785 	}
7786 
7787 #ifdef ALTQ
7788 	if (s && s->qid) {
7789 		pd.act.pqid = s->pqid;
7790 		pd.act.qid = s->qid;
7791 	} else if (r->qid) {
7792 		pd.act.pqid = r->pqid;
7793 		pd.act.qid = r->qid;
7794 	}
7795 	if (action == PF_PASS && pd.act.qid) {
7796 		if (pd.pf_mtag == NULL &&
7797 		    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
7798 			action = PF_DROP;
7799 			REASON_SET(&reason, PFRES_MEMORY);
7800 		} else {
7801 			if (s != NULL)
7802 				pd.pf_mtag->qid_hash = pf_state_hash(s);
7803 			if (pd.tos & IPTOS_LOWDELAY)
7804 				pd.pf_mtag->qid = pd.act.pqid;
7805 			else
7806 				pd.pf_mtag->qid = pd.act.qid;
7807 			/* Add hints for ecn. */
7808 			pd.pf_mtag->hdr = h;
7809 		}
7810 	}
7811 #endif /* ALTQ */
7812 
7813 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
7814 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
7815 	    (s->nat_rule.ptr->action == PF_RDR ||
7816 	    s->nat_rule.ptr->action == PF_BINAT) &&
7817 	    IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
7818 		m->m_flags |= M_SKIP_FIREWALL;
7819 
7820 	/* XXX: Anybody working on it?! */
7821 	if (r->divert.port)
7822 		printf("pf: divert(9) is not supported for IPv6\n");
7823 
7824 	if (log) {
7825 		struct pf_krule *lr;
7826 
7827 		if (s != NULL && s->nat_rule.ptr != NULL &&
7828 		    s->nat_rule.ptr->log & PF_LOG_ALL)
7829 			lr = s->nat_rule.ptr;
7830 		else
7831 			lr = r;
7832 		PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
7833 		    &pd, (s == NULL));
7834 	}
7835 
7836 	pf_counter_u64_critical_enter();
7837 	pf_counter_u64_add_protected(&kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS],
7838 	    pd.tot_len);
7839 	pf_counter_u64_add_protected(&kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS],
7840 	    1);
7841 
7842 	if (action == PF_PASS || r->action == PF_DROP) {
7843 		dirndx = (dir == PF_OUT);
7844 		pf_counter_u64_add_protected(&r->packets[dirndx], 1);
7845 		pf_counter_u64_add_protected(&r->bytes[dirndx], pd.tot_len);
7846 		if (a != NULL) {
7847 			pf_counter_u64_add_protected(&a->packets[dirndx], 1);
7848 			pf_counter_u64_add_protected(&a->bytes[dirndx], pd.tot_len);
7849 		}
7850 		if (s != NULL) {
7851 			if (s->nat_rule.ptr != NULL) {
7852 				pf_counter_u64_add_protected(&s->nat_rule.ptr->packets[dirndx],
7853 				    1);
7854 				pf_counter_u64_add_protected(&s->nat_rule.ptr->bytes[dirndx],
7855 				    pd.tot_len);
7856 			}
7857 			if (s->src_node != NULL) {
7858 				counter_u64_add(s->src_node->packets[dirndx],
7859 				    1);
7860 				counter_u64_add(s->src_node->bytes[dirndx],
7861 				    pd.tot_len);
7862 			}
7863 			if (s->nat_src_node != NULL) {
7864 				counter_u64_add(s->nat_src_node->packets[dirndx],
7865 				    1);
7866 				counter_u64_add(s->nat_src_node->bytes[dirndx],
7867 				    pd.tot_len);
7868 			}
7869 			dirndx = (dir == s->direction) ? 0 : 1;
7870 			s->packets[dirndx]++;
7871 			s->bytes[dirndx] += pd.tot_len;
7872 		}
7873 		tr = r;
7874 		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
7875 		if (nr != NULL && r == &V_pf_default_rule)
7876 			tr = nr;
7877 		if (tr->src.addr.type == PF_ADDR_TABLE)
7878 			pfr_update_stats(tr->src.addr.p.tbl,
7879 			    (s == NULL) ? pd.src :
7880 			    &s->key[(s->direction == PF_IN)]->addr[0],
7881 			    pd.af, pd.tot_len, dir == PF_OUT,
7882 			    r->action == PF_PASS, tr->src.neg);
7883 		if (tr->dst.addr.type == PF_ADDR_TABLE)
7884 			pfr_update_stats(tr->dst.addr.p.tbl,
7885 			    (s == NULL) ? pd.dst :
7886 			    &s->key[(s->direction == PF_IN)]->addr[1],
7887 			    pd.af, pd.tot_len, dir == PF_OUT,
7888 			    r->action == PF_PASS, tr->dst.neg);
7889 	}
7890 	pf_counter_u64_critical_exit();
7891 
7892 	switch (action) {
7893 	case PF_SYNPROXY_DROP:
7894 		m_freem(*m0);
7895 	case PF_DEFER:
7896 		*m0 = NULL;
7897 		action = PF_PASS;
7898 		break;
7899 	case PF_DROP:
7900 		m_freem(*m0);
7901 		*m0 = NULL;
7902 		break;
7903 	default:
7904 		/* pf_route6() returns unlocked. */
7905 		if (r->rt) {
7906 			pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
7907 			return (action);
7908 		}
7909 		if (pf_dummynet(&pd, dir, s, r, m0) != 0) {
7910 			action = PF_DROP;
7911 			REASON_SET(&reason, PFRES_MEMORY);
7912 		}
7913 		break;
7914 	}
7915 
7916 	if (s)
7917 		PF_STATE_UNLOCK(s);
7918 
7919 	/* If reassembled packet passed, create new fragments. */
7920 	if (action == PF_PASS && *m0 && dir == PF_OUT &&
7921 	    (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
7922 		action = pf_refragment6(ifp, m0, mtag);
7923 
7924 	SDT_PROBE4(pf, ip, test6, done, action, reason, r, s);
7925 
7926 	return (action);
7927 }
7928 #endif /* INET6 */
7929