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