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