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