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