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