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