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