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