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