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