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