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