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