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