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