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