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