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