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