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