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