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