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