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