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