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