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