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