xref: /freebsd/sys/netpfil/pf/pf.c (revision 87b759f0fa1f7554d50ce640c40138512bbded44)
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 				pfse->pfse_m->m_flags |= M_SKIP_FIREWALL;
2211 				pfse->pfse_m->m_pkthdr.csum_flags |=
2212 				    CSUM_IP_VALID | CSUM_IP_CHECKED;
2213 				ip_input(pfse->pfse_m);
2214 			} else {
2215 				ip_output(pfse->pfse_m, NULL, NULL, 0, NULL,
2216 				    NULL);
2217 			}
2218 			break;
2219 		}
2220 		case PFSE_ICMP:
2221 			icmp_error(pfse->pfse_m, pfse->icmpopts.type,
2222 			    pfse->icmpopts.code, 0, pfse->icmpopts.mtu);
2223 			break;
2224 #endif /* INET */
2225 #ifdef INET6
2226 		case PFSE_IP6:
2227 			if (pf_isforlocal(pfse->pfse_m, AF_INET6)) {
2228 				pfse->pfse_m->m_flags |= M_SKIP_FIREWALL;
2229 				ip6_input(pfse->pfse_m);
2230 			} else {
2231 				ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL,
2232 				    NULL, NULL);
2233 			}
2234 			break;
2235 		case PFSE_ICMP6:
2236 			icmp6_error(pfse->pfse_m, pfse->icmpopts.type,
2237 			    pfse->icmpopts.code, pfse->icmpopts.mtu);
2238 			break;
2239 #endif /* INET6 */
2240 		default:
2241 			panic("%s: unknown type", __func__);
2242 		}
2243 		free(pfse, M_PFTEMP);
2244 	}
2245 	NET_EPOCH_EXIT(et);
2246 	CURVNET_RESTORE();
2247 }
2248 
2249 #define	pf_purge_thread_period	(hz / 10)
2250 
2251 #ifdef PF_WANT_32_TO_64_COUNTER
2252 static void
2253 pf_status_counter_u64_periodic(void)
2254 {
2255 
2256 	PF_RULES_RASSERT();
2257 
2258 	if ((V_pf_counter_periodic_iter % (pf_purge_thread_period * 10 * 60)) != 0) {
2259 		return;
2260 	}
2261 
2262 	for (int i = 0; i < FCNT_MAX; i++) {
2263 		pf_counter_u64_periodic(&V_pf_status.fcounters[i]);
2264 	}
2265 }
2266 
2267 static void
2268 pf_kif_counter_u64_periodic(void)
2269 {
2270 	struct pfi_kkif *kif;
2271 	size_t r, run;
2272 
2273 	PF_RULES_RASSERT();
2274 
2275 	if (__predict_false(V_pf_allkifcount == 0)) {
2276 		return;
2277 	}
2278 
2279 	if ((V_pf_counter_periodic_iter % (pf_purge_thread_period * 10 * 300)) != 0) {
2280 		return;
2281 	}
2282 
2283 	run = V_pf_allkifcount / 10;
2284 	if (run < 5)
2285 		run = 5;
2286 
2287 	for (r = 0; r < run; r++) {
2288 		kif = LIST_NEXT(V_pf_kifmarker, pfik_allkiflist);
2289 		if (kif == NULL) {
2290 			LIST_REMOVE(V_pf_kifmarker, pfik_allkiflist);
2291 			LIST_INSERT_HEAD(&V_pf_allkiflist, V_pf_kifmarker, pfik_allkiflist);
2292 			break;
2293 		}
2294 
2295 		LIST_REMOVE(V_pf_kifmarker, pfik_allkiflist);
2296 		LIST_INSERT_AFTER(kif, V_pf_kifmarker, pfik_allkiflist);
2297 
2298 		for (int i = 0; i < 2; i++) {
2299 			for (int j = 0; j < 2; j++) {
2300 				for (int k = 0; k < 2; k++) {
2301 					pf_counter_u64_periodic(&kif->pfik_packets[i][j][k]);
2302 					pf_counter_u64_periodic(&kif->pfik_bytes[i][j][k]);
2303 				}
2304 			}
2305 		}
2306 	}
2307 }
2308 
2309 static void
2310 pf_rule_counter_u64_periodic(void)
2311 {
2312 	struct pf_krule *rule;
2313 	size_t r, run;
2314 
2315 	PF_RULES_RASSERT();
2316 
2317 	if (__predict_false(V_pf_allrulecount == 0)) {
2318 		return;
2319 	}
2320 
2321 	if ((V_pf_counter_periodic_iter % (pf_purge_thread_period * 10 * 300)) != 0) {
2322 		return;
2323 	}
2324 
2325 	run = V_pf_allrulecount / 10;
2326 	if (run < 5)
2327 		run = 5;
2328 
2329 	for (r = 0; r < run; r++) {
2330 		rule = LIST_NEXT(V_pf_rulemarker, allrulelist);
2331 		if (rule == NULL) {
2332 			LIST_REMOVE(V_pf_rulemarker, allrulelist);
2333 			LIST_INSERT_HEAD(&V_pf_allrulelist, V_pf_rulemarker, allrulelist);
2334 			break;
2335 		}
2336 
2337 		LIST_REMOVE(V_pf_rulemarker, allrulelist);
2338 		LIST_INSERT_AFTER(rule, V_pf_rulemarker, allrulelist);
2339 
2340 		pf_counter_u64_periodic(&rule->evaluations);
2341 		for (int i = 0; i < 2; i++) {
2342 			pf_counter_u64_periodic(&rule->packets[i]);
2343 			pf_counter_u64_periodic(&rule->bytes[i]);
2344 		}
2345 	}
2346 }
2347 
2348 static void
2349 pf_counter_u64_periodic_main(void)
2350 {
2351 	PF_RULES_RLOCK_TRACKER;
2352 
2353 	V_pf_counter_periodic_iter++;
2354 
2355 	PF_RULES_RLOCK();
2356 	pf_counter_u64_critical_enter();
2357 	pf_status_counter_u64_periodic();
2358 	pf_kif_counter_u64_periodic();
2359 	pf_rule_counter_u64_periodic();
2360 	pf_counter_u64_critical_exit();
2361 	PF_RULES_RUNLOCK();
2362 }
2363 #else
2364 #define	pf_counter_u64_periodic_main()	do { } while (0)
2365 #endif
2366 
2367 void
2368 pf_purge_thread(void *unused __unused)
2369 {
2370 	struct epoch_tracker	 et;
2371 
2372 	VNET_ITERATOR_DECL(vnet_iter);
2373 
2374 	sx_xlock(&pf_end_lock);
2375 	while (pf_end_threads == 0) {
2376 		sx_sleep(pf_purge_thread, &pf_end_lock, 0, "pftm", pf_purge_thread_period);
2377 
2378 		VNET_LIST_RLOCK();
2379 		NET_EPOCH_ENTER(et);
2380 		VNET_FOREACH(vnet_iter) {
2381 			CURVNET_SET(vnet_iter);
2382 
2383 			/* Wait until V_pf_default_rule is initialized. */
2384 			if (V_pf_vnet_active == 0) {
2385 				CURVNET_RESTORE();
2386 				continue;
2387 			}
2388 
2389 			pf_counter_u64_periodic_main();
2390 
2391 			/*
2392 			 *  Process 1/interval fraction of the state
2393 			 * table every run.
2394 			 */
2395 			V_pf_purge_idx =
2396 			    pf_purge_expired_states(V_pf_purge_idx, V_pf_hashmask /
2397 			    (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
2398 
2399 			/*
2400 			 * Purge other expired types every
2401 			 * PFTM_INTERVAL seconds.
2402 			 */
2403 			if (V_pf_purge_idx == 0) {
2404 				/*
2405 				 * Order is important:
2406 				 * - states and src nodes reference rules
2407 				 * - states and rules reference kifs
2408 				 */
2409 				pf_purge_expired_fragments();
2410 				pf_purge_expired_src_nodes();
2411 				pf_purge_unlinked_rules();
2412 				pfi_kkif_purge();
2413 			}
2414 			CURVNET_RESTORE();
2415 		}
2416 		NET_EPOCH_EXIT(et);
2417 		VNET_LIST_RUNLOCK();
2418 	}
2419 
2420 	pf_end_threads++;
2421 	sx_xunlock(&pf_end_lock);
2422 	kproc_exit(0);
2423 }
2424 
2425 void
2426 pf_unload_vnet_purge(void)
2427 {
2428 
2429 	/*
2430 	 * To cleanse up all kifs and rules we need
2431 	 * two runs: first one clears reference flags,
2432 	 * then pf_purge_expired_states() doesn't
2433 	 * raise them, and then second run frees.
2434 	 */
2435 	pf_purge_unlinked_rules();
2436 	pfi_kkif_purge();
2437 
2438 	/*
2439 	 * Now purge everything.
2440 	 */
2441 	pf_purge_expired_states(0, V_pf_hashmask);
2442 	pf_purge_fragments(UINT_MAX);
2443 	pf_purge_expired_src_nodes();
2444 
2445 	/*
2446 	 * Now all kifs & rules should be unreferenced,
2447 	 * thus should be successfully freed.
2448 	 */
2449 	pf_purge_unlinked_rules();
2450 	pfi_kkif_purge();
2451 }
2452 
2453 u_int32_t
2454 pf_state_expires(const struct pf_kstate *state)
2455 {
2456 	u_int32_t	timeout;
2457 	u_int32_t	start;
2458 	u_int32_t	end;
2459 	u_int32_t	states;
2460 
2461 	/* handle all PFTM_* > PFTM_MAX here */
2462 	if (state->timeout == PFTM_PURGE)
2463 		return (time_uptime);
2464 	KASSERT(state->timeout != PFTM_UNLINKED,
2465 	    ("pf_state_expires: timeout == PFTM_UNLINKED"));
2466 	KASSERT((state->timeout < PFTM_MAX),
2467 	    ("pf_state_expires: timeout > PFTM_MAX"));
2468 	timeout = state->rule->timeout[state->timeout];
2469 	if (!timeout)
2470 		timeout = V_pf_default_rule.timeout[state->timeout];
2471 	start = state->rule->timeout[PFTM_ADAPTIVE_START];
2472 	if (start && state->rule != &V_pf_default_rule) {
2473 		end = state->rule->timeout[PFTM_ADAPTIVE_END];
2474 		states = counter_u64_fetch(state->rule->states_cur);
2475 	} else {
2476 		start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
2477 		end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
2478 		states = V_pf_status.states;
2479 	}
2480 	if (end && states > start && start < end) {
2481 		if (states < end) {
2482 			timeout = (u_int64_t)timeout * (end - states) /
2483 			    (end - start);
2484 			return ((state->expire / 1000) + timeout);
2485 		}
2486 		else
2487 			return (time_uptime);
2488 	}
2489 	return ((state->expire / 1000) + timeout);
2490 }
2491 
2492 void
2493 pf_purge_expired_src_nodes(void)
2494 {
2495 	struct pf_ksrc_node_list	 freelist;
2496 	struct pf_srchash	*sh;
2497 	struct pf_ksrc_node	*cur, *next;
2498 	int i;
2499 
2500 	LIST_INIT(&freelist);
2501 	for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask; i++, sh++) {
2502 	    PF_HASHROW_LOCK(sh);
2503 	    LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
2504 		if (cur->states == 0 && cur->expire <= time_uptime) {
2505 			pf_unlink_src_node(cur);
2506 			LIST_INSERT_HEAD(&freelist, cur, entry);
2507 		} else if (cur->rule != NULL)
2508 			cur->rule->rule_ref |= PFRULE_REFS;
2509 	    PF_HASHROW_UNLOCK(sh);
2510 	}
2511 
2512 	pf_free_src_nodes(&freelist);
2513 
2514 	V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
2515 }
2516 
2517 static void
2518 pf_src_tree_remove_state(struct pf_kstate *s)
2519 {
2520 	struct pf_ksrc_node *sn;
2521 	uint32_t timeout;
2522 
2523 	timeout = s->rule->timeout[PFTM_SRC_NODE] ?
2524 	    s->rule->timeout[PFTM_SRC_NODE] :
2525 	    V_pf_default_rule.timeout[PFTM_SRC_NODE];
2526 
2527 	if (s->src_node != NULL) {
2528 		sn = s->src_node;
2529 		PF_SRC_NODE_LOCK(sn);
2530 		if (s->src.tcp_est)
2531 			--sn->conn;
2532 		if (--sn->states == 0)
2533 			sn->expire = time_uptime + timeout;
2534 		PF_SRC_NODE_UNLOCK(sn);
2535 	}
2536 	if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
2537 		sn = s->nat_src_node;
2538 		PF_SRC_NODE_LOCK(sn);
2539 		if (--sn->states == 0)
2540 			sn->expire = time_uptime + timeout;
2541 		PF_SRC_NODE_UNLOCK(sn);
2542 	}
2543 	s->src_node = s->nat_src_node = NULL;
2544 }
2545 
2546 /*
2547  * Unlink and potentilly free a state. Function may be
2548  * called with ID hash row locked, but always returns
2549  * unlocked, since it needs to go through key hash locking.
2550  */
2551 int
2552 pf_unlink_state(struct pf_kstate *s)
2553 {
2554 	struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
2555 
2556 	NET_EPOCH_ASSERT();
2557 	PF_HASHROW_ASSERT(ih);
2558 
2559 	if (s->timeout == PFTM_UNLINKED) {
2560 		/*
2561 		 * State is being processed
2562 		 * by pf_unlink_state() in
2563 		 * an other thread.
2564 		 */
2565 		PF_HASHROW_UNLOCK(ih);
2566 		return (0);	/* XXXGL: undefined actually */
2567 	}
2568 
2569 	if (s->src.state == PF_TCPS_PROXY_DST) {
2570 		/* XXX wire key the right one? */
2571 		pf_send_tcp(s->rule, s->key[PF_SK_WIRE]->af,
2572 		    &s->key[PF_SK_WIRE]->addr[1],
2573 		    &s->key[PF_SK_WIRE]->addr[0],
2574 		    s->key[PF_SK_WIRE]->port[1],
2575 		    s->key[PF_SK_WIRE]->port[0],
2576 		    s->src.seqhi, s->src.seqlo + 1,
2577 		    TH_RST|TH_ACK, 0, 0, 0, true, s->tag, 0, s->act.rtableid);
2578 	}
2579 
2580 	LIST_REMOVE(s, entry);
2581 	pf_src_tree_remove_state(s);
2582 
2583 	if (V_pfsync_delete_state_ptr != NULL)
2584 		V_pfsync_delete_state_ptr(s);
2585 
2586 	STATE_DEC_COUNTERS(s);
2587 
2588 	s->timeout = PFTM_UNLINKED;
2589 
2590 	/* Ensure we remove it from the list of halfopen states, if needed. */
2591 	if (s->key[PF_SK_STACK] != NULL &&
2592 	    s->key[PF_SK_STACK]->proto == IPPROTO_TCP)
2593 		pf_set_protostate(s, PF_PEER_BOTH, TCPS_CLOSED);
2594 
2595 	PF_HASHROW_UNLOCK(ih);
2596 
2597 	pf_detach_state(s);
2598 
2599 	pf_udp_mapping_release(s->udp_mapping);
2600 
2601 	/* pf_state_insert() initialises refs to 2 */
2602 	return (pf_release_staten(s, 2));
2603 }
2604 
2605 struct pf_kstate *
2606 pf_alloc_state(int flags)
2607 {
2608 
2609 	return (uma_zalloc(V_pf_state_z, flags | M_ZERO));
2610 }
2611 
2612 void
2613 pf_free_state(struct pf_kstate *cur)
2614 {
2615 	struct pf_krule_item *ri;
2616 
2617 	KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
2618 	KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
2619 	    cur->timeout));
2620 
2621 	while ((ri = SLIST_FIRST(&cur->match_rules))) {
2622 		SLIST_REMOVE_HEAD(&cur->match_rules, entry);
2623 		free(ri, M_PF_RULE_ITEM);
2624 	}
2625 
2626 	pf_normalize_tcp_cleanup(cur);
2627 	uma_zfree(V_pf_state_z, cur);
2628 	pf_counter_u64_add(&V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
2629 }
2630 
2631 /*
2632  * Called only from pf_purge_thread(), thus serialized.
2633  */
2634 static u_int
2635 pf_purge_expired_states(u_int i, int maxcheck)
2636 {
2637 	struct pf_idhash *ih;
2638 	struct pf_kstate *s;
2639 	struct pf_krule_item *mrm;
2640 	size_t count __unused;
2641 
2642 	V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
2643 
2644 	/*
2645 	 * Go through hash and unlink states that expire now.
2646 	 */
2647 	while (maxcheck > 0) {
2648 		count = 0;
2649 		ih = &V_pf_idhash[i];
2650 
2651 		/* only take the lock if we expect to do work */
2652 		if (!LIST_EMPTY(&ih->states)) {
2653 relock:
2654 			PF_HASHROW_LOCK(ih);
2655 			LIST_FOREACH(s, &ih->states, entry) {
2656 				if (pf_state_expires(s) <= time_uptime) {
2657 					V_pf_status.states -=
2658 					    pf_unlink_state(s);
2659 					goto relock;
2660 				}
2661 				s->rule->rule_ref |= PFRULE_REFS;
2662 				if (s->nat_rule != NULL)
2663 					s->nat_rule->rule_ref |= PFRULE_REFS;
2664 				if (s->anchor != NULL)
2665 					s->anchor->rule_ref |= PFRULE_REFS;
2666 				s->kif->pfik_flags |= PFI_IFLAG_REFS;
2667 				SLIST_FOREACH(mrm, &s->match_rules, entry)
2668 					mrm->r->rule_ref |= PFRULE_REFS;
2669 				if (s->rt_kif)
2670 					s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
2671 				count++;
2672 			}
2673 			PF_HASHROW_UNLOCK(ih);
2674 		}
2675 
2676 		SDT_PROBE2(pf, purge, state, rowcount, i, count);
2677 
2678 		/* Return when we hit end of hash. */
2679 		if (++i > V_pf_hashmask) {
2680 			V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
2681 			return (0);
2682 		}
2683 
2684 		maxcheck--;
2685 	}
2686 
2687 	V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
2688 
2689 	return (i);
2690 }
2691 
2692 static void
2693 pf_purge_unlinked_rules(void)
2694 {
2695 	struct pf_krulequeue tmpq;
2696 	struct pf_krule *r, *r1;
2697 
2698 	/*
2699 	 * If we have overloading task pending, then we'd
2700 	 * better skip purging this time. There is a tiny
2701 	 * probability that overloading task references
2702 	 * an already unlinked rule.
2703 	 */
2704 	PF_OVERLOADQ_LOCK();
2705 	if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
2706 		PF_OVERLOADQ_UNLOCK();
2707 		return;
2708 	}
2709 	PF_OVERLOADQ_UNLOCK();
2710 
2711 	/*
2712 	 * Do naive mark-and-sweep garbage collecting of old rules.
2713 	 * Reference flag is raised by pf_purge_expired_states()
2714 	 * and pf_purge_expired_src_nodes().
2715 	 *
2716 	 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
2717 	 * use a temporary queue.
2718 	 */
2719 	TAILQ_INIT(&tmpq);
2720 	PF_UNLNKDRULES_LOCK();
2721 	TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
2722 		if (!(r->rule_ref & PFRULE_REFS)) {
2723 			TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
2724 			TAILQ_INSERT_TAIL(&tmpq, r, entries);
2725 		} else
2726 			r->rule_ref &= ~PFRULE_REFS;
2727 	}
2728 	PF_UNLNKDRULES_UNLOCK();
2729 
2730 	if (!TAILQ_EMPTY(&tmpq)) {
2731 		PF_CONFIG_LOCK();
2732 		PF_RULES_WLOCK();
2733 		TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
2734 			TAILQ_REMOVE(&tmpq, r, entries);
2735 			pf_free_rule(r);
2736 		}
2737 		PF_RULES_WUNLOCK();
2738 		PF_CONFIG_UNLOCK();
2739 	}
2740 }
2741 
2742 void
2743 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
2744 {
2745 	switch (af) {
2746 #ifdef INET
2747 	case AF_INET: {
2748 		u_int32_t a = ntohl(addr->addr32[0]);
2749 		printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
2750 		    (a>>8)&255, a&255);
2751 		if (p) {
2752 			p = ntohs(p);
2753 			printf(":%u", p);
2754 		}
2755 		break;
2756 	}
2757 #endif /* INET */
2758 #ifdef INET6
2759 	case AF_INET6: {
2760 		u_int16_t b;
2761 		u_int8_t i, curstart, curend, maxstart, maxend;
2762 		curstart = curend = maxstart = maxend = 255;
2763 		for (i = 0; i < 8; i++) {
2764 			if (!addr->addr16[i]) {
2765 				if (curstart == 255)
2766 					curstart = i;
2767 				curend = i;
2768 			} else {
2769 				if ((curend - curstart) >
2770 				    (maxend - maxstart)) {
2771 					maxstart = curstart;
2772 					maxend = curend;
2773 				}
2774 				curstart = curend = 255;
2775 			}
2776 		}
2777 		if ((curend - curstart) >
2778 		    (maxend - maxstart)) {
2779 			maxstart = curstart;
2780 			maxend = curend;
2781 		}
2782 		for (i = 0; i < 8; i++) {
2783 			if (i >= maxstart && i <= maxend) {
2784 				if (i == 0)
2785 					printf(":");
2786 				if (i == maxend)
2787 					printf(":");
2788 			} else {
2789 				b = ntohs(addr->addr16[i]);
2790 				printf("%x", b);
2791 				if (i < 7)
2792 					printf(":");
2793 			}
2794 		}
2795 		if (p) {
2796 			p = ntohs(p);
2797 			printf("[%u]", p);
2798 		}
2799 		break;
2800 	}
2801 #endif /* INET6 */
2802 	}
2803 }
2804 
2805 void
2806 pf_print_state(struct pf_kstate *s)
2807 {
2808 	pf_print_state_parts(s, NULL, NULL);
2809 }
2810 
2811 static void
2812 pf_print_state_parts(struct pf_kstate *s,
2813     struct pf_state_key *skwp, struct pf_state_key *sksp)
2814 {
2815 	struct pf_state_key *skw, *sks;
2816 	u_int8_t proto, dir;
2817 
2818 	/* Do our best to fill these, but they're skipped if NULL */
2819 	skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
2820 	sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
2821 	proto = skw ? skw->proto : (sks ? sks->proto : 0);
2822 	dir = s ? s->direction : 0;
2823 
2824 	switch (proto) {
2825 	case IPPROTO_IPV4:
2826 		printf("IPv4");
2827 		break;
2828 	case IPPROTO_IPV6:
2829 		printf("IPv6");
2830 		break;
2831 	case IPPROTO_TCP:
2832 		printf("TCP");
2833 		break;
2834 	case IPPROTO_UDP:
2835 		printf("UDP");
2836 		break;
2837 	case IPPROTO_ICMP:
2838 		printf("ICMP");
2839 		break;
2840 	case IPPROTO_ICMPV6:
2841 		printf("ICMPv6");
2842 		break;
2843 	default:
2844 		printf("%u", proto);
2845 		break;
2846 	}
2847 	switch (dir) {
2848 	case PF_IN:
2849 		printf(" in");
2850 		break;
2851 	case PF_OUT:
2852 		printf(" out");
2853 		break;
2854 	}
2855 	if (skw) {
2856 		printf(" wire: ");
2857 		pf_print_host(&skw->addr[0], skw->port[0], skw->af);
2858 		printf(" ");
2859 		pf_print_host(&skw->addr[1], skw->port[1], skw->af);
2860 	}
2861 	if (sks) {
2862 		printf(" stack: ");
2863 		if (sks != skw) {
2864 			pf_print_host(&sks->addr[0], sks->port[0], sks->af);
2865 			printf(" ");
2866 			pf_print_host(&sks->addr[1], sks->port[1], sks->af);
2867 		} else
2868 			printf("-");
2869 	}
2870 	if (s) {
2871 		if (proto == IPPROTO_TCP) {
2872 			printf(" [lo=%u high=%u win=%u modulator=%u",
2873 			    s->src.seqlo, s->src.seqhi,
2874 			    s->src.max_win, s->src.seqdiff);
2875 			if (s->src.wscale && s->dst.wscale)
2876 				printf(" wscale=%u",
2877 				    s->src.wscale & PF_WSCALE_MASK);
2878 			printf("]");
2879 			printf(" [lo=%u high=%u win=%u modulator=%u",
2880 			    s->dst.seqlo, s->dst.seqhi,
2881 			    s->dst.max_win, s->dst.seqdiff);
2882 			if (s->src.wscale && s->dst.wscale)
2883 				printf(" wscale=%u",
2884 				s->dst.wscale & PF_WSCALE_MASK);
2885 			printf("]");
2886 		}
2887 		printf(" %u:%u", s->src.state, s->dst.state);
2888 		if (s->rule)
2889 			printf(" @%d", s->rule->nr);
2890 	}
2891 }
2892 
2893 void
2894 pf_print_flags(u_int8_t f)
2895 {
2896 	if (f)
2897 		printf(" ");
2898 	if (f & TH_FIN)
2899 		printf("F");
2900 	if (f & TH_SYN)
2901 		printf("S");
2902 	if (f & TH_RST)
2903 		printf("R");
2904 	if (f & TH_PUSH)
2905 		printf("P");
2906 	if (f & TH_ACK)
2907 		printf("A");
2908 	if (f & TH_URG)
2909 		printf("U");
2910 	if (f & TH_ECE)
2911 		printf("E");
2912 	if (f & TH_CWR)
2913 		printf("W");
2914 }
2915 
2916 #define	PF_SET_SKIP_STEPS(i)					\
2917 	do {							\
2918 		while (head[i] != cur) {			\
2919 			head[i]->skip[i] = cur;			\
2920 			head[i] = TAILQ_NEXT(head[i], entries);	\
2921 		}						\
2922 	} while (0)
2923 
2924 void
2925 pf_calc_skip_steps(struct pf_krulequeue *rules)
2926 {
2927 	struct pf_krule *cur, *prev, *head[PF_SKIP_COUNT];
2928 	int i;
2929 
2930 	cur = TAILQ_FIRST(rules);
2931 	prev = cur;
2932 	for (i = 0; i < PF_SKIP_COUNT; ++i)
2933 		head[i] = cur;
2934 	while (cur != NULL) {
2935 		if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
2936 			PF_SET_SKIP_STEPS(PF_SKIP_IFP);
2937 		if (cur->direction != prev->direction)
2938 			PF_SET_SKIP_STEPS(PF_SKIP_DIR);
2939 		if (cur->af != prev->af)
2940 			PF_SET_SKIP_STEPS(PF_SKIP_AF);
2941 		if (cur->proto != prev->proto)
2942 			PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
2943 		if (cur->src.neg != prev->src.neg ||
2944 		    pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
2945 			PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
2946 		if (cur->dst.neg != prev->dst.neg ||
2947 		    pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
2948 			PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
2949 		if (cur->src.port[0] != prev->src.port[0] ||
2950 		    cur->src.port[1] != prev->src.port[1] ||
2951 		    cur->src.port_op != prev->src.port_op)
2952 			PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
2953 		if (cur->dst.port[0] != prev->dst.port[0] ||
2954 		    cur->dst.port[1] != prev->dst.port[1] ||
2955 		    cur->dst.port_op != prev->dst.port_op)
2956 			PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
2957 
2958 		prev = cur;
2959 		cur = TAILQ_NEXT(cur, entries);
2960 	}
2961 	for (i = 0; i < PF_SKIP_COUNT; ++i)
2962 		PF_SET_SKIP_STEPS(i);
2963 }
2964 
2965 int
2966 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
2967 {
2968 	if (aw1->type != aw2->type)
2969 		return (1);
2970 	switch (aw1->type) {
2971 	case PF_ADDR_ADDRMASK:
2972 	case PF_ADDR_RANGE:
2973 		if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2974 			return (1);
2975 		if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2976 			return (1);
2977 		return (0);
2978 	case PF_ADDR_DYNIFTL:
2979 		return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2980 	case PF_ADDR_NOROUTE:
2981 	case PF_ADDR_URPFFAILED:
2982 		return (0);
2983 	case PF_ADDR_TABLE:
2984 		return (aw1->p.tbl != aw2->p.tbl);
2985 	default:
2986 		printf("invalid address type: %d\n", aw1->type);
2987 		return (1);
2988 	}
2989 }
2990 
2991 /**
2992  * Checksum updates are a little complicated because the checksum in the TCP/UDP
2993  * header isn't always a full checksum. In some cases (i.e. output) it's a
2994  * pseudo-header checksum, which is a partial checksum over src/dst IP
2995  * addresses, protocol number and length.
2996  *
2997  * That means we have the following cases:
2998  *  * Input or forwarding: we don't have TSO, the checksum fields are full
2999  *  	checksums, we need to update the checksum whenever we change anything.
3000  *  * Output (i.e. the checksum is a pseudo-header checksum):
3001  *  	x The field being updated is src/dst address or affects the length of
3002  *  	the packet. We need to update the pseudo-header checksum (note that this
3003  *  	checksum is not ones' complement).
3004  *  	x Some other field is being modified (e.g. src/dst port numbers): We
3005  *  	don't have to update anything.
3006  **/
3007 u_int16_t
3008 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
3009 {
3010 	u_int32_t x;
3011 
3012 	x = cksum + old - new;
3013 	x = (x + (x >> 16)) & 0xffff;
3014 
3015 	/* optimise: eliminate a branch when not udp */
3016 	if (udp && cksum == 0x0000)
3017 		return cksum;
3018 	if (udp && x == 0x0000)
3019 		x = 0xffff;
3020 
3021 	return (u_int16_t)(x);
3022 }
3023 
3024 static void
3025 pf_patch_8(struct mbuf *m, u_int16_t *cksum, u_int8_t *f, u_int8_t v, bool hi,
3026     u_int8_t udp)
3027 {
3028 	u_int16_t old = htons(hi ? (*f << 8) : *f);
3029 	u_int16_t new = htons(hi ? ( v << 8) :  v);
3030 
3031 	if (*f == v)
3032 		return;
3033 
3034 	*f = v;
3035 
3036 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
3037 		return;
3038 
3039 	*cksum = pf_cksum_fixup(*cksum, old, new, udp);
3040 }
3041 
3042 void
3043 pf_patch_16_unaligned(struct mbuf *m, u_int16_t *cksum, void *f, u_int16_t v,
3044     bool hi, u_int8_t udp)
3045 {
3046 	u_int8_t *fb = (u_int8_t *)f;
3047 	u_int8_t *vb = (u_int8_t *)&v;
3048 
3049 	pf_patch_8(m, cksum, fb++, *vb++, hi, udp);
3050 	pf_patch_8(m, cksum, fb++, *vb++, !hi, udp);
3051 }
3052 
3053 void
3054 pf_patch_32_unaligned(struct mbuf *m, u_int16_t *cksum, void *f, u_int32_t v,
3055     bool hi, u_int8_t udp)
3056 {
3057 	u_int8_t *fb = (u_int8_t *)f;
3058 	u_int8_t *vb = (u_int8_t *)&v;
3059 
3060 	pf_patch_8(m, cksum, fb++, *vb++, hi, udp);
3061 	pf_patch_8(m, cksum, fb++, *vb++, !hi, udp);
3062 	pf_patch_8(m, cksum, fb++, *vb++, hi, udp);
3063 	pf_patch_8(m, cksum, fb++, *vb++, !hi, udp);
3064 }
3065 
3066 u_int16_t
3067 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
3068         u_int16_t new, u_int8_t udp)
3069 {
3070 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
3071 		return (cksum);
3072 
3073 	return (pf_cksum_fixup(cksum, old, new, udp));
3074 }
3075 
3076 static void
3077 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
3078         u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
3079         sa_family_t af)
3080 {
3081 	struct pf_addr	ao;
3082 	u_int16_t	po = *p;
3083 
3084 	PF_ACPY(&ao, a, af);
3085 	PF_ACPY(a, an, af);
3086 
3087 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
3088 		*pc = ~*pc;
3089 
3090 	*p = pn;
3091 
3092 	switch (af) {
3093 #ifdef INET
3094 	case AF_INET:
3095 		*ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
3096 		    ao.addr16[0], an->addr16[0], 0),
3097 		    ao.addr16[1], an->addr16[1], 0);
3098 		*p = pn;
3099 
3100 		*pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
3101 		    ao.addr16[0], an->addr16[0], u),
3102 		    ao.addr16[1], an->addr16[1], u);
3103 
3104 		*pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
3105 		break;
3106 #endif /* INET */
3107 #ifdef INET6
3108 	case AF_INET6:
3109 		*pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
3110 		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
3111 		    pf_cksum_fixup(pf_cksum_fixup(*pc,
3112 		    ao.addr16[0], an->addr16[0], u),
3113 		    ao.addr16[1], an->addr16[1], u),
3114 		    ao.addr16[2], an->addr16[2], u),
3115 		    ao.addr16[3], an->addr16[3], u),
3116 		    ao.addr16[4], an->addr16[4], u),
3117 		    ao.addr16[5], an->addr16[5], u),
3118 		    ao.addr16[6], an->addr16[6], u),
3119 		    ao.addr16[7], an->addr16[7], u);
3120 
3121 		*pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
3122 		break;
3123 #endif /* INET6 */
3124 	}
3125 
3126 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
3127 	    CSUM_DELAY_DATA_IPV6)) {
3128 		*pc = ~*pc;
3129 		if (! *pc)
3130 			*pc = 0xffff;
3131 	}
3132 }
3133 
3134 /* Changes a u_int32_t.  Uses a void * so there are no align restrictions */
3135 void
3136 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
3137 {
3138 	u_int32_t	ao;
3139 
3140 	memcpy(&ao, a, sizeof(ao));
3141 	memcpy(a, &an, sizeof(u_int32_t));
3142 	*c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
3143 	    ao % 65536, an % 65536, u);
3144 }
3145 
3146 void
3147 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
3148 {
3149 	u_int32_t	ao;
3150 
3151 	memcpy(&ao, a, sizeof(ao));
3152 	memcpy(a, &an, sizeof(u_int32_t));
3153 
3154 	*c = pf_proto_cksum_fixup(m,
3155 	    pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
3156 	    ao % 65536, an % 65536, udp);
3157 }
3158 
3159 #ifdef INET6
3160 static void
3161 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
3162 {
3163 	struct pf_addr	ao;
3164 
3165 	PF_ACPY(&ao, a, AF_INET6);
3166 	PF_ACPY(a, an, AF_INET6);
3167 
3168 	*c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
3169 	    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
3170 	    pf_cksum_fixup(pf_cksum_fixup(*c,
3171 	    ao.addr16[0], an->addr16[0], u),
3172 	    ao.addr16[1], an->addr16[1], u),
3173 	    ao.addr16[2], an->addr16[2], u),
3174 	    ao.addr16[3], an->addr16[3], u),
3175 	    ao.addr16[4], an->addr16[4], u),
3176 	    ao.addr16[5], an->addr16[5], u),
3177 	    ao.addr16[6], an->addr16[6], u),
3178 	    ao.addr16[7], an->addr16[7], u);
3179 }
3180 #endif /* INET6 */
3181 
3182 static void
3183 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
3184     struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
3185     u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
3186 {
3187 	struct pf_addr	oia, ooa;
3188 
3189 	PF_ACPY(&oia, ia, af);
3190 	if (oa)
3191 		PF_ACPY(&ooa, oa, af);
3192 
3193 	/* Change inner protocol port, fix inner protocol checksum. */
3194 	if (ip != NULL) {
3195 		u_int16_t	oip = *ip;
3196 		u_int32_t	opc;
3197 
3198 		if (pc != NULL)
3199 			opc = *pc;
3200 		*ip = np;
3201 		if (pc != NULL)
3202 			*pc = pf_cksum_fixup(*pc, oip, *ip, u);
3203 		*ic = pf_cksum_fixup(*ic, oip, *ip, 0);
3204 		if (pc != NULL)
3205 			*ic = pf_cksum_fixup(*ic, opc, *pc, 0);
3206 	}
3207 	/* Change inner ip address, fix inner ip and icmp checksums. */
3208 	PF_ACPY(ia, na, af);
3209 	switch (af) {
3210 #ifdef INET
3211 	case AF_INET: {
3212 		u_int32_t	 oh2c = *h2c;
3213 
3214 		*h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
3215 		    oia.addr16[0], ia->addr16[0], 0),
3216 		    oia.addr16[1], ia->addr16[1], 0);
3217 		*ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
3218 		    oia.addr16[0], ia->addr16[0], 0),
3219 		    oia.addr16[1], ia->addr16[1], 0);
3220 		*ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
3221 		break;
3222 	}
3223 #endif /* INET */
3224 #ifdef INET6
3225 	case AF_INET6:
3226 		*ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
3227 		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
3228 		    pf_cksum_fixup(pf_cksum_fixup(*ic,
3229 		    oia.addr16[0], ia->addr16[0], u),
3230 		    oia.addr16[1], ia->addr16[1], u),
3231 		    oia.addr16[2], ia->addr16[2], u),
3232 		    oia.addr16[3], ia->addr16[3], u),
3233 		    oia.addr16[4], ia->addr16[4], u),
3234 		    oia.addr16[5], ia->addr16[5], u),
3235 		    oia.addr16[6], ia->addr16[6], u),
3236 		    oia.addr16[7], ia->addr16[7], u);
3237 		break;
3238 #endif /* INET6 */
3239 	}
3240 	/* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
3241 	if (oa) {
3242 		PF_ACPY(oa, na, af);
3243 		switch (af) {
3244 #ifdef INET
3245 		case AF_INET:
3246 			*hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
3247 			    ooa.addr16[0], oa->addr16[0], 0),
3248 			    ooa.addr16[1], oa->addr16[1], 0);
3249 			break;
3250 #endif /* INET */
3251 #ifdef INET6
3252 		case AF_INET6:
3253 			*ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
3254 			    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
3255 			    pf_cksum_fixup(pf_cksum_fixup(*ic,
3256 			    ooa.addr16[0], oa->addr16[0], u),
3257 			    ooa.addr16[1], oa->addr16[1], u),
3258 			    ooa.addr16[2], oa->addr16[2], u),
3259 			    ooa.addr16[3], oa->addr16[3], u),
3260 			    ooa.addr16[4], oa->addr16[4], u),
3261 			    ooa.addr16[5], oa->addr16[5], u),
3262 			    ooa.addr16[6], oa->addr16[6], u),
3263 			    ooa.addr16[7], oa->addr16[7], u);
3264 			break;
3265 #endif /* INET6 */
3266 		}
3267 	}
3268 }
3269 
3270 /*
3271  * Need to modulate the sequence numbers in the TCP SACK option
3272  * (credits to Krzysztof Pfaff for report and patch)
3273  */
3274 static int
3275 pf_modulate_sack(struct pf_pdesc *pd, struct tcphdr *th,
3276     struct pf_state_peer *dst)
3277 {
3278 	int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
3279 	u_int8_t opts[TCP_MAXOLEN], *opt = opts;
3280 	int copyback = 0, i, olen;
3281 	struct sackblk sack;
3282 
3283 #define	TCPOLEN_SACKLEN	(TCPOLEN_SACK + 2)
3284 	if (hlen < TCPOLEN_SACKLEN ||
3285 	    !pf_pull_hdr(pd->m, pd->off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
3286 		return 0;
3287 
3288 	while (hlen >= TCPOLEN_SACKLEN) {
3289 		size_t startoff = opt - opts;
3290 		olen = opt[1];
3291 		switch (*opt) {
3292 		case TCPOPT_EOL:	/* FALLTHROUGH */
3293 		case TCPOPT_NOP:
3294 			opt++;
3295 			hlen--;
3296 			break;
3297 		case TCPOPT_SACK:
3298 			if (olen > hlen)
3299 				olen = hlen;
3300 			if (olen >= TCPOLEN_SACKLEN) {
3301 				for (i = 2; i + TCPOLEN_SACK <= olen;
3302 				    i += TCPOLEN_SACK) {
3303 					memcpy(&sack, &opt[i], sizeof(sack));
3304 					pf_patch_32_unaligned(pd->m,
3305 					    &th->th_sum, &sack.start,
3306 					    htonl(ntohl(sack.start) - dst->seqdiff),
3307 					    PF_ALGNMNT(startoff),
3308 					    0);
3309 					pf_patch_32_unaligned(pd->m, &th->th_sum,
3310 					    &sack.end,
3311 					    htonl(ntohl(sack.end) - dst->seqdiff),
3312 					    PF_ALGNMNT(startoff),
3313 					    0);
3314 					memcpy(&opt[i], &sack, sizeof(sack));
3315 				}
3316 				copyback = 1;
3317 			}
3318 			/* FALLTHROUGH */
3319 		default:
3320 			if (olen < 2)
3321 				olen = 2;
3322 			hlen -= olen;
3323 			opt += olen;
3324 		}
3325 	}
3326 
3327 	if (copyback)
3328 		m_copyback(pd->m, pd->off + sizeof(*th), thoptlen, (caddr_t)opts);
3329 	return (copyback);
3330 }
3331 
3332 struct mbuf *
3333 pf_build_tcp(const struct pf_krule *r, sa_family_t af,
3334     const struct pf_addr *saddr, const struct pf_addr *daddr,
3335     u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
3336     u_int8_t tcp_flags, u_int16_t win, u_int16_t mss, u_int8_t ttl,
3337     bool skip_firewall, u_int16_t mtag_tag, u_int16_t mtag_flags, int rtableid)
3338 {
3339 	struct mbuf	*m;
3340 	int		 len, tlen;
3341 #ifdef INET
3342 	struct ip	*h = NULL;
3343 #endif /* INET */
3344 #ifdef INET6
3345 	struct ip6_hdr	*h6 = NULL;
3346 #endif /* INET6 */
3347 	struct tcphdr	*th;
3348 	char		*opt;
3349 	struct pf_mtag  *pf_mtag;
3350 
3351 	len = 0;
3352 	th = NULL;
3353 
3354 	/* maximum segment size tcp option */
3355 	tlen = sizeof(struct tcphdr);
3356 	if (mss)
3357 		tlen += 4;
3358 
3359 	switch (af) {
3360 #ifdef INET
3361 	case AF_INET:
3362 		len = sizeof(struct ip) + tlen;
3363 		break;
3364 #endif /* INET */
3365 #ifdef INET6
3366 	case AF_INET6:
3367 		len = sizeof(struct ip6_hdr) + tlen;
3368 		break;
3369 #endif /* INET6 */
3370 	}
3371 
3372 	m = m_gethdr(M_NOWAIT, MT_DATA);
3373 	if (m == NULL)
3374 		return (NULL);
3375 
3376 #ifdef MAC
3377 	mac_netinet_firewall_send(m);
3378 #endif
3379 	if ((pf_mtag = pf_get_mtag(m)) == NULL) {
3380 		m_freem(m);
3381 		return (NULL);
3382 	}
3383 	if (skip_firewall)
3384 		m->m_flags |= M_SKIP_FIREWALL;
3385 	pf_mtag->tag = mtag_tag;
3386 	pf_mtag->flags = mtag_flags;
3387 
3388 	if (rtableid >= 0)
3389 		M_SETFIB(m, rtableid);
3390 
3391 #ifdef ALTQ
3392 	if (r != NULL && r->qid) {
3393 		pf_mtag->qid = r->qid;
3394 
3395 		/* add hints for ecn */
3396 		pf_mtag->hdr = mtod(m, struct ip *);
3397 	}
3398 #endif /* ALTQ */
3399 	m->m_data += max_linkhdr;
3400 	m->m_pkthdr.len = m->m_len = len;
3401 	/* The rest of the stack assumes a rcvif, so provide one.
3402 	 * This is a locally generated packet, so .. close enough. */
3403 	m->m_pkthdr.rcvif = V_loif;
3404 	bzero(m->m_data, len);
3405 	switch (af) {
3406 #ifdef INET
3407 	case AF_INET:
3408 		h = mtod(m, struct ip *);
3409 
3410 		/* IP header fields included in the TCP checksum */
3411 		h->ip_p = IPPROTO_TCP;
3412 		h->ip_len = htons(tlen);
3413 		h->ip_src.s_addr = saddr->v4.s_addr;
3414 		h->ip_dst.s_addr = daddr->v4.s_addr;
3415 
3416 		th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
3417 		break;
3418 #endif /* INET */
3419 #ifdef INET6
3420 	case AF_INET6:
3421 		h6 = mtod(m, struct ip6_hdr *);
3422 
3423 		/* IP header fields included in the TCP checksum */
3424 		h6->ip6_nxt = IPPROTO_TCP;
3425 		h6->ip6_plen = htons(tlen);
3426 		memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
3427 		memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
3428 
3429 		th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
3430 		break;
3431 #endif /* INET6 */
3432 	}
3433 
3434 	/* TCP header */
3435 	th->th_sport = sport;
3436 	th->th_dport = dport;
3437 	th->th_seq = htonl(seq);
3438 	th->th_ack = htonl(ack);
3439 	th->th_off = tlen >> 2;
3440 	th->th_flags = tcp_flags;
3441 	th->th_win = htons(win);
3442 
3443 	if (mss) {
3444 		opt = (char *)(th + 1);
3445 		opt[0] = TCPOPT_MAXSEG;
3446 		opt[1] = 4;
3447 		HTONS(mss);
3448 		bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
3449 	}
3450 
3451 	switch (af) {
3452 #ifdef INET
3453 	case AF_INET:
3454 		/* TCP checksum */
3455 		th->th_sum = in_cksum(m, len);
3456 
3457 		/* Finish the IP header */
3458 		h->ip_v = 4;
3459 		h->ip_hl = sizeof(*h) >> 2;
3460 		h->ip_tos = IPTOS_LOWDELAY;
3461 		h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
3462 		h->ip_len = htons(len);
3463 		h->ip_ttl = ttl ? ttl : V_ip_defttl;
3464 		h->ip_sum = 0;
3465 		break;
3466 #endif /* INET */
3467 #ifdef INET6
3468 	case AF_INET6:
3469 		/* TCP checksum */
3470 		th->th_sum = in6_cksum(m, IPPROTO_TCP,
3471 		    sizeof(struct ip6_hdr), tlen);
3472 
3473 		h6->ip6_vfc |= IPV6_VERSION;
3474 		h6->ip6_hlim = IPV6_DEFHLIM;
3475 		break;
3476 #endif /* INET6 */
3477 	}
3478 
3479 	return (m);
3480 }
3481 
3482 static void
3483 pf_send_sctp_abort(sa_family_t af, struct pf_pdesc *pd,
3484     uint8_t ttl, int rtableid)
3485 {
3486 	struct mbuf		*m;
3487 #ifdef INET
3488 	struct ip		*h = NULL;
3489 #endif /* INET */
3490 #ifdef INET6
3491 	struct ip6_hdr		*h6 = NULL;
3492 #endif /* INET6 */
3493 	struct sctphdr		*hdr;
3494 	struct sctp_chunkhdr	*chunk;
3495 	struct pf_send_entry	*pfse;
3496 	int			 off = 0;
3497 
3498 	MPASS(af == pd->af);
3499 
3500 	m = m_gethdr(M_NOWAIT, MT_DATA);
3501 	if (m == NULL)
3502 		return;
3503 
3504 	m->m_data += max_linkhdr;
3505 	m->m_flags |= M_SKIP_FIREWALL;
3506 	/* The rest of the stack assumes a rcvif, so provide one.
3507 	 * This is a locally generated packet, so .. close enough. */
3508 	m->m_pkthdr.rcvif = V_loif;
3509 
3510 	/* IPv4|6 header */
3511 	switch (af) {
3512 #ifdef INET
3513 	case AF_INET:
3514 		bzero(m->m_data, sizeof(struct ip) + sizeof(*hdr) + sizeof(*chunk));
3515 
3516 		h = mtod(m, struct ip *);
3517 
3518 		/* IP header fields included in the TCP checksum */
3519 
3520 		h->ip_p = IPPROTO_SCTP;
3521 		h->ip_len = htons(sizeof(*h) + sizeof(*hdr) + sizeof(*chunk));
3522 		h->ip_ttl = ttl ? ttl : V_ip_defttl;
3523 		h->ip_src = pd->dst->v4;
3524 		h->ip_dst = pd->src->v4;
3525 
3526 		off += sizeof(struct ip);
3527 		break;
3528 #endif /* INET */
3529 #ifdef INET6
3530 	case AF_INET6:
3531 		bzero(m->m_data, sizeof(struct ip6_hdr) + sizeof(*hdr) + sizeof(*chunk));
3532 
3533 		h6 = mtod(m, struct ip6_hdr *);
3534 
3535 		/* IP header fields included in the TCP checksum */
3536 		h6->ip6_vfc |= IPV6_VERSION;
3537 		h6->ip6_nxt = IPPROTO_SCTP;
3538 		h6->ip6_plen = htons(sizeof(*h6) + sizeof(*hdr) + sizeof(*chunk));
3539 		h6->ip6_hlim = ttl ? ttl : V_ip6_defhlim;
3540 		memcpy(&h6->ip6_src, &pd->dst->v6, sizeof(struct in6_addr));
3541 		memcpy(&h6->ip6_dst, &pd->src->v6, sizeof(struct in6_addr));
3542 
3543 		off += sizeof(struct ip6_hdr);
3544 		break;
3545 #endif /* INET6 */
3546 	}
3547 
3548 	/* SCTP header */
3549 	hdr = mtodo(m, off);
3550 
3551 	hdr->src_port = pd->hdr.sctp.dest_port;
3552 	hdr->dest_port = pd->hdr.sctp.src_port;
3553 	hdr->v_tag = pd->sctp_initiate_tag;
3554 	hdr->checksum = 0;
3555 
3556 	/* Abort chunk. */
3557 	off += sizeof(struct sctphdr);
3558 	chunk = mtodo(m, off);
3559 
3560 	chunk->chunk_type = SCTP_ABORT_ASSOCIATION;
3561 	chunk->chunk_length = htons(sizeof(*chunk));
3562 
3563 	/* SCTP checksum */
3564 	off += sizeof(*chunk);
3565 	m->m_pkthdr.len = m->m_len = off;
3566 
3567 	pf_sctp_checksum(m, off - sizeof(*hdr) - sizeof(*chunk));
3568 
3569 	if (rtableid >= 0)
3570 		M_SETFIB(m, rtableid);
3571 
3572 	/* Allocate outgoing queue entry, mbuf and mbuf tag. */
3573 	pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
3574 	if (pfse == NULL) {
3575 		m_freem(m);
3576 		return;
3577 	}
3578 
3579 	switch (af) {
3580 #ifdef INET
3581 	case AF_INET:
3582 		pfse->pfse_type = PFSE_IP;
3583 		break;
3584 #endif /* INET */
3585 #ifdef INET6
3586 	case AF_INET6:
3587 		pfse->pfse_type = PFSE_IP6;
3588 		break;
3589 #endif /* INET6 */
3590 	}
3591 
3592 	pfse->pfse_m = m;
3593 	pf_send(pfse);
3594 }
3595 
3596 void
3597 pf_send_tcp(const struct pf_krule *r, sa_family_t af,
3598     const struct pf_addr *saddr, const struct pf_addr *daddr,
3599     u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
3600     u_int8_t tcp_flags, u_int16_t win, u_int16_t mss, u_int8_t ttl,
3601     bool skip_firewall, u_int16_t mtag_tag, u_int16_t mtag_flags, int rtableid)
3602 {
3603 	struct pf_send_entry *pfse;
3604 	struct mbuf	*m;
3605 
3606 	m = pf_build_tcp(r, af, saddr, daddr, sport, dport, seq, ack, tcp_flags,
3607 	    win, mss, ttl, skip_firewall, mtag_tag, mtag_flags, rtableid);
3608 	if (m == NULL)
3609 		return;
3610 
3611 	/* Allocate outgoing queue entry, mbuf and mbuf tag. */
3612 	pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
3613 	if (pfse == NULL) {
3614 		m_freem(m);
3615 		return;
3616 	}
3617 
3618 	switch (af) {
3619 #ifdef INET
3620 	case AF_INET:
3621 		pfse->pfse_type = PFSE_IP;
3622 		break;
3623 #endif /* INET */
3624 #ifdef INET6
3625 	case AF_INET6:
3626 		pfse->pfse_type = PFSE_IP6;
3627 		break;
3628 #endif /* INET6 */
3629 	}
3630 
3631 	pfse->pfse_m = m;
3632 	pf_send(pfse);
3633 }
3634 
3635 static void
3636 pf_return(struct pf_krule *r, struct pf_krule *nr, struct pf_pdesc *pd,
3637     struct pf_state_key *sk, struct tcphdr *th,
3638     u_int16_t bproto_sum, u_int16_t bip_sum,
3639     u_short *reason, int rtableid)
3640 {
3641 	struct pf_addr	* const saddr = pd->src;
3642 	struct pf_addr	* const daddr = pd->dst;
3643 
3644 	/* undo NAT changes, if they have taken place */
3645 	if (nr != NULL) {
3646 		PF_ACPY(saddr, &sk->addr[pd->sidx], pd->af);
3647 		PF_ACPY(daddr, &sk->addr[pd->didx], pd->af);
3648 		if (pd->sport)
3649 			*pd->sport = sk->port[pd->sidx];
3650 		if (pd->dport)
3651 			*pd->dport = sk->port[pd->didx];
3652 		if (pd->proto_sum)
3653 			*pd->proto_sum = bproto_sum;
3654 		if (pd->ip_sum)
3655 			*pd->ip_sum = bip_sum;
3656 		m_copyback(pd->m, pd->off, pd->hdrlen, pd->hdr.any);
3657 	}
3658 	if (pd->proto == IPPROTO_TCP &&
3659 	    ((r->rule_flag & PFRULE_RETURNRST) ||
3660 	    (r->rule_flag & PFRULE_RETURN)) &&
3661 	    !(th->th_flags & TH_RST)) {
3662 		u_int32_t	 ack = ntohl(th->th_seq) + pd->p_len;
3663 
3664 		if (pf_check_proto_cksum(pd->m, pd->off, pd->tot_len - pd->off,
3665 		    IPPROTO_TCP, pd->af))
3666 			REASON_SET(reason, PFRES_PROTCKSUM);
3667 		else {
3668 			if (th->th_flags & TH_SYN)
3669 				ack++;
3670 			if (th->th_flags & TH_FIN)
3671 				ack++;
3672 			pf_send_tcp(r, pd->af, pd->dst,
3673 				pd->src, th->th_dport, th->th_sport,
3674 				ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3675 				r->return_ttl, true, 0, 0, rtableid);
3676 		}
3677 	} else if (pd->proto == IPPROTO_SCTP &&
3678 	    (r->rule_flag & PFRULE_RETURN)) {
3679 		pf_send_sctp_abort(pd->af, pd, r->return_ttl, rtableid);
3680 	} else if (pd->proto != IPPROTO_ICMP && pd->af == AF_INET &&
3681 		r->return_icmp)
3682 		pf_send_icmp(pd->m, r->return_icmp >> 8,
3683 			r->return_icmp & 255, pd->af, r, rtableid);
3684 	else if (pd->proto != IPPROTO_ICMPV6 && pd->af == AF_INET6 &&
3685 		r->return_icmp6)
3686 		pf_send_icmp(pd->m, r->return_icmp6 >> 8,
3687 			r->return_icmp6 & 255, pd->af, r, rtableid);
3688 }
3689 
3690 static int
3691 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
3692 {
3693 	struct m_tag *mtag;
3694 	u_int8_t mpcp;
3695 
3696 	mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
3697 	if (mtag == NULL)
3698 		return (0);
3699 
3700 	if (prio == PF_PRIO_ZERO)
3701 		prio = 0;
3702 
3703 	mpcp = *(uint8_t *)(mtag + 1);
3704 
3705 	return (mpcp == prio);
3706 }
3707 
3708 static int
3709 pf_icmp_to_bandlim(uint8_t type)
3710 {
3711 	switch (type) {
3712 		case ICMP_ECHO:
3713 		case ICMP_ECHOREPLY:
3714 			return (BANDLIM_ICMP_ECHO);
3715 		case ICMP_TSTAMP:
3716 		case ICMP_TSTAMPREPLY:
3717 			return (BANDLIM_ICMP_TSTAMP);
3718 		case ICMP_UNREACH:
3719 		default:
3720 			return (BANDLIM_ICMP_UNREACH);
3721 	}
3722 }
3723 
3724 static void
3725 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
3726     struct pf_krule *r, int rtableid)
3727 {
3728 	struct pf_send_entry *pfse;
3729 	struct mbuf *m0;
3730 	struct pf_mtag *pf_mtag;
3731 
3732 	/* ICMP packet rate limitation. */
3733 	switch (af) {
3734 #ifdef INET6
3735 	case AF_INET6:
3736 		if (icmp6_ratelimit(NULL, type, code))
3737 			return;
3738 		break;
3739 #endif
3740 #ifdef INET
3741 	case AF_INET:
3742 		if (badport_bandlim(pf_icmp_to_bandlim(type)) != 0)
3743 			return;
3744 		break;
3745 #endif
3746 	}
3747 
3748 	/* Allocate outgoing queue entry, mbuf and mbuf tag. */
3749 	pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
3750 	if (pfse == NULL)
3751 		return;
3752 
3753 	if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
3754 		free(pfse, M_PFTEMP);
3755 		return;
3756 	}
3757 
3758 	if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
3759 		free(pfse, M_PFTEMP);
3760 		return;
3761 	}
3762 	/* XXX: revisit */
3763 	m0->m_flags |= M_SKIP_FIREWALL;
3764 
3765 	if (rtableid >= 0)
3766 		M_SETFIB(m0, rtableid);
3767 
3768 #ifdef ALTQ
3769 	if (r->qid) {
3770 		pf_mtag->qid = r->qid;
3771 		/* add hints for ecn */
3772 		pf_mtag->hdr = mtod(m0, struct ip *);
3773 	}
3774 #endif /* ALTQ */
3775 
3776 	switch (af) {
3777 #ifdef INET
3778 	case AF_INET:
3779 		pfse->pfse_type = PFSE_ICMP;
3780 		break;
3781 #endif /* INET */
3782 #ifdef INET6
3783 	case AF_INET6:
3784 		pfse->pfse_type = PFSE_ICMP6;
3785 		break;
3786 #endif /* INET6 */
3787 	}
3788 	pfse->pfse_m = m0;
3789 	pfse->icmpopts.type = type;
3790 	pfse->icmpopts.code = code;
3791 	pf_send(pfse);
3792 }
3793 
3794 /*
3795  * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
3796  * If n is 0, they match if they are equal. If n is != 0, they match if they
3797  * are different.
3798  */
3799 int
3800 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
3801     struct pf_addr *b, sa_family_t af)
3802 {
3803 	int	match = 0;
3804 
3805 	switch (af) {
3806 #ifdef INET
3807 	case AF_INET:
3808 		if (IN_ARE_MASKED_ADDR_EQUAL(a->v4, b->v4, m->v4))
3809 			match++;
3810 		break;
3811 #endif /* INET */
3812 #ifdef INET6
3813 	case AF_INET6:
3814 		if (IN6_ARE_MASKED_ADDR_EQUAL(&a->v6, &b->v6, &m->v6))
3815 			match++;
3816 		break;
3817 #endif /* INET6 */
3818 	}
3819 	if (match) {
3820 		if (n)
3821 			return (0);
3822 		else
3823 			return (1);
3824 	} else {
3825 		if (n)
3826 			return (1);
3827 		else
3828 			return (0);
3829 	}
3830 }
3831 
3832 /*
3833  * Return 1 if b <= a <= e, otherwise return 0.
3834  */
3835 int
3836 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
3837     struct pf_addr *a, sa_family_t af)
3838 {
3839 	switch (af) {
3840 #ifdef INET
3841 	case AF_INET:
3842 		if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
3843 		    (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
3844 			return (0);
3845 		break;
3846 #endif /* INET */
3847 #ifdef INET6
3848 	case AF_INET6: {
3849 		int	i;
3850 
3851 		/* check a >= b */
3852 		for (i = 0; i < 4; ++i)
3853 			if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
3854 				break;
3855 			else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
3856 				return (0);
3857 		/* check a <= e */
3858 		for (i = 0; i < 4; ++i)
3859 			if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
3860 				break;
3861 			else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
3862 				return (0);
3863 		break;
3864 	}
3865 #endif /* INET6 */
3866 	}
3867 	return (1);
3868 }
3869 
3870 static int
3871 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
3872 {
3873 	switch (op) {
3874 	case PF_OP_IRG:
3875 		return ((p > a1) && (p < a2));
3876 	case PF_OP_XRG:
3877 		return ((p < a1) || (p > a2));
3878 	case PF_OP_RRG:
3879 		return ((p >= a1) && (p <= a2));
3880 	case PF_OP_EQ:
3881 		return (p == a1);
3882 	case PF_OP_NE:
3883 		return (p != a1);
3884 	case PF_OP_LT:
3885 		return (p < a1);
3886 	case PF_OP_LE:
3887 		return (p <= a1);
3888 	case PF_OP_GT:
3889 		return (p > a1);
3890 	case PF_OP_GE:
3891 		return (p >= a1);
3892 	}
3893 	return (0); /* never reached */
3894 }
3895 
3896 int
3897 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
3898 {
3899 	NTOHS(a1);
3900 	NTOHS(a2);
3901 	NTOHS(p);
3902 	return (pf_match(op, a1, a2, p));
3903 }
3904 
3905 static int
3906 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
3907 {
3908 	if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
3909 		return (0);
3910 	return (pf_match(op, a1, a2, u));
3911 }
3912 
3913 static int
3914 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
3915 {
3916 	if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
3917 		return (0);
3918 	return (pf_match(op, a1, a2, g));
3919 }
3920 
3921 int
3922 pf_match_tag(struct mbuf *m, struct pf_krule *r, int *tag, int mtag)
3923 {
3924 	if (*tag == -1)
3925 		*tag = mtag;
3926 
3927 	return ((!r->match_tag_not && r->match_tag == *tag) ||
3928 	    (r->match_tag_not && r->match_tag != *tag));
3929 }
3930 
3931 static int
3932 pf_match_rcvif(struct mbuf *m, struct pf_krule *r)
3933 {
3934 	struct ifnet *ifp = m->m_pkthdr.rcvif;
3935 	struct pfi_kkif *kif;
3936 
3937 	if (ifp == NULL)
3938 		return (0);
3939 
3940 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
3941 
3942 	if (kif == NULL) {
3943 		DPFPRINTF(PF_DEBUG_URGENT,
3944 		    ("pf_test_via: kif == NULL, @%d via %s\n", r->nr,
3945 			r->rcv_ifname));
3946 		return (0);
3947 	}
3948 
3949 	return (pfi_kkif_match(r->rcv_kif, kif));
3950 }
3951 
3952 int
3953 pf_tag_packet(struct pf_pdesc *pd, int tag)
3954 {
3955 
3956 	KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
3957 
3958 	if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(pd->m)) == NULL))
3959 		return (ENOMEM);
3960 
3961 	pd->pf_mtag->tag = tag;
3962 
3963 	return (0);
3964 }
3965 
3966 #define	PF_ANCHOR_STACKSIZE	32
3967 struct pf_kanchor_stackframe {
3968 	struct pf_kruleset	*rs;
3969 	struct pf_krule		*r;	/* XXX: + match bit */
3970 	struct pf_kanchor	*child;
3971 };
3972 
3973 /*
3974  * XXX: We rely on malloc(9) returning pointer aligned addresses.
3975  */
3976 #define	PF_ANCHORSTACK_MATCH	0x00000001
3977 #define	PF_ANCHORSTACK_MASK	(PF_ANCHORSTACK_MATCH)
3978 
3979 #define	PF_ANCHOR_MATCH(f)	((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
3980 #define	PF_ANCHOR_RULE(f)	(struct pf_krule *)			\
3981 				((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
3982 #define	PF_ANCHOR_SET_MATCH(f)	do { (f)->r = (void *) 			\
3983 				((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH);  \
3984 } while (0)
3985 
3986 void
3987 pf_step_into_anchor(struct pf_kanchor_stackframe *stack, int *depth,
3988     struct pf_kruleset **rs, int n, struct pf_krule **r, struct pf_krule **a,
3989     int *match)
3990 {
3991 	struct pf_kanchor_stackframe	*f;
3992 
3993 	PF_RULES_RASSERT();
3994 
3995 	if (match)
3996 		*match = 0;
3997 	if (*depth >= PF_ANCHOR_STACKSIZE) {
3998 		printf("%s: anchor stack overflow on %s\n",
3999 		    __func__, (*r)->anchor->name);
4000 		*r = TAILQ_NEXT(*r, entries);
4001 		return;
4002 	} else if (*depth == 0 && a != NULL)
4003 		*a = *r;
4004 	f = stack + (*depth)++;
4005 	f->rs = *rs;
4006 	f->r = *r;
4007 	if ((*r)->anchor_wildcard) {
4008 		struct pf_kanchor_node *parent = &(*r)->anchor->children;
4009 
4010 		if ((f->child = RB_MIN(pf_kanchor_node, parent)) == NULL) {
4011 			*r = NULL;
4012 			return;
4013 		}
4014 		*rs = &f->child->ruleset;
4015 	} else {
4016 		f->child = NULL;
4017 		*rs = &(*r)->anchor->ruleset;
4018 	}
4019 	*r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
4020 }
4021 
4022 int
4023 pf_step_out_of_anchor(struct pf_kanchor_stackframe *stack, int *depth,
4024     struct pf_kruleset **rs, int n, struct pf_krule **r, struct pf_krule **a,
4025     int *match)
4026 {
4027 	struct pf_kanchor_stackframe	*f;
4028 	struct pf_krule *fr;
4029 	int quick = 0;
4030 
4031 	PF_RULES_RASSERT();
4032 
4033 	do {
4034 		if (*depth <= 0)
4035 			break;
4036 		f = stack + *depth - 1;
4037 		fr = PF_ANCHOR_RULE(f);
4038 		if (f->child != NULL) {
4039 			/*
4040 			 * This block traverses through
4041 			 * a wildcard anchor.
4042 			 */
4043 			if (match != NULL && *match) {
4044 				/*
4045 				 * If any of "*" matched, then
4046 				 * "foo/ *" matched, mark frame
4047 				 * appropriately.
4048 				 */
4049 				PF_ANCHOR_SET_MATCH(f);
4050 				*match = 0;
4051 			}
4052 			f->child = RB_NEXT(pf_kanchor_node,
4053 			    &fr->anchor->children, f->child);
4054 			if (f->child != NULL) {
4055 				*rs = &f->child->ruleset;
4056 				*r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
4057 				if (*r == NULL)
4058 					continue;
4059 				else
4060 					break;
4061 			}
4062 		}
4063 		(*depth)--;
4064 		if (*depth == 0 && a != NULL)
4065 			*a = NULL;
4066 		*rs = f->rs;
4067 		if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
4068 			quick = fr->quick;
4069 		*r = TAILQ_NEXT(fr, entries);
4070 	} while (*r == NULL);
4071 
4072 	return (quick);
4073 }
4074 
4075 struct pf_keth_anchor_stackframe {
4076 	struct pf_keth_ruleset	*rs;
4077 	struct pf_keth_rule	*r;	/* XXX: + match bit */
4078 	struct pf_keth_anchor	*child;
4079 };
4080 
4081 #define	PF_ETH_ANCHOR_MATCH(f)	((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
4082 #define	PF_ETH_ANCHOR_RULE(f)	(struct pf_keth_rule *)			\
4083 				((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
4084 #define	PF_ETH_ANCHOR_SET_MATCH(f)	do { (f)->r = (void *) 		\
4085 				((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH);  \
4086 } while (0)
4087 
4088 void
4089 pf_step_into_keth_anchor(struct pf_keth_anchor_stackframe *stack, int *depth,
4090     struct pf_keth_ruleset **rs, struct pf_keth_rule **r,
4091     struct pf_keth_rule **a, int *match)
4092 {
4093 	struct pf_keth_anchor_stackframe	*f;
4094 
4095 	NET_EPOCH_ASSERT();
4096 
4097 	if (match)
4098 		*match = 0;
4099 	if (*depth >= PF_ANCHOR_STACKSIZE) {
4100 		printf("%s: anchor stack overflow on %s\n",
4101 		    __func__, (*r)->anchor->name);
4102 		*r = TAILQ_NEXT(*r, entries);
4103 		return;
4104 	} else if (*depth == 0 && a != NULL)
4105 		*a = *r;
4106 	f = stack + (*depth)++;
4107 	f->rs = *rs;
4108 	f->r = *r;
4109 	if ((*r)->anchor_wildcard) {
4110 		struct pf_keth_anchor_node *parent = &(*r)->anchor->children;
4111 
4112 		if ((f->child = RB_MIN(pf_keth_anchor_node, parent)) == NULL) {
4113 			*r = NULL;
4114 			return;
4115 		}
4116 		*rs = &f->child->ruleset;
4117 	} else {
4118 		f->child = NULL;
4119 		*rs = &(*r)->anchor->ruleset;
4120 	}
4121 	*r = TAILQ_FIRST((*rs)->active.rules);
4122 }
4123 
4124 int
4125 pf_step_out_of_keth_anchor(struct pf_keth_anchor_stackframe *stack, int *depth,
4126     struct pf_keth_ruleset **rs, struct pf_keth_rule **r,
4127     struct pf_keth_rule **a, int *match)
4128 {
4129 	struct pf_keth_anchor_stackframe	*f;
4130 	struct pf_keth_rule *fr;
4131 	int quick = 0;
4132 
4133 	NET_EPOCH_ASSERT();
4134 
4135 	do {
4136 		if (*depth <= 0)
4137 			break;
4138 		f = stack + *depth - 1;
4139 		fr = PF_ETH_ANCHOR_RULE(f);
4140 		if (f->child != NULL) {
4141 			/*
4142 			 * This block traverses through
4143 			 * a wildcard anchor.
4144 			 */
4145 			if (match != NULL && *match) {
4146 				/*
4147 				 * If any of "*" matched, then
4148 				 * "foo/ *" matched, mark frame
4149 				 * appropriately.
4150 				 */
4151 				PF_ETH_ANCHOR_SET_MATCH(f);
4152 				*match = 0;
4153 			}
4154 			f->child = RB_NEXT(pf_keth_anchor_node,
4155 			    &fr->anchor->children, f->child);
4156 			if (f->child != NULL) {
4157 				*rs = &f->child->ruleset;
4158 				*r = TAILQ_FIRST((*rs)->active.rules);
4159 				if (*r == NULL)
4160 					continue;
4161 				else
4162 					break;
4163 			}
4164 		}
4165 		(*depth)--;
4166 		if (*depth == 0 && a != NULL)
4167 			*a = NULL;
4168 		*rs = f->rs;
4169 		if (PF_ETH_ANCHOR_MATCH(f) || (match != NULL && *match))
4170 			quick = fr->quick;
4171 		*r = TAILQ_NEXT(fr, entries);
4172 	} while (*r == NULL);
4173 
4174 	return (quick);
4175 }
4176 
4177 #ifdef INET6
4178 void
4179 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
4180     struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
4181 {
4182 	switch (af) {
4183 #ifdef INET
4184 	case AF_INET:
4185 		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
4186 		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
4187 		break;
4188 #endif /* INET */
4189 	case AF_INET6:
4190 		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
4191 		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
4192 		naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
4193 		((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
4194 		naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
4195 		((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
4196 		naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
4197 		((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
4198 		break;
4199 	}
4200 }
4201 
4202 void
4203 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
4204 {
4205 	switch (af) {
4206 #ifdef INET
4207 	case AF_INET:
4208 		addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
4209 		break;
4210 #endif /* INET */
4211 	case AF_INET6:
4212 		if (addr->addr32[3] == 0xffffffff) {
4213 			addr->addr32[3] = 0;
4214 			if (addr->addr32[2] == 0xffffffff) {
4215 				addr->addr32[2] = 0;
4216 				if (addr->addr32[1] == 0xffffffff) {
4217 					addr->addr32[1] = 0;
4218 					addr->addr32[0] =
4219 					    htonl(ntohl(addr->addr32[0]) + 1);
4220 				} else
4221 					addr->addr32[1] =
4222 					    htonl(ntohl(addr->addr32[1]) + 1);
4223 			} else
4224 				addr->addr32[2] =
4225 				    htonl(ntohl(addr->addr32[2]) + 1);
4226 		} else
4227 			addr->addr32[3] =
4228 			    htonl(ntohl(addr->addr32[3]) + 1);
4229 		break;
4230 	}
4231 }
4232 #endif /* INET6 */
4233 
4234 void
4235 pf_rule_to_actions(struct pf_krule *r, struct pf_rule_actions *a)
4236 {
4237 	/*
4238 	 * Modern rules use the same flags in rules as they do in states.
4239 	 */
4240 	a->flags |= (r->scrub_flags & (PFSTATE_NODF|PFSTATE_RANDOMID|
4241 	    PFSTATE_SCRUB_TCP|PFSTATE_SETPRIO));
4242 
4243 	/*
4244 	 * Old-style scrub rules have different flags which need to be translated.
4245 	 */
4246 	if (r->rule_flag & PFRULE_RANDOMID)
4247 		a->flags |= PFSTATE_RANDOMID;
4248 	if (r->scrub_flags & PFSTATE_SETTOS || r->rule_flag & PFRULE_SET_TOS ) {
4249 		a->flags |= PFSTATE_SETTOS;
4250 		a->set_tos = r->set_tos;
4251 	}
4252 
4253 	if (r->qid)
4254 		a->qid = r->qid;
4255 	if (r->pqid)
4256 		a->pqid = r->pqid;
4257 	if (r->rtableid >= 0)
4258 		a->rtableid = r->rtableid;
4259 	a->log |= r->log;
4260 	if (r->min_ttl)
4261 		a->min_ttl = r->min_ttl;
4262 	if (r->max_mss)
4263 		a->max_mss = r->max_mss;
4264 	if (r->dnpipe)
4265 		a->dnpipe = r->dnpipe;
4266 	if (r->dnrpipe)
4267 		a->dnrpipe = r->dnrpipe;
4268 	if (r->dnpipe || r->dnrpipe) {
4269 		if (r->free_flags & PFRULE_DN_IS_PIPE)
4270 			a->flags |= PFSTATE_DN_IS_PIPE;
4271 		else
4272 			a->flags &= ~PFSTATE_DN_IS_PIPE;
4273 	}
4274 	if (r->scrub_flags & PFSTATE_SETPRIO) {
4275 		a->set_prio[0] = r->set_prio[0];
4276 		a->set_prio[1] = r->set_prio[1];
4277 	}
4278 }
4279 
4280 int
4281 pf_socket_lookup(struct pf_pdesc *pd)
4282 {
4283 	struct pf_addr		*saddr, *daddr;
4284 	u_int16_t		 sport, dport;
4285 	struct inpcbinfo	*pi;
4286 	struct inpcb		*inp;
4287 
4288 	pd->lookup.uid = UID_MAX;
4289 	pd->lookup.gid = GID_MAX;
4290 
4291 	switch (pd->proto) {
4292 	case IPPROTO_TCP:
4293 		sport = pd->hdr.tcp.th_sport;
4294 		dport = pd->hdr.tcp.th_dport;
4295 		pi = &V_tcbinfo;
4296 		break;
4297 	case IPPROTO_UDP:
4298 		sport = pd->hdr.udp.uh_sport;
4299 		dport = pd->hdr.udp.uh_dport;
4300 		pi = &V_udbinfo;
4301 		break;
4302 	default:
4303 		return (-1);
4304 	}
4305 	if (pd->dir == PF_IN) {
4306 		saddr = pd->src;
4307 		daddr = pd->dst;
4308 	} else {
4309 		u_int16_t	p;
4310 
4311 		p = sport;
4312 		sport = dport;
4313 		dport = p;
4314 		saddr = pd->dst;
4315 		daddr = pd->src;
4316 	}
4317 	switch (pd->af) {
4318 #ifdef INET
4319 	case AF_INET:
4320 		inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
4321 		    dport, INPLOOKUP_RLOCKPCB, NULL, pd->m);
4322 		if (inp == NULL) {
4323 			inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
4324 			   daddr->v4, dport, INPLOOKUP_WILDCARD |
4325 			   INPLOOKUP_RLOCKPCB, NULL, pd->m);
4326 			if (inp == NULL)
4327 				return (-1);
4328 		}
4329 		break;
4330 #endif /* INET */
4331 #ifdef INET6
4332 	case AF_INET6:
4333 		inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
4334 		    dport, INPLOOKUP_RLOCKPCB, NULL, pd->m);
4335 		if (inp == NULL) {
4336 			inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
4337 			    &daddr->v6, dport, INPLOOKUP_WILDCARD |
4338 			    INPLOOKUP_RLOCKPCB, NULL, pd->m);
4339 			if (inp == NULL)
4340 				return (-1);
4341 		}
4342 		break;
4343 #endif /* INET6 */
4344 	}
4345 	INP_RLOCK_ASSERT(inp);
4346 	pd->lookup.uid = inp->inp_cred->cr_uid;
4347 	pd->lookup.gid = inp->inp_cred->cr_groups[0];
4348 	INP_RUNLOCK(inp);
4349 
4350 	return (1);
4351 }
4352 
4353 u_int8_t
4354 pf_get_wscale(struct pf_pdesc *pd)
4355 {
4356 	struct tcphdr	*th = &pd->hdr.tcp;
4357 	int		 hlen;
4358 	u_int8_t	 hdr[60];
4359 	u_int8_t	*opt, optlen;
4360 	u_int8_t	 wscale = 0;
4361 
4362 	hlen = th->th_off << 2;		/* hlen <= sizeof(hdr) */
4363 	if (hlen <= sizeof(struct tcphdr))
4364 		return (0);
4365 	if (!pf_pull_hdr(pd->m, pd->off, hdr, hlen, NULL, NULL, pd->af))
4366 		return (0);
4367 	opt = hdr + sizeof(struct tcphdr);
4368 	hlen -= sizeof(struct tcphdr);
4369 	while (hlen >= 3) {
4370 		switch (*opt) {
4371 		case TCPOPT_EOL:
4372 		case TCPOPT_NOP:
4373 			++opt;
4374 			--hlen;
4375 			break;
4376 		case TCPOPT_WINDOW:
4377 			wscale = opt[2];
4378 			if (wscale > TCP_MAX_WINSHIFT)
4379 				wscale = TCP_MAX_WINSHIFT;
4380 			wscale |= PF_WSCALE_FLAG;
4381 			/* FALLTHROUGH */
4382 		default:
4383 			optlen = opt[1];
4384 			if (optlen < 2)
4385 				optlen = 2;
4386 			hlen -= optlen;
4387 			opt += optlen;
4388 			break;
4389 		}
4390 	}
4391 	return (wscale);
4392 }
4393 
4394 u_int16_t
4395 pf_get_mss(struct pf_pdesc *pd)
4396 {
4397 	struct tcphdr	*th = &pd->hdr.tcp;
4398 	int		 hlen;
4399 	u_int8_t	 hdr[60];
4400 	u_int8_t	*opt, optlen;
4401 	u_int16_t	 mss = V_tcp_mssdflt;
4402 
4403 	hlen = th->th_off << 2;	/* hlen <= sizeof(hdr) */
4404 	if (hlen <= sizeof(struct tcphdr))
4405 		return (0);
4406 	if (!pf_pull_hdr(pd->m, pd->off, hdr, hlen, NULL, NULL, pd->af))
4407 		return (0);
4408 	opt = hdr + sizeof(struct tcphdr);
4409 	hlen -= sizeof(struct tcphdr);
4410 	while (hlen >= TCPOLEN_MAXSEG) {
4411 		switch (*opt) {
4412 		case TCPOPT_EOL:
4413 		case TCPOPT_NOP:
4414 			++opt;
4415 			--hlen;
4416 			break;
4417 		case TCPOPT_MAXSEG:
4418 			bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
4419 			NTOHS(mss);
4420 			/* FALLTHROUGH */
4421 		default:
4422 			optlen = opt[1];
4423 			if (optlen < 2)
4424 				optlen = 2;
4425 			hlen -= optlen;
4426 			opt += optlen;
4427 			break;
4428 		}
4429 	}
4430 	return (mss);
4431 }
4432 
4433 static u_int16_t
4434 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
4435 {
4436 	struct nhop_object *nh;
4437 #ifdef INET6
4438 	struct in6_addr		dst6;
4439 	uint32_t		scopeid;
4440 #endif /* INET6 */
4441 	int			 hlen = 0;
4442 	uint16_t		 mss = 0;
4443 
4444 	NET_EPOCH_ASSERT();
4445 
4446 	switch (af) {
4447 #ifdef INET
4448 	case AF_INET:
4449 		hlen = sizeof(struct ip);
4450 		nh = fib4_lookup(rtableid, addr->v4, 0, 0, 0);
4451 		if (nh != NULL)
4452 			mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
4453 		break;
4454 #endif /* INET */
4455 #ifdef INET6
4456 	case AF_INET6:
4457 		hlen = sizeof(struct ip6_hdr);
4458 		in6_splitscope(&addr->v6, &dst6, &scopeid);
4459 		nh = fib6_lookup(rtableid, &dst6, scopeid, 0, 0);
4460 		if (nh != NULL)
4461 			mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
4462 		break;
4463 #endif /* INET6 */
4464 	}
4465 
4466 	mss = max(V_tcp_mssdflt, mss);
4467 	mss = min(mss, offer);
4468 	mss = max(mss, 64);		/* sanity - at least max opt space */
4469 	return (mss);
4470 }
4471 
4472 static u_int32_t
4473 pf_tcp_iss(struct pf_pdesc *pd)
4474 {
4475 	MD5_CTX ctx;
4476 	u_int32_t digest[4];
4477 
4478 	if (V_pf_tcp_secret_init == 0) {
4479 		arc4random_buf(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
4480 		MD5Init(&V_pf_tcp_secret_ctx);
4481 		MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
4482 		    sizeof(V_pf_tcp_secret));
4483 		V_pf_tcp_secret_init = 1;
4484 	}
4485 
4486 	ctx = V_pf_tcp_secret_ctx;
4487 
4488 	MD5Update(&ctx, (char *)&pd->hdr.tcp.th_sport, sizeof(u_short));
4489 	MD5Update(&ctx, (char *)&pd->hdr.tcp.th_dport, sizeof(u_short));
4490 	switch (pd->af) {
4491 	case AF_INET6:
4492 		MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
4493 		MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
4494 		break;
4495 	case AF_INET:
4496 		MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
4497 		MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
4498 		break;
4499 	}
4500 	MD5Final((u_char *)digest, &ctx);
4501 	V_pf_tcp_iss_off += 4096;
4502 #define	ISN_RANDOM_INCREMENT (4096 - 1)
4503 	return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
4504 	    V_pf_tcp_iss_off);
4505 #undef	ISN_RANDOM_INCREMENT
4506 }
4507 
4508 static bool
4509 pf_match_eth_addr(const uint8_t *a, const struct pf_keth_rule_addr *r)
4510 {
4511 	bool match = true;
4512 
4513 	/* Always matches if not set */
4514 	if (! r->isset)
4515 		return (!r->neg);
4516 
4517 	for (int i = 0; i < ETHER_ADDR_LEN; i++) {
4518 		if ((a[i] & r->mask[i]) != (r->addr[i] & r->mask[i])) {
4519 			match = false;
4520 			break;
4521 		}
4522 	}
4523 
4524 	return (match ^ r->neg);
4525 }
4526 
4527 static int
4528 pf_match_eth_tag(struct mbuf *m, struct pf_keth_rule *r, int *tag, int mtag)
4529 {
4530 	if (*tag == -1)
4531 		*tag = mtag;
4532 
4533 	return ((!r->match_tag_not && r->match_tag == *tag) ||
4534 	    (r->match_tag_not && r->match_tag != *tag));
4535 }
4536 
4537 static void
4538 pf_bridge_to(struct ifnet *ifp, struct mbuf *m)
4539 {
4540 	/* If we don't have the interface drop the packet. */
4541 	if (ifp == NULL) {
4542 		m_freem(m);
4543 		return;
4544 	}
4545 
4546 	switch (ifp->if_type) {
4547 	case IFT_ETHER:
4548 	case IFT_XETHER:
4549 	case IFT_L2VLAN:
4550 	case IFT_BRIDGE:
4551 	case IFT_IEEE8023ADLAG:
4552 		break;
4553 	default:
4554 		m_freem(m);
4555 		return;
4556 	}
4557 
4558 	ifp->if_transmit(ifp, m);
4559 }
4560 
4561 static int
4562 pf_test_eth_rule(int dir, struct pfi_kkif *kif, struct mbuf **m0)
4563 {
4564 #ifdef INET
4565 	struct ip ip;
4566 #endif
4567 #ifdef INET6
4568 	struct ip6_hdr ip6;
4569 #endif
4570 	struct mbuf *m = *m0;
4571 	struct ether_header *e;
4572 	struct pf_keth_rule *r, *rm, *a = NULL;
4573 	struct pf_keth_ruleset *ruleset = NULL;
4574 	struct pf_mtag *mtag;
4575 	struct pf_keth_ruleq *rules;
4576 	struct pf_addr *src = NULL, *dst = NULL;
4577 	struct pfi_kkif *bridge_to;
4578 	sa_family_t af = 0;
4579 	uint16_t proto;
4580 	int asd = 0, match = 0;
4581 	int tag = -1;
4582 	uint8_t action;
4583 	struct pf_keth_anchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
4584 
4585 	MPASS(kif->pfik_ifp->if_vnet == curvnet);
4586 	NET_EPOCH_ASSERT();
4587 
4588 	PF_RULES_RLOCK_TRACKER;
4589 
4590 	SDT_PROBE3(pf, eth, test_rule, entry, dir, kif->pfik_ifp, m);
4591 
4592 	mtag = pf_find_mtag(m);
4593 	if (mtag != NULL && mtag->flags & PF_MTAG_FLAG_DUMMYNET) {
4594 		/* Dummynet re-injects packets after they've
4595 		 * completed their delay. We've already
4596 		 * processed them, so pass unconditionally. */
4597 
4598 		/* But only once. We may see the packet multiple times (e.g.
4599 		 * PFIL_IN/PFIL_OUT). */
4600 		pf_dummynet_flag_remove(m, mtag);
4601 
4602 		return (PF_PASS);
4603 	}
4604 
4605 	ruleset = V_pf_keth;
4606 	rules = ck_pr_load_ptr(&ruleset->active.rules);
4607 	r = TAILQ_FIRST(rules);
4608 	rm = NULL;
4609 
4610 	if (__predict_false(m->m_len < sizeof(struct ether_header)) &&
4611 	    (m = *m0 = m_pullup(*m0, sizeof(struct ether_header))) == NULL) {
4612 		DPFPRINTF(PF_DEBUG_URGENT,
4613 		    ("pf_test_eth_rule: m_len < sizeof(struct ether_header)"
4614 		     ", pullup failed\n"));
4615 		return (PF_DROP);
4616 	}
4617 	e = mtod(m, struct ether_header *);
4618 	proto = ntohs(e->ether_type);
4619 
4620 	switch (proto) {
4621 #ifdef INET
4622 	case ETHERTYPE_IP: {
4623 		if (m_length(m, NULL) < (sizeof(struct ether_header) +
4624 		    sizeof(ip)))
4625 			return (PF_DROP);
4626 
4627 		af = AF_INET;
4628 		m_copydata(m, sizeof(struct ether_header), sizeof(ip),
4629 		    (caddr_t)&ip);
4630 		src = (struct pf_addr *)&ip.ip_src;
4631 		dst = (struct pf_addr *)&ip.ip_dst;
4632 		break;
4633 	}
4634 #endif /* INET */
4635 #ifdef INET6
4636 	case ETHERTYPE_IPV6: {
4637 		if (m_length(m, NULL) < (sizeof(struct ether_header) +
4638 		    sizeof(ip6)))
4639 			return (PF_DROP);
4640 
4641 		af = AF_INET6;
4642 		m_copydata(m, sizeof(struct ether_header), sizeof(ip6),
4643 		    (caddr_t)&ip6);
4644 		src = (struct pf_addr *)&ip6.ip6_src;
4645 		dst = (struct pf_addr *)&ip6.ip6_dst;
4646 		break;
4647 	}
4648 #endif /* INET6 */
4649 	}
4650 
4651 	PF_RULES_RLOCK();
4652 
4653 	while (r != NULL) {
4654 		counter_u64_add(r->evaluations, 1);
4655 		SDT_PROBE2(pf, eth, test_rule, test, r->nr, r);
4656 
4657 		if (pfi_kkif_match(r->kif, kif) == r->ifnot) {
4658 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4659 			    "kif");
4660 			r = r->skip[PFE_SKIP_IFP].ptr;
4661 		}
4662 		else if (r->direction && r->direction != dir) {
4663 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4664 			    "dir");
4665 			r = r->skip[PFE_SKIP_DIR].ptr;
4666 		}
4667 		else if (r->proto && r->proto != proto) {
4668 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4669 			    "proto");
4670 			r = r->skip[PFE_SKIP_PROTO].ptr;
4671 		}
4672 		else if (! pf_match_eth_addr(e->ether_shost, &r->src)) {
4673 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4674 			    "src");
4675 			r = r->skip[PFE_SKIP_SRC_ADDR].ptr;
4676 		}
4677 		else if (! pf_match_eth_addr(e->ether_dhost, &r->dst)) {
4678 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4679 			    "dst");
4680 			r = r->skip[PFE_SKIP_DST_ADDR].ptr;
4681 		}
4682 		else if (src != NULL && PF_MISMATCHAW(&r->ipsrc.addr, src, af,
4683 		    r->ipsrc.neg, kif, M_GETFIB(m))) {
4684 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4685 			    "ip_src");
4686 			r = r->skip[PFE_SKIP_SRC_IP_ADDR].ptr;
4687 		}
4688 		else if (dst != NULL && PF_MISMATCHAW(&r->ipdst.addr, dst, af,
4689 		    r->ipdst.neg, kif, M_GETFIB(m))) {
4690 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4691 			    "ip_dst");
4692 			r = r->skip[PFE_SKIP_DST_IP_ADDR].ptr;
4693 		}
4694 		else if (r->match_tag && !pf_match_eth_tag(m, r, &tag,
4695 		    mtag ? mtag->tag : 0)) {
4696 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
4697 			    "match_tag");
4698 			r = TAILQ_NEXT(r, entries);
4699 		}
4700 		else {
4701 			if (r->tag)
4702 				tag = r->tag;
4703 			if (r->anchor == NULL) {
4704 				/* Rule matches */
4705 				rm = r;
4706 
4707 				SDT_PROBE2(pf, eth, test_rule, match, r->nr, r);
4708 
4709 				if (r->quick)
4710 					break;
4711 
4712 				r = TAILQ_NEXT(r, entries);
4713 			} else {
4714 				pf_step_into_keth_anchor(anchor_stack, &asd,
4715 				    &ruleset, &r, &a, &match);
4716 			}
4717 		}
4718 		if (r == NULL && pf_step_out_of_keth_anchor(anchor_stack, &asd,
4719 		    &ruleset, &r, &a, &match))
4720 			break;
4721 	}
4722 
4723 	r = rm;
4724 
4725 	SDT_PROBE2(pf, eth, test_rule, final_match, (r != NULL ? r->nr : -1), r);
4726 
4727 	/* Default to pass. */
4728 	if (r == NULL) {
4729 		PF_RULES_RUNLOCK();
4730 		return (PF_PASS);
4731 	}
4732 
4733 	/* Execute action. */
4734 	counter_u64_add(r->packets[dir == PF_OUT], 1);
4735 	counter_u64_add(r->bytes[dir == PF_OUT], m_length(m, NULL));
4736 	pf_update_timestamp(r);
4737 
4738 	/* Shortcut. Don't tag if we're just going to drop anyway. */
4739 	if (r->action == PF_DROP) {
4740 		PF_RULES_RUNLOCK();
4741 		return (PF_DROP);
4742 	}
4743 
4744 	if (tag > 0) {
4745 		if (mtag == NULL)
4746 			mtag = pf_get_mtag(m);
4747 		if (mtag == NULL) {
4748 			PF_RULES_RUNLOCK();
4749 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4750 			return (PF_DROP);
4751 		}
4752 		mtag->tag = tag;
4753 	}
4754 
4755 	if (r->qid != 0) {
4756 		if (mtag == NULL)
4757 			mtag = pf_get_mtag(m);
4758 		if (mtag == NULL) {
4759 			PF_RULES_RUNLOCK();
4760 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4761 			return (PF_DROP);
4762 		}
4763 		mtag->qid = r->qid;
4764 	}
4765 
4766 	action = r->action;
4767 	bridge_to = r->bridge_to;
4768 
4769 	/* Dummynet */
4770 	if (r->dnpipe) {
4771 		struct ip_fw_args dnflow;
4772 
4773 		/* Drop packet if dummynet is not loaded. */
4774 		if (ip_dn_io_ptr == NULL) {
4775 			PF_RULES_RUNLOCK();
4776 			m_freem(m);
4777 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4778 			return (PF_DROP);
4779 		}
4780 		if (mtag == NULL)
4781 			mtag = pf_get_mtag(m);
4782 		if (mtag == NULL) {
4783 			PF_RULES_RUNLOCK();
4784 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4785 			return (PF_DROP);
4786 		}
4787 
4788 		bzero(&dnflow, sizeof(dnflow));
4789 
4790 		/* We don't have port numbers here, so we set 0.  That means
4791 		 * that we'll be somewhat limited in distinguishing flows (i.e.
4792 		 * only based on IP addresses, not based on port numbers), but
4793 		 * it's better than nothing. */
4794 		dnflow.f_id.dst_port = 0;
4795 		dnflow.f_id.src_port = 0;
4796 		dnflow.f_id.proto = 0;
4797 
4798 		dnflow.rule.info = r->dnpipe;
4799 		dnflow.rule.info |= IPFW_IS_DUMMYNET;
4800 		if (r->dnflags & PFRULE_DN_IS_PIPE)
4801 			dnflow.rule.info |= IPFW_IS_PIPE;
4802 
4803 		dnflow.f_id.extra = dnflow.rule.info;
4804 
4805 		dnflow.flags = dir == PF_IN ? IPFW_ARGS_IN : IPFW_ARGS_OUT;
4806 		dnflow.flags |= IPFW_ARGS_ETHER;
4807 		dnflow.ifp = kif->pfik_ifp;
4808 
4809 		switch (af) {
4810 		case AF_INET:
4811 			dnflow.f_id.addr_type = 4;
4812 			dnflow.f_id.src_ip = src->v4.s_addr;
4813 			dnflow.f_id.dst_ip = dst->v4.s_addr;
4814 			break;
4815 		case AF_INET6:
4816 			dnflow.flags |= IPFW_ARGS_IP6;
4817 			dnflow.f_id.addr_type = 6;
4818 			dnflow.f_id.src_ip6 = src->v6;
4819 			dnflow.f_id.dst_ip6 = dst->v6;
4820 			break;
4821 		}
4822 
4823 		PF_RULES_RUNLOCK();
4824 
4825 		mtag->flags |= PF_MTAG_FLAG_DUMMYNET;
4826 		ip_dn_io_ptr(m0, &dnflow);
4827 		if (*m0 != NULL)
4828 			pf_dummynet_flag_remove(m, mtag);
4829 	} else {
4830 		PF_RULES_RUNLOCK();
4831 	}
4832 
4833 	if (action == PF_PASS && bridge_to) {
4834 		pf_bridge_to(bridge_to->pfik_ifp, *m0);
4835 		*m0 = NULL; /* We've eaten the packet. */
4836 	}
4837 
4838 	return (action);
4839 }
4840 
4841 #define PF_TEST_ATTRIB(t, a)\
4842 	do {				\
4843 		if (t) {		\
4844 			r = a;		\
4845 			goto nextrule;	\
4846 		}			\
4847 	} while (0)
4848 
4849 static int
4850 pf_test_rule(struct pf_krule **rm, struct pf_kstate **sm,
4851     struct pf_pdesc *pd, struct pf_krule **am,
4852     struct pf_kruleset **rsm, struct inpcb *inp)
4853 {
4854 	struct pf_krule		*nr = NULL;
4855 	struct pf_addr		* const saddr = pd->src;
4856 	struct pf_addr		* const daddr = pd->dst;
4857 	struct pf_krule		*r, *a = NULL;
4858 	struct pf_kruleset	*ruleset = NULL;
4859 	struct pf_krule_slist	 match_rules;
4860 	struct pf_krule_item	*ri;
4861 	struct pf_ksrc_node	*nsn = NULL;
4862 	struct tcphdr		*th = &pd->hdr.tcp;
4863 	struct pf_state_key	*sk = NULL, *nk = NULL;
4864 	u_short			 reason, transerror;
4865 	int			 rewrite = 0;
4866 	int			 tag = -1;
4867 	int			 asd = 0;
4868 	int			 match = 0;
4869 	int			 state_icmp = 0, icmp_dir, multi;
4870 	u_int16_t		 sport = 0, dport = 0, virtual_type, virtual_id;
4871 	u_int16_t		 bproto_sum = 0, bip_sum = 0;
4872 	u_int8_t		 icmptype = 0, icmpcode = 0;
4873 	struct pf_kanchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
4874 	struct pf_udp_mapping	*udp_mapping = NULL;
4875 
4876 	PF_RULES_RASSERT();
4877 
4878 	SLIST_INIT(&match_rules);
4879 
4880 	if (inp != NULL) {
4881 		INP_LOCK_ASSERT(inp);
4882 		pd->lookup.uid = inp->inp_cred->cr_uid;
4883 		pd->lookup.gid = inp->inp_cred->cr_groups[0];
4884 		pd->lookup.done = 1;
4885 	}
4886 
4887 	switch (pd->virtual_proto) {
4888 	case IPPROTO_TCP:
4889 		sport = th->th_sport;
4890 		dport = th->th_dport;
4891 		break;
4892 	case IPPROTO_UDP:
4893 		sport = pd->hdr.udp.uh_sport;
4894 		dport = pd->hdr.udp.uh_dport;
4895 		break;
4896 	case IPPROTO_SCTP:
4897 		sport = pd->hdr.sctp.src_port;
4898 		dport = pd->hdr.sctp.dest_port;
4899 		break;
4900 #ifdef INET
4901 	case IPPROTO_ICMP:
4902 		MPASS(pd->af == AF_INET);
4903 		icmptype = pd->hdr.icmp.icmp_type;
4904 		icmpcode = pd->hdr.icmp.icmp_code;
4905 		state_icmp = pf_icmp_mapping(pd, icmptype,
4906 		    &icmp_dir, &multi, &virtual_id, &virtual_type);
4907 		if (icmp_dir == PF_IN) {
4908 			sport = virtual_id;
4909 			dport = virtual_type;
4910 		} else {
4911 			sport = virtual_type;
4912 			dport = virtual_id;
4913 		}
4914 		break;
4915 #endif /* INET */
4916 #ifdef INET6
4917 	case IPPROTO_ICMPV6:
4918 		MPASS(pd->af == AF_INET6);
4919 		icmptype = pd->hdr.icmp6.icmp6_type;
4920 		icmpcode = pd->hdr.icmp6.icmp6_code;
4921 		state_icmp = pf_icmp_mapping(pd, icmptype,
4922 		    &icmp_dir, &multi, &virtual_id, &virtual_type);
4923 		if (icmp_dir == PF_IN) {
4924 			sport = virtual_id;
4925 			dport = virtual_type;
4926 		} else {
4927 			sport = virtual_type;
4928 			dport = virtual_id;
4929 		}
4930 
4931 		break;
4932 #endif /* INET6 */
4933 	default:
4934 		sport = dport = 0;
4935 		break;
4936 	}
4937 
4938 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
4939 
4940 	/* check packet for BINAT/NAT/RDR */
4941 	transerror = pf_get_translation(pd, pd->off, &nsn, &sk,
4942 	    &nk, saddr, daddr, sport, dport, anchor_stack, &nr, &udp_mapping);
4943 	switch (transerror) {
4944 	default:
4945 		/* A translation error occurred. */
4946 		REASON_SET(&reason, transerror);
4947 		goto cleanup;
4948 	case PFRES_MAX:
4949 		/* No match. */
4950 		break;
4951 	case PFRES_MATCH:
4952 		KASSERT(sk != NULL, ("%s: null sk", __func__));
4953 		KASSERT(nk != NULL, ("%s: null nk", __func__));
4954 
4955 		if (nr->log) {
4956 			PFLOG_PACKET(PF_PASS, PFRES_MATCH, nr, a,
4957 			    ruleset, pd, 1);
4958 		}
4959 
4960 		if (pd->ip_sum)
4961 			bip_sum = *pd->ip_sum;
4962 
4963 		switch (pd->proto) {
4964 		case IPPROTO_TCP:
4965 			bproto_sum = th->th_sum;
4966 			pd->proto_sum = &th->th_sum;
4967 
4968 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], pd->af) ||
4969 			    nk->port[pd->sidx] != sport) {
4970 				pf_change_ap(pd->m, saddr, &th->th_sport, pd->ip_sum,
4971 				    &th->th_sum, &nk->addr[pd->sidx],
4972 				    nk->port[pd->sidx], 0, pd->af);
4973 				pd->sport = &th->th_sport;
4974 				sport = th->th_sport;
4975 			}
4976 
4977 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], pd->af) ||
4978 			    nk->port[pd->didx] != dport) {
4979 				pf_change_ap(pd->m, daddr, &th->th_dport, pd->ip_sum,
4980 				    &th->th_sum, &nk->addr[pd->didx],
4981 				    nk->port[pd->didx], 0, pd->af);
4982 				dport = th->th_dport;
4983 				pd->dport = &th->th_dport;
4984 			}
4985 			rewrite++;
4986 			break;
4987 		case IPPROTO_UDP:
4988 			bproto_sum = pd->hdr.udp.uh_sum;
4989 			pd->proto_sum = &pd->hdr.udp.uh_sum;
4990 
4991 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], pd->af) ||
4992 			    nk->port[pd->sidx] != sport) {
4993 				pf_change_ap(pd->m, saddr, &pd->hdr.udp.uh_sport,
4994 				    pd->ip_sum, &pd->hdr.udp.uh_sum,
4995 				    &nk->addr[pd->sidx],
4996 				    nk->port[pd->sidx], 1, pd->af);
4997 				sport = pd->hdr.udp.uh_sport;
4998 				pd->sport = &pd->hdr.udp.uh_sport;
4999 			}
5000 
5001 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], pd->af) ||
5002 			    nk->port[pd->didx] != dport) {
5003 				pf_change_ap(pd->m, daddr, &pd->hdr.udp.uh_dport,
5004 				    pd->ip_sum, &pd->hdr.udp.uh_sum,
5005 				    &nk->addr[pd->didx],
5006 				    nk->port[pd->didx], 1, pd->af);
5007 				dport = pd->hdr.udp.uh_dport;
5008 				pd->dport = &pd->hdr.udp.uh_dport;
5009 			}
5010 			rewrite++;
5011 			break;
5012 		case IPPROTO_SCTP: {
5013 			uint16_t checksum = 0;
5014 
5015 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], pd->af) ||
5016 			    nk->port[pd->sidx] != sport) {
5017 				pf_change_ap(pd->m, saddr, &pd->hdr.sctp.src_port,
5018 				    pd->ip_sum, &checksum,
5019 				    &nk->addr[pd->sidx],
5020 				    nk->port[pd->sidx], 1, pd->af);
5021 			}
5022 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], pd->af) ||
5023 			    nk->port[pd->didx] != dport) {
5024 				pf_change_ap(pd->m, daddr, &pd->hdr.sctp.dest_port,
5025 				    pd->ip_sum, &checksum,
5026 				    &nk->addr[pd->didx],
5027 				    nk->port[pd->didx], 1, pd->af);
5028 			}
5029 			break;
5030 		}
5031 #ifdef INET
5032 		case IPPROTO_ICMP:
5033 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
5034 				pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
5035 				    nk->addr[pd->sidx].v4.s_addr, 0);
5036 
5037 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
5038 				pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
5039 				    nk->addr[pd->didx].v4.s_addr, 0);
5040 
5041 			if (virtual_type == htons(ICMP_ECHO) &&
5042 			     nk->port[pd->sidx] != pd->hdr.icmp.icmp_id) {
5043 				pd->hdr.icmp.icmp_cksum = pf_cksum_fixup(
5044 				    pd->hdr.icmp.icmp_cksum, sport,
5045 				    nk->port[pd->sidx], 0);
5046 				pd->hdr.icmp.icmp_id = nk->port[pd->sidx];
5047 				pd->sport = &pd->hdr.icmp.icmp_id;
5048 			}
5049 			m_copyback(pd->m, pd->off, ICMP_MINLEN, (caddr_t)&pd->hdr.icmp);
5050 			break;
5051 #endif /* INET */
5052 #ifdef INET6
5053 		case IPPROTO_ICMPV6:
5054 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
5055 				pf_change_a6(saddr, &pd->hdr.icmp6.icmp6_cksum,
5056 				    &nk->addr[pd->sidx], 0);
5057 
5058 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
5059 				pf_change_a6(daddr, &pd->hdr.icmp6.icmp6_cksum,
5060 				    &nk->addr[pd->didx], 0);
5061 			rewrite++;
5062 			break;
5063 #endif /* INET */
5064 		default:
5065 			switch (pd->af) {
5066 #ifdef INET
5067 			case AF_INET:
5068 				if (PF_ANEQ(saddr,
5069 				    &nk->addr[pd->sidx], AF_INET))
5070 					pf_change_a(&saddr->v4.s_addr,
5071 					    pd->ip_sum,
5072 					    nk->addr[pd->sidx].v4.s_addr, 0);
5073 
5074 				if (PF_ANEQ(daddr,
5075 				    &nk->addr[pd->didx], AF_INET))
5076 					pf_change_a(&daddr->v4.s_addr,
5077 					    pd->ip_sum,
5078 					    nk->addr[pd->didx].v4.s_addr, 0);
5079 				break;
5080 #endif /* INET */
5081 #ifdef INET6
5082 			case AF_INET6:
5083 				if (PF_ANEQ(saddr,
5084 				    &nk->addr[pd->sidx], AF_INET6))
5085 					PF_ACPY(saddr, &nk->addr[pd->sidx], pd->af);
5086 
5087 				if (PF_ANEQ(daddr,
5088 				    &nk->addr[pd->didx], AF_INET6))
5089 					PF_ACPY(daddr, &nk->addr[pd->didx], pd->af);
5090 				break;
5091 #endif /* INET */
5092 			}
5093 			break;
5094 		}
5095 		if (nr->natpass)
5096 			r = NULL;
5097 	}
5098 
5099 	while (r != NULL) {
5100 		pf_counter_u64_add(&r->evaluations, 1);
5101 		PF_TEST_ATTRIB(pfi_kkif_match(r->kif, pd->kif) == r->ifnot,
5102 			r->skip[PF_SKIP_IFP]);
5103 		PF_TEST_ATTRIB(r->direction && r->direction != pd->dir,
5104 			r->skip[PF_SKIP_DIR]);
5105 		PF_TEST_ATTRIB(r->af && r->af != pd->af,
5106 			r->skip[PF_SKIP_AF]);
5107 		PF_TEST_ATTRIB(r->proto && r->proto != pd->proto,
5108 			r->skip[PF_SKIP_PROTO]);
5109 		PF_TEST_ATTRIB(PF_MISMATCHAW(&r->src.addr, saddr, pd->af,
5110 		    r->src.neg, pd->kif, M_GETFIB(pd->m)),
5111 			r->skip[PF_SKIP_SRC_ADDR]);
5112 		PF_TEST_ATTRIB(PF_MISMATCHAW(&r->dst.addr, daddr, pd->af,
5113 		    r->dst.neg, NULL, M_GETFIB(pd->m)),
5114 			r->skip[PF_SKIP_DST_ADDR]);
5115 		switch (pd->virtual_proto) {
5116 		case PF_VPROTO_FRAGMENT:
5117 			/* tcp/udp only. port_op always 0 in other cases */
5118 			PF_TEST_ATTRIB((r->src.port_op || r->dst.port_op),
5119 				TAILQ_NEXT(r, entries));
5120 			PF_TEST_ATTRIB((pd->proto == IPPROTO_TCP && r->flagset),
5121 				TAILQ_NEXT(r, entries));
5122 			/* icmp only. type/code always 0 in other cases */
5123 			PF_TEST_ATTRIB((r->type || r->code),
5124 				TAILQ_NEXT(r, entries));
5125 			/* tcp/udp only. {uid|gid}.op always 0 in other cases */
5126 			PF_TEST_ATTRIB((r->gid.op || r->uid.op),
5127 				TAILQ_NEXT(r, entries));
5128 			break;
5129 
5130 		case IPPROTO_TCP:
5131 			PF_TEST_ATTRIB((r->flagset & th->th_flags) != r->flags,
5132 				TAILQ_NEXT(r, entries));
5133 			/* FALLTHROUGH */
5134 		case IPPROTO_SCTP:
5135 		case IPPROTO_UDP:
5136 			/* tcp/udp only. port_op always 0 in other cases */
5137 			PF_TEST_ATTRIB(r->src.port_op && !pf_match_port(r->src.port_op,
5138 			    r->src.port[0], r->src.port[1], sport),
5139 				r->skip[PF_SKIP_SRC_PORT]);
5140 			/* tcp/udp only. port_op always 0 in other cases */
5141 			PF_TEST_ATTRIB(r->dst.port_op && !pf_match_port(r->dst.port_op,
5142 			    r->dst.port[0], r->dst.port[1], dport),
5143 				r->skip[PF_SKIP_DST_PORT]);
5144 			/* tcp/udp only. uid.op always 0 in other cases */
5145 			PF_TEST_ATTRIB(r->uid.op && (pd->lookup.done || (pd->lookup.done =
5146 			    pf_socket_lookup(pd), 1)) &&
5147 			    !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
5148 			    pd->lookup.uid),
5149 				TAILQ_NEXT(r, entries));
5150 			/* tcp/udp only. gid.op always 0 in other cases */
5151 			PF_TEST_ATTRIB(r->gid.op && (pd->lookup.done || (pd->lookup.done =
5152 			    pf_socket_lookup(pd), 1)) &&
5153 			    !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
5154 			    pd->lookup.gid),
5155 				TAILQ_NEXT(r, entries));
5156 			break;
5157 
5158 		case IPPROTO_ICMP:
5159 		case IPPROTO_ICMPV6:
5160 			/* icmp only. type always 0 in other cases */
5161 			PF_TEST_ATTRIB(r->type && r->type != icmptype + 1,
5162 				TAILQ_NEXT(r, entries));
5163 			/* icmp only. type always 0 in other cases */
5164 			PF_TEST_ATTRIB(r->code && r->code != icmpcode + 1,
5165 				TAILQ_NEXT(r, entries));
5166 			break;
5167 
5168 		default:
5169 			break;
5170 		}
5171 		PF_TEST_ATTRIB(r->tos && !(r->tos == pd->tos),
5172 			TAILQ_NEXT(r, entries));
5173 		PF_TEST_ATTRIB(r->prio &&
5174 		    !pf_match_ieee8021q_pcp(r->prio, pd->m),
5175 			TAILQ_NEXT(r, entries));
5176 		PF_TEST_ATTRIB(r->prob &&
5177 		    r->prob <= arc4random(),
5178 			TAILQ_NEXT(r, entries));
5179 		PF_TEST_ATTRIB(r->match_tag && !pf_match_tag(pd->m, r, &tag,
5180 		    pd->pf_mtag ? pd->pf_mtag->tag : 0),
5181 			TAILQ_NEXT(r, entries));
5182 		PF_TEST_ATTRIB(r->rcv_kif && !pf_match_rcvif(pd->m, r),
5183 			TAILQ_NEXT(r, entries));
5184 		PF_TEST_ATTRIB((r->rule_flag & PFRULE_FRAGMENT &&
5185 		    pd->virtual_proto != PF_VPROTO_FRAGMENT),
5186 			TAILQ_NEXT(r, entries));
5187 		PF_TEST_ATTRIB(r->os_fingerprint != PF_OSFP_ANY &&
5188 		    (pd->virtual_proto != IPPROTO_TCP || !pf_osfp_match(
5189 		    pf_osfp_fingerprint(pd, th),
5190 		    r->os_fingerprint)),
5191 			TAILQ_NEXT(r, entries));
5192 		/* FALLTHROUGH */
5193 		if (r->tag)
5194 			tag = r->tag;
5195 		if (r->anchor == NULL) {
5196 			if (r->action == PF_MATCH) {
5197 				ri = malloc(sizeof(struct pf_krule_item), M_PF_RULE_ITEM, M_NOWAIT | M_ZERO);
5198 				if (ri == NULL) {
5199 					REASON_SET(&reason, PFRES_MEMORY);
5200 					goto cleanup;
5201 				}
5202 				ri->r = r;
5203 				SLIST_INSERT_HEAD(&match_rules, ri, entry);
5204 				pf_counter_u64_critical_enter();
5205 				pf_counter_u64_add_protected(&r->packets[pd->dir == PF_OUT], 1);
5206 				pf_counter_u64_add_protected(&r->bytes[pd->dir == PF_OUT], pd->tot_len);
5207 				pf_counter_u64_critical_exit();
5208 				pf_rule_to_actions(r, &pd->act);
5209 				if (r->log || pd->act.log & PF_LOG_MATCHES)
5210 					PFLOG_PACKET(r->action, PFRES_MATCH, r,
5211 					    a, ruleset, pd, 1);
5212 			} else {
5213 				match = 1;
5214 				*rm = r;
5215 				*am = a;
5216 				*rsm = ruleset;
5217 				if (pd->act.log & PF_LOG_MATCHES)
5218 					PFLOG_PACKET(r->action, PFRES_MATCH, r,
5219 					    a, ruleset, pd, 1);
5220 			}
5221 			if ((*rm)->quick)
5222 				break;
5223 			r = TAILQ_NEXT(r, entries);
5224 		} else
5225 			pf_step_into_anchor(anchor_stack, &asd,
5226 			    &ruleset, PF_RULESET_FILTER, &r, &a,
5227 			    &match);
5228 nextrule:
5229 		if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
5230 		    &ruleset, PF_RULESET_FILTER, &r, &a, &match))
5231 			break;
5232 	}
5233 	r = *rm;
5234 	a = *am;
5235 	ruleset = *rsm;
5236 
5237 	REASON_SET(&reason, PFRES_MATCH);
5238 
5239 	/* apply actions for last matching pass/block rule */
5240 	pf_rule_to_actions(r, &pd->act);
5241 
5242 	if (r->log || pd->act.log & PF_LOG_MATCHES) {
5243 		if (rewrite)
5244 			m_copyback(pd->m, pd->off, pd->hdrlen, pd->hdr.any);
5245 		PFLOG_PACKET(r->action, reason, r, a, ruleset, pd, 1);
5246 	}
5247 
5248 	if (pd->virtual_proto != PF_VPROTO_FRAGMENT &&
5249 	   (r->action == PF_DROP) &&
5250 	    ((r->rule_flag & PFRULE_RETURNRST) ||
5251 	    (r->rule_flag & PFRULE_RETURNICMP) ||
5252 	    (r->rule_flag & PFRULE_RETURN))) {
5253 		pf_return(r, nr, pd, sk, th, bproto_sum,
5254 		    bip_sum, &reason, r->rtableid);
5255 	}
5256 
5257 	if (r->action == PF_DROP)
5258 		goto cleanup;
5259 
5260 	if (tag > 0 && pf_tag_packet(pd, tag)) {
5261 		REASON_SET(&reason, PFRES_MEMORY);
5262 		goto cleanup;
5263 	}
5264 	if (pd->act.rtableid >= 0)
5265 		M_SETFIB(pd->m, pd->act.rtableid);
5266 
5267 	if (pd->virtual_proto != PF_VPROTO_FRAGMENT &&
5268 	   (!state_icmp && (r->keep_state || nr != NULL ||
5269 	    (pd->flags & PFDESC_TCP_NORM)))) {
5270 		int action;
5271 		action = pf_create_state(r, nr, a, pd, nsn, nk, sk,
5272 		    sport, dport, &rewrite, sm, tag, bproto_sum, bip_sum,
5273 		    &match_rules, udp_mapping);
5274 		if (action != PF_PASS) {
5275 			pf_udp_mapping_release(udp_mapping);
5276 			if (action == PF_DROP &&
5277 			    (r->rule_flag & PFRULE_RETURN))
5278 				pf_return(r, nr, pd, sk, th,
5279 				    bproto_sum, bip_sum, &reason,
5280 				    pd->act.rtableid);
5281 			return (action);
5282 		}
5283 	} else {
5284 		while ((ri = SLIST_FIRST(&match_rules))) {
5285 			SLIST_REMOVE_HEAD(&match_rules, entry);
5286 			free(ri, M_PF_RULE_ITEM);
5287 		}
5288 
5289 		uma_zfree(V_pf_state_key_z, sk);
5290 		uma_zfree(V_pf_state_key_z, nk);
5291 		pf_udp_mapping_release(udp_mapping);
5292 	}
5293 
5294 	/* copy back packet headers if we performed NAT operations */
5295 	if (rewrite)
5296 		m_copyback(pd->m, pd->off, pd->hdrlen, pd->hdr.any);
5297 
5298 	if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
5299 	    pd->dir == PF_OUT &&
5300 	    V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, pd->m))
5301 		/*
5302 		 * We want the state created, but we dont
5303 		 * want to send this in case a partner
5304 		 * firewall has to know about it to allow
5305 		 * replies through it.
5306 		 */
5307 		return (PF_DEFER);
5308 
5309 	return (PF_PASS);
5310 
5311 cleanup:
5312 	while ((ri = SLIST_FIRST(&match_rules))) {
5313 		SLIST_REMOVE_HEAD(&match_rules, entry);
5314 		free(ri, M_PF_RULE_ITEM);
5315 	}
5316 
5317 	uma_zfree(V_pf_state_key_z, sk);
5318 	uma_zfree(V_pf_state_key_z, nk);
5319 	pf_udp_mapping_release(udp_mapping);
5320 
5321 	return (PF_DROP);
5322 }
5323 
5324 static int
5325 pf_create_state(struct pf_krule *r, struct pf_krule *nr, struct pf_krule *a,
5326     struct pf_pdesc *pd, struct pf_ksrc_node *nsn, struct pf_state_key *nk,
5327     struct pf_state_key *sk, u_int16_t sport,
5328     u_int16_t dport, int *rewrite, struct pf_kstate **sm,
5329     int tag, u_int16_t bproto_sum, u_int16_t bip_sum,
5330     struct pf_krule_slist *match_rules, struct pf_udp_mapping *udp_mapping)
5331 {
5332 	struct pf_kstate	*s = NULL;
5333 	struct pf_ksrc_node	*sn = NULL;
5334 	struct tcphdr		*th = &pd->hdr.tcp;
5335 	u_int16_t		 mss = V_tcp_mssdflt;
5336 	u_short			 reason, sn_reason;
5337 	struct pf_krule_item	*ri;
5338 
5339 	/* check maximums */
5340 	if (r->max_states &&
5341 	    (counter_u64_fetch(r->states_cur) >= r->max_states)) {
5342 		counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
5343 		REASON_SET(&reason, PFRES_MAXSTATES);
5344 		goto csfailed;
5345 	}
5346 	/* src node for filter rule */
5347 	if ((r->rule_flag & PFRULE_SRCTRACK ||
5348 	    r->rpool.opts & PF_POOL_STICKYADDR) &&
5349 	    (sn_reason = pf_insert_src_node(&sn, r, pd->src, pd->af)) != 0) {
5350 		REASON_SET(&reason, sn_reason);
5351 		goto csfailed;
5352 	}
5353 	/* src node for translation rule */
5354 	if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
5355 	    (sn_reason = pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx],
5356 	    pd->af)) != 0 ) {
5357 		REASON_SET(&reason, sn_reason);
5358 		goto csfailed;
5359 	}
5360 	s = pf_alloc_state(M_NOWAIT);
5361 	if (s == NULL) {
5362 		REASON_SET(&reason, PFRES_MEMORY);
5363 		goto csfailed;
5364 	}
5365 	s->rule = r;
5366 	s->nat_rule = nr;
5367 	s->anchor = a;
5368 	bcopy(match_rules, &s->match_rules, sizeof(s->match_rules));
5369 	memcpy(&s->act, &pd->act, sizeof(struct pf_rule_actions));
5370 
5371 	STATE_INC_COUNTERS(s);
5372 	if (r->allow_opts)
5373 		s->state_flags |= PFSTATE_ALLOWOPTS;
5374 	if (r->rule_flag & PFRULE_STATESLOPPY)
5375 		s->state_flags |= PFSTATE_SLOPPY;
5376 	if (pd->flags & PFDESC_TCP_NORM) /* Set by old-style scrub rules */
5377 		s->state_flags |= PFSTATE_SCRUB_TCP;
5378 	if ((r->rule_flag & PFRULE_PFLOW) ||
5379 	    (nr != NULL && nr->rule_flag & PFRULE_PFLOW))
5380 		s->state_flags |= PFSTATE_PFLOW;
5381 
5382 	s->act.log = pd->act.log & PF_LOG_ALL;
5383 	s->sync_state = PFSYNC_S_NONE;
5384 	s->state_flags |= pd->act.flags; /* Only needed for pfsync and state export */
5385 
5386 	if (nr != NULL)
5387 		s->act.log |= nr->log & PF_LOG_ALL;
5388 	switch (pd->proto) {
5389 	case IPPROTO_TCP:
5390 		s->src.seqlo = ntohl(th->th_seq);
5391 		s->src.seqhi = s->src.seqlo + pd->p_len + 1;
5392 		if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
5393 		    r->keep_state == PF_STATE_MODULATE) {
5394 			/* Generate sequence number modulator */
5395 			if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
5396 			    0)
5397 				s->src.seqdiff = 1;
5398 			pf_change_proto_a(pd->m, &th->th_seq, &th->th_sum,
5399 			    htonl(s->src.seqlo + s->src.seqdiff), 0);
5400 			*rewrite = 1;
5401 		} else
5402 			s->src.seqdiff = 0;
5403 		if (th->th_flags & TH_SYN) {
5404 			s->src.seqhi++;
5405 			s->src.wscale = pf_get_wscale(pd);
5406 		}
5407 		s->src.max_win = MAX(ntohs(th->th_win), 1);
5408 		if (s->src.wscale & PF_WSCALE_MASK) {
5409 			/* Remove scale factor from initial window */
5410 			int win = s->src.max_win;
5411 			win += 1 << (s->src.wscale & PF_WSCALE_MASK);
5412 			s->src.max_win = (win - 1) >>
5413 			    (s->src.wscale & PF_WSCALE_MASK);
5414 		}
5415 		if (th->th_flags & TH_FIN)
5416 			s->src.seqhi++;
5417 		s->dst.seqhi = 1;
5418 		s->dst.max_win = 1;
5419 		pf_set_protostate(s, PF_PEER_SRC, TCPS_SYN_SENT);
5420 		pf_set_protostate(s, PF_PEER_DST, TCPS_CLOSED);
5421 		s->timeout = PFTM_TCP_FIRST_PACKET;
5422 		atomic_add_32(&V_pf_status.states_halfopen, 1);
5423 		break;
5424 	case IPPROTO_UDP:
5425 		pf_set_protostate(s, PF_PEER_SRC, PFUDPS_SINGLE);
5426 		pf_set_protostate(s, PF_PEER_DST, PFUDPS_NO_TRAFFIC);
5427 		s->timeout = PFTM_UDP_FIRST_PACKET;
5428 		break;
5429 	case IPPROTO_SCTP:
5430 		pf_set_protostate(s, PF_PEER_SRC, SCTP_COOKIE_WAIT);
5431 		pf_set_protostate(s, PF_PEER_DST, SCTP_CLOSED);
5432 		s->timeout = PFTM_SCTP_FIRST_PACKET;
5433 		break;
5434 	case IPPROTO_ICMP:
5435 #ifdef INET6
5436 	case IPPROTO_ICMPV6:
5437 #endif
5438 		s->timeout = PFTM_ICMP_FIRST_PACKET;
5439 		break;
5440 	default:
5441 		pf_set_protostate(s, PF_PEER_SRC, PFOTHERS_SINGLE);
5442 		pf_set_protostate(s, PF_PEER_DST, PFOTHERS_NO_TRAFFIC);
5443 		s->timeout = PFTM_OTHER_FIRST_PACKET;
5444 	}
5445 
5446 	if (r->rt) {
5447 		/* pf_map_addr increases the reason counters */
5448 		if ((reason = pf_map_addr_sn(pd->af, r, pd->src, &s->rt_addr,
5449 		    &s->rt_kif, NULL, &sn)) != 0)
5450 			goto csfailed;
5451 		s->rt = r->rt;
5452 	}
5453 
5454 	s->creation = s->expire = pf_get_uptime();
5455 
5456 	if (sn != NULL)
5457 		s->src_node = sn;
5458 	if (nsn != NULL) {
5459 		/* XXX We only modify one side for now. */
5460 		PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
5461 		s->nat_src_node = nsn;
5462 	}
5463 	if (pd->proto == IPPROTO_TCP) {
5464 		if (s->state_flags & PFSTATE_SCRUB_TCP &&
5465 		    pf_normalize_tcp_init(pd, th, &s->src, &s->dst)) {
5466 			REASON_SET(&reason, PFRES_MEMORY);
5467 			goto csfailed;
5468 		}
5469 		if (s->state_flags & PFSTATE_SCRUB_TCP && s->src.scrub &&
5470 		    pf_normalize_tcp_stateful(pd, &reason, th, s,
5471 		    &s->src, &s->dst, rewrite)) {
5472 			/* This really shouldn't happen!!! */
5473 			DPFPRINTF(PF_DEBUG_URGENT,
5474 			    ("pf_normalize_tcp_stateful failed on first "
5475 			     "pkt\n"));
5476 			goto csfailed;
5477 		}
5478 	} else if (pd->proto == IPPROTO_SCTP) {
5479 		if (pf_normalize_sctp_init(pd, &s->src, &s->dst))
5480 			goto csfailed;
5481 		if (! (pd->sctp_flags & (PFDESC_SCTP_INIT | PFDESC_SCTP_ADD_IP)))
5482 			goto csfailed;
5483 	}
5484 	s->direction = pd->dir;
5485 
5486 	/*
5487 	 * sk/nk could already been setup by pf_get_translation().
5488 	 */
5489 	if (nr == NULL) {
5490 		KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
5491 		    __func__, nr, sk, nk));
5492 		sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
5493 		if (sk == NULL)
5494 			goto csfailed;
5495 		nk = sk;
5496 	} else
5497 		KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
5498 		    __func__, nr, sk, nk));
5499 
5500 	/* Swap sk/nk for PF_OUT. */
5501 	if (pf_state_insert(BOUND_IFACE(s, pd->kif), pd->kif,
5502 	    (pd->dir == PF_IN) ? sk : nk,
5503 	    (pd->dir == PF_IN) ? nk : sk, s)) {
5504 		REASON_SET(&reason, PFRES_STATEINS);
5505 		goto drop;
5506 	} else
5507 		*sm = s;
5508 
5509 	if (tag > 0)
5510 		s->tag = tag;
5511 	if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
5512 	    TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
5513 		pf_set_protostate(s, PF_PEER_SRC, PF_TCPS_PROXY_SRC);
5514 		/* undo NAT changes, if they have taken place */
5515 		if (nr != NULL) {
5516 			struct pf_state_key *skt = s->key[PF_SK_WIRE];
5517 			if (pd->dir == PF_OUT)
5518 				skt = s->key[PF_SK_STACK];
5519 			PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
5520 			PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
5521 			if (pd->sport)
5522 				*pd->sport = skt->port[pd->sidx];
5523 			if (pd->dport)
5524 				*pd->dport = skt->port[pd->didx];
5525 			if (pd->proto_sum)
5526 				*pd->proto_sum = bproto_sum;
5527 			if (pd->ip_sum)
5528 				*pd->ip_sum = bip_sum;
5529 			m_copyback(pd->m, pd->off, pd->hdrlen, pd->hdr.any);
5530 		}
5531 		s->src.seqhi = htonl(arc4random());
5532 		/* Find mss option */
5533 		int rtid = M_GETFIB(pd->m);
5534 		mss = pf_get_mss(pd);
5535 		mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
5536 		mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
5537 		s->src.mss = mss;
5538 		pf_send_tcp(r, pd->af, pd->dst, pd->src, th->th_dport,
5539 		    th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
5540 		    TH_SYN|TH_ACK, 0, s->src.mss, 0, true, 0, 0,
5541 		    pd->act.rtableid);
5542 		REASON_SET(&reason, PFRES_SYNPROXY);
5543 		return (PF_SYNPROXY_DROP);
5544 	}
5545 
5546 	s->udp_mapping = udp_mapping;
5547 
5548 	return (PF_PASS);
5549 
5550 csfailed:
5551 	while ((ri = SLIST_FIRST(match_rules))) {
5552 		SLIST_REMOVE_HEAD(match_rules, entry);
5553 		free(ri, M_PF_RULE_ITEM);
5554 	}
5555 
5556 	uma_zfree(V_pf_state_key_z, sk);
5557 	uma_zfree(V_pf_state_key_z, nk);
5558 
5559 	if (sn != NULL) {
5560 		PF_SRC_NODE_LOCK(sn);
5561 		if (--sn->states == 0 && sn->expire == 0) {
5562 			pf_unlink_src_node(sn);
5563 			uma_zfree(V_pf_sources_z, sn);
5564 			counter_u64_add(
5565 			    V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
5566 		}
5567 		PF_SRC_NODE_UNLOCK(sn);
5568 	}
5569 
5570 	if (nsn != sn && nsn != NULL) {
5571 		PF_SRC_NODE_LOCK(nsn);
5572 		if (--nsn->states == 0 && nsn->expire == 0) {
5573 			pf_unlink_src_node(nsn);
5574 			uma_zfree(V_pf_sources_z, nsn);
5575 			counter_u64_add(
5576 			    V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
5577 		}
5578 		PF_SRC_NODE_UNLOCK(nsn);
5579 	}
5580 
5581 drop:
5582 	if (s != NULL) {
5583 		pf_src_tree_remove_state(s);
5584 		s->timeout = PFTM_UNLINKED;
5585 		STATE_DEC_COUNTERS(s);
5586 		pf_free_state(s);
5587 	}
5588 
5589 	return (PF_DROP);
5590 }
5591 
5592 static int
5593 pf_tcp_track_full(struct pf_kstate **state, struct pf_pdesc *pd,
5594     u_short *reason, int *copyback)
5595 {
5596 	struct tcphdr		*th = &pd->hdr.tcp;
5597 	struct pf_state_peer	*src, *dst;
5598 	u_int16_t		 win = ntohs(th->th_win);
5599 	u_int32_t		 ack, end, data_end, seq, orig_seq;
5600 	u_int8_t		 sws, dws, psrc, pdst;
5601 	int			 ackskew;
5602 
5603 	if (pd->dir == (*state)->direction) {
5604 		src = &(*state)->src;
5605 		dst = &(*state)->dst;
5606 		psrc = PF_PEER_SRC;
5607 		pdst = PF_PEER_DST;
5608 	} else {
5609 		src = &(*state)->dst;
5610 		dst = &(*state)->src;
5611 		psrc = PF_PEER_DST;
5612 		pdst = PF_PEER_SRC;
5613 	}
5614 
5615 	if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
5616 		sws = src->wscale & PF_WSCALE_MASK;
5617 		dws = dst->wscale & PF_WSCALE_MASK;
5618 	} else
5619 		sws = dws = 0;
5620 
5621 	/*
5622 	 * Sequence tracking algorithm from Guido van Rooij's paper:
5623 	 *   http://www.madison-gurkha.com/publications/tcp_filtering/
5624 	 *	tcp_filtering.ps
5625 	 */
5626 
5627 	orig_seq = seq = ntohl(th->th_seq);
5628 	if (src->seqlo == 0) {
5629 		/* First packet from this end. Set its state */
5630 
5631 		if (((*state)->state_flags & PFSTATE_SCRUB_TCP || dst->scrub) &&
5632 		    src->scrub == NULL) {
5633 			if (pf_normalize_tcp_init(pd, th, src, dst)) {
5634 				REASON_SET(reason, PFRES_MEMORY);
5635 				return (PF_DROP);
5636 			}
5637 		}
5638 
5639 		/* Deferred generation of sequence number modulator */
5640 		if (dst->seqdiff && !src->seqdiff) {
5641 			/* use random iss for the TCP server */
5642 			while ((src->seqdiff = arc4random() - seq) == 0)
5643 				;
5644 			ack = ntohl(th->th_ack) - dst->seqdiff;
5645 			pf_change_proto_a(pd->m, &th->th_seq, &th->th_sum, htonl(seq +
5646 			    src->seqdiff), 0);
5647 			pf_change_proto_a(pd->m, &th->th_ack, &th->th_sum, htonl(ack), 0);
5648 			*copyback = 1;
5649 		} else {
5650 			ack = ntohl(th->th_ack);
5651 		}
5652 
5653 		end = seq + pd->p_len;
5654 		if (th->th_flags & TH_SYN) {
5655 			end++;
5656 			if (dst->wscale & PF_WSCALE_FLAG) {
5657 				src->wscale = pf_get_wscale(pd);
5658 				if (src->wscale & PF_WSCALE_FLAG) {
5659 					/* Remove scale factor from initial
5660 					 * window */
5661 					sws = src->wscale & PF_WSCALE_MASK;
5662 					win = ((u_int32_t)win + (1 << sws) - 1)
5663 					    >> sws;
5664 					dws = dst->wscale & PF_WSCALE_MASK;
5665 				} else {
5666 					/* fixup other window */
5667 					dst->max_win = MIN(TCP_MAXWIN,
5668 					    (u_int32_t)dst->max_win <<
5669 					    (dst->wscale & PF_WSCALE_MASK));
5670 					/* in case of a retrans SYN|ACK */
5671 					dst->wscale = 0;
5672 				}
5673 			}
5674 		}
5675 		data_end = end;
5676 		if (th->th_flags & TH_FIN)
5677 			end++;
5678 
5679 		src->seqlo = seq;
5680 		if (src->state < TCPS_SYN_SENT)
5681 			pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
5682 
5683 		/*
5684 		 * May need to slide the window (seqhi may have been set by
5685 		 * the crappy stack check or if we picked up the connection
5686 		 * after establishment)
5687 		 */
5688 		if (src->seqhi == 1 ||
5689 		    SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
5690 			src->seqhi = end + MAX(1, dst->max_win << dws);
5691 		if (win > src->max_win)
5692 			src->max_win = win;
5693 
5694 	} else {
5695 		ack = ntohl(th->th_ack) - dst->seqdiff;
5696 		if (src->seqdiff) {
5697 			/* Modulate sequence numbers */
5698 			pf_change_proto_a(pd->m, &th->th_seq, &th->th_sum, htonl(seq +
5699 			    src->seqdiff), 0);
5700 			pf_change_proto_a(pd->m, &th->th_ack, &th->th_sum, htonl(ack), 0);
5701 			*copyback = 1;
5702 		}
5703 		end = seq + pd->p_len;
5704 		if (th->th_flags & TH_SYN)
5705 			end++;
5706 		data_end = end;
5707 		if (th->th_flags & TH_FIN)
5708 			end++;
5709 	}
5710 
5711 	if ((th->th_flags & TH_ACK) == 0) {
5712 		/* Let it pass through the ack skew check */
5713 		ack = dst->seqlo;
5714 	} else if ((ack == 0 &&
5715 	    (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
5716 	    /* broken tcp stacks do not set ack */
5717 	    (dst->state < TCPS_SYN_SENT)) {
5718 		/*
5719 		 * Many stacks (ours included) will set the ACK number in an
5720 		 * FIN|ACK if the SYN times out -- no sequence to ACK.
5721 		 */
5722 		ack = dst->seqlo;
5723 	}
5724 
5725 	if (seq == end) {
5726 		/* Ease sequencing restrictions on no data packets */
5727 		seq = src->seqlo;
5728 		data_end = end = seq;
5729 	}
5730 
5731 	ackskew = dst->seqlo - ack;
5732 
5733 	/*
5734 	 * Need to demodulate the sequence numbers in any TCP SACK options
5735 	 * (Selective ACK). We could optionally validate the SACK values
5736 	 * against the current ACK window, either forwards or backwards, but
5737 	 * I'm not confident that SACK has been implemented properly
5738 	 * everywhere. It wouldn't surprise me if several stacks accidentally
5739 	 * SACK too far backwards of previously ACKed data. There really aren't
5740 	 * any security implications of bad SACKing unless the target stack
5741 	 * doesn't validate the option length correctly. Someone trying to
5742 	 * spoof into a TCP connection won't bother blindly sending SACK
5743 	 * options anyway.
5744 	 */
5745 	if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
5746 		if (pf_modulate_sack(pd, th, dst))
5747 			*copyback = 1;
5748 	}
5749 
5750 #define	MAXACKWINDOW (0xffff + 1500)	/* 1500 is an arbitrary fudge factor */
5751 	if (SEQ_GEQ(src->seqhi, data_end) &&
5752 	    /* Last octet inside other's window space */
5753 	    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
5754 	    /* Retrans: not more than one window back */
5755 	    (ackskew >= -MAXACKWINDOW) &&
5756 	    /* Acking not more than one reassembled fragment backwards */
5757 	    (ackskew <= (MAXACKWINDOW << sws)) &&
5758 	    /* Acking not more than one window forward */
5759 	    ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
5760 	    (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo))) {
5761 	    /* Require an exact/+1 sequence match on resets when possible */
5762 
5763 		if (dst->scrub || src->scrub) {
5764 			if (pf_normalize_tcp_stateful(pd, reason, th,
5765 			    *state, src, dst, copyback))
5766 				return (PF_DROP);
5767 		}
5768 
5769 		/* update max window */
5770 		if (src->max_win < win)
5771 			src->max_win = win;
5772 		/* synchronize sequencing */
5773 		if (SEQ_GT(end, src->seqlo))
5774 			src->seqlo = end;
5775 		/* slide the window of what the other end can send */
5776 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
5777 			dst->seqhi = ack + MAX((win << sws), 1);
5778 
5779 		/* update states */
5780 		if (th->th_flags & TH_SYN)
5781 			if (src->state < TCPS_SYN_SENT)
5782 				pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
5783 		if (th->th_flags & TH_FIN)
5784 			if (src->state < TCPS_CLOSING)
5785 				pf_set_protostate(*state, psrc, TCPS_CLOSING);
5786 		if (th->th_flags & TH_ACK) {
5787 			if (dst->state == TCPS_SYN_SENT) {
5788 				pf_set_protostate(*state, pdst,
5789 				    TCPS_ESTABLISHED);
5790 				if (src->state == TCPS_ESTABLISHED &&
5791 				    (*state)->src_node != NULL &&
5792 				    pf_src_connlimit(state)) {
5793 					REASON_SET(reason, PFRES_SRCLIMIT);
5794 					return (PF_DROP);
5795 				}
5796 			} else if (dst->state == TCPS_CLOSING)
5797 				pf_set_protostate(*state, pdst,
5798 				    TCPS_FIN_WAIT_2);
5799 		}
5800 		if (th->th_flags & TH_RST)
5801 			pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
5802 
5803 		/* update expire time */
5804 		(*state)->expire = pf_get_uptime();
5805 		if (src->state >= TCPS_FIN_WAIT_2 &&
5806 		    dst->state >= TCPS_FIN_WAIT_2)
5807 			(*state)->timeout = PFTM_TCP_CLOSED;
5808 		else if (src->state >= TCPS_CLOSING &&
5809 		    dst->state >= TCPS_CLOSING)
5810 			(*state)->timeout = PFTM_TCP_FIN_WAIT;
5811 		else if (src->state < TCPS_ESTABLISHED ||
5812 		    dst->state < TCPS_ESTABLISHED)
5813 			(*state)->timeout = PFTM_TCP_OPENING;
5814 		else if (src->state >= TCPS_CLOSING ||
5815 		    dst->state >= TCPS_CLOSING)
5816 			(*state)->timeout = PFTM_TCP_CLOSING;
5817 		else
5818 			(*state)->timeout = PFTM_TCP_ESTABLISHED;
5819 
5820 		/* Fall through to PASS packet */
5821 
5822 	} else if ((dst->state < TCPS_SYN_SENT ||
5823 		dst->state >= TCPS_FIN_WAIT_2 ||
5824 		src->state >= TCPS_FIN_WAIT_2) &&
5825 	    SEQ_GEQ(src->seqhi + MAXACKWINDOW, data_end) &&
5826 	    /* Within a window forward of the originating packet */
5827 	    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
5828 	    /* Within a window backward of the originating packet */
5829 
5830 		/*
5831 		 * This currently handles three situations:
5832 		 *  1) Stupid stacks will shotgun SYNs before their peer
5833 		 *     replies.
5834 		 *  2) When PF catches an already established stream (the
5835 		 *     firewall rebooted, the state table was flushed, routes
5836 		 *     changed...)
5837 		 *  3) Packets get funky immediately after the connection
5838 		 *     closes (this should catch Solaris spurious ACK|FINs
5839 		 *     that web servers like to spew after a close)
5840 		 *
5841 		 * This must be a little more careful than the above code
5842 		 * since packet floods will also be caught here. We don't
5843 		 * update the TTL here to mitigate the damage of a packet
5844 		 * flood and so the same code can handle awkward establishment
5845 		 * and a loosened connection close.
5846 		 * In the establishment case, a correct peer response will
5847 		 * validate the connection, go through the normal state code
5848 		 * and keep updating the state TTL.
5849 		 */
5850 
5851 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
5852 			printf("pf: loose state match: ");
5853 			pf_print_state(*state);
5854 			pf_print_flags(th->th_flags);
5855 			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
5856 			    "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
5857 			    pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
5858 			    (unsigned long long)(*state)->packets[1],
5859 			    pd->dir == PF_IN ? "in" : "out",
5860 			    pd->dir == (*state)->direction ? "fwd" : "rev");
5861 		}
5862 
5863 		if (dst->scrub || src->scrub) {
5864 			if (pf_normalize_tcp_stateful(pd, reason, th,
5865 			    *state, src, dst, copyback))
5866 				return (PF_DROP);
5867 		}
5868 
5869 		/* update max window */
5870 		if (src->max_win < win)
5871 			src->max_win = win;
5872 		/* synchronize sequencing */
5873 		if (SEQ_GT(end, src->seqlo))
5874 			src->seqlo = end;
5875 		/* slide the window of what the other end can send */
5876 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
5877 			dst->seqhi = ack + MAX((win << sws), 1);
5878 
5879 		/*
5880 		 * Cannot set dst->seqhi here since this could be a shotgunned
5881 		 * SYN and not an already established connection.
5882 		 */
5883 
5884 		if (th->th_flags & TH_FIN)
5885 			if (src->state < TCPS_CLOSING)
5886 				pf_set_protostate(*state, psrc, TCPS_CLOSING);
5887 		if (th->th_flags & TH_RST)
5888 			pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
5889 
5890 		/* Fall through to PASS packet */
5891 
5892 	} else {
5893 		if ((*state)->dst.state == TCPS_SYN_SENT &&
5894 		    (*state)->src.state == TCPS_SYN_SENT) {
5895 			/* Send RST for state mismatches during handshake */
5896 			if (!(th->th_flags & TH_RST))
5897 				pf_send_tcp((*state)->rule, pd->af,
5898 				    pd->dst, pd->src, th->th_dport,
5899 				    th->th_sport, ntohl(th->th_ack), 0,
5900 				    TH_RST, 0, 0,
5901 				    (*state)->rule->return_ttl, true, 0, 0,
5902 				    (*state)->act.rtableid);
5903 			src->seqlo = 0;
5904 			src->seqhi = 1;
5905 			src->max_win = 1;
5906 		} else if (V_pf_status.debug >= PF_DEBUG_MISC) {
5907 			printf("pf: BAD state: ");
5908 			pf_print_state(*state);
5909 			pf_print_flags(th->th_flags);
5910 			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
5911 			    "pkts=%llu:%llu dir=%s,%s\n",
5912 			    seq, orig_seq, ack, pd->p_len, ackskew,
5913 			    (unsigned long long)(*state)->packets[0],
5914 			    (unsigned long long)(*state)->packets[1],
5915 			    pd->dir == PF_IN ? "in" : "out",
5916 			    pd->dir == (*state)->direction ? "fwd" : "rev");
5917 			printf("pf: State failure on: %c %c %c %c | %c %c\n",
5918 			    SEQ_GEQ(src->seqhi, data_end) ? ' ' : '1',
5919 			    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
5920 			    ' ': '2',
5921 			    (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
5922 			    (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
5923 			    SEQ_GEQ(src->seqhi + MAXACKWINDOW, data_end) ?' ' :'5',
5924 			    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
5925 		}
5926 		REASON_SET(reason, PFRES_BADSTATE);
5927 		return (PF_DROP);
5928 	}
5929 
5930 	return (PF_PASS);
5931 }
5932 
5933 static int
5934 pf_tcp_track_sloppy(struct pf_kstate **state, struct pf_pdesc *pd, u_short *reason)
5935 {
5936 	struct tcphdr		*th = &pd->hdr.tcp;
5937 	struct pf_state_peer	*src, *dst;
5938 	u_int8_t		 psrc, pdst;
5939 
5940 	if (pd->dir == (*state)->direction) {
5941 		src = &(*state)->src;
5942 		dst = &(*state)->dst;
5943 		psrc = PF_PEER_SRC;
5944 		pdst = PF_PEER_DST;
5945 	} else {
5946 		src = &(*state)->dst;
5947 		dst = &(*state)->src;
5948 		psrc = PF_PEER_DST;
5949 		pdst = PF_PEER_SRC;
5950 	}
5951 
5952 	if (th->th_flags & TH_SYN)
5953 		if (src->state < TCPS_SYN_SENT)
5954 			pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
5955 	if (th->th_flags & TH_FIN)
5956 		if (src->state < TCPS_CLOSING)
5957 			pf_set_protostate(*state, psrc, TCPS_CLOSING);
5958 	if (th->th_flags & TH_ACK) {
5959 		if (dst->state == TCPS_SYN_SENT) {
5960 			pf_set_protostate(*state, pdst, TCPS_ESTABLISHED);
5961 			if (src->state == TCPS_ESTABLISHED &&
5962 			    (*state)->src_node != NULL &&
5963 			    pf_src_connlimit(state)) {
5964 				REASON_SET(reason, PFRES_SRCLIMIT);
5965 				return (PF_DROP);
5966 			}
5967 		} else if (dst->state == TCPS_CLOSING) {
5968 			pf_set_protostate(*state, pdst, TCPS_FIN_WAIT_2);
5969 		} else if (src->state == TCPS_SYN_SENT &&
5970 		    dst->state < TCPS_SYN_SENT) {
5971 			/*
5972 			 * Handle a special sloppy case where we only see one
5973 			 * half of the connection. If there is a ACK after
5974 			 * the initial SYN without ever seeing a packet from
5975 			 * the destination, set the connection to established.
5976 			 */
5977 			pf_set_protostate(*state, PF_PEER_BOTH,
5978 			    TCPS_ESTABLISHED);
5979 			dst->state = src->state = TCPS_ESTABLISHED;
5980 			if ((*state)->src_node != NULL &&
5981 			    pf_src_connlimit(state)) {
5982 				REASON_SET(reason, PFRES_SRCLIMIT);
5983 				return (PF_DROP);
5984 			}
5985 		} else if (src->state == TCPS_CLOSING &&
5986 		    dst->state == TCPS_ESTABLISHED &&
5987 		    dst->seqlo == 0) {
5988 			/*
5989 			 * Handle the closing of half connections where we
5990 			 * don't see the full bidirectional FIN/ACK+ACK
5991 			 * handshake.
5992 			 */
5993 			pf_set_protostate(*state, pdst, TCPS_CLOSING);
5994 		}
5995 	}
5996 	if (th->th_flags & TH_RST)
5997 		pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
5998 
5999 	/* update expire time */
6000 	(*state)->expire = pf_get_uptime();
6001 	if (src->state >= TCPS_FIN_WAIT_2 &&
6002 	    dst->state >= TCPS_FIN_WAIT_2)
6003 		(*state)->timeout = PFTM_TCP_CLOSED;
6004 	else if (src->state >= TCPS_CLOSING &&
6005 	    dst->state >= TCPS_CLOSING)
6006 		(*state)->timeout = PFTM_TCP_FIN_WAIT;
6007 	else if (src->state < TCPS_ESTABLISHED ||
6008 	    dst->state < TCPS_ESTABLISHED)
6009 		(*state)->timeout = PFTM_TCP_OPENING;
6010 	else if (src->state >= TCPS_CLOSING ||
6011 	    dst->state >= TCPS_CLOSING)
6012 		(*state)->timeout = PFTM_TCP_CLOSING;
6013 	else
6014 		(*state)->timeout = PFTM_TCP_ESTABLISHED;
6015 
6016 	return (PF_PASS);
6017 }
6018 
6019 static int
6020 pf_synproxy(struct pf_pdesc *pd, struct pf_kstate **state, u_short *reason)
6021 {
6022 	struct pf_state_key	*sk = (*state)->key[pd->didx];
6023 	struct tcphdr		*th = &pd->hdr.tcp;
6024 
6025 	if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
6026 		if (pd->dir != (*state)->direction) {
6027 			REASON_SET(reason, PFRES_SYNPROXY);
6028 			return (PF_SYNPROXY_DROP);
6029 		}
6030 		if (th->th_flags & TH_SYN) {
6031 			if (ntohl(th->th_seq) != (*state)->src.seqlo) {
6032 				REASON_SET(reason, PFRES_SYNPROXY);
6033 				return (PF_DROP);
6034 			}
6035 			pf_send_tcp((*state)->rule, pd->af, pd->dst,
6036 			    pd->src, th->th_dport, th->th_sport,
6037 			    (*state)->src.seqhi, ntohl(th->th_seq) + 1,
6038 			    TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, true, 0, 0,
6039 			    (*state)->act.rtableid);
6040 			REASON_SET(reason, PFRES_SYNPROXY);
6041 			return (PF_SYNPROXY_DROP);
6042 		} else if ((th->th_flags & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
6043 		    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
6044 		    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
6045 			REASON_SET(reason, PFRES_SYNPROXY);
6046 			return (PF_DROP);
6047 		} else if ((*state)->src_node != NULL &&
6048 		    pf_src_connlimit(state)) {
6049 			REASON_SET(reason, PFRES_SRCLIMIT);
6050 			return (PF_DROP);
6051 		} else
6052 			pf_set_protostate(*state, PF_PEER_SRC,
6053 			    PF_TCPS_PROXY_DST);
6054 	}
6055 	if ((*state)->src.state == PF_TCPS_PROXY_DST) {
6056 		if (pd->dir == (*state)->direction) {
6057 			if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
6058 			    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
6059 			    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
6060 				REASON_SET(reason, PFRES_SYNPROXY);
6061 				return (PF_DROP);
6062 			}
6063 			(*state)->src.max_win = MAX(ntohs(th->th_win), 1);
6064 			if ((*state)->dst.seqhi == 1)
6065 				(*state)->dst.seqhi = htonl(arc4random());
6066 			pf_send_tcp((*state)->rule, pd->af,
6067 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
6068 			    sk->port[pd->sidx], sk->port[pd->didx],
6069 			    (*state)->dst.seqhi, 0, TH_SYN, 0,
6070 			    (*state)->src.mss, 0, false, (*state)->tag, 0,
6071 			    (*state)->act.rtableid);
6072 			REASON_SET(reason, PFRES_SYNPROXY);
6073 			return (PF_SYNPROXY_DROP);
6074 		} else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
6075 		    (TH_SYN|TH_ACK)) ||
6076 		    (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
6077 			REASON_SET(reason, PFRES_SYNPROXY);
6078 			return (PF_DROP);
6079 		} else {
6080 			(*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
6081 			(*state)->dst.seqlo = ntohl(th->th_seq);
6082 			pf_send_tcp((*state)->rule, pd->af, pd->dst,
6083 			    pd->src, th->th_dport, th->th_sport,
6084 			    ntohl(th->th_ack), ntohl(th->th_seq) + 1,
6085 			    TH_ACK, (*state)->src.max_win, 0, 0, false,
6086 			    (*state)->tag, 0, (*state)->act.rtableid);
6087 			pf_send_tcp((*state)->rule, pd->af,
6088 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
6089 			    sk->port[pd->sidx], sk->port[pd->didx],
6090 			    (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
6091 			    TH_ACK, (*state)->dst.max_win, 0, 0, true, 0, 0,
6092 			    (*state)->act.rtableid);
6093 			(*state)->src.seqdiff = (*state)->dst.seqhi -
6094 			    (*state)->src.seqlo;
6095 			(*state)->dst.seqdiff = (*state)->src.seqhi -
6096 			    (*state)->dst.seqlo;
6097 			(*state)->src.seqhi = (*state)->src.seqlo +
6098 			    (*state)->dst.max_win;
6099 			(*state)->dst.seqhi = (*state)->dst.seqlo +
6100 			    (*state)->src.max_win;
6101 			(*state)->src.wscale = (*state)->dst.wscale = 0;
6102 			pf_set_protostate(*state, PF_PEER_BOTH,
6103 			    TCPS_ESTABLISHED);
6104 			REASON_SET(reason, PFRES_SYNPROXY);
6105 			return (PF_SYNPROXY_DROP);
6106 		}
6107 	}
6108 
6109 	return (PF_PASS);
6110 }
6111 
6112 static int
6113 pf_test_state_tcp(struct pf_kstate **state, struct pf_pdesc *pd,
6114     u_short *reason)
6115 {
6116 	struct pf_state_key_cmp	 key;
6117 	struct tcphdr		*th = &pd->hdr.tcp;
6118 	int			 copyback = 0;
6119 	int			 action;
6120 	struct pf_state_peer	*src, *dst;
6121 
6122 	bzero(&key, sizeof(key));
6123 	key.af = pd->af;
6124 	key.proto = IPPROTO_TCP;
6125 	if (pd->dir == PF_IN)	{	/* wire side, straight */
6126 		PF_ACPY(&key.addr[0], pd->src, key.af);
6127 		PF_ACPY(&key.addr[1], pd->dst, key.af);
6128 		key.port[0] = th->th_sport;
6129 		key.port[1] = th->th_dport;
6130 	} else {			/* stack side, reverse */
6131 		PF_ACPY(&key.addr[1], pd->src, key.af);
6132 		PF_ACPY(&key.addr[0], pd->dst, key.af);
6133 		key.port[1] = th->th_sport;
6134 		key.port[0] = th->th_dport;
6135 	}
6136 
6137 	STATE_LOOKUP(&key, *state, pd);
6138 
6139 	if (pd->dir == (*state)->direction) {
6140 		src = &(*state)->src;
6141 		dst = &(*state)->dst;
6142 	} else {
6143 		src = &(*state)->dst;
6144 		dst = &(*state)->src;
6145 	}
6146 
6147 	if ((action = pf_synproxy(pd, state, reason)) != PF_PASS)
6148 		return (action);
6149 
6150 	if (dst->state >= TCPS_FIN_WAIT_2 &&
6151 	    src->state >= TCPS_FIN_WAIT_2 &&
6152 	    (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) ||
6153 	    ((th->th_flags & (TH_SYN|TH_ACK|TH_RST)) == TH_ACK &&
6154 	    pf_syncookie_check(pd) && pd->dir == PF_IN))) {
6155 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
6156 			printf("pf: state reuse ");
6157 			pf_print_state(*state);
6158 			pf_print_flags(th->th_flags);
6159 			printf("\n");
6160 		}
6161 		/* XXX make sure it's the same direction ?? */
6162 		pf_set_protostate(*state, PF_PEER_BOTH, TCPS_CLOSED);
6163 		pf_unlink_state(*state);
6164 		*state = NULL;
6165 		return (PF_DROP);
6166 	}
6167 
6168 	if ((*state)->state_flags & PFSTATE_SLOPPY) {
6169 		if (pf_tcp_track_sloppy(state, pd, reason) == PF_DROP)
6170 			return (PF_DROP);
6171 	} else {
6172 		if (pf_tcp_track_full(state, pd, reason,
6173 		    &copyback) == PF_DROP)
6174 			return (PF_DROP);
6175 	}
6176 
6177 	/* translate source/destination address, if necessary */
6178 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
6179 		struct pf_state_key *nk = (*state)->key[pd->didx];
6180 
6181 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
6182 		    nk->port[pd->sidx] != th->th_sport)
6183 			pf_change_ap(pd->m, pd->src, &th->th_sport,
6184 			    pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
6185 			    nk->port[pd->sidx], 0, pd->af);
6186 
6187 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
6188 		    nk->port[pd->didx] != th->th_dport)
6189 			pf_change_ap(pd->m, pd->dst, &th->th_dport,
6190 			    pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
6191 			    nk->port[pd->didx], 0, pd->af);
6192 		copyback = 1;
6193 	}
6194 
6195 	/* Copyback sequence modulation or stateful scrub changes if needed */
6196 	if (copyback)
6197 		m_copyback(pd->m, pd->off, sizeof(*th), (caddr_t)th);
6198 
6199 	return (PF_PASS);
6200 }
6201 
6202 static int
6203 pf_test_state_udp(struct pf_kstate **state, struct pf_pdesc *pd)
6204 {
6205 	struct pf_state_peer	*src, *dst;
6206 	struct pf_state_key_cmp	 key;
6207 	struct udphdr		*uh = &pd->hdr.udp;
6208 	uint8_t			 psrc, pdst;
6209 
6210 	bzero(&key, sizeof(key));
6211 	key.af = pd->af;
6212 	key.proto = IPPROTO_UDP;
6213 	if (pd->dir == PF_IN)	{	/* wire side, straight */
6214 		PF_ACPY(&key.addr[0], pd->src, key.af);
6215 		PF_ACPY(&key.addr[1], pd->dst, key.af);
6216 		key.port[0] = uh->uh_sport;
6217 		key.port[1] = uh->uh_dport;
6218 	} else {			/* stack side, reverse */
6219 		PF_ACPY(&key.addr[1], pd->src, key.af);
6220 		PF_ACPY(&key.addr[0], pd->dst, key.af);
6221 		key.port[1] = uh->uh_sport;
6222 		key.port[0] = uh->uh_dport;
6223 	}
6224 
6225 	STATE_LOOKUP(&key, *state, pd);
6226 
6227 	if (pd->dir == (*state)->direction) {
6228 		src = &(*state)->src;
6229 		dst = &(*state)->dst;
6230 		psrc = PF_PEER_SRC;
6231 		pdst = PF_PEER_DST;
6232 	} else {
6233 		src = &(*state)->dst;
6234 		dst = &(*state)->src;
6235 		psrc = PF_PEER_DST;
6236 		pdst = PF_PEER_SRC;
6237 	}
6238 
6239 	/* update states */
6240 	if (src->state < PFUDPS_SINGLE)
6241 		pf_set_protostate(*state, psrc, PFUDPS_SINGLE);
6242 	if (dst->state == PFUDPS_SINGLE)
6243 		pf_set_protostate(*state, pdst, PFUDPS_MULTIPLE);
6244 
6245 	/* update expire time */
6246 	(*state)->expire = pf_get_uptime();
6247 	if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
6248 		(*state)->timeout = PFTM_UDP_MULTIPLE;
6249 	else
6250 		(*state)->timeout = PFTM_UDP_SINGLE;
6251 
6252 	/* translate source/destination address, if necessary */
6253 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
6254 		struct pf_state_key *nk = (*state)->key[pd->didx];
6255 
6256 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
6257 		    nk->port[pd->sidx] != uh->uh_sport)
6258 			pf_change_ap(pd->m, pd->src, &uh->uh_sport, pd->ip_sum,
6259 			    &uh->uh_sum, &nk->addr[pd->sidx],
6260 			    nk->port[pd->sidx], 1, pd->af);
6261 
6262 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
6263 		    nk->port[pd->didx] != uh->uh_dport)
6264 			pf_change_ap(pd->m, pd->dst, &uh->uh_dport, pd->ip_sum,
6265 			    &uh->uh_sum, &nk->addr[pd->didx],
6266 			    nk->port[pd->didx], 1, pd->af);
6267 		m_copyback(pd->m, pd->off, sizeof(*uh), (caddr_t)uh);
6268 	}
6269 
6270 	return (PF_PASS);
6271 }
6272 
6273 static int
6274 pf_test_state_sctp(struct pf_kstate **state, struct pf_pdesc *pd,
6275     u_short *reason)
6276 {
6277 	struct pf_state_key_cmp	 key;
6278 	struct pf_state_peer	*src, *dst;
6279 	struct sctphdr		*sh = &pd->hdr.sctp;
6280 	u_int8_t		 psrc; //, pdst;
6281 
6282 	bzero(&key, sizeof(key));
6283 	key.af = pd->af;
6284 	key.proto = IPPROTO_SCTP;
6285 	if (pd->dir == PF_IN)	{	/* wire side, straight */
6286 		PF_ACPY(&key.addr[0], pd->src, key.af);
6287 		PF_ACPY(&key.addr[1], pd->dst, key.af);
6288 		key.port[0] = sh->src_port;
6289 		key.port[1] = sh->dest_port;
6290 	} else {			/* stack side, reverse */
6291 		PF_ACPY(&key.addr[1], pd->src, key.af);
6292 		PF_ACPY(&key.addr[0], pd->dst, key.af);
6293 		key.port[1] = sh->src_port;
6294 		key.port[0] = sh->dest_port;
6295 	}
6296 
6297 	STATE_LOOKUP(&key, *state, pd);
6298 
6299 	if (pd->dir == (*state)->direction) {
6300 		src = &(*state)->src;
6301 		dst = &(*state)->dst;
6302 		psrc = PF_PEER_SRC;
6303 	} else {
6304 		src = &(*state)->dst;
6305 		dst = &(*state)->src;
6306 		psrc = PF_PEER_DST;
6307 	}
6308 
6309 	if ((src->state >= SCTP_SHUTDOWN_SENT || src->state == SCTP_CLOSED) &&
6310 	    (dst->state >= SCTP_SHUTDOWN_SENT || dst->state == SCTP_CLOSED) &&
6311 	    pd->sctp_flags & PFDESC_SCTP_INIT) {
6312 		pf_set_protostate(*state, PF_PEER_BOTH, SCTP_CLOSED);
6313 		pf_unlink_state(*state);
6314 		*state = NULL;
6315 		return (PF_DROP);
6316 	}
6317 
6318 	/* Track state. */
6319 	if (pd->sctp_flags & PFDESC_SCTP_INIT) {
6320 		if (src->state < SCTP_COOKIE_WAIT) {
6321 			pf_set_protostate(*state, psrc, SCTP_COOKIE_WAIT);
6322 			(*state)->timeout = PFTM_SCTP_OPENING;
6323 		}
6324 	}
6325 	if (pd->sctp_flags & PFDESC_SCTP_INIT_ACK) {
6326 		MPASS(dst->scrub != NULL);
6327 		if (dst->scrub->pfss_v_tag == 0)
6328 			dst->scrub->pfss_v_tag = pd->sctp_initiate_tag;
6329 	}
6330 
6331 	if (pd->sctp_flags & (PFDESC_SCTP_COOKIE | PFDESC_SCTP_HEARTBEAT_ACK)) {
6332 		if (src->state < SCTP_ESTABLISHED) {
6333 			pf_set_protostate(*state, psrc, SCTP_ESTABLISHED);
6334 			(*state)->timeout = PFTM_SCTP_ESTABLISHED;
6335 		}
6336 	}
6337 	if (pd->sctp_flags & (PFDESC_SCTP_SHUTDOWN | PFDESC_SCTP_ABORT |
6338 	    PFDESC_SCTP_SHUTDOWN_COMPLETE)) {
6339 		if (src->state < SCTP_SHUTDOWN_PENDING) {
6340 			pf_set_protostate(*state, psrc, SCTP_SHUTDOWN_PENDING);
6341 			(*state)->timeout = PFTM_SCTP_CLOSING;
6342 		}
6343 	}
6344 	if (pd->sctp_flags & (PFDESC_SCTP_SHUTDOWN_COMPLETE)) {
6345 		pf_set_protostate(*state, psrc, SCTP_CLOSED);
6346 		(*state)->timeout = PFTM_SCTP_CLOSED;
6347 	}
6348 
6349 	if (src->scrub != NULL) {
6350 		if (src->scrub->pfss_v_tag == 0) {
6351 			src->scrub->pfss_v_tag = pd->hdr.sctp.v_tag;
6352 		} else  if (src->scrub->pfss_v_tag != pd->hdr.sctp.v_tag)
6353 			return (PF_DROP);
6354 	}
6355 
6356 	(*state)->expire = pf_get_uptime();
6357 
6358 	/* translate source/destination address, if necessary */
6359 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
6360 		uint16_t checksum = 0;
6361 		struct pf_state_key *nk = (*state)->key[pd->didx];
6362 
6363 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
6364 		    nk->port[pd->sidx] != pd->hdr.sctp.src_port) {
6365 			pf_change_ap(pd->m, pd->src, &pd->hdr.sctp.src_port,
6366 			    pd->ip_sum, &checksum, &nk->addr[pd->sidx],
6367 			    nk->port[pd->sidx], 1, pd->af);
6368 		}
6369 
6370 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
6371 		    nk->port[pd->didx] != pd->hdr.sctp.dest_port) {
6372 			pf_change_ap(pd->m, pd->dst, &pd->hdr.sctp.dest_port,
6373 			    pd->ip_sum, &checksum, &nk->addr[pd->didx],
6374 			    nk->port[pd->didx], 1, pd->af);
6375 		}
6376 	}
6377 
6378 	return (PF_PASS);
6379 }
6380 
6381 static void
6382 pf_sctp_multihome_detach_addr(const struct pf_kstate *s)
6383 {
6384 	struct pf_sctp_endpoint key;
6385 	struct pf_sctp_endpoint *ep;
6386 	struct pf_state_key *sks = s->key[PF_SK_STACK];
6387 	struct pf_sctp_source *i, *tmp;
6388 
6389 	if (sks == NULL || sks->proto != IPPROTO_SCTP || s->dst.scrub == NULL)
6390 		return;
6391 
6392 	PF_SCTP_ENDPOINTS_LOCK();
6393 
6394 	key.v_tag = s->dst.scrub->pfss_v_tag;
6395 	ep  = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
6396 	if (ep != NULL) {
6397 		TAILQ_FOREACH_SAFE(i, &ep->sources, entry, tmp) {
6398 			if (pf_addr_cmp(&i->addr,
6399 			    &s->key[PF_SK_WIRE]->addr[s->direction == PF_OUT],
6400 			    s->key[PF_SK_WIRE]->af) == 0) {
6401 				SDT_PROBE3(pf, sctp, multihome, remove,
6402 				    key.v_tag, s, i);
6403 				TAILQ_REMOVE(&ep->sources, i, entry);
6404 				free(i, M_PFTEMP);
6405 				break;
6406 			}
6407 		}
6408 
6409 		if (TAILQ_EMPTY(&ep->sources)) {
6410 			RB_REMOVE(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
6411 			free(ep, M_PFTEMP);
6412 		}
6413 	}
6414 
6415 	/* Other direction. */
6416 	key.v_tag = s->src.scrub->pfss_v_tag;
6417 	ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
6418 	if (ep != NULL) {
6419 		TAILQ_FOREACH_SAFE(i, &ep->sources, entry, tmp) {
6420 			if (pf_addr_cmp(&i->addr,
6421 			    &s->key[PF_SK_WIRE]->addr[s->direction == PF_IN],
6422 			    s->key[PF_SK_WIRE]->af) == 0) {
6423 				SDT_PROBE3(pf, sctp, multihome, remove,
6424 				    key.v_tag, s, i);
6425 				TAILQ_REMOVE(&ep->sources, i, entry);
6426 				free(i, M_PFTEMP);
6427 				break;
6428 			}
6429 		}
6430 
6431 		if (TAILQ_EMPTY(&ep->sources)) {
6432 			RB_REMOVE(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
6433 			free(ep, M_PFTEMP);
6434 		}
6435 	}
6436 
6437 	PF_SCTP_ENDPOINTS_UNLOCK();
6438 }
6439 
6440 static void
6441 pf_sctp_multihome_add_addr(struct pf_pdesc *pd, struct pf_addr *a, uint32_t v_tag)
6442 {
6443 	struct pf_sctp_endpoint key = {
6444 		.v_tag = v_tag,
6445 	};
6446 	struct pf_sctp_source *i;
6447 	struct pf_sctp_endpoint *ep;
6448 
6449 	PF_SCTP_ENDPOINTS_LOCK();
6450 
6451 	ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
6452 	if (ep == NULL) {
6453 		ep = malloc(sizeof(struct pf_sctp_endpoint),
6454 		    M_PFTEMP, M_NOWAIT);
6455 		if (ep == NULL) {
6456 			PF_SCTP_ENDPOINTS_UNLOCK();
6457 			return;
6458 		}
6459 
6460 		ep->v_tag = v_tag;
6461 		TAILQ_INIT(&ep->sources);
6462 		RB_INSERT(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
6463 	}
6464 
6465 	/* Avoid inserting duplicates. */
6466 	TAILQ_FOREACH(i, &ep->sources, entry) {
6467 		if (pf_addr_cmp(&i->addr, a, pd->af) == 0) {
6468 			PF_SCTP_ENDPOINTS_UNLOCK();
6469 			return;
6470 		}
6471 	}
6472 
6473 	i = malloc(sizeof(*i), M_PFTEMP, M_NOWAIT);
6474 	if (i == NULL) {
6475 		PF_SCTP_ENDPOINTS_UNLOCK();
6476 		return;
6477 	}
6478 
6479 	i->af = pd->af;
6480 	memcpy(&i->addr, a, sizeof(*a));
6481 	TAILQ_INSERT_TAIL(&ep->sources, i, entry);
6482 	SDT_PROBE2(pf, sctp, multihome, add, v_tag, i);
6483 
6484 	PF_SCTP_ENDPOINTS_UNLOCK();
6485 }
6486 
6487 static void
6488 pf_sctp_multihome_delayed(struct pf_pdesc *pd, struct pfi_kkif *kif,
6489     struct pf_kstate *s, int action)
6490 {
6491 	struct pf_sctp_multihome_job	*j, *tmp;
6492 	struct pf_sctp_source		*i;
6493 	int			 ret __unused;
6494 	struct pf_kstate	*sm = NULL;
6495 	struct pf_krule		*ra = NULL;
6496 	struct pf_krule		*r = &V_pf_default_rule;
6497 	struct pf_kruleset	*rs = NULL;
6498 	bool do_extra = true;
6499 
6500 	PF_RULES_RLOCK_TRACKER;
6501 
6502 again:
6503 	TAILQ_FOREACH_SAFE(j, &pd->sctp_multihome_jobs, next, tmp) {
6504 		if (s == NULL || action != PF_PASS)
6505 			goto free;
6506 
6507 		/* Confirm we don't recurse here. */
6508 		MPASS(! (pd->sctp_flags & PFDESC_SCTP_ADD_IP));
6509 
6510 		switch (j->op) {
6511 		case  SCTP_ADD_IP_ADDRESS: {
6512 			uint32_t v_tag = pd->sctp_initiate_tag;
6513 
6514 			if (v_tag == 0) {
6515 				if (s->direction == pd->dir)
6516 					v_tag = s->src.scrub->pfss_v_tag;
6517 				else
6518 					v_tag = s->dst.scrub->pfss_v_tag;
6519 			}
6520 
6521 			/*
6522 			 * Avoid duplicating states. We'll already have
6523 			 * created a state based on the source address of
6524 			 * the packet, but SCTP endpoints may also list this
6525 			 * address again in the INIT(_ACK) parameters.
6526 			 */
6527 			if (pf_addr_cmp(&j->src, pd->src, pd->af) == 0) {
6528 				break;
6529 			}
6530 
6531 			j->pd.sctp_flags |= PFDESC_SCTP_ADD_IP;
6532 			PF_RULES_RLOCK();
6533 			sm = NULL;
6534 			/*
6535 			 * New connections need to be floating, because
6536 			 * we cannot know what interfaces it will use.
6537 			 * That's why we pass V_pfi_all rather than kif.
6538 			 */
6539 			j->pd.kif = V_pfi_all;
6540 			ret = pf_test_rule(&r, &sm,
6541 			    &j->pd, &ra, &rs, NULL);
6542 			PF_RULES_RUNLOCK();
6543 			SDT_PROBE4(pf, sctp, multihome, test, kif, r, j->pd.m, ret);
6544 			if (ret != PF_DROP && sm != NULL) {
6545 				/* Inherit v_tag values. */
6546 				if (sm->direction == s->direction) {
6547 					sm->src.scrub->pfss_v_tag = s->src.scrub->pfss_v_tag;
6548 					sm->dst.scrub->pfss_v_tag = s->dst.scrub->pfss_v_tag;
6549 				} else {
6550 					sm->src.scrub->pfss_v_tag = s->dst.scrub->pfss_v_tag;
6551 					sm->dst.scrub->pfss_v_tag = s->src.scrub->pfss_v_tag;
6552 				}
6553 				PF_STATE_UNLOCK(sm);
6554 			} else {
6555 				/* If we try duplicate inserts? */
6556 				break;
6557 			}
6558 
6559 			/* Only add the address if we've actually allowed the state. */
6560 			pf_sctp_multihome_add_addr(pd, &j->src, v_tag);
6561 
6562 			if (! do_extra) {
6563 				break;
6564 			}
6565 			/*
6566 			 * We need to do this for each of our source addresses.
6567 			 * Find those based on the verification tag.
6568 			 */
6569 			struct pf_sctp_endpoint key = {
6570 				.v_tag = pd->hdr.sctp.v_tag,
6571 			};
6572 			struct pf_sctp_endpoint *ep;
6573 
6574 			PF_SCTP_ENDPOINTS_LOCK();
6575 			ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
6576 			if (ep == NULL) {
6577 				PF_SCTP_ENDPOINTS_UNLOCK();
6578 				break;
6579 			}
6580 			MPASS(ep != NULL);
6581 
6582 			TAILQ_FOREACH(i, &ep->sources, entry) {
6583 				struct pf_sctp_multihome_job *nj;
6584 
6585 				/* SCTP can intermingle IPv4 and IPv6. */
6586 				if (i->af != pd->af)
6587 					continue;
6588 
6589 				nj = malloc(sizeof(*nj), M_PFTEMP, M_NOWAIT | M_ZERO);
6590 				if (! nj) {
6591 					continue;
6592 				}
6593 				memcpy(&nj->pd, &j->pd, sizeof(j->pd));
6594 				memcpy(&nj->src, &j->src, sizeof(nj->src));
6595 				nj->pd.src = &nj->src;
6596 				// New destination address!
6597 				memcpy(&nj->dst, &i->addr, sizeof(nj->dst));
6598 				nj->pd.dst = &nj->dst;
6599 				nj->pd.m = j->pd.m;
6600 				nj->op = j->op;
6601 
6602 				TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, nj, next);
6603 			}
6604 			PF_SCTP_ENDPOINTS_UNLOCK();
6605 
6606 			break;
6607 		}
6608 		case SCTP_DEL_IP_ADDRESS: {
6609 			struct pf_state_key_cmp key;
6610 			uint8_t psrc;
6611 
6612 			bzero(&key, sizeof(key));
6613 			key.af = j->pd.af;
6614 			key.proto = IPPROTO_SCTP;
6615 			if (j->pd.dir == PF_IN)	{	/* wire side, straight */
6616 				PF_ACPY(&key.addr[0], j->pd.src, key.af);
6617 				PF_ACPY(&key.addr[1], j->pd.dst, key.af);
6618 				key.port[0] = j->pd.hdr.sctp.src_port;
6619 				key.port[1] = j->pd.hdr.sctp.dest_port;
6620 			} else {			/* stack side, reverse */
6621 				PF_ACPY(&key.addr[1], j->pd.src, key.af);
6622 				PF_ACPY(&key.addr[0], j->pd.dst, key.af);
6623 				key.port[1] = j->pd.hdr.sctp.src_port;
6624 				key.port[0] = j->pd.hdr.sctp.dest_port;
6625 			}
6626 
6627 			sm = pf_find_state(kif, &key, j->pd.dir);
6628 			if (sm != NULL) {
6629 				PF_STATE_LOCK_ASSERT(sm);
6630 				if (j->pd.dir == sm->direction) {
6631 					psrc = PF_PEER_SRC;
6632 				} else {
6633 					psrc = PF_PEER_DST;
6634 				}
6635 				pf_set_protostate(sm, psrc, SCTP_SHUTDOWN_PENDING);
6636 				sm->timeout = PFTM_SCTP_CLOSING;
6637 				PF_STATE_UNLOCK(sm);
6638 			}
6639 			break;
6640 		default:
6641 			panic("Unknown op %#x", j->op);
6642 		}
6643 	}
6644 
6645 	free:
6646 		TAILQ_REMOVE(&pd->sctp_multihome_jobs, j, next);
6647 		free(j, M_PFTEMP);
6648 	}
6649 
6650 	/* We may have inserted extra work while processing the list. */
6651 	if (! TAILQ_EMPTY(&pd->sctp_multihome_jobs)) {
6652 		do_extra = false;
6653 		goto again;
6654 	}
6655 }
6656 
6657 static int
6658 pf_multihome_scan(int start, int len, struct pf_pdesc *pd, int op)
6659 {
6660 	int			 off = 0;
6661 	struct pf_sctp_multihome_job	*job;
6662 
6663 	while (off < len) {
6664 		struct sctp_paramhdr h;
6665 
6666 		if (!pf_pull_hdr(pd->m, start + off, &h, sizeof(h), NULL, NULL,
6667 		    pd->af))
6668 			return (PF_DROP);
6669 
6670 		/* Parameters are at least 4 bytes. */
6671 		if (ntohs(h.param_length) < 4)
6672 			return (PF_DROP);
6673 
6674 		switch (ntohs(h.param_type)) {
6675 		case  SCTP_IPV4_ADDRESS: {
6676 			struct in_addr t;
6677 
6678 			if (ntohs(h.param_length) !=
6679 			    (sizeof(struct sctp_paramhdr) + sizeof(t)))
6680 				return (PF_DROP);
6681 
6682 			if (!pf_pull_hdr(pd->m, start + off + sizeof(h), &t, sizeof(t),
6683 			    NULL, NULL, pd->af))
6684 				return (PF_DROP);
6685 
6686 			if (in_nullhost(t))
6687 				t.s_addr = pd->src->v4.s_addr;
6688 
6689 			/*
6690 			 * We hold the state lock (idhash) here, which means
6691 			 * that we can't acquire the keyhash, or we'll get a
6692 			 * LOR (and potentially double-lock things too). We also
6693 			 * can't release the state lock here, so instead we'll
6694 			 * enqueue this for async handling.
6695 			 * There's a relatively small race here, in that a
6696 			 * packet using the new addresses could arrive already,
6697 			 * but that's just though luck for it.
6698 			 */
6699 			job = malloc(sizeof(*job), M_PFTEMP, M_NOWAIT | M_ZERO);
6700 			if (! job)
6701 				return (PF_DROP);
6702 
6703 			memcpy(&job->pd, pd, sizeof(*pd));
6704 
6705 			// New source address!
6706 			memcpy(&job->src, &t, sizeof(t));
6707 			job->pd.src = &job->src;
6708 			memcpy(&job->dst, pd->dst, sizeof(job->dst));
6709 			job->pd.dst = &job->dst;
6710 			job->pd.m = pd->m;
6711 			job->op = op;
6712 
6713 			TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, job, next);
6714 			break;
6715 		}
6716 #ifdef INET6
6717 		case SCTP_IPV6_ADDRESS: {
6718 			struct in6_addr t;
6719 
6720 			if (ntohs(h.param_length) !=
6721 			    (sizeof(struct sctp_paramhdr) + sizeof(t)))
6722 				return (PF_DROP);
6723 
6724 			if (!pf_pull_hdr(pd->m, start + off + sizeof(h), &t, sizeof(t),
6725 			    NULL, NULL, pd->af))
6726 				return (PF_DROP);
6727 			if (memcmp(&t, &pd->src->v6, sizeof(t)) == 0)
6728 				break;
6729 			if (memcmp(&t, &in6addr_any, sizeof(t)) == 0)
6730 				memcpy(&t, &pd->src->v6, sizeof(t));
6731 
6732 			job = malloc(sizeof(*job), M_PFTEMP, M_NOWAIT | M_ZERO);
6733 			if (! job)
6734 				return (PF_DROP);
6735 
6736 			memcpy(&job->pd, pd, sizeof(*pd));
6737 			memcpy(&job->src, &t, sizeof(t));
6738 			job->pd.src = &job->src;
6739 			memcpy(&job->dst, pd->dst, sizeof(job->dst));
6740 			job->pd.dst = &job->dst;
6741 			job->pd.m = pd->m;
6742 			job->op = op;
6743 
6744 			TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, job, next);
6745 			break;
6746 		}
6747 #endif
6748 		case SCTP_ADD_IP_ADDRESS: {
6749 			int ret;
6750 			struct sctp_asconf_paramhdr ah;
6751 
6752 			if (!pf_pull_hdr(pd->m, start + off, &ah, sizeof(ah),
6753 			    NULL, NULL, pd->af))
6754 				return (PF_DROP);
6755 
6756 			ret = pf_multihome_scan(start + off + sizeof(ah),
6757 			    ntohs(ah.ph.param_length) - sizeof(ah), pd,
6758 			    SCTP_ADD_IP_ADDRESS);
6759 			if (ret != PF_PASS)
6760 				return (ret);
6761 			break;
6762 		}
6763 		case SCTP_DEL_IP_ADDRESS: {
6764 			int ret;
6765 			struct sctp_asconf_paramhdr ah;
6766 
6767 			if (!pf_pull_hdr(pd->m, start + off, &ah, sizeof(ah),
6768 			    NULL, NULL, pd->af))
6769 				return (PF_DROP);
6770 			ret = pf_multihome_scan(start + off + sizeof(ah),
6771 			    ntohs(ah.ph.param_length) - sizeof(ah), pd,
6772 			    SCTP_DEL_IP_ADDRESS);
6773 			if (ret != PF_PASS)
6774 				return (ret);
6775 			break;
6776 		}
6777 		default:
6778 			break;
6779 		}
6780 
6781 		off += roundup(ntohs(h.param_length), 4);
6782 	}
6783 
6784 	return (PF_PASS);
6785 }
6786 int
6787 pf_multihome_scan_init(int start, int len, struct pf_pdesc *pd)
6788 {
6789 	start += sizeof(struct sctp_init_chunk);
6790 	len -= sizeof(struct sctp_init_chunk);
6791 
6792 	return (pf_multihome_scan(start, len, pd, SCTP_ADD_IP_ADDRESS));
6793 }
6794 
6795 int
6796 pf_multihome_scan_asconf(int start, int len, struct pf_pdesc *pd)
6797 {
6798 	start += sizeof(struct sctp_asconf_chunk);
6799 	len -= sizeof(struct sctp_asconf_chunk);
6800 
6801 	return (pf_multihome_scan(start, len, pd, SCTP_ADD_IP_ADDRESS));
6802 }
6803 
6804 int
6805 pf_icmp_state_lookup(struct pf_state_key_cmp *key, struct pf_pdesc *pd,
6806     struct pf_kstate **state, int direction,
6807     u_int16_t icmpid, u_int16_t type, int icmp_dir,
6808     int *iidx, int multi, int inner)
6809 {
6810 	key->af = pd->af;
6811 	key->proto = pd->proto;
6812 	if (icmp_dir == PF_IN) {
6813 		*iidx = pd->sidx;
6814 		key->port[pd->sidx] = icmpid;
6815 		key->port[pd->didx] = type;
6816 	} else {
6817 		*iidx = pd->didx;
6818 		key->port[pd->sidx] = type;
6819 		key->port[pd->didx] = icmpid;
6820 	}
6821 	if (pf_state_key_addr_setup(pd, key, multi))
6822 		return (PF_DROP);
6823 
6824 	STATE_LOOKUP(key, *state, pd);
6825 
6826 	if ((*state)->state_flags & PFSTATE_SLOPPY)
6827 		return (-1);
6828 
6829 	/* Is this ICMP message flowing in right direction? */
6830 	if ((*state)->rule->type &&
6831 	    (((!inner && (*state)->direction == direction) ||
6832 	    (inner && (*state)->direction != direction)) ?
6833 	    PF_IN : PF_OUT) != icmp_dir) {
6834 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
6835 			printf("pf: icmp type %d in wrong direction (%d): ",
6836 			    ntohs(type), icmp_dir);
6837 			pf_print_state(*state);
6838 			printf("\n");
6839 		}
6840 		PF_STATE_UNLOCK(*state);
6841 		*state = NULL;
6842 		return (PF_DROP);
6843 	}
6844 	return (-1);
6845 }
6846 
6847 static int
6848 pf_test_state_icmp(struct pf_kstate **state, struct pf_pdesc *pd,
6849     u_short *reason)
6850 {
6851 	struct pf_addr  *saddr = pd->src, *daddr = pd->dst;
6852 	u_int16_t	*icmpsum, virtual_id, virtual_type;
6853 	u_int8_t	 icmptype, icmpcode;
6854 	int		 icmp_dir, iidx, ret, multi;
6855 	struct pf_state_key_cmp key;
6856 #ifdef INET
6857 	u_int16_t	 icmpid;
6858 #endif
6859 
6860 	MPASS(*state == NULL);
6861 
6862 	bzero(&key, sizeof(key));
6863 	switch (pd->proto) {
6864 #ifdef INET
6865 	case IPPROTO_ICMP:
6866 		icmptype = pd->hdr.icmp.icmp_type;
6867 		icmpcode = pd->hdr.icmp.icmp_code;
6868 		icmpid = pd->hdr.icmp.icmp_id;
6869 		icmpsum = &pd->hdr.icmp.icmp_cksum;
6870 		break;
6871 #endif /* INET */
6872 #ifdef INET6
6873 	case IPPROTO_ICMPV6:
6874 		icmptype = pd->hdr.icmp6.icmp6_type;
6875 		icmpcode = pd->hdr.icmp6.icmp6_code;
6876 #ifdef INET
6877 		icmpid = pd->hdr.icmp6.icmp6_id;
6878 #endif
6879 		icmpsum = &pd->hdr.icmp6.icmp6_cksum;
6880 		break;
6881 #endif /* INET6 */
6882 	}
6883 
6884 	if (pf_icmp_mapping(pd, icmptype, &icmp_dir, &multi,
6885 	    &virtual_id, &virtual_type) == 0) {
6886 		/*
6887 		 * ICMP query/reply message not related to a TCP/UDP packet.
6888 		 * Search for an ICMP state.
6889 		 */
6890 		ret = pf_icmp_state_lookup(&key, pd, state, pd->dir,
6891 		    virtual_id, virtual_type, icmp_dir, &iidx,
6892 		    PF_ICMP_MULTI_NONE, 0);
6893 		if (ret >= 0) {
6894 			MPASS(*state == NULL);
6895 			if (ret == PF_DROP && pd->af == AF_INET6 &&
6896 			    icmp_dir == PF_OUT) {
6897 				ret = pf_icmp_state_lookup(&key, pd, state,
6898 				    pd->dir, virtual_id, virtual_type,
6899 				    icmp_dir, &iidx, multi, 0);
6900 				if (ret >= 0) {
6901 					MPASS(*state == NULL);
6902 					return (ret);
6903 				}
6904 			} else
6905 				return (ret);
6906 		}
6907 
6908 		(*state)->expire = pf_get_uptime();
6909 		(*state)->timeout = PFTM_ICMP_ERROR_REPLY;
6910 
6911 		/* translate source/destination address, if necessary */
6912 		if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
6913 			struct pf_state_key *nk = (*state)->key[pd->didx];
6914 
6915 			switch (pd->af) {
6916 #ifdef INET
6917 			case AF_INET:
6918 				if (PF_ANEQ(pd->src,
6919 				    &nk->addr[pd->sidx], AF_INET))
6920 					pf_change_a(&saddr->v4.s_addr,
6921 					    pd->ip_sum,
6922 					    nk->addr[pd->sidx].v4.s_addr, 0);
6923 
6924 				if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
6925 				    AF_INET))
6926 					pf_change_a(&daddr->v4.s_addr,
6927 					    pd->ip_sum,
6928 					    nk->addr[pd->didx].v4.s_addr, 0);
6929 
6930 				if (nk->port[iidx] !=
6931 				    pd->hdr.icmp.icmp_id) {
6932 					pd->hdr.icmp.icmp_cksum =
6933 					    pf_cksum_fixup(
6934 					    pd->hdr.icmp.icmp_cksum, icmpid,
6935 					    nk->port[iidx], 0);
6936 					pd->hdr.icmp.icmp_id =
6937 					    nk->port[iidx];
6938 				}
6939 
6940 				m_copyback(pd->m, pd->off, ICMP_MINLEN,
6941 				    (caddr_t )&pd->hdr.icmp);
6942 				break;
6943 #endif /* INET */
6944 #ifdef INET6
6945 			case AF_INET6:
6946 				if (PF_ANEQ(pd->src,
6947 				    &nk->addr[pd->sidx], AF_INET6))
6948 					pf_change_a6(saddr,
6949 					    &pd->hdr.icmp6.icmp6_cksum,
6950 					    &nk->addr[pd->sidx], 0);
6951 
6952 				if (PF_ANEQ(pd->dst,
6953 				    &nk->addr[pd->didx], AF_INET6))
6954 					pf_change_a6(daddr,
6955 					    &pd->hdr.icmp6.icmp6_cksum,
6956 					    &nk->addr[pd->didx], 0);
6957 
6958 				m_copyback(pd->m, pd->off, sizeof(struct icmp6_hdr),
6959 				    (caddr_t )&pd->hdr.icmp6);
6960 				break;
6961 #endif /* INET6 */
6962 			}
6963 		}
6964 		return (PF_PASS);
6965 
6966 	} else {
6967 		/*
6968 		 * ICMP error message in response to a TCP/UDP packet.
6969 		 * Extract the inner TCP/UDP header and search for that state.
6970 		 */
6971 
6972 		struct pf_pdesc	pd2;
6973 		bzero(&pd2, sizeof pd2);
6974 #ifdef INET
6975 		struct ip	h2;
6976 #endif /* INET */
6977 #ifdef INET6
6978 		struct ip6_hdr	h2_6;
6979 		int		fragoff2, extoff2;
6980 		u_int32_t	jumbolen;
6981 #endif /* INET6 */
6982 		int		ipoff2 = 0;
6983 
6984 		pd2.af = pd->af;
6985 		pd2.dir = pd->dir;
6986 		/* Payload packet is from the opposite direction. */
6987 		pd2.sidx = (pd->dir == PF_IN) ? 1 : 0;
6988 		pd2.didx = (pd->dir == PF_IN) ? 0 : 1;
6989 		pd2.m = pd->m;
6990 		switch (pd->af) {
6991 #ifdef INET
6992 		case AF_INET:
6993 			/* offset of h2 in mbuf chain */
6994 			ipoff2 = pd->off + ICMP_MINLEN;
6995 
6996 			if (!pf_pull_hdr(pd->m, ipoff2, &h2, sizeof(h2),
6997 			    NULL, reason, pd2.af)) {
6998 				DPFPRINTF(PF_DEBUG_MISC,
6999 				    ("pf: ICMP error message too short "
7000 				    "(ip)\n"));
7001 				return (PF_DROP);
7002 			}
7003 			/*
7004 			 * ICMP error messages don't refer to non-first
7005 			 * fragments
7006 			 */
7007 			if (h2.ip_off & htons(IP_OFFMASK)) {
7008 				REASON_SET(reason, PFRES_FRAG);
7009 				return (PF_DROP);
7010 			}
7011 
7012 			/* offset of protocol header that follows h2 */
7013 			pd2.off = ipoff2 + (h2.ip_hl << 2);
7014 
7015 			pd2.proto = h2.ip_p;
7016 			pd2.src = (struct pf_addr *)&h2.ip_src;
7017 			pd2.dst = (struct pf_addr *)&h2.ip_dst;
7018 			pd2.ip_sum = &h2.ip_sum;
7019 			break;
7020 #endif /* INET */
7021 #ifdef INET6
7022 		case AF_INET6:
7023 			ipoff2 = pd->off + sizeof(struct icmp6_hdr);
7024 
7025 			if (!pf_pull_hdr(pd->m, ipoff2, &h2_6, sizeof(h2_6),
7026 			    NULL, reason, pd2.af)) {
7027 				DPFPRINTF(PF_DEBUG_MISC,
7028 				    ("pf: ICMP error message too short "
7029 				    "(ip6)\n"));
7030 				return (PF_DROP);
7031 			}
7032 			pd2.off = ipoff2;
7033 			if (pf_walk_header6(pd->m, &h2_6, &pd2.off, &extoff2,
7034 				&fragoff2, &pd2.proto, &jumbolen,
7035 				reason) != PF_PASS)
7036 				return (PF_DROP);
7037 
7038 			pd2.src = (struct pf_addr *)&h2_6.ip6_src;
7039 			pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
7040 			pd2.ip_sum = NULL;
7041 			break;
7042 #endif /* INET6 */
7043 		}
7044 
7045 		if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
7046 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
7047 				printf("pf: BAD ICMP %d:%d outer dst: ",
7048 				    icmptype, icmpcode);
7049 				pf_print_host(pd->src, 0, pd->af);
7050 				printf(" -> ");
7051 				pf_print_host(pd->dst, 0, pd->af);
7052 				printf(" inner src: ");
7053 				pf_print_host(pd2.src, 0, pd2.af);
7054 				printf(" -> ");
7055 				pf_print_host(pd2.dst, 0, pd2.af);
7056 				printf("\n");
7057 			}
7058 			REASON_SET(reason, PFRES_BADSTATE);
7059 			return (PF_DROP);
7060 		}
7061 
7062 		switch (pd2.proto) {
7063 		case IPPROTO_TCP: {
7064 			struct tcphdr		 th;
7065 			u_int32_t		 seq;
7066 			struct pf_state_peer	*src, *dst;
7067 			u_int8_t		 dws;
7068 			int			 copyback = 0;
7069 
7070 			/*
7071 			 * Only the first 8 bytes of the TCP header can be
7072 			 * expected. Don't access any TCP header fields after
7073 			 * th_seq, an ackskew test is not possible.
7074 			 */
7075 			if (!pf_pull_hdr(pd->m, pd2.off, &th, 8, NULL, reason,
7076 			    pd2.af)) {
7077 				DPFPRINTF(PF_DEBUG_MISC,
7078 				    ("pf: ICMP error message too short "
7079 				    "(tcp)\n"));
7080 				return (PF_DROP);
7081 			}
7082 
7083 			key.af = pd2.af;
7084 			key.proto = IPPROTO_TCP;
7085 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
7086 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
7087 			key.port[pd2.sidx] = th.th_sport;
7088 			key.port[pd2.didx] = th.th_dport;
7089 
7090 			STATE_LOOKUP(&key, *state, pd);
7091 
7092 			if (pd->dir == (*state)->direction) {
7093 				src = &(*state)->dst;
7094 				dst = &(*state)->src;
7095 			} else {
7096 				src = &(*state)->src;
7097 				dst = &(*state)->dst;
7098 			}
7099 
7100 			if (src->wscale && dst->wscale)
7101 				dws = dst->wscale & PF_WSCALE_MASK;
7102 			else
7103 				dws = 0;
7104 
7105 			/* Demodulate sequence number */
7106 			seq = ntohl(th.th_seq) - src->seqdiff;
7107 			if (src->seqdiff) {
7108 				pf_change_a(&th.th_seq, icmpsum,
7109 				    htonl(seq), 0);
7110 				copyback = 1;
7111 			}
7112 
7113 			if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
7114 			    (!SEQ_GEQ(src->seqhi, seq) ||
7115 			    !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
7116 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
7117 					printf("pf: BAD ICMP %d:%d ",
7118 					    icmptype, icmpcode);
7119 					pf_print_host(pd->src, 0, pd->af);
7120 					printf(" -> ");
7121 					pf_print_host(pd->dst, 0, pd->af);
7122 					printf(" state: ");
7123 					pf_print_state(*state);
7124 					printf(" seq=%u\n", seq);
7125 				}
7126 				REASON_SET(reason, PFRES_BADSTATE);
7127 				return (PF_DROP);
7128 			} else {
7129 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
7130 					printf("pf: OK ICMP %d:%d ",
7131 					    icmptype, icmpcode);
7132 					pf_print_host(pd->src, 0, pd->af);
7133 					printf(" -> ");
7134 					pf_print_host(pd->dst, 0, pd->af);
7135 					printf(" state: ");
7136 					pf_print_state(*state);
7137 					printf(" seq=%u\n", seq);
7138 				}
7139 			}
7140 
7141 			/* translate source/destination address, if necessary */
7142 			if ((*state)->key[PF_SK_WIRE] !=
7143 			    (*state)->key[PF_SK_STACK]) {
7144 				struct pf_state_key *nk =
7145 				    (*state)->key[pd->didx];
7146 
7147 				if (PF_ANEQ(pd2.src,
7148 				    &nk->addr[pd2.sidx], pd2.af) ||
7149 				    nk->port[pd2.sidx] != th.th_sport)
7150 					pf_change_icmp(pd2.src, &th.th_sport,
7151 					    daddr, &nk->addr[pd2.sidx],
7152 					    nk->port[pd2.sidx], NULL,
7153 					    pd2.ip_sum, icmpsum,
7154 					    pd->ip_sum, 0, pd2.af);
7155 
7156 				if (PF_ANEQ(pd2.dst,
7157 				    &nk->addr[pd2.didx], pd2.af) ||
7158 				    nk->port[pd2.didx] != th.th_dport)
7159 					pf_change_icmp(pd2.dst, &th.th_dport,
7160 					    saddr, &nk->addr[pd2.didx],
7161 					    nk->port[pd2.didx], NULL,
7162 					    pd2.ip_sum, icmpsum,
7163 					    pd->ip_sum, 0, pd2.af);
7164 				copyback = 1;
7165 			}
7166 
7167 			if (copyback) {
7168 				switch (pd2.af) {
7169 #ifdef INET
7170 				case AF_INET:
7171 					m_copyback(pd->m, pd->off, ICMP_MINLEN,
7172 					    (caddr_t )&pd->hdr.icmp);
7173 					m_copyback(pd->m, ipoff2, sizeof(h2),
7174 					    (caddr_t )&h2);
7175 					break;
7176 #endif /* INET */
7177 #ifdef INET6
7178 				case AF_INET6:
7179 					m_copyback(pd->m, pd->off,
7180 					    sizeof(struct icmp6_hdr),
7181 					    (caddr_t )&pd->hdr.icmp6);
7182 					m_copyback(pd->m, ipoff2, sizeof(h2_6),
7183 					    (caddr_t )&h2_6);
7184 					break;
7185 #endif /* INET6 */
7186 				}
7187 				m_copyback(pd->m, pd2.off, 8, (caddr_t)&th);
7188 			}
7189 
7190 			return (PF_PASS);
7191 			break;
7192 		}
7193 		case IPPROTO_UDP: {
7194 			struct udphdr		uh;
7195 
7196 			if (!pf_pull_hdr(pd->m, pd2.off, &uh, sizeof(uh),
7197 			    NULL, reason, pd2.af)) {
7198 				DPFPRINTF(PF_DEBUG_MISC,
7199 				    ("pf: ICMP error message too short "
7200 				    "(udp)\n"));
7201 				return (PF_DROP);
7202 			}
7203 
7204 			key.af = pd2.af;
7205 			key.proto = IPPROTO_UDP;
7206 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
7207 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
7208 			key.port[pd2.sidx] = uh.uh_sport;
7209 			key.port[pd2.didx] = uh.uh_dport;
7210 
7211 			STATE_LOOKUP(&key, *state, pd);
7212 
7213 			/* translate source/destination address, if necessary */
7214 			if ((*state)->key[PF_SK_WIRE] !=
7215 			    (*state)->key[PF_SK_STACK]) {
7216 				struct pf_state_key *nk =
7217 				    (*state)->key[pd->didx];
7218 
7219 				if (PF_ANEQ(pd2.src,
7220 				    &nk->addr[pd2.sidx], pd2.af) ||
7221 				    nk->port[pd2.sidx] != uh.uh_sport)
7222 					pf_change_icmp(pd2.src, &uh.uh_sport,
7223 					    daddr, &nk->addr[pd2.sidx],
7224 					    nk->port[pd2.sidx], &uh.uh_sum,
7225 					    pd2.ip_sum, icmpsum,
7226 					    pd->ip_sum, 1, pd2.af);
7227 
7228 				if (PF_ANEQ(pd2.dst,
7229 				    &nk->addr[pd2.didx], pd2.af) ||
7230 				    nk->port[pd2.didx] != uh.uh_dport)
7231 					pf_change_icmp(pd2.dst, &uh.uh_dport,
7232 					    saddr, &nk->addr[pd2.didx],
7233 					    nk->port[pd2.didx], &uh.uh_sum,
7234 					    pd2.ip_sum, icmpsum,
7235 					    pd->ip_sum, 1, pd2.af);
7236 
7237 				switch (pd2.af) {
7238 #ifdef INET
7239 				case AF_INET:
7240 					m_copyback(pd->m, pd->off, ICMP_MINLEN,
7241 					    (caddr_t )&pd->hdr.icmp);
7242 					m_copyback(pd->m, ipoff2, sizeof(h2), (caddr_t)&h2);
7243 					break;
7244 #endif /* INET */
7245 #ifdef INET6
7246 				case AF_INET6:
7247 					m_copyback(pd->m, pd->off,
7248 					    sizeof(struct icmp6_hdr),
7249 					    (caddr_t )&pd->hdr.icmp6);
7250 					m_copyback(pd->m, ipoff2, sizeof(h2_6),
7251 					    (caddr_t )&h2_6);
7252 					break;
7253 #endif /* INET6 */
7254 				}
7255 				m_copyback(pd->m, pd2.off, sizeof(uh), (caddr_t)&uh);
7256 			}
7257 			return (PF_PASS);
7258 			break;
7259 		}
7260 #ifdef INET
7261 		case IPPROTO_ICMP: {
7262 			struct icmp	*iih = &pd2.hdr.icmp;
7263 
7264 			if (pd2.af != AF_INET) {
7265 				REASON_SET(reason, PFRES_NORM);
7266 				return (PF_DROP);
7267 			}
7268 
7269 			if (!pf_pull_hdr(pd->m, pd2.off, iih, ICMP_MINLEN,
7270 			    NULL, reason, pd2.af)) {
7271 				DPFPRINTF(PF_DEBUG_MISC,
7272 				    ("pf: ICMP error message too short i"
7273 				    "(icmp)\n"));
7274 				return (PF_DROP);
7275 			}
7276 
7277 			icmpid = iih->icmp_id;
7278 			pf_icmp_mapping(&pd2, iih->icmp_type,
7279 			    &icmp_dir, &multi, &virtual_id, &virtual_type);
7280 
7281 			ret = pf_icmp_state_lookup(&key, &pd2, state,
7282 			    pd2.dir, virtual_id, virtual_type,
7283 			    icmp_dir, &iidx, PF_ICMP_MULTI_NONE, 1);
7284 			if (ret >= 0) {
7285 				MPASS(*state == NULL);
7286 				return (ret);
7287 			}
7288 
7289 			/* translate source/destination address, if necessary */
7290 			if ((*state)->key[PF_SK_WIRE] !=
7291 			    (*state)->key[PF_SK_STACK]) {
7292 				struct pf_state_key *nk =
7293 				    (*state)->key[pd->didx];
7294 
7295 				if (PF_ANEQ(pd2.src,
7296 				    &nk->addr[pd2.sidx], pd2.af) ||
7297 				    (virtual_type == htons(ICMP_ECHO) &&
7298 				    nk->port[iidx] != iih->icmp_id))
7299 					pf_change_icmp(pd2.src,
7300 					    (virtual_type == htons(ICMP_ECHO)) ?
7301 					    &iih->icmp_id : NULL,
7302 					    daddr, &nk->addr[pd2.sidx],
7303 					    (virtual_type == htons(ICMP_ECHO)) ?
7304 					    nk->port[iidx] : 0, NULL,
7305 					    pd2.ip_sum, icmpsum,
7306 					    pd->ip_sum, 0, AF_INET);
7307 
7308 				if (PF_ANEQ(pd2.dst,
7309 				    &nk->addr[pd2.didx], pd2.af))
7310 					pf_change_icmp(pd2.dst, NULL, NULL,
7311 					    &nk->addr[pd2.didx], 0, NULL,
7312 					    pd2.ip_sum, icmpsum, pd->ip_sum, 0,
7313 					    AF_INET);
7314 
7315 				m_copyback(pd->m, pd->off, ICMP_MINLEN, (caddr_t)&pd->hdr.icmp);
7316 				m_copyback(pd->m, ipoff2, sizeof(h2), (caddr_t)&h2);
7317 				m_copyback(pd->m, pd2.off, ICMP_MINLEN, (caddr_t)iih);
7318 			}
7319 			return (PF_PASS);
7320 			break;
7321 		}
7322 #endif /* INET */
7323 #ifdef INET6
7324 		case IPPROTO_ICMPV6: {
7325 			struct icmp6_hdr	*iih = &pd2.hdr.icmp6;
7326 
7327 			if (pd2.af != AF_INET6) {
7328 				REASON_SET(reason, PFRES_NORM);
7329 				return (PF_DROP);
7330 			}
7331 
7332 			if (!pf_pull_hdr(pd->m, pd2.off, iih,
7333 			    sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
7334 				DPFPRINTF(PF_DEBUG_MISC,
7335 				    ("pf: ICMP error message too short "
7336 				    "(icmp6)\n"));
7337 				return (PF_DROP);
7338 			}
7339 
7340 			pf_icmp_mapping(&pd2, iih->icmp6_type,
7341 			    &icmp_dir, &multi, &virtual_id, &virtual_type);
7342 
7343 			ret = pf_icmp_state_lookup(&key, &pd2, state,
7344 			    pd->dir, virtual_id, virtual_type,
7345 			    icmp_dir, &iidx, PF_ICMP_MULTI_NONE, 1);
7346 			if (ret >= 0) {
7347 				MPASS(*state == NULL);
7348 				if (ret == PF_DROP && pd2.af == AF_INET6 &&
7349 				    icmp_dir == PF_OUT) {
7350 					ret = pf_icmp_state_lookup(&key, &pd2,
7351 					    state, pd->dir,
7352 					    virtual_id, virtual_type,
7353 					    icmp_dir, &iidx, multi, 1);
7354 					if (ret >= 0) {
7355 						MPASS(*state == NULL);
7356 						return (ret);
7357 					}
7358 				} else
7359 					return (ret);
7360 			}
7361 
7362 			/* translate source/destination address, if necessary */
7363 			if ((*state)->key[PF_SK_WIRE] !=
7364 			    (*state)->key[PF_SK_STACK]) {
7365 				struct pf_state_key *nk =
7366 				    (*state)->key[pd->didx];
7367 
7368 				if (PF_ANEQ(pd2.src,
7369 				    &nk->addr[pd2.sidx], pd2.af) ||
7370 				    ((virtual_type == htons(ICMP6_ECHO_REQUEST)) &&
7371 				    nk->port[pd2.sidx] != iih->icmp6_id))
7372 					pf_change_icmp(pd2.src,
7373 					    (virtual_type == htons(ICMP6_ECHO_REQUEST))
7374 					    ? &iih->icmp6_id : NULL,
7375 					    daddr, &nk->addr[pd2.sidx],
7376 					    (virtual_type == htons(ICMP6_ECHO_REQUEST))
7377 					    ? nk->port[iidx] : 0, NULL,
7378 					    pd2.ip_sum, icmpsum,
7379 					    pd->ip_sum, 0, AF_INET6);
7380 
7381 				if (PF_ANEQ(pd2.dst,
7382 				    &nk->addr[pd2.didx], pd2.af))
7383 					pf_change_icmp(pd2.dst, NULL, NULL,
7384 					    &nk->addr[pd2.didx], 0, NULL,
7385 					    pd2.ip_sum, icmpsum,
7386 					    pd->ip_sum, 0, AF_INET6);
7387 
7388 				m_copyback(pd->m, pd->off, sizeof(struct icmp6_hdr),
7389 				    (caddr_t)&pd->hdr.icmp6);
7390 				m_copyback(pd->m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
7391 				m_copyback(pd->m, pd2.off, sizeof(struct icmp6_hdr),
7392 				    (caddr_t)iih);
7393 			}
7394 			return (PF_PASS);
7395 			break;
7396 		}
7397 #endif /* INET6 */
7398 		default: {
7399 			key.af = pd2.af;
7400 			key.proto = pd2.proto;
7401 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
7402 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
7403 			key.port[0] = key.port[1] = 0;
7404 
7405 			STATE_LOOKUP(&key, *state, pd);
7406 
7407 			/* translate source/destination address, if necessary */
7408 			if ((*state)->key[PF_SK_WIRE] !=
7409 			    (*state)->key[PF_SK_STACK]) {
7410 				struct pf_state_key *nk =
7411 				    (*state)->key[pd->didx];
7412 
7413 				if (PF_ANEQ(pd2.src,
7414 				    &nk->addr[pd2.sidx], pd2.af))
7415 					pf_change_icmp(pd2.src, NULL, daddr,
7416 					    &nk->addr[pd2.sidx], 0, NULL,
7417 					    pd2.ip_sum, icmpsum,
7418 					    pd->ip_sum, 0, pd2.af);
7419 
7420 				if (PF_ANEQ(pd2.dst,
7421 				    &nk->addr[pd2.didx], pd2.af))
7422 					pf_change_icmp(pd2.dst, NULL, saddr,
7423 					    &nk->addr[pd2.didx], 0, NULL,
7424 					    pd2.ip_sum, icmpsum,
7425 					    pd->ip_sum, 0, pd2.af);
7426 
7427 				switch (pd2.af) {
7428 #ifdef INET
7429 				case AF_INET:
7430 					m_copyback(pd->m, pd->off, ICMP_MINLEN,
7431 					    (caddr_t)&pd->hdr.icmp);
7432 					m_copyback(pd->m, ipoff2, sizeof(h2), (caddr_t)&h2);
7433 					break;
7434 #endif /* INET */
7435 #ifdef INET6
7436 				case AF_INET6:
7437 					m_copyback(pd->m, pd->off,
7438 					    sizeof(struct icmp6_hdr),
7439 					    (caddr_t )&pd->hdr.icmp6);
7440 					m_copyback(pd->m, ipoff2, sizeof(h2_6),
7441 					    (caddr_t )&h2_6);
7442 					break;
7443 #endif /* INET6 */
7444 				}
7445 			}
7446 			return (PF_PASS);
7447 			break;
7448 		}
7449 		}
7450 	}
7451 }
7452 
7453 static int
7454 pf_test_state_other(struct pf_kstate **state, struct pf_pdesc *pd)
7455 {
7456 	struct pf_state_peer	*src, *dst;
7457 	struct pf_state_key_cmp	 key;
7458 	uint8_t			 psrc, pdst;
7459 
7460 	bzero(&key, sizeof(key));
7461 	key.af = pd->af;
7462 	key.proto = pd->proto;
7463 	if (pd->dir == PF_IN)	{
7464 		PF_ACPY(&key.addr[0], pd->src, key.af);
7465 		PF_ACPY(&key.addr[1], pd->dst, key.af);
7466 		key.port[0] = key.port[1] = 0;
7467 	} else {
7468 		PF_ACPY(&key.addr[1], pd->src, key.af);
7469 		PF_ACPY(&key.addr[0], pd->dst, key.af);
7470 		key.port[1] = key.port[0] = 0;
7471 	}
7472 
7473 	STATE_LOOKUP(&key, *state, pd);
7474 
7475 	if (pd->dir == (*state)->direction) {
7476 		src = &(*state)->src;
7477 		dst = &(*state)->dst;
7478 		psrc = PF_PEER_SRC;
7479 		pdst = PF_PEER_DST;
7480 	} else {
7481 		src = &(*state)->dst;
7482 		dst = &(*state)->src;
7483 		psrc = PF_PEER_DST;
7484 		pdst = PF_PEER_SRC;
7485 	}
7486 
7487 	/* update states */
7488 	if (src->state < PFOTHERS_SINGLE)
7489 		pf_set_protostate(*state, psrc, PFOTHERS_SINGLE);
7490 	if (dst->state == PFOTHERS_SINGLE)
7491 		pf_set_protostate(*state, pdst, PFOTHERS_MULTIPLE);
7492 
7493 	/* update expire time */
7494 	(*state)->expire = pf_get_uptime();
7495 	if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
7496 		(*state)->timeout = PFTM_OTHER_MULTIPLE;
7497 	else
7498 		(*state)->timeout = PFTM_OTHER_SINGLE;
7499 
7500 	/* translate source/destination address, if necessary */
7501 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
7502 		struct pf_state_key *nk = (*state)->key[pd->didx];
7503 
7504 		KASSERT(nk, ("%s: nk is null", __func__));
7505 		KASSERT(pd, ("%s: pd is null", __func__));
7506 		KASSERT(pd->src, ("%s: pd->src is null", __func__));
7507 		KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
7508 		switch (pd->af) {
7509 #ifdef INET
7510 		case AF_INET:
7511 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
7512 				pf_change_a(&pd->src->v4.s_addr,
7513 				    pd->ip_sum,
7514 				    nk->addr[pd->sidx].v4.s_addr,
7515 				    0);
7516 
7517 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
7518 				pf_change_a(&pd->dst->v4.s_addr,
7519 				    pd->ip_sum,
7520 				    nk->addr[pd->didx].v4.s_addr,
7521 				    0);
7522 
7523 			break;
7524 #endif /* INET */
7525 #ifdef INET6
7526 		case AF_INET6:
7527 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET6))
7528 				PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
7529 
7530 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET6))
7531 				PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
7532 #endif /* INET6 */
7533 		}
7534 	}
7535 	return (PF_PASS);
7536 }
7537 
7538 /*
7539  * ipoff and off are measured from the start of the mbuf chain.
7540  * h must be at "ipoff" on the mbuf chain.
7541  */
7542 void *
7543 pf_pull_hdr(const struct mbuf *m, int off, void *p, int len,
7544     u_short *actionp, u_short *reasonp, sa_family_t af)
7545 {
7546 	switch (af) {
7547 #ifdef INET
7548 	case AF_INET: {
7549 		const struct ip	*h = mtod(m, struct ip *);
7550 		u_int16_t	 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
7551 
7552 		if (fragoff) {
7553 			if (fragoff >= len)
7554 				ACTION_SET(actionp, PF_PASS);
7555 			else {
7556 				ACTION_SET(actionp, PF_DROP);
7557 				REASON_SET(reasonp, PFRES_FRAG);
7558 			}
7559 			return (NULL);
7560 		}
7561 		if (m->m_pkthdr.len < off + len ||
7562 		    ntohs(h->ip_len) < off + len) {
7563 			ACTION_SET(actionp, PF_DROP);
7564 			REASON_SET(reasonp, PFRES_SHORT);
7565 			return (NULL);
7566 		}
7567 		break;
7568 	}
7569 #endif /* INET */
7570 #ifdef INET6
7571 	case AF_INET6: {
7572 		const struct ip6_hdr	*h = mtod(m, struct ip6_hdr *);
7573 
7574 		if (m->m_pkthdr.len < off + len ||
7575 		    (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
7576 		    (unsigned)(off + len)) {
7577 			ACTION_SET(actionp, PF_DROP);
7578 			REASON_SET(reasonp, PFRES_SHORT);
7579 			return (NULL);
7580 		}
7581 		break;
7582 	}
7583 #endif /* INET6 */
7584 	}
7585 	m_copydata(m, off, len, p);
7586 	return (p);
7587 }
7588 
7589 int
7590 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kkif *kif,
7591     int rtableid)
7592 {
7593 	struct ifnet		*ifp;
7594 
7595 	/*
7596 	 * Skip check for addresses with embedded interface scope,
7597 	 * as they would always match anyway.
7598 	 */
7599 	if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
7600 		return (1);
7601 
7602 	if (af != AF_INET && af != AF_INET6)
7603 		return (0);
7604 
7605 	if (kif == V_pfi_all)
7606 		return (1);
7607 
7608 	/* Skip checks for ipsec interfaces */
7609 	if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
7610 		return (1);
7611 
7612 	ifp = (kif != NULL) ? kif->pfik_ifp : NULL;
7613 
7614 	switch (af) {
7615 #ifdef INET6
7616 	case AF_INET6:
7617 		return (fib6_check_urpf(rtableid, &addr->v6, 0, NHR_NONE,
7618 		    ifp));
7619 #endif
7620 #ifdef INET
7621 	case AF_INET:
7622 		return (fib4_check_urpf(rtableid, addr->v4, 0, NHR_NONE,
7623 		    ifp));
7624 #endif
7625 	}
7626 
7627 	return (0);
7628 }
7629 
7630 #ifdef INET
7631 static void
7632 pf_route(struct mbuf **m, struct pf_krule *r, struct ifnet *oifp,
7633     struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
7634 {
7635 	struct mbuf		*m0, *m1, *md;
7636 	struct sockaddr_in	dst;
7637 	struct ip		*ip;
7638 	struct pfi_kkif		*nkif = NULL;
7639 	struct ifnet		*ifp = NULL;
7640 	struct pf_addr		 naddr;
7641 	int			 error = 0;
7642 	uint16_t		 ip_len, ip_off;
7643 	uint16_t		 tmp;
7644 	int			 r_rt, r_dir;
7645 
7646 	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
7647 
7648 	if (s) {
7649 		r_rt = s->rt;
7650 		r_dir = s->direction;
7651 	} else {
7652 		r_rt = r->rt;
7653 		r_dir = r->direction;
7654 	}
7655 
7656 	KASSERT(pd->dir == PF_IN || pd->dir == PF_OUT ||
7657 	    r_dir == PF_IN || r_dir == PF_OUT, ("%s: invalid direction",
7658 	    __func__));
7659 
7660 	if ((pd->pf_mtag == NULL &&
7661 	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
7662 	    pd->pf_mtag->routed++ > 3) {
7663 		m0 = *m;
7664 		*m = NULL;
7665 		goto bad_locked;
7666 	}
7667 
7668 	if (r_rt == PF_DUPTO) {
7669 		if ((pd->pf_mtag->flags & PF_MTAG_FLAG_DUPLICATED)) {
7670 			if (s == NULL) {
7671 				ifp = r->rpool.cur->kif ?
7672 				    r->rpool.cur->kif->pfik_ifp : NULL;
7673 			} else {
7674 				ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
7675 				/* If pfsync'd */
7676 				if (ifp == NULL && r->rpool.cur != NULL)
7677 					ifp = r->rpool.cur->kif ?
7678 					    r->rpool.cur->kif->pfik_ifp : NULL;
7679 				PF_STATE_UNLOCK(s);
7680 			}
7681 			if (ifp == oifp) {
7682 				/* When the 2nd interface is not skipped */
7683 				return;
7684 			} else {
7685 				m0 = *m;
7686 				*m = NULL;
7687 				goto bad;
7688 			}
7689 		} else {
7690 			pd->pf_mtag->flags |= PF_MTAG_FLAG_DUPLICATED;
7691 			if (((m0 = m_dup(*m, M_NOWAIT)) == NULL)) {
7692 				if (s)
7693 					PF_STATE_UNLOCK(s);
7694 				return;
7695 			}
7696 		}
7697 	} else {
7698 		if ((r_rt == PF_REPLYTO) == (r_dir == pd->dir)) {
7699 			pf_dummynet(pd, s, r, m);
7700 			if (s)
7701 				PF_STATE_UNLOCK(s);
7702 			return;
7703 		}
7704 		m0 = *m;
7705 	}
7706 
7707 	ip = mtod(m0, struct ip *);
7708 
7709 	bzero(&dst, sizeof(dst));
7710 	dst.sin_family = AF_INET;
7711 	dst.sin_len = sizeof(dst);
7712 	dst.sin_addr = ip->ip_dst;
7713 
7714 	bzero(&naddr, sizeof(naddr));
7715 
7716 	if (s == NULL) {
7717 		if (TAILQ_EMPTY(&r->rpool.list)) {
7718 			DPFPRINTF(PF_DEBUG_URGENT,
7719 			    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
7720 			goto bad_locked;
7721 		}
7722 		pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
7723 		    &naddr, &nkif, NULL);
7724 		if (!PF_AZERO(&naddr, AF_INET))
7725 			dst.sin_addr.s_addr = naddr.v4.s_addr;
7726 		ifp = nkif ? nkif->pfik_ifp : NULL;
7727 	} else {
7728 		struct pfi_kkif *kif;
7729 
7730 		if (!PF_AZERO(&s->rt_addr, AF_INET))
7731 			dst.sin_addr.s_addr =
7732 			    s->rt_addr.v4.s_addr;
7733 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
7734 		kif = s->rt_kif;
7735 		/* If pfsync'd */
7736 		if (ifp == NULL && r->rpool.cur != NULL) {
7737 			ifp = r->rpool.cur->kif ?
7738 			    r->rpool.cur->kif->pfik_ifp : NULL;
7739 			kif = r->rpool.cur->kif;
7740 		}
7741 		if (ifp != NULL && kif != NULL &&
7742 		    r->rule_flag & PFRULE_IFBOUND &&
7743 		    r->rt == PF_REPLYTO &&
7744 		    s->kif == V_pfi_all) {
7745 			s->kif = kif;
7746 			s->orig_kif = oifp->if_pf_kif;
7747 		}
7748 
7749 		PF_STATE_UNLOCK(s);
7750 	}
7751 
7752 	if (ifp == NULL)
7753 		goto bad;
7754 
7755 	if (pd->dir == PF_IN) {
7756 		if (pf_test(AF_INET, PF_OUT, PFIL_FWD, ifp, &m0, inp,
7757 		    &pd->act) != PF_PASS)
7758 			goto bad;
7759 		else if (m0 == NULL)
7760 			goto done;
7761 		if (m0->m_len < sizeof(struct ip)) {
7762 			DPFPRINTF(PF_DEBUG_URGENT,
7763 			    ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
7764 			goto bad;
7765 		}
7766 		ip = mtod(m0, struct ip *);
7767 	}
7768 
7769 	if (ifp->if_flags & IFF_LOOPBACK)
7770 		m0->m_flags |= M_SKIP_FIREWALL;
7771 
7772 	ip_len = ntohs(ip->ip_len);
7773 	ip_off = ntohs(ip->ip_off);
7774 
7775 	/* Copied from FreeBSD 10.0-CURRENT ip_output. */
7776 	m0->m_pkthdr.csum_flags |= CSUM_IP;
7777 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
7778 		in_delayed_cksum(m0);
7779 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
7780 	}
7781 	if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
7782 		pf_sctp_checksum(m0, (uint32_t)(ip->ip_hl << 2));
7783 		m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
7784 	}
7785 
7786 	if (pd->dir == PF_IN) {
7787 		/*
7788 		 * Make sure dummynet gets the correct direction, in case it needs to
7789 		 * re-inject later.
7790 		 */
7791 		pd->dir = PF_OUT;
7792 
7793 		/*
7794 		 * The following processing is actually the rest of the inbound processing, even
7795 		 * though we've marked it as outbound (so we don't look through dummynet) and it
7796 		 * happens after the outbound processing (pf_test(PF_OUT) above).
7797 		 * Swap the dummynet pipe numbers, because it's going to come to the wrong
7798 		 * conclusion about what direction it's processing, and we can't fix it or it
7799 		 * will re-inject incorrectly. Swapping the pipe numbers means that its incorrect
7800 		 * decision will pick the right pipe, and everything will mostly work as expected.
7801 		 */
7802 		tmp = pd->act.dnrpipe;
7803 		pd->act.dnrpipe = pd->act.dnpipe;
7804 		pd->act.dnpipe = tmp;
7805 	}
7806 
7807 	/*
7808 	 * If small enough for interface, or the interface will take
7809 	 * care of the fragmentation for us, we can just send directly.
7810 	 */
7811 	if (ip_len <= ifp->if_mtu ||
7812 	    (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
7813 		ip->ip_sum = 0;
7814 		if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
7815 			ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
7816 			m0->m_pkthdr.csum_flags &= ~CSUM_IP;
7817 		}
7818 		m_clrprotoflags(m0);	/* Avoid confusing lower layers. */
7819 
7820 		md = m0;
7821 		error = pf_dummynet_route(pd, s, r, ifp, sintosa(&dst), &md);
7822 		if (md != NULL)
7823 			error = (*ifp->if_output)(ifp, md, sintosa(&dst), NULL);
7824 		goto done;
7825 	}
7826 
7827 	/* Balk when DF bit is set or the interface didn't support TSO. */
7828 	if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
7829 		error = EMSGSIZE;
7830 		KMOD_IPSTAT_INC(ips_cantfrag);
7831 		if (r_rt != PF_DUPTO) {
7832 			if (s && s->nat_rule != NULL)
7833 				PACKET_UNDO_NAT(m0, pd,
7834 				    (ip->ip_hl << 2) + (ip_off & IP_OFFMASK),
7835 				    s);
7836 
7837 			icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
7838 			    ifp->if_mtu);
7839 			goto done;
7840 		} else
7841 			goto bad;
7842 	}
7843 
7844 	error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
7845 	if (error)
7846 		goto bad;
7847 
7848 	for (; m0; m0 = m1) {
7849 		m1 = m0->m_nextpkt;
7850 		m0->m_nextpkt = NULL;
7851 		if (error == 0) {
7852 			m_clrprotoflags(m0);
7853 			md = m0;
7854 			pd->pf_mtag = pf_find_mtag(md);
7855 			error = pf_dummynet_route(pd, s, r, ifp,
7856 			    sintosa(&dst), &md);
7857 			if (md != NULL)
7858 				error = (*ifp->if_output)(ifp, md,
7859 				    sintosa(&dst), NULL);
7860 		} else
7861 			m_freem(m0);
7862 	}
7863 
7864 	if (error == 0)
7865 		KMOD_IPSTAT_INC(ips_fragmented);
7866 
7867 done:
7868 	if (r_rt != PF_DUPTO)
7869 		*m = NULL;
7870 	return;
7871 
7872 bad_locked:
7873 	if (s)
7874 		PF_STATE_UNLOCK(s);
7875 bad:
7876 	m_freem(m0);
7877 	goto done;
7878 }
7879 #endif /* INET */
7880 
7881 #ifdef INET6
7882 static void
7883 pf_route6(struct mbuf **m, struct pf_krule *r, struct ifnet *oifp,
7884     struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
7885 {
7886 	struct mbuf		*m0, *md;
7887 	struct sockaddr_in6	dst;
7888 	struct ip6_hdr		*ip6;
7889 	struct pfi_kkif		*nkif = NULL;
7890 	struct ifnet		*ifp = NULL;
7891 	struct pf_addr		 naddr;
7892 	int			 r_rt, r_dir;
7893 
7894 	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
7895 
7896 	if (s) {
7897 		r_rt = s->rt;
7898 		r_dir = s->direction;
7899 	} else {
7900 		r_rt = r->rt;
7901 		r_dir = r->direction;
7902 	}
7903 
7904 	KASSERT(pd->dir == PF_IN || pd->dir == PF_OUT ||
7905 	    r_dir == PF_IN || r_dir == PF_OUT, ("%s: invalid direction",
7906 	    __func__));
7907 
7908 	if ((pd->pf_mtag == NULL &&
7909 	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
7910 	    pd->pf_mtag->routed++ > 3) {
7911 		m0 = *m;
7912 		*m = NULL;
7913 		goto bad_locked;
7914 	}
7915 
7916 	if (r_rt == PF_DUPTO) {
7917 		if ((pd->pf_mtag->flags & PF_MTAG_FLAG_DUPLICATED)) {
7918 			if (s == NULL) {
7919 				ifp = r->rpool.cur->kif ?
7920 				    r->rpool.cur->kif->pfik_ifp : NULL;
7921 			} else {
7922 				ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
7923 				/* If pfsync'd */
7924 				if (ifp == NULL && r->rpool.cur != NULL)
7925 					ifp = r->rpool.cur->kif ?
7926 					    r->rpool.cur->kif->pfik_ifp : NULL;
7927 				PF_STATE_UNLOCK(s);
7928 			}
7929 			if (ifp == oifp) {
7930 				/* When the 2nd interface is not skipped */
7931 				return;
7932 			} else {
7933 				m0 = *m;
7934 				*m = NULL;
7935 				goto bad;
7936 			}
7937 		} else {
7938 			pd->pf_mtag->flags |= PF_MTAG_FLAG_DUPLICATED;
7939 			if (((m0 = m_dup(*m, M_NOWAIT)) == NULL)) {
7940 				if (s)
7941 					PF_STATE_UNLOCK(s);
7942 				return;
7943 			}
7944 		}
7945 	} else {
7946 		if ((r_rt == PF_REPLYTO) == (r_dir == pd->dir)) {
7947 			pf_dummynet(pd, s, r, m);
7948 			if (s)
7949 				PF_STATE_UNLOCK(s);
7950 			return;
7951 		}
7952 		m0 = *m;
7953 	}
7954 
7955 	ip6 = mtod(m0, struct ip6_hdr *);
7956 
7957 	bzero(&dst, sizeof(dst));
7958 	dst.sin6_family = AF_INET6;
7959 	dst.sin6_len = sizeof(dst);
7960 	dst.sin6_addr = ip6->ip6_dst;
7961 
7962 	bzero(&naddr, sizeof(naddr));
7963 
7964 	if (s == NULL) {
7965 		if (TAILQ_EMPTY(&r->rpool.list)) {
7966 			DPFPRINTF(PF_DEBUG_URGENT,
7967 			    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
7968 			goto bad_locked;
7969 		}
7970 		pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
7971 		    &naddr, &nkif, NULL);
7972 		if (!PF_AZERO(&naddr, AF_INET6))
7973 			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
7974 			    &naddr, AF_INET6);
7975 		ifp = nkif ? nkif->pfik_ifp : NULL;
7976 	} else {
7977 		struct pfi_kkif *kif;
7978 
7979 		if (!PF_AZERO(&s->rt_addr, AF_INET6))
7980 			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
7981 			    &s->rt_addr, AF_INET6);
7982 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
7983 		kif = s->rt_kif;
7984 		/* If pfsync'd */
7985 		if (ifp == NULL && r->rpool.cur != NULL) {
7986 			ifp = r->rpool.cur->kif ?
7987 			    r->rpool.cur->kif->pfik_ifp : NULL;
7988 			kif = r->rpool.cur->kif;
7989 		}
7990 		if (ifp != NULL && kif != NULL &&
7991 		    r->rule_flag & PFRULE_IFBOUND &&
7992 		    r->rt == PF_REPLYTO &&
7993 		    s->kif == V_pfi_all) {
7994 			s->kif = kif;
7995 			s->orig_kif = oifp->if_pf_kif;
7996 		}
7997 	}
7998 
7999 	if (s)
8000 		PF_STATE_UNLOCK(s);
8001 
8002 	if (ifp == NULL)
8003 		goto bad;
8004 
8005 	if (pd->dir == PF_IN) {
8006 		if (pf_test(AF_INET6, PF_OUT, PFIL_FWD, ifp, &m0, inp,
8007 		    &pd->act) != PF_PASS)
8008 			goto bad;
8009 		else if (m0 == NULL)
8010 			goto done;
8011 		if (m0->m_len < sizeof(struct ip6_hdr)) {
8012 			DPFPRINTF(PF_DEBUG_URGENT,
8013 			    ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
8014 			    __func__));
8015 			goto bad;
8016 		}
8017 		ip6 = mtod(m0, struct ip6_hdr *);
8018 	}
8019 
8020 	if (ifp->if_flags & IFF_LOOPBACK)
8021 		m0->m_flags |= M_SKIP_FIREWALL;
8022 
8023 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
8024 	    ~ifp->if_hwassist) {
8025 		uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
8026 		in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
8027 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
8028 	}
8029 
8030 	/*
8031 	 * If the packet is too large for the outgoing interface,
8032 	 * send back an icmp6 error.
8033 	 */
8034 	if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
8035 		dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
8036 	if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu) {
8037 		md = m0;
8038 		pf_dummynet_route(pd, s, r, ifp, sintosa(&dst), &md);
8039 		if (md != NULL)
8040 			nd6_output_ifp(ifp, ifp, md, &dst, NULL);
8041 	}
8042 	else {
8043 		in6_ifstat_inc(ifp, ifs6_in_toobig);
8044 		if (r_rt != PF_DUPTO) {
8045 			if (s && s->nat_rule != NULL)
8046 				PACKET_UNDO_NAT(m0, pd,
8047 				    ((caddr_t)ip6 - m0->m_data) +
8048 				    sizeof(struct ip6_hdr), s);
8049 
8050 			icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
8051 		} else
8052 			goto bad;
8053 	}
8054 
8055 done:
8056 	if (r_rt != PF_DUPTO)
8057 		*m = NULL;
8058 	return;
8059 
8060 bad_locked:
8061 	if (s)
8062 		PF_STATE_UNLOCK(s);
8063 bad:
8064 	m_freem(m0);
8065 	goto done;
8066 }
8067 #endif /* INET6 */
8068 
8069 /*
8070  * FreeBSD supports cksum offloads for the following drivers.
8071  *  em(4), fxp(4), lge(4), nge(4), re(4), ti(4), txp(4), xl(4)
8072  *
8073  * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
8074  *  network driver performed cksum including pseudo header, need to verify
8075  *   csum_data
8076  * CSUM_DATA_VALID :
8077  *  network driver performed cksum, needs to additional pseudo header
8078  *  cksum computation with partial csum_data(i.e. lack of H/W support for
8079  *  pseudo header, for instance sk(4) and possibly gem(4))
8080  *
8081  * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
8082  * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
8083  * TCP/UDP layer.
8084  * Also, set csum_data to 0xffff to force cksum validation.
8085  */
8086 static int
8087 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
8088 {
8089 	u_int16_t sum = 0;
8090 	int hw_assist = 0;
8091 	struct ip *ip;
8092 
8093 	if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
8094 		return (1);
8095 	if (m->m_pkthdr.len < off + len)
8096 		return (1);
8097 
8098 	switch (p) {
8099 	case IPPROTO_TCP:
8100 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
8101 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
8102 				sum = m->m_pkthdr.csum_data;
8103 			} else {
8104 				ip = mtod(m, struct ip *);
8105 				sum = in_pseudo(ip->ip_src.s_addr,
8106 				ip->ip_dst.s_addr, htonl((u_short)len +
8107 				m->m_pkthdr.csum_data + IPPROTO_TCP));
8108 			}
8109 			sum ^= 0xffff;
8110 			++hw_assist;
8111 		}
8112 		break;
8113 	case IPPROTO_UDP:
8114 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
8115 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
8116 				sum = m->m_pkthdr.csum_data;
8117 			} else {
8118 				ip = mtod(m, struct ip *);
8119 				sum = in_pseudo(ip->ip_src.s_addr,
8120 				ip->ip_dst.s_addr, htonl((u_short)len +
8121 				m->m_pkthdr.csum_data + IPPROTO_UDP));
8122 			}
8123 			sum ^= 0xffff;
8124 			++hw_assist;
8125 		}
8126 		break;
8127 	case IPPROTO_ICMP:
8128 #ifdef INET6
8129 	case IPPROTO_ICMPV6:
8130 #endif /* INET6 */
8131 		break;
8132 	default:
8133 		return (1);
8134 	}
8135 
8136 	if (!hw_assist) {
8137 		switch (af) {
8138 		case AF_INET:
8139 			if (p == IPPROTO_ICMP) {
8140 				if (m->m_len < off)
8141 					return (1);
8142 				m->m_data += off;
8143 				m->m_len -= off;
8144 				sum = in_cksum(m, len);
8145 				m->m_data -= off;
8146 				m->m_len += off;
8147 			} else {
8148 				if (m->m_len < sizeof(struct ip))
8149 					return (1);
8150 				sum = in4_cksum(m, p, off, len);
8151 			}
8152 			break;
8153 #ifdef INET6
8154 		case AF_INET6:
8155 			if (m->m_len < sizeof(struct ip6_hdr))
8156 				return (1);
8157 			sum = in6_cksum(m, p, off, len);
8158 			break;
8159 #endif /* INET6 */
8160 		}
8161 	}
8162 	if (sum) {
8163 		switch (p) {
8164 		case IPPROTO_TCP:
8165 		    {
8166 			KMOD_TCPSTAT_INC(tcps_rcvbadsum);
8167 			break;
8168 		    }
8169 		case IPPROTO_UDP:
8170 		    {
8171 			KMOD_UDPSTAT_INC(udps_badsum);
8172 			break;
8173 		    }
8174 #ifdef INET
8175 		case IPPROTO_ICMP:
8176 		    {
8177 			KMOD_ICMPSTAT_INC(icps_checksum);
8178 			break;
8179 		    }
8180 #endif
8181 #ifdef INET6
8182 		case IPPROTO_ICMPV6:
8183 		    {
8184 			KMOD_ICMP6STAT_INC(icp6s_checksum);
8185 			break;
8186 		    }
8187 #endif /* INET6 */
8188 		}
8189 		return (1);
8190 	} else {
8191 		if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
8192 			m->m_pkthdr.csum_flags |=
8193 			    (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
8194 			m->m_pkthdr.csum_data = 0xffff;
8195 		}
8196 	}
8197 	return (0);
8198 }
8199 
8200 static bool
8201 pf_pdesc_to_dnflow(const struct pf_pdesc *pd, const struct pf_krule *r,
8202     const struct pf_kstate *s, struct ip_fw_args *dnflow)
8203 {
8204 	int dndir = r->direction;
8205 
8206 	if (s && dndir == PF_INOUT) {
8207 		dndir = s->direction;
8208 	} else if (dndir == PF_INOUT) {
8209 		/* Assume primary direction. Happens when we've set dnpipe in
8210 		 * the ethernet level code. */
8211 		dndir = pd->dir;
8212 	}
8213 
8214 	if (pd->pf_mtag->flags & PF_MTAG_FLAG_DUMMYNETED)
8215 		return (false);
8216 
8217 	memset(dnflow, 0, sizeof(*dnflow));
8218 
8219 	if (pd->dport != NULL)
8220 		dnflow->f_id.dst_port = ntohs(*pd->dport);
8221 	if (pd->sport != NULL)
8222 		dnflow->f_id.src_port = ntohs(*pd->sport);
8223 
8224 	if (pd->dir == PF_IN)
8225 		dnflow->flags |= IPFW_ARGS_IN;
8226 	else
8227 		dnflow->flags |= IPFW_ARGS_OUT;
8228 
8229 	if (pd->dir != dndir && pd->act.dnrpipe) {
8230 		dnflow->rule.info = pd->act.dnrpipe;
8231 	}
8232 	else if (pd->dir == dndir && pd->act.dnpipe) {
8233 		dnflow->rule.info = pd->act.dnpipe;
8234 	}
8235 	else {
8236 		return (false);
8237 	}
8238 
8239 	dnflow->rule.info |= IPFW_IS_DUMMYNET;
8240 	if (r->free_flags & PFRULE_DN_IS_PIPE || pd->act.flags & PFSTATE_DN_IS_PIPE)
8241 		dnflow->rule.info |= IPFW_IS_PIPE;
8242 
8243 	dnflow->f_id.proto = pd->proto;
8244 	dnflow->f_id.extra = dnflow->rule.info;
8245 	switch (pd->af) {
8246 	case AF_INET:
8247 		dnflow->f_id.addr_type = 4;
8248 		dnflow->f_id.src_ip = ntohl(pd->src->v4.s_addr);
8249 		dnflow->f_id.dst_ip = ntohl(pd->dst->v4.s_addr);
8250 		break;
8251 	case AF_INET6:
8252 		dnflow->flags |= IPFW_ARGS_IP6;
8253 		dnflow->f_id.addr_type = 6;
8254 		dnflow->f_id.src_ip6 = pd->src->v6;
8255 		dnflow->f_id.dst_ip6 = pd->dst->v6;
8256 		break;
8257 	}
8258 
8259 	return (true);
8260 }
8261 
8262 int
8263 pf_test_eth(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0,
8264     struct inpcb *inp)
8265 {
8266 	struct pfi_kkif		*kif;
8267 	struct mbuf		*m = *m0;
8268 
8269 	M_ASSERTPKTHDR(m);
8270 	MPASS(ifp->if_vnet == curvnet);
8271 	NET_EPOCH_ASSERT();
8272 
8273 	if (!V_pf_status.running)
8274 		return (PF_PASS);
8275 
8276 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
8277 
8278 	if (kif == NULL) {
8279 		DPFPRINTF(PF_DEBUG_URGENT,
8280 		    ("%s: kif == NULL, if_xname %s\n", __func__, ifp->if_xname));
8281 		return (PF_DROP);
8282 	}
8283 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
8284 		return (PF_PASS);
8285 
8286 	if (m->m_flags & M_SKIP_FIREWALL)
8287 		return (PF_PASS);
8288 
8289 	if (__predict_false(! M_WRITABLE(*m0))) {
8290 		m = *m0 = m_unshare(*m0, M_NOWAIT);
8291 		if (*m0 == NULL)
8292 			return (PF_DROP);
8293 	}
8294 
8295 	/* Stateless! */
8296 	return (pf_test_eth_rule(dir, kif, m0));
8297 }
8298 
8299 static __inline void
8300 pf_dummynet_flag_remove(struct mbuf *m, struct pf_mtag *pf_mtag)
8301 {
8302 	struct m_tag *mtag;
8303 
8304 	pf_mtag->flags &= ~PF_MTAG_FLAG_DUMMYNET;
8305 
8306 	/* dummynet adds this tag, but pf does not need it,
8307 	 * and keeping it creates unexpected behavior,
8308 	 * e.g. in case of divert(4) usage right after dummynet. */
8309 	mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
8310 	if (mtag != NULL)
8311 		m_tag_delete(m, mtag);
8312 }
8313 
8314 static int
8315 pf_dummynet(struct pf_pdesc *pd, struct pf_kstate *s,
8316     struct pf_krule *r, struct mbuf **m0)
8317 {
8318 	return (pf_dummynet_route(pd, s, r, NULL, NULL, m0));
8319 }
8320 
8321 static int
8322 pf_dummynet_route(struct pf_pdesc *pd, struct pf_kstate *s,
8323     struct pf_krule *r, struct ifnet *ifp, struct sockaddr *sa,
8324     struct mbuf **m0)
8325 {
8326 	NET_EPOCH_ASSERT();
8327 
8328 	if (pd->act.dnpipe || pd->act.dnrpipe) {
8329 		struct ip_fw_args dnflow;
8330 		if (ip_dn_io_ptr == NULL) {
8331 			m_freem(*m0);
8332 			*m0 = NULL;
8333 			return (ENOMEM);
8334 		}
8335 
8336 		if (pd->pf_mtag == NULL &&
8337 		    ((pd->pf_mtag = pf_get_mtag(*m0)) == NULL)) {
8338 			m_freem(*m0);
8339 			*m0 = NULL;
8340 			return (ENOMEM);
8341 		}
8342 
8343 		if (ifp != NULL) {
8344 			pd->pf_mtag->flags |= PF_MTAG_FLAG_ROUTE_TO;
8345 
8346 			pd->pf_mtag->if_index = ifp->if_index;
8347 			pd->pf_mtag->if_idxgen = ifp->if_idxgen;
8348 
8349 			MPASS(sa != NULL);
8350 
8351 			switch (pd->af) {
8352 			case AF_INET:
8353 				memcpy(&pd->pf_mtag->dst, sa,
8354 				    sizeof(struct sockaddr_in));
8355 				break;
8356 			case AF_INET6:
8357 				memcpy(&pd->pf_mtag->dst, sa,
8358 				    sizeof(struct sockaddr_in6));
8359 				break;
8360 			}
8361 		}
8362 
8363 		if (s != NULL && s->nat_rule != NULL &&
8364 		    s->nat_rule->action == PF_RDR &&
8365 		    (
8366 #ifdef INET
8367 		    (pd->af == AF_INET && IN_LOOPBACK(ntohl(pd->dst->v4.s_addr))) ||
8368 #endif
8369 		    (pd->af == AF_INET6 && IN6_IS_ADDR_LOOPBACK(&pd->dst->v6)))) {
8370 			/*
8371 			 * If we're redirecting to loopback mark this packet
8372 			 * as being local. Otherwise it might get dropped
8373 			 * if dummynet re-injects.
8374 			 */
8375 			(*m0)->m_pkthdr.rcvif = V_loif;
8376 		}
8377 
8378 		if (pf_pdesc_to_dnflow(pd, r, s, &dnflow)) {
8379 			pd->pf_mtag->flags |= PF_MTAG_FLAG_DUMMYNET;
8380 			pd->pf_mtag->flags |= PF_MTAG_FLAG_DUMMYNETED;
8381 			ip_dn_io_ptr(m0, &dnflow);
8382 			if (*m0 != NULL) {
8383 				pd->pf_mtag->flags &= ~PF_MTAG_FLAG_ROUTE_TO;
8384 				pf_dummynet_flag_remove(*m0, pd->pf_mtag);
8385 			}
8386 		}
8387 	}
8388 
8389 	return (0);
8390 }
8391 
8392 #ifdef INET6
8393 static int
8394 pf_walk_option6(struct mbuf *m, int off, int end, uint32_t *jumbolen,
8395     u_short *reason)
8396 {
8397 	struct ip6_opt		 opt;
8398 	struct ip6_opt_jumbo	 jumbo;
8399 	struct ip6_hdr		*h = mtod(m, struct ip6_hdr *);
8400 
8401 	while (off < end) {
8402 		if (!pf_pull_hdr(m, off, &opt.ip6o_type, sizeof(opt.ip6o_type),
8403 			NULL, reason, AF_INET6)) {
8404 			DPFPRINTF(PF_DEBUG_MISC, ("IPv6 short opt type"));
8405 			return (PF_DROP);
8406 		}
8407 		if (opt.ip6o_type == IP6OPT_PAD1) {
8408 			off++;
8409 			continue;
8410 		}
8411 		if (!pf_pull_hdr(m, off, &opt, sizeof(opt), NULL, reason,
8412 			AF_INET6)) {
8413 			DPFPRINTF(PF_DEBUG_MISC, ("IPv6 short opt"));
8414 			return (PF_DROP);
8415 		}
8416 		if (off + sizeof(opt) + opt.ip6o_len > end) {
8417 			DPFPRINTF(PF_DEBUG_MISC, ("IPv6 long opt"));
8418 			REASON_SET(reason, PFRES_IPOPTIONS);
8419 			return (PF_DROP);
8420 		}
8421 		switch (opt.ip6o_type) {
8422 		case IP6OPT_JUMBO:
8423 			if (*jumbolen != 0) {
8424 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 multiple jumbo"));
8425 				REASON_SET(reason, PFRES_IPOPTIONS);
8426 				return (PF_DROP);
8427 			}
8428 			if (ntohs(h->ip6_plen) != 0) {
8429 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 bad jumbo plen"));
8430 				REASON_SET(reason, PFRES_IPOPTIONS);
8431 				return (PF_DROP);
8432 			}
8433 			if (!pf_pull_hdr(m, off, &jumbo, sizeof(jumbo), NULL,
8434 				reason, AF_INET6)) {
8435 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 short jumbo"));
8436 				return (PF_DROP);
8437 			}
8438 			memcpy(jumbolen, jumbo.ip6oj_jumbo_len,
8439 			    sizeof(*jumbolen));
8440 			*jumbolen = ntohl(*jumbolen);
8441 			if (*jumbolen < IPV6_MAXPACKET) {
8442 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 short jumbolen"));
8443 				REASON_SET(reason, PFRES_IPOPTIONS);
8444 				return (PF_DROP);
8445 			}
8446 			break;
8447 		default:
8448 			break;
8449 		}
8450 		off += sizeof(opt) + opt.ip6o_len;
8451 	}
8452 
8453 	return (PF_PASS);
8454 }
8455 
8456 int
8457 pf_walk_header6(struct mbuf *m, struct ip6_hdr *h, int *off, int *extoff,
8458     int *fragoff, uint8_t *nxt, uint32_t *jumbolen, u_short *reason)
8459 {
8460 	struct ip6_frag		 frag;
8461 	struct ip6_ext		 ext;
8462 	struct ip6_rthdr	 rthdr;
8463 	int			 rthdr_cnt = 0;
8464 
8465 	*off += sizeof(struct ip6_hdr);
8466 	*extoff = *fragoff = 0;
8467 	*nxt = h->ip6_nxt;
8468 	*jumbolen = 0;
8469 	for (;;) {
8470 		switch (*nxt) {
8471 		case IPPROTO_FRAGMENT:
8472 			if (*fragoff != 0) {
8473 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 multiple fragment"));
8474 				REASON_SET(reason, PFRES_FRAG);
8475 				return (PF_DROP);
8476 			}
8477 			/* jumbo payload packets cannot be fragmented */
8478 			if (*jumbolen != 0) {
8479 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 fragmented jumbo"));
8480 				REASON_SET(reason, PFRES_FRAG);
8481 				return (PF_DROP);
8482 			}
8483 			if (!pf_pull_hdr(m, *off, &frag, sizeof(frag), NULL,
8484 				reason, AF_INET6)) {
8485 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 short fragment"));
8486 				return (PF_DROP);
8487 			}
8488 			*fragoff = *off;
8489 			/* stop walking over non initial fragments */
8490 			if ((frag.ip6f_offlg & IP6F_OFF_MASK) != 0)
8491 				return (PF_PASS);
8492 			*off += sizeof(frag);
8493 			*nxt = frag.ip6f_nxt;
8494 			break;
8495 		case IPPROTO_ROUTING:
8496 			if (rthdr_cnt++) {
8497 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 multiple rthdr"));
8498 				REASON_SET(reason, PFRES_IPOPTIONS);
8499 				return (PF_DROP);
8500 			}
8501 			if (!pf_pull_hdr(m, *off, &rthdr, sizeof(rthdr), NULL,
8502 				reason, AF_INET6)) {
8503 				/* fragments may be short */
8504 				if (*fragoff != 0) {
8505 					*off = *fragoff;
8506 					*nxt = IPPROTO_FRAGMENT;
8507 					return (PF_PASS);
8508 				}
8509 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 short rthdr"));
8510 				return (PF_DROP);
8511 			}
8512 			if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
8513 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 rthdr0"));
8514 				REASON_SET(reason, PFRES_IPOPTIONS);
8515 				return (PF_DROP);
8516 			}
8517 			/* FALLTHROUGH */
8518 		case IPPROTO_AH:
8519 		case IPPROTO_HOPOPTS:
8520 		case IPPROTO_DSTOPTS:
8521 			if (!pf_pull_hdr(m, *off, &ext, sizeof(ext), NULL,
8522 				reason, AF_INET6)) {
8523 				/* fragments may be short */
8524 				if (*fragoff != 0) {
8525 					*off = *fragoff;
8526 					*nxt = IPPROTO_FRAGMENT;
8527 					return (PF_PASS);
8528 				}
8529 				DPFPRINTF(PF_DEBUG_MISC, ("IPv6 short exthdr"));
8530 				return (PF_DROP);
8531 			}
8532 			/* reassembly needs the ext header before the frag */
8533 			if (*fragoff == 0)
8534 				*extoff = *off;
8535 			if (*nxt == IPPROTO_HOPOPTS && *fragoff == 0) {
8536 				if (pf_walk_option6(m, *off + sizeof(ext),
8537 					*off + (ext.ip6e_len + 1) * 8, jumbolen,
8538 					reason) != PF_PASS)
8539 					return (PF_DROP);
8540 				if (ntohs(h->ip6_plen) == 0 && *jumbolen != 0) {
8541 					DPFPRINTF(PF_DEBUG_MISC,
8542 					    ("IPv6 missing jumbo"));
8543 					REASON_SET(reason, PFRES_IPOPTIONS);
8544 					return (PF_DROP);
8545 				}
8546 			}
8547 			if (*nxt == IPPROTO_AH)
8548 				*off += (ext.ip6e_len + 2) * 4;
8549 			else
8550 				*off += (ext.ip6e_len + 1) * 8;
8551 			*nxt = ext.ip6e_nxt;
8552 			break;
8553 		case IPPROTO_TCP:
8554 		case IPPROTO_UDP:
8555 		case IPPROTO_SCTP:
8556 		case IPPROTO_ICMPV6:
8557 			/* fragments may be short, ignore inner header then */
8558 			if (*fragoff != 0 && ntohs(h->ip6_plen) < *off +
8559 			    (*nxt == IPPROTO_TCP ? sizeof(struct tcphdr) :
8560 			    *nxt == IPPROTO_UDP ? sizeof(struct udphdr) :
8561 			    *nxt == IPPROTO_SCTP ? sizeof(struct sctphdr) :
8562 			    sizeof(struct icmp6_hdr))) {
8563 				*off = *fragoff;
8564 				*nxt = IPPROTO_FRAGMENT;
8565 			}
8566 			/* FALLTHROUGH */
8567 		default:
8568 			return (PF_PASS);
8569 		}
8570 	}
8571 }
8572 #endif
8573 
8574 static void
8575 pf_init_pdesc(struct pf_pdesc *pd, struct mbuf *m)
8576 {
8577 	memset(pd, 0, sizeof(*pd));
8578 	pd->pf_mtag = pf_find_mtag(m);
8579 	pd->m = m;
8580 }
8581 
8582 static int
8583 pf_setup_pdesc(sa_family_t af, int dir, struct pf_pdesc *pd, struct mbuf **m0,
8584     u_short *action, u_short *reason, struct pfi_kkif *kif,
8585     struct pf_rule_actions *default_actions)
8586 {
8587 	pd->af = af;
8588 	pd->dir = dir;
8589 	pd->kif = kif;
8590 	pd->m = *m0;
8591 	pd->sidx = (dir == PF_IN) ? 0 : 1;
8592 	pd->didx = (dir == PF_IN) ? 1 : 0;
8593 
8594 	TAILQ_INIT(&pd->sctp_multihome_jobs);
8595 	if (default_actions != NULL)
8596 		memcpy(&pd->act, default_actions, sizeof(pd->act));
8597 
8598 	if (pd->pf_mtag && pd->pf_mtag->dnpipe) {
8599 		pd->act.dnpipe = pd->pf_mtag->dnpipe;
8600 		pd->act.flags = pd->pf_mtag->dnflags;
8601 	}
8602 
8603 	switch (af) {
8604 #ifdef INET
8605 	case AF_INET: {
8606 		struct ip *h;
8607 
8608 		if (__predict_false((*m0)->m_len < sizeof(struct ip)) &&
8609 		    (pd->m = *m0 = m_pullup(*m0, sizeof(struct ip))) == NULL) {
8610 			DPFPRINTF(PF_DEBUG_URGENT,
8611 			    ("pf_test: m_len < sizeof(struct ip), pullup failed\n"));
8612 			*action = PF_DROP;
8613 			REASON_SET(reason, PFRES_SHORT);
8614 			return (-1);
8615 		}
8616 
8617 		if (pf_normalize_ip(m0, reason, pd) != PF_PASS) {
8618 			/* We do IP header normalization and packet reassembly here */
8619 			*action = PF_DROP;
8620 			return (-1);
8621 		}
8622 		pd->m = *m0;
8623 
8624 		h = mtod(pd->m, struct ip *);
8625 		pd->off = h->ip_hl << 2;
8626 		if (pd->off < (int)sizeof(*h)) {
8627 			*action = PF_DROP;
8628 			REASON_SET(reason, PFRES_SHORT);
8629 			return (-1);
8630 		}
8631 		pd->src = (struct pf_addr *)&h->ip_src;
8632 		pd->dst = (struct pf_addr *)&h->ip_dst;
8633 		pd->ip_sum = &h->ip_sum;
8634 		pd->proto_sum = NULL;
8635 		pd->virtual_proto = pd->proto = h->ip_p;
8636 		pd->tos = h->ip_tos;
8637 		pd->ttl = h->ip_ttl;
8638 		pd->tot_len = ntohs(h->ip_len);
8639 		pd->act.rtableid = -1;
8640 
8641 		if (h->ip_hl > 5)	/* has options */
8642 			pd->badopts++;
8643 
8644 		if (h->ip_off & htons(IP_MF | IP_OFFMASK))
8645 			pd->virtual_proto = PF_VPROTO_FRAGMENT;
8646 
8647 		break;
8648 	}
8649 #endif
8650 #ifdef INET6
8651 	case AF_INET6: {
8652 		struct ip6_hdr *h;
8653 		int fragoff;
8654 		uint32_t jumbolen;
8655 		uint8_t nxt;
8656 
8657 		if (__predict_false((*m0)->m_len < sizeof(struct ip6_hdr)) &&
8658 		    (pd->m = *m0 = m_pullup(*m0, sizeof(struct ip6_hdr))) == NULL) {
8659 			DPFPRINTF(PF_DEBUG_URGENT,
8660 			    ("pf_test6: m_len < sizeof(struct ip6_hdr)"
8661 			     ", pullup failed\n"));
8662 			*action = PF_DROP;
8663 			REASON_SET(reason, PFRES_SHORT);
8664 			return (-1);
8665 		}
8666 
8667 		h = mtod(pd->m, struct ip6_hdr *);
8668 		pd->off = 0;
8669 		if (pf_walk_header6(pd->m, h, &pd->off, &pd->extoff, &fragoff, &nxt,
8670 		    &jumbolen, reason) != PF_PASS) {
8671 			*action = PF_DROP;
8672 			return (-1);
8673 		}
8674 
8675 		h = mtod(pd->m, struct ip6_hdr *);
8676 		pd->src = (struct pf_addr *)&h->ip6_src;
8677 		pd->dst = (struct pf_addr *)&h->ip6_dst;
8678 		pd->ip_sum = NULL;
8679 		pd->proto_sum = NULL;
8680 		pd->tos = IPV6_DSCP(h);
8681 		pd->ttl = h->ip6_hlim;
8682 		pd->tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
8683 		pd->virtual_proto = pd->proto = h->ip6_nxt;
8684 		pd->act.rtableid = -1;
8685 
8686 		if (fragoff != 0)
8687 			pd->virtual_proto = PF_VPROTO_FRAGMENT;
8688 
8689 		/*
8690 		 * we do not support jumbogram.  if we keep going, zero ip6_plen
8691 		 * will do something bad, so drop the packet for now.
8692 		 */
8693 		if (htons(h->ip6_plen) == 0) {
8694 			*action = PF_DROP;
8695 			return (-1);
8696 		}
8697 
8698 		/* We do IP header normalization and packet reassembly here */
8699 		if (pf_normalize_ip6(m0, fragoff, reason, pd) !=
8700 		    PF_PASS) {
8701 			*action = PF_DROP;
8702 			return (-1);
8703 		}
8704 		pd->m = *m0;
8705 		if (pd->m == NULL) {
8706 			/* packet sits in reassembly queue, no error */
8707 			*action = PF_PASS;
8708 			return (-1);
8709 		}
8710 
8711 		/*
8712 		 * Reassembly may have changed the next protocol from fragment
8713 		 * to something else, so update.
8714 		 */
8715 		h = mtod(pd->m, struct ip6_hdr *);
8716 		pd->virtual_proto = pd->proto = h->ip6_nxt;
8717 		pd->off = 0;
8718 
8719 		if (pf_walk_header6(pd->m, h, &pd->off, &pd->extoff, &fragoff, &nxt,
8720 			&jumbolen, reason) != PF_PASS) {
8721 			*action = PF_DROP;
8722 			return (-1);
8723 		}
8724 
8725 		if (fragoff != 0)
8726 			pd->virtual_proto = PF_VPROTO_FRAGMENT;
8727 
8728 		break;
8729 	}
8730 #endif
8731 	default:
8732 		panic("pf_setup_pdesc called with illegal af %u", af);
8733 	}
8734 
8735 	switch (pd->virtual_proto) {
8736 	case IPPROTO_TCP: {
8737 		struct tcphdr *th = &pd->hdr.tcp;
8738 
8739 		if (!pf_pull_hdr(pd->m, pd->off, th, sizeof(*th), action,
8740 			reason, af)) {
8741 			*action = PF_DROP;
8742 			REASON_SET(reason, PFRES_SHORT);
8743 			return (-1);
8744 		}
8745 		pd->hdrlen = sizeof(*th);
8746 		pd->p_len = pd->tot_len - pd->off - (th->th_off << 2);
8747 		pd->sport = &th->th_sport;
8748 		pd->dport = &th->th_dport;
8749 		break;
8750 	}
8751 	case IPPROTO_UDP: {
8752 		struct udphdr *uh = &pd->hdr.udp;
8753 
8754 		if (!pf_pull_hdr(pd->m, pd->off, uh, sizeof(*uh), action,
8755 			reason, af)) {
8756 			*action = PF_DROP;
8757 			REASON_SET(reason, PFRES_SHORT);
8758 			return (-1);
8759 		}
8760 		pd->hdrlen = sizeof(*uh);
8761 		if (uh->uh_dport == 0 ||
8762 		    ntohs(uh->uh_ulen) > pd->m->m_pkthdr.len - pd->off ||
8763 		    ntohs(uh->uh_ulen) < sizeof(struct udphdr)) {
8764 			*action = PF_DROP;
8765 			REASON_SET(reason, PFRES_SHORT);
8766 			return (-1);
8767 		}
8768 		pd->sport = &uh->uh_sport;
8769 		pd->dport = &uh->uh_dport;
8770 		break;
8771 	}
8772 	case IPPROTO_SCTP: {
8773 		if (!pf_pull_hdr(pd->m, pd->off, &pd->hdr.sctp, sizeof(pd->hdr.sctp),
8774 		    action, reason, af)) {
8775 			*action = PF_DROP;
8776 			REASON_SET(reason, PFRES_SHORT);
8777 			return (-1);
8778 		}
8779 		pd->hdrlen = sizeof(pd->hdr.sctp);
8780 		pd->p_len = pd->tot_len - pd->off;
8781 
8782 		pd->sport = &pd->hdr.sctp.src_port;
8783 		pd->dport = &pd->hdr.sctp.dest_port;
8784 		if (pd->hdr.sctp.src_port == 0 || pd->hdr.sctp.dest_port == 0) {
8785 			*action = PF_DROP;
8786 			REASON_SET(reason, PFRES_SHORT);
8787 			return (-1);
8788 		}
8789 		if (pf_scan_sctp(pd) != PF_PASS) {
8790 			*action = PF_DROP;
8791 			REASON_SET(reason, PFRES_SHORT);
8792 			return (-1);
8793 		}
8794 		break;
8795 	}
8796 	case IPPROTO_ICMP: {
8797 		if (!pf_pull_hdr(pd->m, pd->off, &pd->hdr.icmp, ICMP_MINLEN,
8798 			action, reason, af)) {
8799 			*action = PF_DROP;
8800 			REASON_SET(reason, PFRES_SHORT);
8801 			return (-1);
8802 		}
8803 		pd->hdrlen = ICMP_MINLEN;
8804 		break;
8805 	}
8806 #ifdef INET6
8807 	case IPPROTO_ICMPV6: {
8808 		size_t icmp_hlen = sizeof(struct icmp6_hdr);
8809 
8810 		if (!pf_pull_hdr(pd->m, pd->off, &pd->hdr.icmp6, icmp_hlen,
8811 			action, reason, af)) {
8812 			*action = PF_DROP;
8813 			REASON_SET(reason, PFRES_SHORT);
8814 			return (-1);
8815 		}
8816 		/* ICMP headers we look further into to match state */
8817 		switch (pd->hdr.icmp6.icmp6_type) {
8818 		case MLD_LISTENER_QUERY:
8819 		case MLD_LISTENER_REPORT:
8820 			icmp_hlen = sizeof(struct mld_hdr);
8821 			break;
8822 		case ND_NEIGHBOR_SOLICIT:
8823 		case ND_NEIGHBOR_ADVERT:
8824 			icmp_hlen = sizeof(struct nd_neighbor_solicit);
8825 			break;
8826 		}
8827 		if (icmp_hlen > sizeof(struct icmp6_hdr) &&
8828 		    !pf_pull_hdr(pd->m, pd->off, &pd->hdr.icmp6, icmp_hlen,
8829 			action, reason, af)) {
8830 			*action = PF_DROP;
8831 			REASON_SET(reason, PFRES_SHORT);
8832 			return (-1);
8833 		}
8834 		pd->hdrlen = icmp_hlen;
8835 		break;
8836 	}
8837 #endif
8838 	}
8839 	return (0);
8840 }
8841 
8842 static void
8843 pf_counters_inc(int action, struct pf_pdesc *pd,
8844     struct pf_kstate *s, struct pf_krule *r, struct pf_krule *a)
8845 {
8846 	struct pf_krule		*tr;
8847 	int			 dir = pd->dir;
8848 	int			 dirndx;
8849 
8850 	pf_counter_u64_critical_enter();
8851 	pf_counter_u64_add_protected(
8852 	    &pd->kif->pfik_bytes[pd->af == AF_INET6][dir == PF_OUT][action != PF_PASS],
8853 	    pd->tot_len);
8854 	pf_counter_u64_add_protected(
8855 	    &pd->kif->pfik_packets[pd->af == AF_INET6][dir == PF_OUT][action != PF_PASS],
8856 	    1);
8857 
8858 	if (action == PF_PASS || r->action == PF_DROP) {
8859 		dirndx = (dir == PF_OUT);
8860 		pf_counter_u64_add_protected(&r->packets[dirndx], 1);
8861 		pf_counter_u64_add_protected(&r->bytes[dirndx], pd->tot_len);
8862 		pf_update_timestamp(r);
8863 
8864 		if (a != NULL) {
8865 			pf_counter_u64_add_protected(&a->packets[dirndx], 1);
8866 			pf_counter_u64_add_protected(&a->bytes[dirndx], pd->tot_len);
8867 		}
8868 		if (s != NULL) {
8869 			struct pf_krule_item	*ri;
8870 
8871 			if (s->nat_rule != NULL) {
8872 				pf_counter_u64_add_protected(&s->nat_rule->packets[dirndx],
8873 				    1);
8874 				pf_counter_u64_add_protected(&s->nat_rule->bytes[dirndx],
8875 				    pd->tot_len);
8876 			}
8877 			if (s->src_node != NULL) {
8878 				counter_u64_add(s->src_node->packets[dirndx],
8879 				    1);
8880 				counter_u64_add(s->src_node->bytes[dirndx],
8881 				    pd->tot_len);
8882 			}
8883 			if (s->nat_src_node != NULL) {
8884 				counter_u64_add(s->nat_src_node->packets[dirndx],
8885 				    1);
8886 				counter_u64_add(s->nat_src_node->bytes[dirndx],
8887 				    pd->tot_len);
8888 			}
8889 			dirndx = (dir == s->direction) ? 0 : 1;
8890 			s->packets[dirndx]++;
8891 			s->bytes[dirndx] += pd->tot_len;
8892 
8893 			SLIST_FOREACH(ri, &s->match_rules, entry) {
8894 				pf_counter_u64_add_protected(&ri->r->packets[dirndx], 1);
8895 				pf_counter_u64_add_protected(&ri->r->bytes[dirndx], pd->tot_len);
8896 			}
8897 		}
8898 
8899 		tr = r;
8900 		if (s != NULL && s->nat_rule != NULL &&
8901 		    r == &V_pf_default_rule)
8902 			tr = s->nat_rule;
8903 
8904 		if (tr->src.addr.type == PF_ADDR_TABLE)
8905 			pfr_update_stats(tr->src.addr.p.tbl,
8906 			    (s == NULL) ? pd->src :
8907 			    &s->key[(s->direction == PF_IN)]->
8908 				addr[(s->direction == PF_OUT)],
8909 			    pd->af, pd->tot_len, dir == PF_OUT,
8910 			    r->action == PF_PASS, tr->src.neg);
8911 		if (tr->dst.addr.type == PF_ADDR_TABLE)
8912 			pfr_update_stats(tr->dst.addr.p.tbl,
8913 			    (s == NULL) ? pd->dst :
8914 			    &s->key[(s->direction == PF_IN)]->
8915 				addr[(s->direction == PF_IN)],
8916 			    pd->af, pd->tot_len, dir == PF_OUT,
8917 			    r->action == PF_PASS, tr->dst.neg);
8918 	}
8919 	pf_counter_u64_critical_exit();
8920 }
8921 
8922 #if defined(INET) || defined(INET6)
8923 int
8924 pf_test(sa_family_t af, int dir, int pflags, struct ifnet *ifp, struct mbuf **m0,
8925     struct inpcb *inp, struct pf_rule_actions *default_actions)
8926 {
8927 	struct pfi_kkif		*kif;
8928 	u_short			 action, reason = 0;
8929 	struct m_tag		*mtag;
8930 	struct pf_krule		*a = NULL, *r = &V_pf_default_rule;
8931 	struct pf_kstate	*s = NULL;
8932 	struct pf_kruleset	*ruleset = NULL;
8933 	struct pf_pdesc		 pd;
8934 	int			 use_2nd_queue = 0;
8935 	uint16_t		 tag;
8936 	uint8_t			 rt;
8937 
8938 	PF_RULES_RLOCK_TRACKER;
8939 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: bad direction %d\n", __func__, dir));
8940 	M_ASSERTPKTHDR(*m0);
8941 
8942 	if (!V_pf_status.running)
8943 		return (PF_PASS);
8944 
8945 	PF_RULES_RLOCK();
8946 
8947 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
8948 
8949 	if (__predict_false(kif == NULL)) {
8950 		DPFPRINTF(PF_DEBUG_URGENT,
8951 		    ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
8952 		PF_RULES_RUNLOCK();
8953 		return (PF_DROP);
8954 	}
8955 	if (kif->pfik_flags & PFI_IFLAG_SKIP) {
8956 		PF_RULES_RUNLOCK();
8957 		return (PF_PASS);
8958 	}
8959 
8960 	if ((*m0)->m_flags & M_SKIP_FIREWALL) {
8961 		PF_RULES_RUNLOCK();
8962 		return (PF_PASS);
8963 	}
8964 
8965 #ifdef INET6
8966 	/*
8967 	 * If we end up changing IP addresses (e.g. binat) the stack may get
8968 	 * confused and fail to send the icmp6 packet too big error. Just send
8969 	 * it here, before we do any NAT.
8970 	 */
8971 	if (af == AF_INET6 && dir == PF_OUT && pflags & PFIL_FWD &&
8972 	    IN6_LINKMTU(ifp) < pf_max_frag_size(*m0)) {
8973 		PF_RULES_RUNLOCK();
8974 		icmp6_error(*m0, ICMP6_PACKET_TOO_BIG, 0, IN6_LINKMTU(ifp));
8975 		*m0 = NULL;
8976 		return (PF_DROP);
8977 	}
8978 #endif
8979 
8980 	if (__predict_false(! M_WRITABLE(*m0))) {
8981 		*m0 = m_unshare(*m0, M_NOWAIT);
8982 		if (*m0 == NULL)
8983 			return (PF_DROP);
8984 	}
8985 
8986 	pf_init_pdesc(&pd, *m0);
8987 
8988 	if (pd.pf_mtag != NULL && (pd.pf_mtag->flags & PF_MTAG_FLAG_ROUTE_TO)) {
8989 		pd.pf_mtag->flags &= ~PF_MTAG_FLAG_ROUTE_TO;
8990 
8991 		ifp = ifnet_byindexgen(pd.pf_mtag->if_index,
8992 		    pd.pf_mtag->if_idxgen);
8993 		if (ifp == NULL || ifp->if_flags & IFF_DYING) {
8994 			PF_RULES_RUNLOCK();
8995 			m_freem(*m0);
8996 			*m0 = NULL;
8997 			return (PF_PASS);
8998 		}
8999 		PF_RULES_RUNLOCK();
9000 		(ifp->if_output)(ifp, *m0, sintosa(&pd.pf_mtag->dst), NULL);
9001 		*m0 = NULL;
9002 		return (PF_PASS);
9003 	}
9004 
9005 	if (ip_dn_io_ptr != NULL && pd.pf_mtag != NULL &&
9006 	    pd.pf_mtag->flags & PF_MTAG_FLAG_DUMMYNET) {
9007 		/* Dummynet re-injects packets after they've
9008 		 * completed their delay. We've already
9009 		 * processed them, so pass unconditionally. */
9010 
9011 		/* But only once. We may see the packet multiple times (e.g.
9012 		 * PFIL_IN/PFIL_OUT). */
9013 		pf_dummynet_flag_remove(pd.m, pd.pf_mtag);
9014 		PF_RULES_RUNLOCK();
9015 
9016 		return (PF_PASS);
9017 	}
9018 
9019 	if (pf_setup_pdesc(af, dir, &pd, m0, &action, &reason,
9020 		kif, default_actions) == -1) {
9021 		if (action != PF_PASS)
9022 			pd.act.log |= PF_LOG_FORCE;
9023 		goto done;
9024 	}
9025 
9026 	if (__predict_false(ip_divert_ptr != NULL) &&
9027 	    ((mtag = m_tag_locate(pd.m, MTAG_PF_DIVERT, 0, NULL)) != NULL)) {
9028 		struct pf_divert_mtag *dt = (struct pf_divert_mtag *)(mtag+1);
9029 		if ((dt->idir == PF_DIVERT_MTAG_DIR_IN && dir == PF_IN) ||
9030 		    (dt->idir == PF_DIVERT_MTAG_DIR_OUT && dir == PF_OUT)) {
9031 			if (pd.pf_mtag == NULL &&
9032 			    ((pd.pf_mtag = pf_get_mtag(pd.m)) == NULL)) {
9033 				action = PF_DROP;
9034 				goto done;
9035 			}
9036 			pd.pf_mtag->flags |= PF_MTAG_FLAG_PACKET_LOOPED;
9037 		}
9038 		if (pd.pf_mtag && pd.pf_mtag->flags & PF_MTAG_FLAG_FASTFWD_OURS_PRESENT) {
9039 			pd.m->m_flags |= M_FASTFWD_OURS;
9040 			pd.pf_mtag->flags &= ~PF_MTAG_FLAG_FASTFWD_OURS_PRESENT;
9041 		}
9042 		m_tag_delete(pd.m, mtag);
9043 
9044 		mtag = m_tag_locate(pd.m, MTAG_IPFW_RULE, 0, NULL);
9045 		if (mtag != NULL)
9046 			m_tag_delete(pd.m, mtag);
9047 	}
9048 
9049 	switch (pd.virtual_proto) {
9050 	case PF_VPROTO_FRAGMENT:
9051 		/*
9052 		 * handle fragments that aren't reassembled by
9053 		 * normalization
9054 		 */
9055 		if (kif == NULL || r == NULL) /* pflog */
9056 			action = PF_DROP;
9057 		else
9058 			action = pf_test_rule(&r, &s, &pd, &a,
9059 			    &ruleset, inp);
9060 		if (action != PF_PASS)
9061 			REASON_SET(&reason, PFRES_FRAG);
9062 		break;
9063 
9064 	case IPPROTO_TCP: {
9065 		/* Respond to SYN with a syncookie. */
9066 		if ((pd.hdr.tcp.th_flags & (TH_SYN|TH_ACK|TH_RST)) == TH_SYN &&
9067 		    pd.dir == PF_IN && pf_synflood_check(&pd)) {
9068 			pf_syncookie_send(&pd);
9069 			action = PF_DROP;
9070 			break;
9071 		}
9072 
9073 		if ((pd.hdr.tcp.th_flags & TH_ACK) && pd.p_len == 0)
9074 			use_2nd_queue = 1;
9075 		action = pf_normalize_tcp(&pd);
9076 		if (action == PF_DROP)
9077 			goto done;
9078 		action = pf_test_state_tcp(&s, &pd, &reason);
9079 		if (action == PF_PASS) {
9080 			if (V_pfsync_update_state_ptr != NULL)
9081 				V_pfsync_update_state_ptr(s);
9082 			r = s->rule;
9083 			a = s->anchor;
9084 		} else if (s == NULL) {
9085 			/* Validate remote SYN|ACK, re-create original SYN if
9086 			 * valid. */
9087 			if ((pd.hdr.tcp.th_flags & (TH_SYN|TH_ACK|TH_RST)) ==
9088 			    TH_ACK && pf_syncookie_validate(&pd) &&
9089 			    pd.dir == PF_IN) {
9090 				struct mbuf *msyn;
9091 
9092 				msyn = pf_syncookie_recreate_syn(&pd);
9093 				if (msyn == NULL) {
9094 					action = PF_DROP;
9095 					break;
9096 				}
9097 
9098 				action = pf_test(af, dir, pflags, ifp, &msyn, inp,
9099 				    &pd.act);
9100 				m_freem(msyn);
9101 				if (action != PF_PASS)
9102 					break;
9103 
9104 				action = pf_test_state_tcp(&s, &pd, &reason);
9105 				if (action != PF_PASS || s == NULL) {
9106 					action = PF_DROP;
9107 					break;
9108 				}
9109 
9110 				s->src.seqhi = ntohl(pd.hdr.tcp.th_ack) - 1;
9111 				s->src.seqlo = ntohl(pd.hdr.tcp.th_seq) - 1;
9112 				pf_set_protostate(s, PF_PEER_SRC, PF_TCPS_PROXY_DST);
9113 				action = pf_synproxy(&pd, &s, &reason);
9114 				break;
9115 			} else {
9116 				action = pf_test_rule(&r, &s, &pd,
9117 				    &a, &ruleset, inp);
9118 			}
9119 		}
9120 		break;
9121 	}
9122 
9123 	case IPPROTO_UDP: {
9124 		action = pf_test_state_udp(&s, &pd);
9125 		if (action == PF_PASS) {
9126 			if (V_pfsync_update_state_ptr != NULL)
9127 				V_pfsync_update_state_ptr(s);
9128 			r = s->rule;
9129 			a = s->anchor;
9130 		} else if (s == NULL)
9131 			action = pf_test_rule(&r, &s, &pd,
9132 			    &a, &ruleset, inp);
9133 		break;
9134 	}
9135 
9136 	case IPPROTO_SCTP: {
9137 		action = pf_normalize_sctp(&pd);
9138 		if (action == PF_DROP)
9139 			goto done;
9140 		action = pf_test_state_sctp(&s, &pd, &reason);
9141 		if (action == PF_PASS) {
9142 			if (V_pfsync_update_state_ptr != NULL)
9143 				V_pfsync_update_state_ptr(s);
9144 			r = s->rule;
9145 			a = s->anchor;
9146 		} else if (s == NULL) {
9147 			action = pf_test_rule(&r, &s,
9148 			    &pd, &a, &ruleset, inp);
9149 		}
9150 		break;
9151 	}
9152 
9153 	case IPPROTO_ICMP: {
9154 		if (af != AF_INET) {
9155 			action = PF_DROP;
9156 			REASON_SET(&reason, PFRES_NORM);
9157 			DPFPRINTF(PF_DEBUG_MISC,
9158 			    ("dropping IPv6 packet with ICMPv4 payload"));
9159 			goto done;
9160 		}
9161 		action = pf_test_state_icmp(&s, &pd, &reason);
9162 		if (action == PF_PASS) {
9163 			if (V_pfsync_update_state_ptr != NULL)
9164 				V_pfsync_update_state_ptr(s);
9165 			r = s->rule;
9166 			a = s->anchor;
9167 		} else if (s == NULL)
9168 			action = pf_test_rule(&r, &s, &pd,
9169 			    &a, &ruleset, inp);
9170 		break;
9171 	}
9172 
9173 	case IPPROTO_ICMPV6: {
9174 		if (af != AF_INET6) {
9175 			action = PF_DROP;
9176 			REASON_SET(&reason, PFRES_NORM);
9177 			DPFPRINTF(PF_DEBUG_MISC,
9178 			    ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
9179 			goto done;
9180 		}
9181 		action = pf_test_state_icmp(&s, &pd, &reason);
9182 		if (action == PF_PASS) {
9183 			if (V_pfsync_update_state_ptr != NULL)
9184 				V_pfsync_update_state_ptr(s);
9185 			r = s->rule;
9186 			a = s->anchor;
9187 		} else if (s == NULL)
9188 			action = pf_test_rule(&r, &s, &pd,
9189 			    &a, &ruleset, inp);
9190 		break;
9191 	}
9192 
9193 	default:
9194 		action = pf_test_state_other(&s, &pd);
9195 		if (action == PF_PASS) {
9196 			if (V_pfsync_update_state_ptr != NULL)
9197 				V_pfsync_update_state_ptr(s);
9198 			r = s->rule;
9199 			a = s->anchor;
9200 		} else if (s == NULL)
9201 			action = pf_test_rule(&r, &s, &pd,
9202 			    &a, &ruleset, inp);
9203 		break;
9204 	}
9205 
9206 done:
9207 	PF_RULES_RUNLOCK();
9208 
9209 	if (pd.m == NULL)
9210 		goto eat_pkt;
9211 
9212 	if (action == PF_PASS && pd.badopts &&
9213 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
9214 		action = PF_DROP;
9215 		REASON_SET(&reason, PFRES_IPOPTIONS);
9216 		pd.act.log = PF_LOG_FORCE;
9217 		DPFPRINTF(PF_DEBUG_MISC,
9218 		    ("pf: dropping packet with dangerous headers\n"));
9219 	}
9220 
9221 	if (s) {
9222 		uint8_t log = pd.act.log;
9223 		memcpy(&pd.act, &s->act, sizeof(struct pf_rule_actions));
9224 		pd.act.log |= log;
9225 		tag = s->tag;
9226 		rt = s->rt;
9227 	} else {
9228 		tag = r->tag;
9229 		rt = r->rt;
9230 	}
9231 
9232 	if (tag > 0 && pf_tag_packet(&pd, tag)) {
9233 		action = PF_DROP;
9234 		REASON_SET(&reason, PFRES_MEMORY);
9235 	}
9236 
9237 	pf_scrub(&pd);
9238 	if (pd.proto == IPPROTO_TCP && pd.act.max_mss)
9239 		pf_normalize_mss(&pd);
9240 
9241 	if (pd.act.rtableid >= 0)
9242 		M_SETFIB(pd.m, pd.act.rtableid);
9243 
9244 	if (pd.act.flags & PFSTATE_SETPRIO) {
9245 		if (pd.tos & IPTOS_LOWDELAY)
9246 			use_2nd_queue = 1;
9247 		if (vlan_set_pcp(pd.m, pd.act.set_prio[use_2nd_queue])) {
9248 			action = PF_DROP;
9249 			REASON_SET(&reason, PFRES_MEMORY);
9250 			pd.act.log = PF_LOG_FORCE;
9251 			DPFPRINTF(PF_DEBUG_MISC,
9252 			    ("pf: failed to allocate 802.1q mtag\n"));
9253 		}
9254 	}
9255 
9256 #ifdef ALTQ
9257 	if (action == PF_PASS && pd.act.qid) {
9258 		if (pd.pf_mtag == NULL &&
9259 		    ((pd.pf_mtag = pf_get_mtag(pd.m)) == NULL)) {
9260 			action = PF_DROP;
9261 			REASON_SET(&reason, PFRES_MEMORY);
9262 		} else {
9263 			if (s != NULL)
9264 				pd.pf_mtag->qid_hash = pf_state_hash(s);
9265 			if (use_2nd_queue || (pd.tos & IPTOS_LOWDELAY))
9266 				pd.pf_mtag->qid = pd.act.pqid;
9267 			else
9268 				pd.pf_mtag->qid = pd.act.qid;
9269 			/* Add hints for ecn. */
9270 			pd.pf_mtag->hdr = mtod(pd.m, void *);
9271 		}
9272 	}
9273 #endif /* ALTQ */
9274 
9275 	/*
9276 	 * connections redirected to loopback should not match sockets
9277 	 * bound specifically to loopback due to security implications,
9278 	 * see tcp_input() and in_pcblookup_listen().
9279 	 */
9280 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
9281 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule != NULL &&
9282 	    (s->nat_rule->action == PF_RDR ||
9283 	    s->nat_rule->action == PF_BINAT) &&
9284 	    pf_is_loopback(af, pd.dst))
9285 		pd.m->m_flags |= M_SKIP_FIREWALL;
9286 
9287 	if (af == AF_INET && __predict_false(ip_divert_ptr != NULL) &&
9288 	    action == PF_PASS && r->divert.port && !PACKET_LOOPED(&pd)) {
9289 		mtag = m_tag_alloc(MTAG_PF_DIVERT, 0,
9290 		    sizeof(struct pf_divert_mtag), M_NOWAIT | M_ZERO);
9291 		if (mtag != NULL) {
9292 			((struct pf_divert_mtag *)(mtag+1))->port =
9293 			    ntohs(r->divert.port);
9294 			((struct pf_divert_mtag *)(mtag+1))->idir =
9295 			    (dir == PF_IN) ? PF_DIVERT_MTAG_DIR_IN :
9296 			    PF_DIVERT_MTAG_DIR_OUT;
9297 
9298 			if (s)
9299 				PF_STATE_UNLOCK(s);
9300 
9301 			m_tag_prepend(pd.m, mtag);
9302 			if (pd.m->m_flags & M_FASTFWD_OURS) {
9303 				if (pd.pf_mtag == NULL &&
9304 				    ((pd.pf_mtag = pf_get_mtag(pd.m)) == NULL)) {
9305 					action = PF_DROP;
9306 					REASON_SET(&reason, PFRES_MEMORY);
9307 					pd.act.log = PF_LOG_FORCE;
9308 					DPFPRINTF(PF_DEBUG_MISC,
9309 					    ("pf: failed to allocate tag\n"));
9310 				} else {
9311 					pd.pf_mtag->flags |=
9312 					    PF_MTAG_FLAG_FASTFWD_OURS_PRESENT;
9313 					pd.m->m_flags &= ~M_FASTFWD_OURS;
9314 				}
9315 			}
9316 			ip_divert_ptr(*m0, dir == PF_IN);
9317 			*m0 = NULL;
9318 
9319 			return (action);
9320 		} else {
9321 			/* XXX: ipfw has the same behaviour! */
9322 			action = PF_DROP;
9323 			REASON_SET(&reason, PFRES_MEMORY);
9324 			pd.act.log = PF_LOG_FORCE;
9325 			DPFPRINTF(PF_DEBUG_MISC,
9326 			    ("pf: failed to allocate divert tag\n"));
9327 		}
9328 	}
9329 	/* XXX: Anybody working on it?! */
9330 	if (af == AF_INET6 && r->divert.port)
9331 		printf("pf: divert(9) is not supported for IPv6\n");
9332 
9333 	/* this flag will need revising if the pkt is forwarded */
9334 	if (pd.pf_mtag)
9335 		pd.pf_mtag->flags &= ~PF_MTAG_FLAG_PACKET_LOOPED;
9336 
9337 	if (pd.act.log) {
9338 		struct pf_krule		*lr;
9339 		struct pf_krule_item	*ri;
9340 
9341 		if (s != NULL && s->nat_rule != NULL &&
9342 		    s->nat_rule->log & PF_LOG_ALL)
9343 			lr = s->nat_rule;
9344 		else
9345 			lr = r;
9346 
9347 		if (pd.act.log & PF_LOG_FORCE || lr->log & PF_LOG_ALL)
9348 			PFLOG_PACKET(action, reason, lr, a,
9349 			    ruleset, &pd, (s == NULL));
9350 		if (s) {
9351 			SLIST_FOREACH(ri, &s->match_rules, entry)
9352 				if (ri->r->log & PF_LOG_ALL)
9353 					PFLOG_PACKET(action,
9354 					    reason, ri->r, a, ruleset, &pd, 0);
9355 		}
9356 	}
9357 
9358 	pf_counters_inc(action, &pd, s, r, a);
9359 
9360 	switch (action) {
9361 	case PF_SYNPROXY_DROP:
9362 		m_freem(*m0);
9363 	case PF_DEFER:
9364 		*m0 = NULL;
9365 		action = PF_PASS;
9366 		break;
9367 	case PF_DROP:
9368 		m_freem(*m0);
9369 		*m0 = NULL;
9370 		break;
9371 	default:
9372 		if (rt) {
9373 			switch (af) {
9374 #ifdef INET
9375 			case AF_INET:
9376 				/* pf_route() returns unlocked. */
9377 				pf_route(m0, r, kif->pfik_ifp, s, &pd, inp);
9378 				break;
9379 #endif
9380 #ifdef INET6
9381 			case AF_INET6:
9382 				/* pf_route6() returns unlocked. */
9383 				pf_route6(m0, r, kif->pfik_ifp, s, &pd, inp);
9384 				break;
9385 #endif
9386 			}
9387 			goto out;
9388 		}
9389 		if (pf_dummynet(&pd, s, r, m0) != 0) {
9390 			action = PF_DROP;
9391 			REASON_SET(&reason, PFRES_MEMORY);
9392 		}
9393 		break;
9394 	}
9395 
9396 eat_pkt:
9397 	SDT_PROBE4(pf, ip, test, done, action, reason, r, s);
9398 
9399 	if (s && action != PF_DROP) {
9400 		if (!s->if_index_in && dir == PF_IN)
9401 			s->if_index_in = ifp->if_index;
9402 		else if (!s->if_index_out && dir == PF_OUT)
9403 			s->if_index_out = ifp->if_index;
9404 	}
9405 
9406 	if (s)
9407 		PF_STATE_UNLOCK(s);
9408 
9409 #ifdef INET6
9410 	/* If reassembled packet passed, create new fragments. */
9411 	if (af == AF_INET6 && action == PF_PASS && *m0 && dir == PF_OUT &&
9412 	    (mtag = m_tag_find(pd.m, PACKET_TAG_PF_REASSEMBLED, NULL)) != NULL)
9413 		action = pf_refragment6(ifp, m0, mtag, pflags & PFIL_FWD);
9414 #endif
9415 
9416 out:
9417 	pf_sctp_multihome_delayed(&pd, kif, s, action);
9418 
9419 	return (action);
9420 }
9421 #endif /* INET || INET6 */
9422