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