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