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