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