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