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