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