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