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