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