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