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