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