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