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