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