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