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