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