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