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