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