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