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