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