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