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