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