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