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