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