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