xref: /freebsd/sys/netpfil/pf/pf.c (revision 6aae3517ed2500fb963ba0a4264b4756088dd0f4)
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 rm_priotracker in_ifa_tracker;
1597 		struct ip *ip;
1598 		struct in_ifaddr *ia = NULL;
1599 
1600 		ip = mtod(m, struct ip *);
1601 		IN_IFADDR_RLOCK(&in_ifa_tracker);
1602 		LIST_FOREACH(ia, INADDR_HASH(ip->ip_dst.s_addr), ia_hash) {
1603 			if (IA_SIN(ia)->sin_addr.s_addr == ip->ip_dst.s_addr) {
1604 				IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1605 				return (true);
1606 			}
1607 		}
1608 		IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1609 		break;
1610 	}
1611 #endif
1612 #ifdef INET6
1613 	case AF_INET6: {
1614 		struct ip6_hdr *ip6;
1615 		struct in6_ifaddr *ia;
1616 		ip6 = mtod(m, struct ip6_hdr *);
1617 		ia = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */, false);
1618 		if (ia == NULL)
1619 			return (false);
1620 		return (! (ia->ia6_flags & IN6_IFF_NOTREADY));
1621 	}
1622 #endif
1623 	default:
1624 		panic("Unsupported af %d", af);
1625 	}
1626 
1627 	return (false);
1628 }
1629 
1630 void
1631 pf_intr(void *v)
1632 {
1633 	struct epoch_tracker et;
1634 	struct pf_send_head queue;
1635 	struct pf_send_entry *pfse, *next;
1636 
1637 	CURVNET_SET((struct vnet *)v);
1638 
1639 	PF_SENDQ_LOCK();
1640 	queue = V_pf_sendqueue;
1641 	STAILQ_INIT(&V_pf_sendqueue);
1642 	PF_SENDQ_UNLOCK();
1643 
1644 	NET_EPOCH_ENTER(et);
1645 
1646 	STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1647 		switch (pfse->pfse_type) {
1648 #ifdef INET
1649 		case PFSE_IP: {
1650 			if (pf_isforlocal(pfse->pfse_m, AF_INET)) {
1651 				pfse->pfse_m->m_flags |= M_SKIP_FIREWALL;
1652 				pfse->pfse_m->m_pkthdr.csum_flags |=
1653 				    CSUM_IP_VALID | CSUM_IP_CHECKED;
1654 				ip_input(pfse->pfse_m);
1655 			} else {
1656 				ip_output(pfse->pfse_m, NULL, NULL, 0, NULL,
1657 				    NULL);
1658 			}
1659 			break;
1660 		}
1661 		case PFSE_ICMP:
1662 			icmp_error(pfse->pfse_m, pfse->icmpopts.type,
1663 			    pfse->icmpopts.code, 0, pfse->icmpopts.mtu);
1664 			break;
1665 #endif /* INET */
1666 #ifdef INET6
1667 		case PFSE_IP6:
1668 			if (pf_isforlocal(pfse->pfse_m, AF_INET6)) {
1669 				pfse->pfse_m->m_flags |= M_SKIP_FIREWALL;
1670 				ip6_input(pfse->pfse_m);
1671 			} else {
1672 				ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL,
1673 				    NULL, NULL);
1674 			}
1675 			break;
1676 		case PFSE_ICMP6:
1677 			icmp6_error(pfse->pfse_m, pfse->icmpopts.type,
1678 			    pfse->icmpopts.code, pfse->icmpopts.mtu);
1679 			break;
1680 #endif /* INET6 */
1681 		default:
1682 			panic("%s: unknown type", __func__);
1683 		}
1684 		free(pfse, M_PFTEMP);
1685 	}
1686 	NET_EPOCH_EXIT(et);
1687 	CURVNET_RESTORE();
1688 }
1689 
1690 #define	pf_purge_thread_period	(hz / 10)
1691 
1692 #ifdef PF_WANT_32_TO_64_COUNTER
1693 static void
1694 pf_status_counter_u64_periodic(void)
1695 {
1696 
1697 	PF_RULES_RASSERT();
1698 
1699 	if ((V_pf_counter_periodic_iter % (pf_purge_thread_period * 10 * 60)) != 0) {
1700 		return;
1701 	}
1702 
1703 	for (int i = 0; i < FCNT_MAX; i++) {
1704 		pf_counter_u64_periodic(&V_pf_status.fcounters[i]);
1705 	}
1706 }
1707 
1708 static void
1709 pf_kif_counter_u64_periodic(void)
1710 {
1711 	struct pfi_kkif *kif;
1712 	size_t r, run;
1713 
1714 	PF_RULES_RASSERT();
1715 
1716 	if (__predict_false(V_pf_allkifcount == 0)) {
1717 		return;
1718 	}
1719 
1720 	if ((V_pf_counter_periodic_iter % (pf_purge_thread_period * 10 * 300)) != 0) {
1721 		return;
1722 	}
1723 
1724 	run = V_pf_allkifcount / 10;
1725 	if (run < 5)
1726 		run = 5;
1727 
1728 	for (r = 0; r < run; r++) {
1729 		kif = LIST_NEXT(V_pf_kifmarker, pfik_allkiflist);
1730 		if (kif == NULL) {
1731 			LIST_REMOVE(V_pf_kifmarker, pfik_allkiflist);
1732 			LIST_INSERT_HEAD(&V_pf_allkiflist, V_pf_kifmarker, pfik_allkiflist);
1733 			break;
1734 		}
1735 
1736 		LIST_REMOVE(V_pf_kifmarker, pfik_allkiflist);
1737 		LIST_INSERT_AFTER(kif, V_pf_kifmarker, pfik_allkiflist);
1738 
1739 		for (int i = 0; i < 2; i++) {
1740 			for (int j = 0; j < 2; j++) {
1741 				for (int k = 0; k < 2; k++) {
1742 					pf_counter_u64_periodic(&kif->pfik_packets[i][j][k]);
1743 					pf_counter_u64_periodic(&kif->pfik_bytes[i][j][k]);
1744 				}
1745 			}
1746 		}
1747 	}
1748 }
1749 
1750 static void
1751 pf_rule_counter_u64_periodic(void)
1752 {
1753 	struct pf_krule *rule;
1754 	size_t r, run;
1755 
1756 	PF_RULES_RASSERT();
1757 
1758 	if (__predict_false(V_pf_allrulecount == 0)) {
1759 		return;
1760 	}
1761 
1762 	if ((V_pf_counter_periodic_iter % (pf_purge_thread_period * 10 * 300)) != 0) {
1763 		return;
1764 	}
1765 
1766 	run = V_pf_allrulecount / 10;
1767 	if (run < 5)
1768 		run = 5;
1769 
1770 	for (r = 0; r < run; r++) {
1771 		rule = LIST_NEXT(V_pf_rulemarker, allrulelist);
1772 		if (rule == NULL) {
1773 			LIST_REMOVE(V_pf_rulemarker, allrulelist);
1774 			LIST_INSERT_HEAD(&V_pf_allrulelist, V_pf_rulemarker, allrulelist);
1775 			break;
1776 		}
1777 
1778 		LIST_REMOVE(V_pf_rulemarker, allrulelist);
1779 		LIST_INSERT_AFTER(rule, V_pf_rulemarker, allrulelist);
1780 
1781 		pf_counter_u64_periodic(&rule->evaluations);
1782 		for (int i = 0; i < 2; i++) {
1783 			pf_counter_u64_periodic(&rule->packets[i]);
1784 			pf_counter_u64_periodic(&rule->bytes[i]);
1785 		}
1786 	}
1787 }
1788 
1789 static void
1790 pf_counter_u64_periodic_main(void)
1791 {
1792 	PF_RULES_RLOCK_TRACKER;
1793 
1794 	V_pf_counter_periodic_iter++;
1795 
1796 	PF_RULES_RLOCK();
1797 	pf_counter_u64_critical_enter();
1798 	pf_status_counter_u64_periodic();
1799 	pf_kif_counter_u64_periodic();
1800 	pf_rule_counter_u64_periodic();
1801 	pf_counter_u64_critical_exit();
1802 	PF_RULES_RUNLOCK();
1803 }
1804 #else
1805 #define	pf_counter_u64_periodic_main()	do { } while (0)
1806 #endif
1807 
1808 void
1809 pf_purge_thread(void *unused __unused)
1810 {
1811 	VNET_ITERATOR_DECL(vnet_iter);
1812 
1813 	sx_xlock(&pf_end_lock);
1814 	while (pf_end_threads == 0) {
1815 		sx_sleep(pf_purge_thread, &pf_end_lock, 0, "pftm", pf_purge_thread_period);
1816 
1817 		VNET_LIST_RLOCK();
1818 		VNET_FOREACH(vnet_iter) {
1819 			CURVNET_SET(vnet_iter);
1820 
1821 			/* Wait until V_pf_default_rule is initialized. */
1822 			if (V_pf_vnet_active == 0) {
1823 				CURVNET_RESTORE();
1824 				continue;
1825 			}
1826 
1827 			pf_counter_u64_periodic_main();
1828 
1829 			/*
1830 			 *  Process 1/interval fraction of the state
1831 			 * table every run.
1832 			 */
1833 			V_pf_purge_idx =
1834 			    pf_purge_expired_states(V_pf_purge_idx, pf_hashmask /
1835 			    (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1836 
1837 			/*
1838 			 * Purge other expired types every
1839 			 * PFTM_INTERVAL seconds.
1840 			 */
1841 			if (V_pf_purge_idx == 0) {
1842 				/*
1843 				 * Order is important:
1844 				 * - states and src nodes reference rules
1845 				 * - states and rules reference kifs
1846 				 */
1847 				pf_purge_expired_fragments();
1848 				pf_purge_expired_src_nodes();
1849 				pf_purge_unlinked_rules();
1850 				pfi_kkif_purge();
1851 			}
1852 			CURVNET_RESTORE();
1853 		}
1854 		VNET_LIST_RUNLOCK();
1855 	}
1856 
1857 	pf_end_threads++;
1858 	sx_xunlock(&pf_end_lock);
1859 	kproc_exit(0);
1860 }
1861 
1862 void
1863 pf_unload_vnet_purge(void)
1864 {
1865 
1866 	/*
1867 	 * To cleanse up all kifs and rules we need
1868 	 * two runs: first one clears reference flags,
1869 	 * then pf_purge_expired_states() doesn't
1870 	 * raise them, and then second run frees.
1871 	 */
1872 	pf_purge_unlinked_rules();
1873 	pfi_kkif_purge();
1874 
1875 	/*
1876 	 * Now purge everything.
1877 	 */
1878 	pf_purge_expired_states(0, pf_hashmask);
1879 	pf_purge_fragments(UINT_MAX);
1880 	pf_purge_expired_src_nodes();
1881 
1882 	/*
1883 	 * Now all kifs & rules should be unreferenced,
1884 	 * thus should be successfully freed.
1885 	 */
1886 	pf_purge_unlinked_rules();
1887 	pfi_kkif_purge();
1888 }
1889 
1890 u_int32_t
1891 pf_state_expires(const struct pf_kstate *state)
1892 {
1893 	u_int32_t	timeout;
1894 	u_int32_t	start;
1895 	u_int32_t	end;
1896 	u_int32_t	states;
1897 
1898 	/* handle all PFTM_* > PFTM_MAX here */
1899 	if (state->timeout == PFTM_PURGE)
1900 		return (time_uptime);
1901 	KASSERT(state->timeout != PFTM_UNLINKED,
1902 	    ("pf_state_expires: timeout == PFTM_UNLINKED"));
1903 	KASSERT((state->timeout < PFTM_MAX),
1904 	    ("pf_state_expires: timeout > PFTM_MAX"));
1905 	timeout = state->rule.ptr->timeout[state->timeout];
1906 	if (!timeout)
1907 		timeout = V_pf_default_rule.timeout[state->timeout];
1908 	start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1909 	if (start && state->rule.ptr != &V_pf_default_rule) {
1910 		end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1911 		states = counter_u64_fetch(state->rule.ptr->states_cur);
1912 	} else {
1913 		start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1914 		end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1915 		states = V_pf_status.states;
1916 	}
1917 	if (end && states > start && start < end) {
1918 		if (states < end) {
1919 			timeout = (u_int64_t)timeout * (end - states) /
1920 			    (end - start);
1921 			return (state->expire + timeout);
1922 		}
1923 		else
1924 			return (time_uptime);
1925 	}
1926 	return (state->expire + timeout);
1927 }
1928 
1929 void
1930 pf_purge_expired_src_nodes()
1931 {
1932 	struct pf_ksrc_node_list	 freelist;
1933 	struct pf_srchash	*sh;
1934 	struct pf_ksrc_node	*cur, *next;
1935 	int i;
1936 
1937 	LIST_INIT(&freelist);
1938 	for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1939 	    PF_HASHROW_LOCK(sh);
1940 	    LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1941 		if (cur->states == 0 && cur->expire <= time_uptime) {
1942 			pf_unlink_src_node(cur);
1943 			LIST_INSERT_HEAD(&freelist, cur, entry);
1944 		} else if (cur->rule.ptr != NULL)
1945 			cur->rule.ptr->rule_ref |= PFRULE_REFS;
1946 	    PF_HASHROW_UNLOCK(sh);
1947 	}
1948 
1949 	pf_free_src_nodes(&freelist);
1950 
1951 	V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1952 }
1953 
1954 static void
1955 pf_src_tree_remove_state(struct pf_kstate *s)
1956 {
1957 	struct pf_ksrc_node *sn;
1958 	struct pf_srchash *sh;
1959 	uint32_t timeout;
1960 
1961 	timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1962 	    s->rule.ptr->timeout[PFTM_SRC_NODE] :
1963 	    V_pf_default_rule.timeout[PFTM_SRC_NODE];
1964 
1965 	if (s->src_node != NULL) {
1966 		sn = s->src_node;
1967 		sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1968 	    	PF_HASHROW_LOCK(sh);
1969 		if (s->src.tcp_est)
1970 			--sn->conn;
1971 		if (--sn->states == 0)
1972 			sn->expire = time_uptime + timeout;
1973 	    	PF_HASHROW_UNLOCK(sh);
1974 	}
1975 	if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1976 		sn = s->nat_src_node;
1977 		sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1978 	    	PF_HASHROW_LOCK(sh);
1979 		if (--sn->states == 0)
1980 			sn->expire = time_uptime + timeout;
1981 	    	PF_HASHROW_UNLOCK(sh);
1982 	}
1983 	s->src_node = s->nat_src_node = NULL;
1984 }
1985 
1986 /*
1987  * Unlink and potentilly free a state. Function may be
1988  * called with ID hash row locked, but always returns
1989  * unlocked, since it needs to go through key hash locking.
1990  */
1991 int
1992 pf_unlink_state(struct pf_kstate *s, u_int flags)
1993 {
1994 	struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1995 
1996 	if ((flags & PF_ENTER_LOCKED) == 0)
1997 		PF_HASHROW_LOCK(ih);
1998 	else
1999 		PF_HASHROW_ASSERT(ih);
2000 
2001 	if (s->timeout == PFTM_UNLINKED) {
2002 		/*
2003 		 * State is being processed
2004 		 * by pf_unlink_state() in
2005 		 * an other thread.
2006 		 */
2007 		PF_HASHROW_UNLOCK(ih);
2008 		return (0);	/* XXXGL: undefined actually */
2009 	}
2010 
2011 	if (s->src.state == PF_TCPS_PROXY_DST) {
2012 		/* XXX wire key the right one? */
2013 		pf_send_tcp(s->rule.ptr, s->key[PF_SK_WIRE]->af,
2014 		    &s->key[PF_SK_WIRE]->addr[1],
2015 		    &s->key[PF_SK_WIRE]->addr[0],
2016 		    s->key[PF_SK_WIRE]->port[1],
2017 		    s->key[PF_SK_WIRE]->port[0],
2018 		    s->src.seqhi, s->src.seqlo + 1,
2019 		    TH_RST|TH_ACK, 0, 0, 0, 1, s->tag);
2020 	}
2021 
2022 	LIST_REMOVE(s, entry);
2023 	pf_src_tree_remove_state(s);
2024 
2025 	if (V_pfsync_delete_state_ptr != NULL)
2026 		V_pfsync_delete_state_ptr(s);
2027 
2028 	STATE_DEC_COUNTERS(s);
2029 
2030 	s->timeout = PFTM_UNLINKED;
2031 
2032 	/* Ensure we remove it from the list of halfopen states, if needed. */
2033 	if (s->key[PF_SK_STACK] != NULL &&
2034 	    s->key[PF_SK_STACK]->proto == IPPROTO_TCP)
2035 		pf_set_protostate(s, PF_PEER_BOTH, TCPS_CLOSED);
2036 
2037 	PF_HASHROW_UNLOCK(ih);
2038 
2039 	pf_detach_state(s);
2040 	/* pf_state_insert() initialises refs to 2 */
2041 	return (pf_release_staten(s, 2));
2042 }
2043 
2044 struct pf_kstate *
2045 pf_alloc_state(int flags)
2046 {
2047 
2048 	return (uma_zalloc(V_pf_state_z, flags | M_ZERO));
2049 }
2050 
2051 void
2052 pf_free_state(struct pf_kstate *cur)
2053 {
2054 
2055 	KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
2056 	KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
2057 	    cur->timeout));
2058 
2059 	pf_normalize_tcp_cleanup(cur);
2060 	uma_zfree(V_pf_state_z, cur);
2061 	pf_counter_u64_add(&V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
2062 }
2063 
2064 /*
2065  * Called only from pf_purge_thread(), thus serialized.
2066  */
2067 static u_int
2068 pf_purge_expired_states(u_int i, int maxcheck)
2069 {
2070 	struct pf_idhash *ih;
2071 	struct pf_kstate *s;
2072 
2073 	V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
2074 
2075 	/*
2076 	 * Go through hash and unlink states that expire now.
2077 	 */
2078 	while (maxcheck > 0) {
2079 		ih = &V_pf_idhash[i];
2080 
2081 		/* only take the lock if we expect to do work */
2082 		if (!LIST_EMPTY(&ih->states)) {
2083 relock:
2084 			PF_HASHROW_LOCK(ih);
2085 			LIST_FOREACH(s, &ih->states, entry) {
2086 				if (pf_state_expires(s) <= time_uptime) {
2087 					V_pf_status.states -=
2088 					    pf_unlink_state(s, PF_ENTER_LOCKED);
2089 					goto relock;
2090 				}
2091 				s->rule.ptr->rule_ref |= PFRULE_REFS;
2092 				if (s->nat_rule.ptr != NULL)
2093 					s->nat_rule.ptr->rule_ref |= PFRULE_REFS;
2094 				if (s->anchor.ptr != NULL)
2095 					s->anchor.ptr->rule_ref |= PFRULE_REFS;
2096 				s->kif->pfik_flags |= PFI_IFLAG_REFS;
2097 				if (s->rt_kif)
2098 					s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
2099 			}
2100 			PF_HASHROW_UNLOCK(ih);
2101 		}
2102 
2103 		/* Return when we hit end of hash. */
2104 		if (++i > pf_hashmask) {
2105 			V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
2106 			return (0);
2107 		}
2108 
2109 		maxcheck--;
2110 	}
2111 
2112 	V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
2113 
2114 	return (i);
2115 }
2116 
2117 static void
2118 pf_purge_unlinked_rules()
2119 {
2120 	struct pf_krulequeue tmpq;
2121 	struct pf_krule *r, *r1;
2122 
2123 	/*
2124 	 * If we have overloading task pending, then we'd
2125 	 * better skip purging this time. There is a tiny
2126 	 * probability that overloading task references
2127 	 * an already unlinked rule.
2128 	 */
2129 	PF_OVERLOADQ_LOCK();
2130 	if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
2131 		PF_OVERLOADQ_UNLOCK();
2132 		return;
2133 	}
2134 	PF_OVERLOADQ_UNLOCK();
2135 
2136 	/*
2137 	 * Do naive mark-and-sweep garbage collecting of old rules.
2138 	 * Reference flag is raised by pf_purge_expired_states()
2139 	 * and pf_purge_expired_src_nodes().
2140 	 *
2141 	 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
2142 	 * use a temporary queue.
2143 	 */
2144 	TAILQ_INIT(&tmpq);
2145 	PF_UNLNKDRULES_LOCK();
2146 	TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
2147 		if (!(r->rule_ref & PFRULE_REFS)) {
2148 			TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
2149 			TAILQ_INSERT_TAIL(&tmpq, r, entries);
2150 		} else
2151 			r->rule_ref &= ~PFRULE_REFS;
2152 	}
2153 	PF_UNLNKDRULES_UNLOCK();
2154 
2155 	if (!TAILQ_EMPTY(&tmpq)) {
2156 		PF_RULES_WLOCK();
2157 		TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
2158 			TAILQ_REMOVE(&tmpq, r, entries);
2159 			pf_free_rule(r);
2160 		}
2161 		PF_RULES_WUNLOCK();
2162 	}
2163 }
2164 
2165 void
2166 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
2167 {
2168 	switch (af) {
2169 #ifdef INET
2170 	case AF_INET: {
2171 		u_int32_t a = ntohl(addr->addr32[0]);
2172 		printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
2173 		    (a>>8)&255, a&255);
2174 		if (p) {
2175 			p = ntohs(p);
2176 			printf(":%u", p);
2177 		}
2178 		break;
2179 	}
2180 #endif /* INET */
2181 #ifdef INET6
2182 	case AF_INET6: {
2183 		u_int16_t b;
2184 		u_int8_t i, curstart, curend, maxstart, maxend;
2185 		curstart = curend = maxstart = maxend = 255;
2186 		for (i = 0; i < 8; i++) {
2187 			if (!addr->addr16[i]) {
2188 				if (curstart == 255)
2189 					curstart = i;
2190 				curend = i;
2191 			} else {
2192 				if ((curend - curstart) >
2193 				    (maxend - maxstart)) {
2194 					maxstart = curstart;
2195 					maxend = curend;
2196 				}
2197 				curstart = curend = 255;
2198 			}
2199 		}
2200 		if ((curend - curstart) >
2201 		    (maxend - maxstart)) {
2202 			maxstart = curstart;
2203 			maxend = curend;
2204 		}
2205 		for (i = 0; i < 8; i++) {
2206 			if (i >= maxstart && i <= maxend) {
2207 				if (i == 0)
2208 					printf(":");
2209 				if (i == maxend)
2210 					printf(":");
2211 			} else {
2212 				b = ntohs(addr->addr16[i]);
2213 				printf("%x", b);
2214 				if (i < 7)
2215 					printf(":");
2216 			}
2217 		}
2218 		if (p) {
2219 			p = ntohs(p);
2220 			printf("[%u]", p);
2221 		}
2222 		break;
2223 	}
2224 #endif /* INET6 */
2225 	}
2226 }
2227 
2228 void
2229 pf_print_state(struct pf_kstate *s)
2230 {
2231 	pf_print_state_parts(s, NULL, NULL);
2232 }
2233 
2234 static void
2235 pf_print_state_parts(struct pf_kstate *s,
2236     struct pf_state_key *skwp, struct pf_state_key *sksp)
2237 {
2238 	struct pf_state_key *skw, *sks;
2239 	u_int8_t proto, dir;
2240 
2241 	/* Do our best to fill these, but they're skipped if NULL */
2242 	skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
2243 	sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
2244 	proto = skw ? skw->proto : (sks ? sks->proto : 0);
2245 	dir = s ? s->direction : 0;
2246 
2247 	switch (proto) {
2248 	case IPPROTO_IPV4:
2249 		printf("IPv4");
2250 		break;
2251 	case IPPROTO_IPV6:
2252 		printf("IPv6");
2253 		break;
2254 	case IPPROTO_TCP:
2255 		printf("TCP");
2256 		break;
2257 	case IPPROTO_UDP:
2258 		printf("UDP");
2259 		break;
2260 	case IPPROTO_ICMP:
2261 		printf("ICMP");
2262 		break;
2263 	case IPPROTO_ICMPV6:
2264 		printf("ICMPv6");
2265 		break;
2266 	default:
2267 		printf("%u", proto);
2268 		break;
2269 	}
2270 	switch (dir) {
2271 	case PF_IN:
2272 		printf(" in");
2273 		break;
2274 	case PF_OUT:
2275 		printf(" out");
2276 		break;
2277 	}
2278 	if (skw) {
2279 		printf(" wire: ");
2280 		pf_print_host(&skw->addr[0], skw->port[0], skw->af);
2281 		printf(" ");
2282 		pf_print_host(&skw->addr[1], skw->port[1], skw->af);
2283 	}
2284 	if (sks) {
2285 		printf(" stack: ");
2286 		if (sks != skw) {
2287 			pf_print_host(&sks->addr[0], sks->port[0], sks->af);
2288 			printf(" ");
2289 			pf_print_host(&sks->addr[1], sks->port[1], sks->af);
2290 		} else
2291 			printf("-");
2292 	}
2293 	if (s) {
2294 		if (proto == IPPROTO_TCP) {
2295 			printf(" [lo=%u high=%u win=%u modulator=%u",
2296 			    s->src.seqlo, s->src.seqhi,
2297 			    s->src.max_win, s->src.seqdiff);
2298 			if (s->src.wscale && s->dst.wscale)
2299 				printf(" wscale=%u",
2300 				    s->src.wscale & PF_WSCALE_MASK);
2301 			printf("]");
2302 			printf(" [lo=%u high=%u win=%u modulator=%u",
2303 			    s->dst.seqlo, s->dst.seqhi,
2304 			    s->dst.max_win, s->dst.seqdiff);
2305 			if (s->src.wscale && s->dst.wscale)
2306 				printf(" wscale=%u",
2307 				s->dst.wscale & PF_WSCALE_MASK);
2308 			printf("]");
2309 		}
2310 		printf(" %u:%u", s->src.state, s->dst.state);
2311 	}
2312 }
2313 
2314 void
2315 pf_print_flags(u_int8_t f)
2316 {
2317 	if (f)
2318 		printf(" ");
2319 	if (f & TH_FIN)
2320 		printf("F");
2321 	if (f & TH_SYN)
2322 		printf("S");
2323 	if (f & TH_RST)
2324 		printf("R");
2325 	if (f & TH_PUSH)
2326 		printf("P");
2327 	if (f & TH_ACK)
2328 		printf("A");
2329 	if (f & TH_URG)
2330 		printf("U");
2331 	if (f & TH_ECE)
2332 		printf("E");
2333 	if (f & TH_CWR)
2334 		printf("W");
2335 }
2336 
2337 #define	PF_SET_SKIP_STEPS(i)					\
2338 	do {							\
2339 		while (head[i] != cur) {			\
2340 			head[i]->skip[i].ptr = cur;		\
2341 			head[i] = TAILQ_NEXT(head[i], entries);	\
2342 		}						\
2343 	} while (0)
2344 
2345 void
2346 pf_calc_skip_steps(struct pf_krulequeue *rules)
2347 {
2348 	struct pf_krule *cur, *prev, *head[PF_SKIP_COUNT];
2349 	int i;
2350 
2351 	cur = TAILQ_FIRST(rules);
2352 	prev = cur;
2353 	for (i = 0; i < PF_SKIP_COUNT; ++i)
2354 		head[i] = cur;
2355 	while (cur != NULL) {
2356 		if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
2357 			PF_SET_SKIP_STEPS(PF_SKIP_IFP);
2358 		if (cur->direction != prev->direction)
2359 			PF_SET_SKIP_STEPS(PF_SKIP_DIR);
2360 		if (cur->af != prev->af)
2361 			PF_SET_SKIP_STEPS(PF_SKIP_AF);
2362 		if (cur->proto != prev->proto)
2363 			PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
2364 		if (cur->src.neg != prev->src.neg ||
2365 		    pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
2366 			PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
2367 		if (cur->src.port[0] != prev->src.port[0] ||
2368 		    cur->src.port[1] != prev->src.port[1] ||
2369 		    cur->src.port_op != prev->src.port_op)
2370 			PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
2371 		if (cur->dst.neg != prev->dst.neg ||
2372 		    pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
2373 			PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
2374 		if (cur->dst.port[0] != prev->dst.port[0] ||
2375 		    cur->dst.port[1] != prev->dst.port[1] ||
2376 		    cur->dst.port_op != prev->dst.port_op)
2377 			PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
2378 
2379 		prev = cur;
2380 		cur = TAILQ_NEXT(cur, entries);
2381 	}
2382 	for (i = 0; i < PF_SKIP_COUNT; ++i)
2383 		PF_SET_SKIP_STEPS(i);
2384 }
2385 
2386 static int
2387 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
2388 {
2389 	if (aw1->type != aw2->type)
2390 		return (1);
2391 	switch (aw1->type) {
2392 	case PF_ADDR_ADDRMASK:
2393 	case PF_ADDR_RANGE:
2394 		if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2395 			return (1);
2396 		if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2397 			return (1);
2398 		return (0);
2399 	case PF_ADDR_DYNIFTL:
2400 		return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2401 	case PF_ADDR_NOROUTE:
2402 	case PF_ADDR_URPFFAILED:
2403 		return (0);
2404 	case PF_ADDR_TABLE:
2405 		return (aw1->p.tbl != aw2->p.tbl);
2406 	default:
2407 		printf("invalid address type: %d\n", aw1->type);
2408 		return (1);
2409 	}
2410 }
2411 
2412 /**
2413  * Checksum updates are a little complicated because the checksum in the TCP/UDP
2414  * header isn't always a full checksum. In some cases (i.e. output) it's a
2415  * pseudo-header checksum, which is a partial checksum over src/dst IP
2416  * addresses, protocol number and length.
2417  *
2418  * That means we have the following cases:
2419  *  * Input or forwarding: we don't have TSO, the checksum fields are full
2420  *  	checksums, we need to update the checksum whenever we change anything.
2421  *  * Output (i.e. the checksum is a pseudo-header checksum):
2422  *  	x The field being updated is src/dst address or affects the length of
2423  *  	the packet. We need to update the pseudo-header checksum (note that this
2424  *  	checksum is not ones' complement).
2425  *  	x Some other field is being modified (e.g. src/dst port numbers): We
2426  *  	don't have to update anything.
2427  **/
2428 u_int16_t
2429 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2430 {
2431 	u_int32_t x;
2432 
2433 	x = cksum + old - new;
2434 	x = (x + (x >> 16)) & 0xffff;
2435 
2436 	/* optimise: eliminate a branch when not udp */
2437 	if (udp && cksum == 0x0000)
2438 		return cksum;
2439 	if (udp && x == 0x0000)
2440 		x = 0xffff;
2441 
2442 	return (u_int16_t)(x);
2443 }
2444 
2445 static void
2446 pf_patch_8(struct mbuf *m, u_int16_t *cksum, u_int8_t *f, u_int8_t v, bool hi,
2447     u_int8_t udp)
2448 {
2449 	u_int16_t old = htons(hi ? (*f << 8) : *f);
2450 	u_int16_t new = htons(hi ? ( v << 8) :  v);
2451 
2452 	if (*f == v)
2453 		return;
2454 
2455 	*f = v;
2456 
2457 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2458 		return;
2459 
2460 	*cksum = pf_cksum_fixup(*cksum, old, new, udp);
2461 }
2462 
2463 void
2464 pf_patch_16_unaligned(struct mbuf *m, u_int16_t *cksum, void *f, u_int16_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 }
2473 
2474 void
2475 pf_patch_32_unaligned(struct mbuf *m, u_int16_t *cksum, void *f, u_int32_t v,
2476     bool hi, u_int8_t udp)
2477 {
2478 	u_int8_t *fb = (u_int8_t *)f;
2479 	u_int8_t *vb = (u_int8_t *)&v;
2480 
2481 	pf_patch_8(m, cksum, fb++, *vb++, hi, udp);
2482 	pf_patch_8(m, cksum, fb++, *vb++, !hi, udp);
2483 	pf_patch_8(m, cksum, fb++, *vb++, hi, udp);
2484 	pf_patch_8(m, cksum, fb++, *vb++, !hi, udp);
2485 }
2486 
2487 u_int16_t
2488 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2489         u_int16_t new, u_int8_t udp)
2490 {
2491 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2492 		return (cksum);
2493 
2494 	return (pf_cksum_fixup(cksum, old, new, udp));
2495 }
2496 
2497 static void
2498 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2499         u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2500         sa_family_t af)
2501 {
2502 	struct pf_addr	ao;
2503 	u_int16_t	po = *p;
2504 
2505 	PF_ACPY(&ao, a, af);
2506 	PF_ACPY(a, an, af);
2507 
2508 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2509 		*pc = ~*pc;
2510 
2511 	*p = pn;
2512 
2513 	switch (af) {
2514 #ifdef INET
2515 	case AF_INET:
2516 		*ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2517 		    ao.addr16[0], an->addr16[0], 0),
2518 		    ao.addr16[1], an->addr16[1], 0);
2519 		*p = pn;
2520 
2521 		*pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2522 		    ao.addr16[0], an->addr16[0], u),
2523 		    ao.addr16[1], an->addr16[1], u);
2524 
2525 		*pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2526 		break;
2527 #endif /* INET */
2528 #ifdef INET6
2529 	case AF_INET6:
2530 		*pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2531 		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2532 		    pf_cksum_fixup(pf_cksum_fixup(*pc,
2533 		    ao.addr16[0], an->addr16[0], u),
2534 		    ao.addr16[1], an->addr16[1], u),
2535 		    ao.addr16[2], an->addr16[2], u),
2536 		    ao.addr16[3], an->addr16[3], u),
2537 		    ao.addr16[4], an->addr16[4], u),
2538 		    ao.addr16[5], an->addr16[5], u),
2539 		    ao.addr16[6], an->addr16[6], u),
2540 		    ao.addr16[7], an->addr16[7], u);
2541 
2542 		*pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2543 		break;
2544 #endif /* INET6 */
2545 	}
2546 
2547 	if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2548 	    CSUM_DELAY_DATA_IPV6)) {
2549 		*pc = ~*pc;
2550 		if (! *pc)
2551 			*pc = 0xffff;
2552 	}
2553 }
2554 
2555 /* Changes a u_int32_t.  Uses a void * so there are no align restrictions */
2556 void
2557 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2558 {
2559 	u_int32_t	ao;
2560 
2561 	memcpy(&ao, a, sizeof(ao));
2562 	memcpy(a, &an, sizeof(u_int32_t));
2563 	*c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2564 	    ao % 65536, an % 65536, u);
2565 }
2566 
2567 void
2568 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2569 {
2570 	u_int32_t	ao;
2571 
2572 	memcpy(&ao, a, sizeof(ao));
2573 	memcpy(a, &an, sizeof(u_int32_t));
2574 
2575 	*c = pf_proto_cksum_fixup(m,
2576 	    pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2577 	    ao % 65536, an % 65536, udp);
2578 }
2579 
2580 #ifdef INET6
2581 static void
2582 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2583 {
2584 	struct pf_addr	ao;
2585 
2586 	PF_ACPY(&ao, a, AF_INET6);
2587 	PF_ACPY(a, an, AF_INET6);
2588 
2589 	*c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2590 	    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2591 	    pf_cksum_fixup(pf_cksum_fixup(*c,
2592 	    ao.addr16[0], an->addr16[0], u),
2593 	    ao.addr16[1], an->addr16[1], u),
2594 	    ao.addr16[2], an->addr16[2], u),
2595 	    ao.addr16[3], an->addr16[3], u),
2596 	    ao.addr16[4], an->addr16[4], u),
2597 	    ao.addr16[5], an->addr16[5], u),
2598 	    ao.addr16[6], an->addr16[6], u),
2599 	    ao.addr16[7], an->addr16[7], u);
2600 }
2601 #endif /* INET6 */
2602 
2603 static void
2604 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2605     struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2606     u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2607 {
2608 	struct pf_addr	oia, ooa;
2609 
2610 	PF_ACPY(&oia, ia, af);
2611 	if (oa)
2612 		PF_ACPY(&ooa, oa, af);
2613 
2614 	/* Change inner protocol port, fix inner protocol checksum. */
2615 	if (ip != NULL) {
2616 		u_int16_t	oip = *ip;
2617 		u_int32_t	opc;
2618 
2619 		if (pc != NULL)
2620 			opc = *pc;
2621 		*ip = np;
2622 		if (pc != NULL)
2623 			*pc = pf_cksum_fixup(*pc, oip, *ip, u);
2624 		*ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2625 		if (pc != NULL)
2626 			*ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2627 	}
2628 	/* Change inner ip address, fix inner ip and icmp checksums. */
2629 	PF_ACPY(ia, na, af);
2630 	switch (af) {
2631 #ifdef INET
2632 	case AF_INET: {
2633 		u_int32_t	 oh2c = *h2c;
2634 
2635 		*h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2636 		    oia.addr16[0], ia->addr16[0], 0),
2637 		    oia.addr16[1], ia->addr16[1], 0);
2638 		*ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2639 		    oia.addr16[0], ia->addr16[0], 0),
2640 		    oia.addr16[1], ia->addr16[1], 0);
2641 		*ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2642 		break;
2643 	}
2644 #endif /* INET */
2645 #ifdef INET6
2646 	case AF_INET6:
2647 		*ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2648 		    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2649 		    pf_cksum_fixup(pf_cksum_fixup(*ic,
2650 		    oia.addr16[0], ia->addr16[0], u),
2651 		    oia.addr16[1], ia->addr16[1], u),
2652 		    oia.addr16[2], ia->addr16[2], u),
2653 		    oia.addr16[3], ia->addr16[3], u),
2654 		    oia.addr16[4], ia->addr16[4], u),
2655 		    oia.addr16[5], ia->addr16[5], u),
2656 		    oia.addr16[6], ia->addr16[6], u),
2657 		    oia.addr16[7], ia->addr16[7], u);
2658 		break;
2659 #endif /* INET6 */
2660 	}
2661 	/* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2662 	if (oa) {
2663 		PF_ACPY(oa, na, af);
2664 		switch (af) {
2665 #ifdef INET
2666 		case AF_INET:
2667 			*hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2668 			    ooa.addr16[0], oa->addr16[0], 0),
2669 			    ooa.addr16[1], oa->addr16[1], 0);
2670 			break;
2671 #endif /* INET */
2672 #ifdef INET6
2673 		case AF_INET6:
2674 			*ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2675 			    pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2676 			    pf_cksum_fixup(pf_cksum_fixup(*ic,
2677 			    ooa.addr16[0], oa->addr16[0], u),
2678 			    ooa.addr16[1], oa->addr16[1], u),
2679 			    ooa.addr16[2], oa->addr16[2], u),
2680 			    ooa.addr16[3], oa->addr16[3], u),
2681 			    ooa.addr16[4], oa->addr16[4], u),
2682 			    ooa.addr16[5], oa->addr16[5], u),
2683 			    ooa.addr16[6], oa->addr16[6], u),
2684 			    ooa.addr16[7], oa->addr16[7], u);
2685 			break;
2686 #endif /* INET6 */
2687 		}
2688 	}
2689 }
2690 
2691 /*
2692  * Need to modulate the sequence numbers in the TCP SACK option
2693  * (credits to Krzysztof Pfaff for report and patch)
2694  */
2695 static int
2696 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2697     struct tcphdr *th, struct pf_state_peer *dst)
2698 {
2699 	int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2700 	u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2701 	int copyback = 0, i, olen;
2702 	struct sackblk sack;
2703 
2704 #define	TCPOLEN_SACKLEN	(TCPOLEN_SACK + 2)
2705 	if (hlen < TCPOLEN_SACKLEN ||
2706 	    !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2707 		return 0;
2708 
2709 	while (hlen >= TCPOLEN_SACKLEN) {
2710 		size_t startoff = opt - opts;
2711 		olen = opt[1];
2712 		switch (*opt) {
2713 		case TCPOPT_EOL:	/* FALLTHROUGH */
2714 		case TCPOPT_NOP:
2715 			opt++;
2716 			hlen--;
2717 			break;
2718 		case TCPOPT_SACK:
2719 			if (olen > hlen)
2720 				olen = hlen;
2721 			if (olen >= TCPOLEN_SACKLEN) {
2722 				for (i = 2; i + TCPOLEN_SACK <= olen;
2723 				    i += TCPOLEN_SACK) {
2724 					memcpy(&sack, &opt[i], sizeof(sack));
2725 					pf_patch_32_unaligned(m,
2726 					    &th->th_sum, &sack.start,
2727 					    htonl(ntohl(sack.start) - dst->seqdiff),
2728 					    PF_ALGNMNT(startoff),
2729 					    0);
2730 					pf_patch_32_unaligned(m, &th->th_sum,
2731 					    &sack.end,
2732 					    htonl(ntohl(sack.end) - dst->seqdiff),
2733 					    PF_ALGNMNT(startoff),
2734 					    0);
2735 					memcpy(&opt[i], &sack, sizeof(sack));
2736 				}
2737 				copyback = 1;
2738 			}
2739 			/* FALLTHROUGH */
2740 		default:
2741 			if (olen < 2)
2742 				olen = 2;
2743 			hlen -= olen;
2744 			opt += olen;
2745 		}
2746 	}
2747 
2748 	if (copyback)
2749 		m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2750 	return (copyback);
2751 }
2752 
2753 struct mbuf *
2754 pf_build_tcp(const struct pf_krule *r, sa_family_t af,
2755     const struct pf_addr *saddr, const struct pf_addr *daddr,
2756     u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2757     u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2758     u_int16_t rtag)
2759 {
2760 	struct mbuf	*m;
2761 	int		 len, tlen;
2762 #ifdef INET
2763 	struct ip	*h = NULL;
2764 #endif /* INET */
2765 #ifdef INET6
2766 	struct ip6_hdr	*h6 = NULL;
2767 #endif /* INET6 */
2768 	struct tcphdr	*th;
2769 	char		*opt;
2770 	struct pf_mtag  *pf_mtag;
2771 
2772 	len = 0;
2773 	th = NULL;
2774 
2775 	/* maximum segment size tcp option */
2776 	tlen = sizeof(struct tcphdr);
2777 	if (mss)
2778 		tlen += 4;
2779 
2780 	switch (af) {
2781 #ifdef INET
2782 	case AF_INET:
2783 		len = sizeof(struct ip) + tlen;
2784 		break;
2785 #endif /* INET */
2786 #ifdef INET6
2787 	case AF_INET6:
2788 		len = sizeof(struct ip6_hdr) + tlen;
2789 		break;
2790 #endif /* INET6 */
2791 	default:
2792 		panic("%s: unsupported af %d", __func__, af);
2793 	}
2794 
2795 	m = m_gethdr(M_NOWAIT, MT_DATA);
2796 	if (m == NULL)
2797 		return (NULL);
2798 
2799 #ifdef MAC
2800 	mac_netinet_firewall_send(m);
2801 #endif
2802 	if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2803 		m_freem(m);
2804 		return (NULL);
2805 	}
2806 	if (tag)
2807 		m->m_flags |= M_SKIP_FIREWALL;
2808 	pf_mtag->tag = rtag;
2809 
2810 	if (r != NULL && r->rtableid >= 0)
2811 		M_SETFIB(m, r->rtableid);
2812 
2813 #ifdef ALTQ
2814 	if (r != NULL && r->qid) {
2815 		pf_mtag->qid = r->qid;
2816 
2817 		/* add hints for ecn */
2818 		pf_mtag->hdr = mtod(m, struct ip *);
2819 	}
2820 #endif /* ALTQ */
2821 	m->m_data += max_linkhdr;
2822 	m->m_pkthdr.len = m->m_len = len;
2823 	/* The rest of the stack assumes a rcvif, so provide one.
2824 	 * This is a locally generated packet, so .. close enough. */
2825 	m->m_pkthdr.rcvif = V_loif;
2826 	bzero(m->m_data, len);
2827 	switch (af) {
2828 #ifdef INET
2829 	case AF_INET:
2830 		h = mtod(m, struct ip *);
2831 
2832 		/* IP header fields included in the TCP checksum */
2833 		h->ip_p = IPPROTO_TCP;
2834 		h->ip_len = htons(tlen);
2835 		h->ip_src.s_addr = saddr->v4.s_addr;
2836 		h->ip_dst.s_addr = daddr->v4.s_addr;
2837 
2838 		th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2839 		break;
2840 #endif /* INET */
2841 #ifdef INET6
2842 	case AF_INET6:
2843 		h6 = mtod(m, struct ip6_hdr *);
2844 
2845 		/* IP header fields included in the TCP checksum */
2846 		h6->ip6_nxt = IPPROTO_TCP;
2847 		h6->ip6_plen = htons(tlen);
2848 		memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2849 		memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2850 
2851 		th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2852 		break;
2853 #endif /* INET6 */
2854 	}
2855 
2856 	/* TCP header */
2857 	th->th_sport = sport;
2858 	th->th_dport = dport;
2859 	th->th_seq = htonl(seq);
2860 	th->th_ack = htonl(ack);
2861 	th->th_off = tlen >> 2;
2862 	th->th_flags = flags;
2863 	th->th_win = htons(win);
2864 
2865 	if (mss) {
2866 		opt = (char *)(th + 1);
2867 		opt[0] = TCPOPT_MAXSEG;
2868 		opt[1] = 4;
2869 		HTONS(mss);
2870 		bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2871 	}
2872 
2873 	switch (af) {
2874 #ifdef INET
2875 	case AF_INET:
2876 		/* TCP checksum */
2877 		th->th_sum = in_cksum(m, len);
2878 
2879 		/* Finish the IP header */
2880 		h->ip_v = 4;
2881 		h->ip_hl = sizeof(*h) >> 2;
2882 		h->ip_tos = IPTOS_LOWDELAY;
2883 		h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2884 		h->ip_len = htons(len);
2885 		h->ip_ttl = ttl ? ttl : V_ip_defttl;
2886 		h->ip_sum = 0;
2887 		break;
2888 #endif /* INET */
2889 #ifdef INET6
2890 	case AF_INET6:
2891 		/* TCP checksum */
2892 		th->th_sum = in6_cksum(m, IPPROTO_TCP,
2893 		    sizeof(struct ip6_hdr), tlen);
2894 
2895 		h6->ip6_vfc |= IPV6_VERSION;
2896 		h6->ip6_hlim = IPV6_DEFHLIM;
2897 		break;
2898 #endif /* INET6 */
2899 	}
2900 
2901 	return (m);
2902 }
2903 
2904 void
2905 pf_send_tcp(const struct pf_krule *r, sa_family_t af,
2906     const struct pf_addr *saddr, const struct pf_addr *daddr,
2907     u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2908     u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2909     u_int16_t rtag)
2910 {
2911 	struct pf_send_entry *pfse;
2912 	struct mbuf	*m;
2913 
2914 	m = pf_build_tcp(r, af, saddr, daddr, sport, dport, seq, ack, flags,
2915 	    win, mss, ttl, tag, rtag);
2916 	if (m == NULL)
2917 		return;
2918 
2919 	/* Allocate outgoing queue entry, mbuf and mbuf tag. */
2920 	pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2921 	if (pfse == NULL) {
2922 		m_freem(m);
2923 		return;
2924 	}
2925 
2926 	switch (af) {
2927 #ifdef INET
2928 	case AF_INET:
2929 		pfse->pfse_type = PFSE_IP;
2930 		break;
2931 #endif /* INET */
2932 #ifdef INET6
2933 	case AF_INET6:
2934 		pfse->pfse_type = PFSE_IP6;
2935 		break;
2936 #endif /* INET6 */
2937 	}
2938 
2939 	pfse->pfse_m = m;
2940 	pf_send(pfse);
2941 }
2942 
2943 static void
2944 pf_return(struct pf_krule *r, struct pf_krule *nr, struct pf_pdesc *pd,
2945     struct pf_state_key *sk, int off, struct mbuf *m, struct tcphdr *th,
2946     struct pfi_kkif *kif, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen,
2947     u_short *reason)
2948 {
2949 	struct pf_addr	* const saddr = pd->src;
2950 	struct pf_addr	* const daddr = pd->dst;
2951 	sa_family_t	 af = pd->af;
2952 
2953 	/* undo NAT changes, if they have taken place */
2954 	if (nr != NULL) {
2955 		PF_ACPY(saddr, &sk->addr[pd->sidx], af);
2956 		PF_ACPY(daddr, &sk->addr[pd->didx], af);
2957 		if (pd->sport)
2958 			*pd->sport = sk->port[pd->sidx];
2959 		if (pd->dport)
2960 			*pd->dport = sk->port[pd->didx];
2961 		if (pd->proto_sum)
2962 			*pd->proto_sum = bproto_sum;
2963 		if (pd->ip_sum)
2964 			*pd->ip_sum = bip_sum;
2965 		m_copyback(m, off, hdrlen, pd->hdr.any);
2966 	}
2967 	if (pd->proto == IPPROTO_TCP &&
2968 	    ((r->rule_flag & PFRULE_RETURNRST) ||
2969 	    (r->rule_flag & PFRULE_RETURN)) &&
2970 	    !(th->th_flags & TH_RST)) {
2971 		u_int32_t	 ack = ntohl(th->th_seq) + pd->p_len;
2972 		int		 len = 0;
2973 #ifdef INET
2974 		struct ip	*h4;
2975 #endif
2976 #ifdef INET6
2977 		struct ip6_hdr	*h6;
2978 #endif
2979 
2980 		switch (af) {
2981 #ifdef INET
2982 		case AF_INET:
2983 			h4 = mtod(m, struct ip *);
2984 			len = ntohs(h4->ip_len) - off;
2985 			break;
2986 #endif
2987 #ifdef INET6
2988 		case AF_INET6:
2989 			h6 = mtod(m, struct ip6_hdr *);
2990 			len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
2991 			break;
2992 #endif
2993 		}
2994 
2995 		if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
2996 			REASON_SET(reason, PFRES_PROTCKSUM);
2997 		else {
2998 			if (th->th_flags & TH_SYN)
2999 				ack++;
3000 			if (th->th_flags & TH_FIN)
3001 				ack++;
3002 			pf_send_tcp(r, af, pd->dst,
3003 				pd->src, th->th_dport, th->th_sport,
3004 				ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3005 				r->return_ttl, 1, 0);
3006 		}
3007 	} else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3008 		r->return_icmp)
3009 		pf_send_icmp(m, r->return_icmp >> 8,
3010 			r->return_icmp & 255, af, r);
3011 	else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3012 		r->return_icmp6)
3013 		pf_send_icmp(m, r->return_icmp6 >> 8,
3014 			r->return_icmp6 & 255, af, r);
3015 }
3016 
3017 static int
3018 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
3019 {
3020 	struct m_tag *mtag;
3021 	u_int8_t mpcp;
3022 
3023 	mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
3024 	if (mtag == NULL)
3025 		return (0);
3026 
3027 	if (prio == PF_PRIO_ZERO)
3028 		prio = 0;
3029 
3030 	mpcp = *(uint8_t *)(mtag + 1);
3031 
3032 	return (mpcp == prio);
3033 }
3034 
3035 static void
3036 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
3037     struct pf_krule *r)
3038 {
3039 	struct pf_send_entry *pfse;
3040 	struct mbuf *m0;
3041 	struct pf_mtag *pf_mtag;
3042 
3043 	/* Allocate outgoing queue entry, mbuf and mbuf tag. */
3044 	pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
3045 	if (pfse == NULL)
3046 		return;
3047 
3048 	if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
3049 		free(pfse, M_PFTEMP);
3050 		return;
3051 	}
3052 
3053 	if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
3054 		free(pfse, M_PFTEMP);
3055 		return;
3056 	}
3057 	/* XXX: revisit */
3058 	m0->m_flags |= M_SKIP_FIREWALL;
3059 
3060 	if (r->rtableid >= 0)
3061 		M_SETFIB(m0, r->rtableid);
3062 
3063 #ifdef ALTQ
3064 	if (r->qid) {
3065 		pf_mtag->qid = r->qid;
3066 		/* add hints for ecn */
3067 		pf_mtag->hdr = mtod(m0, struct ip *);
3068 	}
3069 #endif /* ALTQ */
3070 
3071 	switch (af) {
3072 #ifdef INET
3073 	case AF_INET:
3074 		pfse->pfse_type = PFSE_ICMP;
3075 		break;
3076 #endif /* INET */
3077 #ifdef INET6
3078 	case AF_INET6:
3079 		pfse->pfse_type = PFSE_ICMP6;
3080 		break;
3081 #endif /* INET6 */
3082 	}
3083 	pfse->pfse_m = m0;
3084 	pfse->icmpopts.type = type;
3085 	pfse->icmpopts.code = code;
3086 	pf_send(pfse);
3087 }
3088 
3089 /*
3090  * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
3091  * If n is 0, they match if they are equal. If n is != 0, they match if they
3092  * are different.
3093  */
3094 int
3095 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
3096     struct pf_addr *b, sa_family_t af)
3097 {
3098 	int	match = 0;
3099 
3100 	switch (af) {
3101 #ifdef INET
3102 	case AF_INET:
3103 		if ((a->addr32[0] & m->addr32[0]) ==
3104 		    (b->addr32[0] & m->addr32[0]))
3105 			match++;
3106 		break;
3107 #endif /* INET */
3108 #ifdef INET6
3109 	case AF_INET6:
3110 		if (((a->addr32[0] & m->addr32[0]) ==
3111 		     (b->addr32[0] & m->addr32[0])) &&
3112 		    ((a->addr32[1] & m->addr32[1]) ==
3113 		     (b->addr32[1] & m->addr32[1])) &&
3114 		    ((a->addr32[2] & m->addr32[2]) ==
3115 		     (b->addr32[2] & m->addr32[2])) &&
3116 		    ((a->addr32[3] & m->addr32[3]) ==
3117 		     (b->addr32[3] & m->addr32[3])))
3118 			match++;
3119 		break;
3120 #endif /* INET6 */
3121 	}
3122 	if (match) {
3123 		if (n)
3124 			return (0);
3125 		else
3126 			return (1);
3127 	} else {
3128 		if (n)
3129 			return (1);
3130 		else
3131 			return (0);
3132 	}
3133 }
3134 
3135 /*
3136  * Return 1 if b <= a <= e, otherwise return 0.
3137  */
3138 int
3139 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
3140     struct pf_addr *a, sa_family_t af)
3141 {
3142 	switch (af) {
3143 #ifdef INET
3144 	case AF_INET:
3145 		if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
3146 		    (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
3147 			return (0);
3148 		break;
3149 #endif /* INET */
3150 #ifdef INET6
3151 	case AF_INET6: {
3152 		int	i;
3153 
3154 		/* check a >= b */
3155 		for (i = 0; i < 4; ++i)
3156 			if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
3157 				break;
3158 			else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
3159 				return (0);
3160 		/* check a <= e */
3161 		for (i = 0; i < 4; ++i)
3162 			if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
3163 				break;
3164 			else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
3165 				return (0);
3166 		break;
3167 	}
3168 #endif /* INET6 */
3169 	}
3170 	return (1);
3171 }
3172 
3173 static int
3174 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
3175 {
3176 	switch (op) {
3177 	case PF_OP_IRG:
3178 		return ((p > a1) && (p < a2));
3179 	case PF_OP_XRG:
3180 		return ((p < a1) || (p > a2));
3181 	case PF_OP_RRG:
3182 		return ((p >= a1) && (p <= a2));
3183 	case PF_OP_EQ:
3184 		return (p == a1);
3185 	case PF_OP_NE:
3186 		return (p != a1);
3187 	case PF_OP_LT:
3188 		return (p < a1);
3189 	case PF_OP_LE:
3190 		return (p <= a1);
3191 	case PF_OP_GT:
3192 		return (p > a1);
3193 	case PF_OP_GE:
3194 		return (p >= a1);
3195 	}
3196 	return (0); /* never reached */
3197 }
3198 
3199 int
3200 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
3201 {
3202 	NTOHS(a1);
3203 	NTOHS(a2);
3204 	NTOHS(p);
3205 	return (pf_match(op, a1, a2, p));
3206 }
3207 
3208 static int
3209 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
3210 {
3211 	if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
3212 		return (0);
3213 	return (pf_match(op, a1, a2, u));
3214 }
3215 
3216 static int
3217 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
3218 {
3219 	if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
3220 		return (0);
3221 	return (pf_match(op, a1, a2, g));
3222 }
3223 
3224 int
3225 pf_match_tag(struct mbuf *m, struct pf_krule *r, int *tag, int mtag)
3226 {
3227 	if (*tag == -1)
3228 		*tag = mtag;
3229 
3230 	return ((!r->match_tag_not && r->match_tag == *tag) ||
3231 	    (r->match_tag_not && r->match_tag != *tag));
3232 }
3233 
3234 int
3235 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
3236 {
3237 
3238 	KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
3239 
3240 	if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
3241 		return (ENOMEM);
3242 
3243 	pd->pf_mtag->tag = tag;
3244 
3245 	return (0);
3246 }
3247 
3248 #define	PF_ANCHOR_STACKSIZE	32
3249 struct pf_kanchor_stackframe {
3250 	struct pf_kruleset	*rs;
3251 	struct pf_krule		*r;	/* XXX: + match bit */
3252 	struct pf_kanchor	*child;
3253 };
3254 
3255 /*
3256  * XXX: We rely on malloc(9) returning pointer aligned addresses.
3257  */
3258 #define	PF_ANCHORSTACK_MATCH	0x00000001
3259 #define	PF_ANCHORSTACK_MASK	(PF_ANCHORSTACK_MATCH)
3260 
3261 #define	PF_ANCHOR_MATCH(f)	((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
3262 #define	PF_ANCHOR_RULE(f)	(struct pf_krule *)			\
3263 				((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
3264 #define	PF_ANCHOR_SET_MATCH(f)	do { (f)->r = (void *) 			\
3265 				((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH);  \
3266 } while (0)
3267 
3268 void
3269 pf_step_into_anchor(struct pf_kanchor_stackframe *stack, int *depth,
3270     struct pf_kruleset **rs, int n, struct pf_krule **r, struct pf_krule **a,
3271     int *match)
3272 {
3273 	struct pf_kanchor_stackframe	*f;
3274 
3275 	PF_RULES_RASSERT();
3276 
3277 	if (match)
3278 		*match = 0;
3279 	if (*depth >= PF_ANCHOR_STACKSIZE) {
3280 		printf("%s: anchor stack overflow on %s\n",
3281 		    __func__, (*r)->anchor->name);
3282 		*r = TAILQ_NEXT(*r, entries);
3283 		return;
3284 	} else if (*depth == 0 && a != NULL)
3285 		*a = *r;
3286 	f = stack + (*depth)++;
3287 	f->rs = *rs;
3288 	f->r = *r;
3289 	if ((*r)->anchor_wildcard) {
3290 		struct pf_kanchor_node *parent = &(*r)->anchor->children;
3291 
3292 		if ((f->child = RB_MIN(pf_kanchor_node, parent)) == NULL) {
3293 			*r = NULL;
3294 			return;
3295 		}
3296 		*rs = &f->child->ruleset;
3297 	} else {
3298 		f->child = NULL;
3299 		*rs = &(*r)->anchor->ruleset;
3300 	}
3301 	*r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
3302 }
3303 
3304 int
3305 pf_step_out_of_anchor(struct pf_kanchor_stackframe *stack, int *depth,
3306     struct pf_kruleset **rs, int n, struct pf_krule **r, struct pf_krule **a,
3307     int *match)
3308 {
3309 	struct pf_kanchor_stackframe	*f;
3310 	struct pf_krule *fr;
3311 	int quick = 0;
3312 
3313 	PF_RULES_RASSERT();
3314 
3315 	do {
3316 		if (*depth <= 0)
3317 			break;
3318 		f = stack + *depth - 1;
3319 		fr = PF_ANCHOR_RULE(f);
3320 		if (f->child != NULL) {
3321 			struct pf_kanchor_node *parent;
3322 
3323 			/*
3324 			 * This block traverses through
3325 			 * a wildcard anchor.
3326 			 */
3327 			parent = &fr->anchor->children;
3328 			if (match != NULL && *match) {
3329 				/*
3330 				 * If any of "*" matched, then
3331 				 * "foo/ *" matched, mark frame
3332 				 * appropriately.
3333 				 */
3334 				PF_ANCHOR_SET_MATCH(f);
3335 				*match = 0;
3336 			}
3337 			f->child = RB_NEXT(pf_kanchor_node, parent, f->child);
3338 			if (f->child != NULL) {
3339 				*rs = &f->child->ruleset;
3340 				*r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
3341 				if (*r == NULL)
3342 					continue;
3343 				else
3344 					break;
3345 			}
3346 		}
3347 		(*depth)--;
3348 		if (*depth == 0 && a != NULL)
3349 			*a = NULL;
3350 		*rs = f->rs;
3351 		if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
3352 			quick = fr->quick;
3353 		*r = TAILQ_NEXT(fr, entries);
3354 	} while (*r == NULL);
3355 
3356 	return (quick);
3357 }
3358 
3359 #ifdef INET6
3360 void
3361 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
3362     struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
3363 {
3364 	switch (af) {
3365 #ifdef INET
3366 	case AF_INET:
3367 		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
3368 		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
3369 		break;
3370 #endif /* INET */
3371 	case AF_INET6:
3372 		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
3373 		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
3374 		naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
3375 		((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
3376 		naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
3377 		((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
3378 		naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
3379 		((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
3380 		break;
3381 	}
3382 }
3383 
3384 void
3385 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
3386 {
3387 	switch (af) {
3388 #ifdef INET
3389 	case AF_INET:
3390 		addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
3391 		break;
3392 #endif /* INET */
3393 	case AF_INET6:
3394 		if (addr->addr32[3] == 0xffffffff) {
3395 			addr->addr32[3] = 0;
3396 			if (addr->addr32[2] == 0xffffffff) {
3397 				addr->addr32[2] = 0;
3398 				if (addr->addr32[1] == 0xffffffff) {
3399 					addr->addr32[1] = 0;
3400 					addr->addr32[0] =
3401 					    htonl(ntohl(addr->addr32[0]) + 1);
3402 				} else
3403 					addr->addr32[1] =
3404 					    htonl(ntohl(addr->addr32[1]) + 1);
3405 			} else
3406 				addr->addr32[2] =
3407 				    htonl(ntohl(addr->addr32[2]) + 1);
3408 		} else
3409 			addr->addr32[3] =
3410 			    htonl(ntohl(addr->addr32[3]) + 1);
3411 		break;
3412 	}
3413 }
3414 #endif /* INET6 */
3415 
3416 void
3417 pf_rule_to_actions(struct pf_krule *r, struct pf_rule_actions *a)
3418 {
3419 	if (r->qid)
3420 		a->qid = r->qid;
3421 	if (r->pqid)
3422 		a->pqid = r->pqid;
3423 	if (r->dnpipe)
3424 		a->dnpipe = r->dnpipe;
3425 	if (r->dnrpipe)
3426 		a->dnpipe = r->dnrpipe;
3427 	if (r->free_flags & PFRULE_DN_IS_PIPE)
3428 		a->flags |= PFRULE_DN_IS_PIPE;
3429 }
3430 
3431 int
3432 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
3433 {
3434 	struct pf_addr		*saddr, *daddr;
3435 	u_int16_t		 sport, dport;
3436 	struct inpcbinfo	*pi;
3437 	struct inpcb		*inp;
3438 
3439 	pd->lookup.uid = UID_MAX;
3440 	pd->lookup.gid = GID_MAX;
3441 
3442 	switch (pd->proto) {
3443 	case IPPROTO_TCP:
3444 		sport = pd->hdr.tcp.th_sport;
3445 		dport = pd->hdr.tcp.th_dport;
3446 		pi = &V_tcbinfo;
3447 		break;
3448 	case IPPROTO_UDP:
3449 		sport = pd->hdr.udp.uh_sport;
3450 		dport = pd->hdr.udp.uh_dport;
3451 		pi = &V_udbinfo;
3452 		break;
3453 	default:
3454 		return (-1);
3455 	}
3456 	if (direction == PF_IN) {
3457 		saddr = pd->src;
3458 		daddr = pd->dst;
3459 	} else {
3460 		u_int16_t	p;
3461 
3462 		p = sport;
3463 		sport = dport;
3464 		dport = p;
3465 		saddr = pd->dst;
3466 		daddr = pd->src;
3467 	}
3468 	switch (pd->af) {
3469 #ifdef INET
3470 	case AF_INET:
3471 		inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
3472 		    dport, INPLOOKUP_RLOCKPCB, NULL, m);
3473 		if (inp == NULL) {
3474 			inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
3475 			   daddr->v4, dport, INPLOOKUP_WILDCARD |
3476 			   INPLOOKUP_RLOCKPCB, NULL, m);
3477 			if (inp == NULL)
3478 				return (-1);
3479 		}
3480 		break;
3481 #endif /* INET */
3482 #ifdef INET6
3483 	case AF_INET6:
3484 		inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
3485 		    dport, INPLOOKUP_RLOCKPCB, NULL, m);
3486 		if (inp == NULL) {
3487 			inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
3488 			    &daddr->v6, dport, INPLOOKUP_WILDCARD |
3489 			    INPLOOKUP_RLOCKPCB, NULL, m);
3490 			if (inp == NULL)
3491 				return (-1);
3492 		}
3493 		break;
3494 #endif /* INET6 */
3495 
3496 	default:
3497 		return (-1);
3498 	}
3499 	INP_RLOCK_ASSERT(inp);
3500 	pd->lookup.uid = inp->inp_cred->cr_uid;
3501 	pd->lookup.gid = inp->inp_cred->cr_groups[0];
3502 	INP_RUNLOCK(inp);
3503 
3504 	return (1);
3505 }
3506 
3507 u_int8_t
3508 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3509 {
3510 	int		 hlen;
3511 	u_int8_t	 hdr[60];
3512 	u_int8_t	*opt, optlen;
3513 	u_int8_t	 wscale = 0;
3514 
3515 	hlen = th_off << 2;		/* hlen <= sizeof(hdr) */
3516 	if (hlen <= sizeof(struct tcphdr))
3517 		return (0);
3518 	if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3519 		return (0);
3520 	opt = hdr + sizeof(struct tcphdr);
3521 	hlen -= sizeof(struct tcphdr);
3522 	while (hlen >= 3) {
3523 		switch (*opt) {
3524 		case TCPOPT_EOL:
3525 		case TCPOPT_NOP:
3526 			++opt;
3527 			--hlen;
3528 			break;
3529 		case TCPOPT_WINDOW:
3530 			wscale = opt[2];
3531 			if (wscale > TCP_MAX_WINSHIFT)
3532 				wscale = TCP_MAX_WINSHIFT;
3533 			wscale |= PF_WSCALE_FLAG;
3534 			/* FALLTHROUGH */
3535 		default:
3536 			optlen = opt[1];
3537 			if (optlen < 2)
3538 				optlen = 2;
3539 			hlen -= optlen;
3540 			opt += optlen;
3541 			break;
3542 		}
3543 	}
3544 	return (wscale);
3545 }
3546 
3547 u_int16_t
3548 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3549 {
3550 	int		 hlen;
3551 	u_int8_t	 hdr[60];
3552 	u_int8_t	*opt, optlen;
3553 	u_int16_t	 mss = V_tcp_mssdflt;
3554 
3555 	hlen = th_off << 2;	/* hlen <= sizeof(hdr) */
3556 	if (hlen <= sizeof(struct tcphdr))
3557 		return (0);
3558 	if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3559 		return (0);
3560 	opt = hdr + sizeof(struct tcphdr);
3561 	hlen -= sizeof(struct tcphdr);
3562 	while (hlen >= TCPOLEN_MAXSEG) {
3563 		switch (*opt) {
3564 		case TCPOPT_EOL:
3565 		case TCPOPT_NOP:
3566 			++opt;
3567 			--hlen;
3568 			break;
3569 		case TCPOPT_MAXSEG:
3570 			bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3571 			NTOHS(mss);
3572 			/* FALLTHROUGH */
3573 		default:
3574 			optlen = opt[1];
3575 			if (optlen < 2)
3576 				optlen = 2;
3577 			hlen -= optlen;
3578 			opt += optlen;
3579 			break;
3580 		}
3581 	}
3582 	return (mss);
3583 }
3584 
3585 static u_int16_t
3586 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3587 {
3588 	struct nhop_object *nh;
3589 #ifdef INET6
3590 	struct in6_addr		dst6;
3591 	uint32_t		scopeid;
3592 #endif /* INET6 */
3593 	int			 hlen = 0;
3594 	uint16_t		 mss = 0;
3595 
3596 	NET_EPOCH_ASSERT();
3597 
3598 	switch (af) {
3599 #ifdef INET
3600 	case AF_INET:
3601 		hlen = sizeof(struct ip);
3602 		nh = fib4_lookup(rtableid, addr->v4, 0, 0, 0);
3603 		if (nh != NULL)
3604 			mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
3605 		break;
3606 #endif /* INET */
3607 #ifdef INET6
3608 	case AF_INET6:
3609 		hlen = sizeof(struct ip6_hdr);
3610 		in6_splitscope(&addr->v6, &dst6, &scopeid);
3611 		nh = fib6_lookup(rtableid, &dst6, scopeid, 0, 0);
3612 		if (nh != NULL)
3613 			mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
3614 		break;
3615 #endif /* INET6 */
3616 	}
3617 
3618 	mss = max(V_tcp_mssdflt, mss);
3619 	mss = min(mss, offer);
3620 	mss = max(mss, 64);		/* sanity - at least max opt space */
3621 	return (mss);
3622 }
3623 
3624 static u_int32_t
3625 pf_tcp_iss(struct pf_pdesc *pd)
3626 {
3627 	MD5_CTX ctx;
3628 	u_int32_t digest[4];
3629 
3630 	if (V_pf_tcp_secret_init == 0) {
3631 		arc4random_buf(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3632 		MD5Init(&V_pf_tcp_secret_ctx);
3633 		MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3634 		    sizeof(V_pf_tcp_secret));
3635 		V_pf_tcp_secret_init = 1;
3636 	}
3637 
3638 	ctx = V_pf_tcp_secret_ctx;
3639 
3640 	MD5Update(&ctx, (char *)&pd->hdr.tcp.th_sport, sizeof(u_short));
3641 	MD5Update(&ctx, (char *)&pd->hdr.tcp.th_dport, sizeof(u_short));
3642 	if (pd->af == AF_INET6) {
3643 		MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3644 		MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3645 	} else {
3646 		MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3647 		MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3648 	}
3649 	MD5Final((u_char *)digest, &ctx);
3650 	V_pf_tcp_iss_off += 4096;
3651 #define	ISN_RANDOM_INCREMENT (4096 - 1)
3652 	return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3653 	    V_pf_tcp_iss_off);
3654 #undef	ISN_RANDOM_INCREMENT
3655 }
3656 
3657 static int
3658 pf_test_rule(struct pf_krule **rm, struct pf_kstate **sm, int direction,
3659     struct pfi_kkif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3660     struct pf_krule **am, struct pf_kruleset **rsm, struct inpcb *inp)
3661 {
3662 	struct pf_krule		*nr = NULL;
3663 	struct pf_addr		* const saddr = pd->src;
3664 	struct pf_addr		* const daddr = pd->dst;
3665 	sa_family_t		 af = pd->af;
3666 	struct pf_krule		*r, *a = NULL;
3667 	struct pf_kruleset	*ruleset = NULL;
3668 	struct pf_ksrc_node	*nsn = NULL;
3669 	struct tcphdr		*th = &pd->hdr.tcp;
3670 	struct pf_state_key	*sk = NULL, *nk = NULL;
3671 	u_short			 reason;
3672 	int			 rewrite = 0, hdrlen = 0;
3673 	int			 tag = -1, rtableid = -1;
3674 	int			 asd = 0;
3675 	int			 match = 0;
3676 	int			 state_icmp = 0;
3677 	u_int16_t		 sport = 0, dport = 0;
3678 	u_int16_t		 bproto_sum = 0, bip_sum = 0;
3679 	u_int8_t		 icmptype = 0, icmpcode = 0;
3680 	struct pf_kanchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
3681 
3682 	PF_RULES_RASSERT();
3683 
3684 	if (inp != NULL) {
3685 		INP_LOCK_ASSERT(inp);
3686 		pd->lookup.uid = inp->inp_cred->cr_uid;
3687 		pd->lookup.gid = inp->inp_cred->cr_groups[0];
3688 		pd->lookup.done = 1;
3689 	}
3690 
3691 	switch (pd->proto) {
3692 	case IPPROTO_TCP:
3693 		sport = th->th_sport;
3694 		dport = th->th_dport;
3695 		hdrlen = sizeof(*th);
3696 		break;
3697 	case IPPROTO_UDP:
3698 		sport = pd->hdr.udp.uh_sport;
3699 		dport = pd->hdr.udp.uh_dport;
3700 		hdrlen = sizeof(pd->hdr.udp);
3701 		break;
3702 #ifdef INET
3703 	case IPPROTO_ICMP:
3704 		if (pd->af != AF_INET)
3705 			break;
3706 		sport = dport = pd->hdr.icmp.icmp_id;
3707 		hdrlen = sizeof(pd->hdr.icmp);
3708 		icmptype = pd->hdr.icmp.icmp_type;
3709 		icmpcode = pd->hdr.icmp.icmp_code;
3710 
3711 		if (icmptype == ICMP_UNREACH ||
3712 		    icmptype == ICMP_SOURCEQUENCH ||
3713 		    icmptype == ICMP_REDIRECT ||
3714 		    icmptype == ICMP_TIMXCEED ||
3715 		    icmptype == ICMP_PARAMPROB)
3716 			state_icmp++;
3717 		break;
3718 #endif /* INET */
3719 #ifdef INET6
3720 	case IPPROTO_ICMPV6:
3721 		if (af != AF_INET6)
3722 			break;
3723 		sport = dport = pd->hdr.icmp6.icmp6_id;
3724 		hdrlen = sizeof(pd->hdr.icmp6);
3725 		icmptype = pd->hdr.icmp6.icmp6_type;
3726 		icmpcode = pd->hdr.icmp6.icmp6_code;
3727 
3728 		if (icmptype == ICMP6_DST_UNREACH ||
3729 		    icmptype == ICMP6_PACKET_TOO_BIG ||
3730 		    icmptype == ICMP6_TIME_EXCEEDED ||
3731 		    icmptype == ICMP6_PARAM_PROB)
3732 			state_icmp++;
3733 		break;
3734 #endif /* INET6 */
3735 	default:
3736 		sport = dport = hdrlen = 0;
3737 		break;
3738 	}
3739 
3740 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3741 
3742 	/* check packet for BINAT/NAT/RDR */
3743 	if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3744 	    &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3745 		KASSERT(sk != NULL, ("%s: null sk", __func__));
3746 		KASSERT(nk != NULL, ("%s: null nk", __func__));
3747 
3748 		if (nr->log) {
3749 			PFLOG_PACKET(kif, m, af, direction, PFRES_MATCH, nr, a,
3750 			    ruleset, pd, 1);
3751 		}
3752 
3753 		if (pd->ip_sum)
3754 			bip_sum = *pd->ip_sum;
3755 
3756 		switch (pd->proto) {
3757 		case IPPROTO_TCP:
3758 			bproto_sum = th->th_sum;
3759 			pd->proto_sum = &th->th_sum;
3760 
3761 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3762 			    nk->port[pd->sidx] != sport) {
3763 				pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3764 				    &th->th_sum, &nk->addr[pd->sidx],
3765 				    nk->port[pd->sidx], 0, af);
3766 				pd->sport = &th->th_sport;
3767 				sport = th->th_sport;
3768 			}
3769 
3770 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3771 			    nk->port[pd->didx] != dport) {
3772 				pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3773 				    &th->th_sum, &nk->addr[pd->didx],
3774 				    nk->port[pd->didx], 0, af);
3775 				dport = th->th_dport;
3776 				pd->dport = &th->th_dport;
3777 			}
3778 			rewrite++;
3779 			break;
3780 		case IPPROTO_UDP:
3781 			bproto_sum = pd->hdr.udp.uh_sum;
3782 			pd->proto_sum = &pd->hdr.udp.uh_sum;
3783 
3784 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3785 			    nk->port[pd->sidx] != sport) {
3786 				pf_change_ap(m, saddr, &pd->hdr.udp.uh_sport,
3787 				    pd->ip_sum, &pd->hdr.udp.uh_sum,
3788 				    &nk->addr[pd->sidx],
3789 				    nk->port[pd->sidx], 1, af);
3790 				sport = pd->hdr.udp.uh_sport;
3791 				pd->sport = &pd->hdr.udp.uh_sport;
3792 			}
3793 
3794 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3795 			    nk->port[pd->didx] != dport) {
3796 				pf_change_ap(m, daddr, &pd->hdr.udp.uh_dport,
3797 				    pd->ip_sum, &pd->hdr.udp.uh_sum,
3798 				    &nk->addr[pd->didx],
3799 				    nk->port[pd->didx], 1, af);
3800 				dport = pd->hdr.udp.uh_dport;
3801 				pd->dport = &pd->hdr.udp.uh_dport;
3802 			}
3803 			rewrite++;
3804 			break;
3805 #ifdef INET
3806 		case IPPROTO_ICMP:
3807 			nk->port[0] = nk->port[1];
3808 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3809 				pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3810 				    nk->addr[pd->sidx].v4.s_addr, 0);
3811 
3812 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3813 				pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3814 				    nk->addr[pd->didx].v4.s_addr, 0);
3815 
3816 			if (nk->port[1] != pd->hdr.icmp.icmp_id) {
3817 				pd->hdr.icmp.icmp_cksum = pf_cksum_fixup(
3818 				    pd->hdr.icmp.icmp_cksum, sport,
3819 				    nk->port[1], 0);
3820 				pd->hdr.icmp.icmp_id = nk->port[1];
3821 				pd->sport = &pd->hdr.icmp.icmp_id;
3822 			}
3823 			m_copyback(m, off, ICMP_MINLEN, (caddr_t)&pd->hdr.icmp);
3824 			break;
3825 #endif /* INET */
3826 #ifdef INET6
3827 		case IPPROTO_ICMPV6:
3828 			nk->port[0] = nk->port[1];
3829 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3830 				pf_change_a6(saddr, &pd->hdr.icmp6.icmp6_cksum,
3831 				    &nk->addr[pd->sidx], 0);
3832 
3833 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3834 				pf_change_a6(daddr, &pd->hdr.icmp6.icmp6_cksum,
3835 				    &nk->addr[pd->didx], 0);
3836 			rewrite++;
3837 			break;
3838 #endif /* INET */
3839 		default:
3840 			switch (af) {
3841 #ifdef INET
3842 			case AF_INET:
3843 				if (PF_ANEQ(saddr,
3844 				    &nk->addr[pd->sidx], AF_INET))
3845 					pf_change_a(&saddr->v4.s_addr,
3846 					    pd->ip_sum,
3847 					    nk->addr[pd->sidx].v4.s_addr, 0);
3848 
3849 				if (PF_ANEQ(daddr,
3850 				    &nk->addr[pd->didx], AF_INET))
3851 					pf_change_a(&daddr->v4.s_addr,
3852 					    pd->ip_sum,
3853 					    nk->addr[pd->didx].v4.s_addr, 0);
3854 				break;
3855 #endif /* INET */
3856 #ifdef INET6
3857 			case AF_INET6:
3858 				if (PF_ANEQ(saddr,
3859 				    &nk->addr[pd->sidx], AF_INET6))
3860 					PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3861 
3862 				if (PF_ANEQ(daddr,
3863 				    &nk->addr[pd->didx], AF_INET6))
3864 					PF_ACPY(daddr, &nk->addr[pd->didx], af);
3865 				break;
3866 #endif /* INET */
3867 			}
3868 			break;
3869 		}
3870 		if (nr->natpass)
3871 			r = NULL;
3872 		pd->nat_rule = nr;
3873 	}
3874 
3875 	while (r != NULL) {
3876 		pf_counter_u64_add(&r->evaluations, 1);
3877 		if (pfi_kkif_match(r->kif, kif) == r->ifnot)
3878 			r = r->skip[PF_SKIP_IFP].ptr;
3879 		else if (r->direction && r->direction != direction)
3880 			r = r->skip[PF_SKIP_DIR].ptr;
3881 		else if (r->af && r->af != af)
3882 			r = r->skip[PF_SKIP_AF].ptr;
3883 		else if (r->proto && r->proto != pd->proto)
3884 			r = r->skip[PF_SKIP_PROTO].ptr;
3885 		else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3886 		    r->src.neg, kif, M_GETFIB(m)))
3887 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3888 		/* tcp/udp only. port_op always 0 in other cases */
3889 		else if (r->src.port_op && !pf_match_port(r->src.port_op,
3890 		    r->src.port[0], r->src.port[1], sport))
3891 			r = r->skip[PF_SKIP_SRC_PORT].ptr;
3892 		else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3893 		    r->dst.neg, NULL, M_GETFIB(m)))
3894 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
3895 		/* tcp/udp only. port_op always 0 in other cases */
3896 		else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3897 		    r->dst.port[0], r->dst.port[1], dport))
3898 			r = r->skip[PF_SKIP_DST_PORT].ptr;
3899 		/* icmp only. type always 0 in other cases */
3900 		else if (r->type && r->type != icmptype + 1)
3901 			r = TAILQ_NEXT(r, entries);
3902 		/* icmp only. type always 0 in other cases */
3903 		else if (r->code && r->code != icmpcode + 1)
3904 			r = TAILQ_NEXT(r, entries);
3905 		else if (r->tos && !(r->tos == pd->tos))
3906 			r = TAILQ_NEXT(r, entries);
3907 		else if (r->rule_flag & PFRULE_FRAGMENT)
3908 			r = TAILQ_NEXT(r, entries);
3909 		else if (pd->proto == IPPROTO_TCP &&
3910 		    (r->flagset & th->th_flags) != r->flags)
3911 			r = TAILQ_NEXT(r, entries);
3912 		/* tcp/udp only. uid.op always 0 in other cases */
3913 		else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3914 		    pf_socket_lookup(direction, pd, m), 1)) &&
3915 		    !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3916 		    pd->lookup.uid))
3917 			r = TAILQ_NEXT(r, entries);
3918 		/* tcp/udp only. gid.op always 0 in other cases */
3919 		else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3920 		    pf_socket_lookup(direction, pd, m), 1)) &&
3921 		    !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3922 		    pd->lookup.gid))
3923 			r = TAILQ_NEXT(r, entries);
3924 		else if (r->prio &&
3925 		    !pf_match_ieee8021q_pcp(r->prio, m))
3926 			r = TAILQ_NEXT(r, entries);
3927 		else if (r->prob &&
3928 		    r->prob <= arc4random())
3929 			r = TAILQ_NEXT(r, entries);
3930 		else if (r->match_tag && !pf_match_tag(m, r, &tag,
3931 		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
3932 			r = TAILQ_NEXT(r, entries);
3933 		else if (r->os_fingerprint != PF_OSFP_ANY &&
3934 		    (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3935 		    pf_osfp_fingerprint(pd, m, off, th),
3936 		    r->os_fingerprint)))
3937 			r = TAILQ_NEXT(r, entries);
3938 		else {
3939 			if (r->tag)
3940 				tag = r->tag;
3941 			if (r->rtableid >= 0)
3942 				rtableid = r->rtableid;
3943 			if (r->anchor == NULL) {
3944 				if (r->action == PF_MATCH) {
3945 					pf_counter_u64_critical_enter();
3946 					pf_counter_u64_add_protected(&r->packets[direction == PF_OUT], 1);
3947 					pf_counter_u64_add_protected(&r->bytes[direction == PF_OUT], pd->tot_len);
3948 					pf_counter_u64_critical_exit();
3949 					pf_rule_to_actions(r, &pd->act);
3950 					if (r->log)
3951 						PFLOG_PACKET(kif, m, af,
3952 						    direction, PFRES_MATCH, r,
3953 						    a, ruleset, pd, 1);
3954 				} else {
3955 					match = 1;
3956 					*rm = r;
3957 					*am = a;
3958 					*rsm = ruleset;
3959 				}
3960 				if ((*rm)->quick)
3961 					break;
3962 				r = TAILQ_NEXT(r, entries);
3963 			} else
3964 				pf_step_into_anchor(anchor_stack, &asd,
3965 				    &ruleset, PF_RULESET_FILTER, &r, &a,
3966 				    &match);
3967 		}
3968 		if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3969 		    &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3970 			break;
3971 	}
3972 	r = *rm;
3973 	a = *am;
3974 	ruleset = *rsm;
3975 
3976 	REASON_SET(&reason, PFRES_MATCH);
3977 
3978 	/* apply actions for last matching pass/block rule */
3979 	pf_rule_to_actions(r, &pd->act);
3980 
3981 	if (r->log) {
3982 		if (rewrite)
3983 			m_copyback(m, off, hdrlen, pd->hdr.any);
3984 		PFLOG_PACKET(kif, m, af, direction, reason, r, a,
3985 		    ruleset, pd, 1);
3986 	}
3987 
3988 	if ((r->action == PF_DROP) &&
3989 	    ((r->rule_flag & PFRULE_RETURNRST) ||
3990 	    (r->rule_flag & PFRULE_RETURNICMP) ||
3991 	    (r->rule_flag & PFRULE_RETURN))) {
3992 		pf_return(r, nr, pd, sk, off, m, th, kif, bproto_sum,
3993 		    bip_sum, hdrlen, &reason);
3994 	}
3995 
3996 	if (r->action == PF_DROP)
3997 		goto cleanup;
3998 
3999 	if (tag > 0 && pf_tag_packet(m, pd, tag)) {
4000 		REASON_SET(&reason, PFRES_MEMORY);
4001 		goto cleanup;
4002 	}
4003 	if (rtableid >= 0)
4004 		M_SETFIB(m, rtableid);
4005 
4006 	if (!state_icmp && (r->keep_state || nr != NULL ||
4007 	    (pd->flags & PFDESC_TCP_NORM))) {
4008 		int action;
4009 		action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
4010 		    sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
4011 		    hdrlen);
4012 		if (action != PF_PASS) {
4013 			if (action == PF_DROP &&
4014 			    (r->rule_flag & PFRULE_RETURN))
4015 				pf_return(r, nr, pd, sk, off, m, th, kif,
4016 				    bproto_sum, bip_sum, hdrlen, &reason);
4017 			return (action);
4018 		}
4019 	} else {
4020 		if (sk != NULL)
4021 			uma_zfree(V_pf_state_key_z, sk);
4022 		if (nk != NULL)
4023 			uma_zfree(V_pf_state_key_z, nk);
4024 	}
4025 
4026 	/* copy back packet headers if we performed NAT operations */
4027 	if (rewrite)
4028 		m_copyback(m, off, hdrlen, pd->hdr.any);
4029 
4030 	if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
4031 	    direction == PF_OUT &&
4032 	    V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, m))
4033 		/*
4034 		 * We want the state created, but we dont
4035 		 * want to send this in case a partner
4036 		 * firewall has to know about it to allow
4037 		 * replies through it.
4038 		 */
4039 		return (PF_DEFER);
4040 
4041 	return (PF_PASS);
4042 
4043 cleanup:
4044 	if (sk != NULL)
4045 		uma_zfree(V_pf_state_key_z, sk);
4046 	if (nk != NULL)
4047 		uma_zfree(V_pf_state_key_z, nk);
4048 	return (PF_DROP);
4049 }
4050 
4051 static int
4052 pf_create_state(struct pf_krule *r, struct pf_krule *nr, struct pf_krule *a,
4053     struct pf_pdesc *pd, struct pf_ksrc_node *nsn, struct pf_state_key *nk,
4054     struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
4055     u_int16_t dport, int *rewrite, struct pfi_kkif *kif, struct pf_kstate **sm,
4056     int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
4057 {
4058 	struct pf_kstate	*s = NULL;
4059 	struct pf_ksrc_node	*sn = NULL;
4060 	struct tcphdr		*th = &pd->hdr.tcp;
4061 	u_int16_t		 mss = V_tcp_mssdflt;
4062 	u_short			 reason;
4063 
4064 	/* check maximums */
4065 	if (r->max_states &&
4066 	    (counter_u64_fetch(r->states_cur) >= r->max_states)) {
4067 		counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
4068 		REASON_SET(&reason, PFRES_MAXSTATES);
4069 		goto csfailed;
4070 	}
4071 	/* src node for filter rule */
4072 	if ((r->rule_flag & PFRULE_SRCTRACK ||
4073 	    r->rpool.opts & PF_POOL_STICKYADDR) &&
4074 	    pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
4075 		REASON_SET(&reason, PFRES_SRCLIMIT);
4076 		goto csfailed;
4077 	}
4078 	/* src node for translation rule */
4079 	if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
4080 	    pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
4081 		REASON_SET(&reason, PFRES_SRCLIMIT);
4082 		goto csfailed;
4083 	}
4084 	s = pf_alloc_state(M_NOWAIT);
4085 	if (s == NULL) {
4086 		REASON_SET(&reason, PFRES_MEMORY);
4087 		goto csfailed;
4088 	}
4089 	s->rule.ptr = r;
4090 	s->nat_rule.ptr = nr;
4091 	s->anchor.ptr = a;
4092 	STATE_INC_COUNTERS(s);
4093 	if (r->allow_opts)
4094 		s->state_flags |= PFSTATE_ALLOWOPTS;
4095 	if (r->rule_flag & PFRULE_STATESLOPPY)
4096 		s->state_flags |= PFSTATE_SLOPPY;
4097 	s->log = r->log & PF_LOG_ALL;
4098 	s->sync_state = PFSYNC_S_NONE;
4099 	s->qid = pd->act.qid;
4100 	s->pqid = pd->act.pqid;
4101 	s->dnpipe = pd->act.dnpipe;
4102 	s->dnrpipe = pd->act.dnrpipe;
4103 	s->state_flags |= pd->act.flags;
4104 	if (nr != NULL)
4105 		s->log |= nr->log & PF_LOG_ALL;
4106 	switch (pd->proto) {
4107 	case IPPROTO_TCP:
4108 		s->src.seqlo = ntohl(th->th_seq);
4109 		s->src.seqhi = s->src.seqlo + pd->p_len + 1;
4110 		if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
4111 		    r->keep_state == PF_STATE_MODULATE) {
4112 			/* Generate sequence number modulator */
4113 			if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
4114 			    0)
4115 				s->src.seqdiff = 1;
4116 			pf_change_proto_a(m, &th->th_seq, &th->th_sum,
4117 			    htonl(s->src.seqlo + s->src.seqdiff), 0);
4118 			*rewrite = 1;
4119 		} else
4120 			s->src.seqdiff = 0;
4121 		if (th->th_flags & TH_SYN) {
4122 			s->src.seqhi++;
4123 			s->src.wscale = pf_get_wscale(m, off,
4124 			    th->th_off, pd->af);
4125 		}
4126 		s->src.max_win = MAX(ntohs(th->th_win), 1);
4127 		if (s->src.wscale & PF_WSCALE_MASK) {
4128 			/* Remove scale factor from initial window */
4129 			int win = s->src.max_win;
4130 			win += 1 << (s->src.wscale & PF_WSCALE_MASK);
4131 			s->src.max_win = (win - 1) >>
4132 			    (s->src.wscale & PF_WSCALE_MASK);
4133 		}
4134 		if (th->th_flags & TH_FIN)
4135 			s->src.seqhi++;
4136 		s->dst.seqhi = 1;
4137 		s->dst.max_win = 1;
4138 		pf_set_protostate(s, PF_PEER_SRC, TCPS_SYN_SENT);
4139 		pf_set_protostate(s, PF_PEER_DST, TCPS_CLOSED);
4140 		s->timeout = PFTM_TCP_FIRST_PACKET;
4141 		atomic_add_32(&V_pf_status.states_halfopen, 1);
4142 		break;
4143 	case IPPROTO_UDP:
4144 		pf_set_protostate(s, PF_PEER_SRC, PFUDPS_SINGLE);
4145 		pf_set_protostate(s, PF_PEER_DST, PFUDPS_NO_TRAFFIC);
4146 		s->timeout = PFTM_UDP_FIRST_PACKET;
4147 		break;
4148 	case IPPROTO_ICMP:
4149 #ifdef INET6
4150 	case IPPROTO_ICMPV6:
4151 #endif
4152 		s->timeout = PFTM_ICMP_FIRST_PACKET;
4153 		break;
4154 	default:
4155 		pf_set_protostate(s, PF_PEER_SRC, PFOTHERS_SINGLE);
4156 		pf_set_protostate(s, PF_PEER_DST, PFOTHERS_NO_TRAFFIC);
4157 		s->timeout = PFTM_OTHER_FIRST_PACKET;
4158 	}
4159 
4160 	if (r->rt) {
4161 		if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
4162 			REASON_SET(&reason, PFRES_MAPFAILED);
4163 			pf_src_tree_remove_state(s);
4164 			s->timeout = PFTM_UNLINKED;
4165 			STATE_DEC_COUNTERS(s);
4166 			pf_free_state(s);
4167 			goto csfailed;
4168 		}
4169 		s->rt_kif = r->rpool.cur->kif;
4170 	}
4171 
4172 	s->creation = time_uptime;
4173 	s->expire = time_uptime;
4174 
4175 	if (sn != NULL)
4176 		s->src_node = sn;
4177 	if (nsn != NULL) {
4178 		/* XXX We only modify one side for now. */
4179 		PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
4180 		s->nat_src_node = nsn;
4181 	}
4182 	if (pd->proto == IPPROTO_TCP) {
4183 		if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
4184 		    off, pd, th, &s->src, &s->dst)) {
4185 			REASON_SET(&reason, PFRES_MEMORY);
4186 			pf_src_tree_remove_state(s);
4187 			s->timeout = PFTM_UNLINKED;
4188 			STATE_DEC_COUNTERS(s);
4189 			pf_free_state(s);
4190 			return (PF_DROP);
4191 		}
4192 		if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
4193 		    pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
4194 		    &s->src, &s->dst, rewrite)) {
4195 			/* This really shouldn't happen!!! */
4196 			DPFPRINTF(PF_DEBUG_URGENT,
4197 			    ("pf_normalize_tcp_stateful failed on first "
4198 			     "pkt\n"));
4199 			pf_src_tree_remove_state(s);
4200 			s->timeout = PFTM_UNLINKED;
4201 			STATE_DEC_COUNTERS(s);
4202 			pf_free_state(s);
4203 			return (PF_DROP);
4204 		}
4205 	}
4206 	s->direction = pd->dir;
4207 
4208 	/*
4209 	 * sk/nk could already been setup by pf_get_translation().
4210 	 */
4211 	if (nr == NULL) {
4212 		KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
4213 		    __func__, nr, sk, nk));
4214 		sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
4215 		if (sk == NULL)
4216 			goto csfailed;
4217 		nk = sk;
4218 	} else
4219 		KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
4220 		    __func__, nr, sk, nk));
4221 
4222 	/* Swap sk/nk for PF_OUT. */
4223 	if (pf_state_insert(BOUND_IFACE(r, kif), kif,
4224 	    (pd->dir == PF_IN) ? sk : nk,
4225 	    (pd->dir == PF_IN) ? nk : sk, s)) {
4226 		REASON_SET(&reason, PFRES_STATEINS);
4227 		pf_src_tree_remove_state(s);
4228 		s->timeout = PFTM_UNLINKED;
4229 		STATE_DEC_COUNTERS(s);
4230 		pf_free_state(s);
4231 		return (PF_DROP);
4232 	} else
4233 		*sm = s;
4234 
4235 	if (tag > 0)
4236 		s->tag = tag;
4237 	if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
4238 	    TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
4239 		pf_set_protostate(s, PF_PEER_SRC, PF_TCPS_PROXY_SRC);
4240 		/* undo NAT changes, if they have taken place */
4241 		if (nr != NULL) {
4242 			struct pf_state_key *skt = s->key[PF_SK_WIRE];
4243 			if (pd->dir == PF_OUT)
4244 				skt = s->key[PF_SK_STACK];
4245 			PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
4246 			PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
4247 			if (pd->sport)
4248 				*pd->sport = skt->port[pd->sidx];
4249 			if (pd->dport)
4250 				*pd->dport = skt->port[pd->didx];
4251 			if (pd->proto_sum)
4252 				*pd->proto_sum = bproto_sum;
4253 			if (pd->ip_sum)
4254 				*pd->ip_sum = bip_sum;
4255 			m_copyback(m, off, hdrlen, pd->hdr.any);
4256 		}
4257 		s->src.seqhi = htonl(arc4random());
4258 		/* Find mss option */
4259 		int rtid = M_GETFIB(m);
4260 		mss = pf_get_mss(m, off, th->th_off, pd->af);
4261 		mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
4262 		mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
4263 		s->src.mss = mss;
4264 		pf_send_tcp(r, pd->af, pd->dst, pd->src, th->th_dport,
4265 		    th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
4266 		    TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0);
4267 		REASON_SET(&reason, PFRES_SYNPROXY);
4268 		return (PF_SYNPROXY_DROP);
4269 	}
4270 
4271 	return (PF_PASS);
4272 
4273 csfailed:
4274 	if (sk != NULL)
4275 		uma_zfree(V_pf_state_key_z, sk);
4276 	if (nk != NULL)
4277 		uma_zfree(V_pf_state_key_z, nk);
4278 
4279 	if (sn != NULL) {
4280 		struct pf_srchash *sh;
4281 
4282 		sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
4283 		PF_HASHROW_LOCK(sh);
4284 		if (--sn->states == 0 && sn->expire == 0) {
4285 			pf_unlink_src_node(sn);
4286 			uma_zfree(V_pf_sources_z, sn);
4287 			counter_u64_add(
4288 			    V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
4289 		}
4290 		PF_HASHROW_UNLOCK(sh);
4291 	}
4292 
4293 	if (nsn != sn && nsn != NULL) {
4294 		struct pf_srchash *sh;
4295 
4296 		sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
4297 		PF_HASHROW_LOCK(sh);
4298 		if (--nsn->states == 0 && nsn->expire == 0) {
4299 			pf_unlink_src_node(nsn);
4300 			uma_zfree(V_pf_sources_z, nsn);
4301 			counter_u64_add(
4302 			    V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
4303 		}
4304 		PF_HASHROW_UNLOCK(sh);
4305 	}
4306 
4307 	return (PF_DROP);
4308 }
4309 
4310 static int
4311 pf_test_fragment(struct pf_krule **rm, int direction, struct pfi_kkif *kif,
4312     struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_krule **am,
4313     struct pf_kruleset **rsm)
4314 {
4315 	struct pf_krule		*r, *a = NULL;
4316 	struct pf_kruleset	*ruleset = NULL;
4317 	sa_family_t		 af = pd->af;
4318 	u_short			 reason;
4319 	int			 tag = -1;
4320 	int			 asd = 0;
4321 	int			 match = 0;
4322 	struct pf_kanchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
4323 
4324 	PF_RULES_RASSERT();
4325 
4326 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
4327 	while (r != NULL) {
4328 		pf_counter_u64_add(&r->evaluations, 1);
4329 		if (pfi_kkif_match(r->kif, kif) == r->ifnot)
4330 			r = r->skip[PF_SKIP_IFP].ptr;
4331 		else if (r->direction && r->direction != direction)
4332 			r = r->skip[PF_SKIP_DIR].ptr;
4333 		else if (r->af && r->af != af)
4334 			r = r->skip[PF_SKIP_AF].ptr;
4335 		else if (r->proto && r->proto != pd->proto)
4336 			r = r->skip[PF_SKIP_PROTO].ptr;
4337 		else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
4338 		    r->src.neg, kif, M_GETFIB(m)))
4339 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
4340 		else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
4341 		    r->dst.neg, NULL, M_GETFIB(m)))
4342 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
4343 		else if (r->tos && !(r->tos == pd->tos))
4344 			r = TAILQ_NEXT(r, entries);
4345 		else if (r->os_fingerprint != PF_OSFP_ANY)
4346 			r = TAILQ_NEXT(r, entries);
4347 		else if (pd->proto == IPPROTO_UDP &&
4348 		    (r->src.port_op || r->dst.port_op))
4349 			r = TAILQ_NEXT(r, entries);
4350 		else if (pd->proto == IPPROTO_TCP &&
4351 		    (r->src.port_op || r->dst.port_op || r->flagset))
4352 			r = TAILQ_NEXT(r, entries);
4353 		else if ((pd->proto == IPPROTO_ICMP ||
4354 		    pd->proto == IPPROTO_ICMPV6) &&
4355 		    (r->type || r->code))
4356 			r = TAILQ_NEXT(r, entries);
4357 		else if (r->prio &&
4358 		    !pf_match_ieee8021q_pcp(r->prio, m))
4359 			r = TAILQ_NEXT(r, entries);
4360 		else if (r->prob && r->prob <=
4361 		    (arc4random() % (UINT_MAX - 1) + 1))
4362 			r = TAILQ_NEXT(r, entries);
4363 		else if (r->match_tag && !pf_match_tag(m, r, &tag,
4364 		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
4365 			r = TAILQ_NEXT(r, entries);
4366 		else {
4367 			if (r->anchor == NULL) {
4368 				if (r->action == PF_MATCH) {
4369 					pf_counter_u64_critical_enter();
4370 					pf_counter_u64_add_protected(&r->packets[direction == PF_OUT], 1);
4371 					pf_counter_u64_add_protected(&r->bytes[direction == PF_OUT], pd->tot_len);
4372 					pf_counter_u64_critical_exit();
4373 					pf_rule_to_actions(r, &pd->act);
4374 					if (r->log)
4375 						PFLOG_PACKET(kif, m, af,
4376 						    direction, PFRES_MATCH, r,
4377 						    a, ruleset, pd, 1);
4378 				} else {
4379 					match = 1;
4380 					*rm = r;
4381 					*am = a;
4382 					*rsm = ruleset;
4383 				}
4384 				if ((*rm)->quick)
4385 					break;
4386 				r = TAILQ_NEXT(r, entries);
4387 			} else
4388 				pf_step_into_anchor(anchor_stack, &asd,
4389 				    &ruleset, PF_RULESET_FILTER, &r, &a,
4390 				    &match);
4391 		}
4392 		if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
4393 		    &ruleset, PF_RULESET_FILTER, &r, &a, &match))
4394 			break;
4395 	}
4396 	r = *rm;
4397 	a = *am;
4398 	ruleset = *rsm;
4399 
4400 	REASON_SET(&reason, PFRES_MATCH);
4401 
4402 	/* apply actions for last matching pass/block rule */
4403 	pf_rule_to_actions(r, &pd->act);
4404 
4405 	if (r->log)
4406 		PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
4407 		    1);
4408 
4409 	if (r->action != PF_PASS)
4410 		return (PF_DROP);
4411 
4412 	if (tag > 0 && pf_tag_packet(m, pd, tag)) {
4413 		REASON_SET(&reason, PFRES_MEMORY);
4414 		return (PF_DROP);
4415 	}
4416 
4417 	return (PF_PASS);
4418 }
4419 
4420 static int
4421 pf_tcp_track_full(struct pf_kstate **state, struct pfi_kkif *kif,
4422     struct mbuf *m, int off, struct pf_pdesc *pd, u_short *reason,
4423     int *copyback)
4424 {
4425 	struct tcphdr		*th = &pd->hdr.tcp;
4426 	struct pf_state_peer	*src, *dst;
4427 	u_int16_t		 win = ntohs(th->th_win);
4428 	u_int32_t		 ack, end, seq, orig_seq;
4429 	u_int8_t		 sws, dws, psrc, pdst;
4430 	int			 ackskew;
4431 
4432 	if (pd->dir == (*state)->direction) {
4433 		src = &(*state)->src;
4434 		dst = &(*state)->dst;
4435 		psrc = PF_PEER_SRC;
4436 		pdst = PF_PEER_DST;
4437 	} else {
4438 		src = &(*state)->dst;
4439 		dst = &(*state)->src;
4440 		psrc = PF_PEER_DST;
4441 		pdst = PF_PEER_SRC;
4442 	}
4443 
4444 	if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
4445 		sws = src->wscale & PF_WSCALE_MASK;
4446 		dws = dst->wscale & PF_WSCALE_MASK;
4447 	} else
4448 		sws = dws = 0;
4449 
4450 	/*
4451 	 * Sequence tracking algorithm from Guido van Rooij's paper:
4452 	 *   http://www.madison-gurkha.com/publications/tcp_filtering/
4453 	 *	tcp_filtering.ps
4454 	 */
4455 
4456 	orig_seq = seq = ntohl(th->th_seq);
4457 	if (src->seqlo == 0) {
4458 		/* First packet from this end. Set its state */
4459 
4460 		if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
4461 		    src->scrub == NULL) {
4462 			if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
4463 				REASON_SET(reason, PFRES_MEMORY);
4464 				return (PF_DROP);
4465 			}
4466 		}
4467 
4468 		/* Deferred generation of sequence number modulator */
4469 		if (dst->seqdiff && !src->seqdiff) {
4470 			/* use random iss for the TCP server */
4471 			while ((src->seqdiff = arc4random() - seq) == 0)
4472 				;
4473 			ack = ntohl(th->th_ack) - dst->seqdiff;
4474 			pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4475 			    src->seqdiff), 0);
4476 			pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4477 			*copyback = 1;
4478 		} else {
4479 			ack = ntohl(th->th_ack);
4480 		}
4481 
4482 		end = seq + pd->p_len;
4483 		if (th->th_flags & TH_SYN) {
4484 			end++;
4485 			if (dst->wscale & PF_WSCALE_FLAG) {
4486 				src->wscale = pf_get_wscale(m, off, th->th_off,
4487 				    pd->af);
4488 				if (src->wscale & PF_WSCALE_FLAG) {
4489 					/* Remove scale factor from initial
4490 					 * window */
4491 					sws = src->wscale & PF_WSCALE_MASK;
4492 					win = ((u_int32_t)win + (1 << sws) - 1)
4493 					    >> sws;
4494 					dws = dst->wscale & PF_WSCALE_MASK;
4495 				} else {
4496 					/* fixup other window */
4497 					dst->max_win <<= dst->wscale &
4498 					    PF_WSCALE_MASK;
4499 					/* in case of a retrans SYN|ACK */
4500 					dst->wscale = 0;
4501 				}
4502 			}
4503 		}
4504 		if (th->th_flags & TH_FIN)
4505 			end++;
4506 
4507 		src->seqlo = seq;
4508 		if (src->state < TCPS_SYN_SENT)
4509 			pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
4510 
4511 		/*
4512 		 * May need to slide the window (seqhi may have been set by
4513 		 * the crappy stack check or if we picked up the connection
4514 		 * after establishment)
4515 		 */
4516 		if (src->seqhi == 1 ||
4517 		    SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4518 			src->seqhi = end + MAX(1, dst->max_win << dws);
4519 		if (win > src->max_win)
4520 			src->max_win = win;
4521 
4522 	} else {
4523 		ack = ntohl(th->th_ack) - dst->seqdiff;
4524 		if (src->seqdiff) {
4525 			/* Modulate sequence numbers */
4526 			pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4527 			    src->seqdiff), 0);
4528 			pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4529 			*copyback = 1;
4530 		}
4531 		end = seq + pd->p_len;
4532 		if (th->th_flags & TH_SYN)
4533 			end++;
4534 		if (th->th_flags & TH_FIN)
4535 			end++;
4536 	}
4537 
4538 	if ((th->th_flags & TH_ACK) == 0) {
4539 		/* Let it pass through the ack skew check */
4540 		ack = dst->seqlo;
4541 	} else if ((ack == 0 &&
4542 	    (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4543 	    /* broken tcp stacks do not set ack */
4544 	    (dst->state < TCPS_SYN_SENT)) {
4545 		/*
4546 		 * Many stacks (ours included) will set the ACK number in an
4547 		 * FIN|ACK if the SYN times out -- no sequence to ACK.
4548 		 */
4549 		ack = dst->seqlo;
4550 	}
4551 
4552 	if (seq == end) {
4553 		/* Ease sequencing restrictions on no data packets */
4554 		seq = src->seqlo;
4555 		end = seq;
4556 	}
4557 
4558 	ackskew = dst->seqlo - ack;
4559 
4560 	/*
4561 	 * Need to demodulate the sequence numbers in any TCP SACK options
4562 	 * (Selective ACK). We could optionally validate the SACK values
4563 	 * against the current ACK window, either forwards or backwards, but
4564 	 * I'm not confident that SACK has been implemented properly
4565 	 * everywhere. It wouldn't surprise me if several stacks accidentally
4566 	 * SACK too far backwards of previously ACKed data. There really aren't
4567 	 * any security implications of bad SACKing unless the target stack
4568 	 * doesn't validate the option length correctly. Someone trying to
4569 	 * spoof into a TCP connection won't bother blindly sending SACK
4570 	 * options anyway.
4571 	 */
4572 	if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4573 		if (pf_modulate_sack(m, off, pd, th, dst))
4574 			*copyback = 1;
4575 	}
4576 
4577 #define	MAXACKWINDOW (0xffff + 1500)	/* 1500 is an arbitrary fudge factor */
4578 	if (SEQ_GEQ(src->seqhi, end) &&
4579 	    /* Last octet inside other's window space */
4580 	    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4581 	    /* Retrans: not more than one window back */
4582 	    (ackskew >= -MAXACKWINDOW) &&
4583 	    /* Acking not more than one reassembled fragment backwards */
4584 	    (ackskew <= (MAXACKWINDOW << sws)) &&
4585 	    /* Acking not more than one window forward */
4586 	    ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4587 	    (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4588 	    (pd->flags & PFDESC_IP_REAS) == 0)) {
4589 	    /* Require an exact/+1 sequence match on resets when possible */
4590 
4591 		if (dst->scrub || src->scrub) {
4592 			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4593 			    *state, src, dst, copyback))
4594 				return (PF_DROP);
4595 		}
4596 
4597 		/* update max window */
4598 		if (src->max_win < win)
4599 			src->max_win = win;
4600 		/* synchronize sequencing */
4601 		if (SEQ_GT(end, src->seqlo))
4602 			src->seqlo = end;
4603 		/* slide the window of what the other end can send */
4604 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4605 			dst->seqhi = ack + MAX((win << sws), 1);
4606 
4607 		/* update states */
4608 		if (th->th_flags & TH_SYN)
4609 			if (src->state < TCPS_SYN_SENT)
4610 				pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
4611 		if (th->th_flags & TH_FIN)
4612 			if (src->state < TCPS_CLOSING)
4613 				pf_set_protostate(*state, psrc, TCPS_CLOSING);
4614 		if (th->th_flags & TH_ACK) {
4615 			if (dst->state == TCPS_SYN_SENT) {
4616 				pf_set_protostate(*state, pdst,
4617 				    TCPS_ESTABLISHED);
4618 				if (src->state == TCPS_ESTABLISHED &&
4619 				    (*state)->src_node != NULL &&
4620 				    pf_src_connlimit(state)) {
4621 					REASON_SET(reason, PFRES_SRCLIMIT);
4622 					return (PF_DROP);
4623 				}
4624 			} else if (dst->state == TCPS_CLOSING)
4625 				pf_set_protostate(*state, pdst,
4626 				    TCPS_FIN_WAIT_2);
4627 		}
4628 		if (th->th_flags & TH_RST)
4629 			pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
4630 
4631 		/* update expire time */
4632 		(*state)->expire = time_uptime;
4633 		if (src->state >= TCPS_FIN_WAIT_2 &&
4634 		    dst->state >= TCPS_FIN_WAIT_2)
4635 			(*state)->timeout = PFTM_TCP_CLOSED;
4636 		else if (src->state >= TCPS_CLOSING &&
4637 		    dst->state >= TCPS_CLOSING)
4638 			(*state)->timeout = PFTM_TCP_FIN_WAIT;
4639 		else if (src->state < TCPS_ESTABLISHED ||
4640 		    dst->state < TCPS_ESTABLISHED)
4641 			(*state)->timeout = PFTM_TCP_OPENING;
4642 		else if (src->state >= TCPS_CLOSING ||
4643 		    dst->state >= TCPS_CLOSING)
4644 			(*state)->timeout = PFTM_TCP_CLOSING;
4645 		else
4646 			(*state)->timeout = PFTM_TCP_ESTABLISHED;
4647 
4648 		/* Fall through to PASS packet */
4649 
4650 	} else if ((dst->state < TCPS_SYN_SENT ||
4651 		dst->state >= TCPS_FIN_WAIT_2 ||
4652 		src->state >= TCPS_FIN_WAIT_2) &&
4653 	    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4654 	    /* Within a window forward of the originating packet */
4655 	    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4656 	    /* Within a window backward of the originating packet */
4657 
4658 		/*
4659 		 * This currently handles three situations:
4660 		 *  1) Stupid stacks will shotgun SYNs before their peer
4661 		 *     replies.
4662 		 *  2) When PF catches an already established stream (the
4663 		 *     firewall rebooted, the state table was flushed, routes
4664 		 *     changed...)
4665 		 *  3) Packets get funky immediately after the connection
4666 		 *     closes (this should catch Solaris spurious ACK|FINs
4667 		 *     that web servers like to spew after a close)
4668 		 *
4669 		 * This must be a little more careful than the above code
4670 		 * since packet floods will also be caught here. We don't
4671 		 * update the TTL here to mitigate the damage of a packet
4672 		 * flood and so the same code can handle awkward establishment
4673 		 * and a loosened connection close.
4674 		 * In the establishment case, a correct peer response will
4675 		 * validate the connection, go through the normal state code
4676 		 * and keep updating the state TTL.
4677 		 */
4678 
4679 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
4680 			printf("pf: loose state match: ");
4681 			pf_print_state(*state);
4682 			pf_print_flags(th->th_flags);
4683 			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4684 			    "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4685 			    pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4686 			    (unsigned long long)(*state)->packets[1],
4687 			    pd->dir == PF_IN ? "in" : "out",
4688 			    pd->dir == (*state)->direction ? "fwd" : "rev");
4689 		}
4690 
4691 		if (dst->scrub || src->scrub) {
4692 			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4693 			    *state, src, dst, copyback))
4694 				return (PF_DROP);
4695 		}
4696 
4697 		/* update max window */
4698 		if (src->max_win < win)
4699 			src->max_win = win;
4700 		/* synchronize sequencing */
4701 		if (SEQ_GT(end, src->seqlo))
4702 			src->seqlo = end;
4703 		/* slide the window of what the other end can send */
4704 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4705 			dst->seqhi = ack + MAX((win << sws), 1);
4706 
4707 		/*
4708 		 * Cannot set dst->seqhi here since this could be a shotgunned
4709 		 * SYN and not an already established connection.
4710 		 */
4711 
4712 		if (th->th_flags & TH_FIN)
4713 			if (src->state < TCPS_CLOSING)
4714 				pf_set_protostate(*state, psrc, TCPS_CLOSING);
4715 		if (th->th_flags & TH_RST)
4716 			pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
4717 
4718 		/* Fall through to PASS packet */
4719 
4720 	} else {
4721 		if ((*state)->dst.state == TCPS_SYN_SENT &&
4722 		    (*state)->src.state == TCPS_SYN_SENT) {
4723 			/* Send RST for state mismatches during handshake */
4724 			if (!(th->th_flags & TH_RST))
4725 				pf_send_tcp((*state)->rule.ptr, pd->af,
4726 				    pd->dst, pd->src, th->th_dport,
4727 				    th->th_sport, ntohl(th->th_ack), 0,
4728 				    TH_RST, 0, 0,
4729 				    (*state)->rule.ptr->return_ttl, 1, 0);
4730 			src->seqlo = 0;
4731 			src->seqhi = 1;
4732 			src->max_win = 1;
4733 		} else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4734 			printf("pf: BAD state: ");
4735 			pf_print_state(*state);
4736 			pf_print_flags(th->th_flags);
4737 			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4738 			    "pkts=%llu:%llu dir=%s,%s\n",
4739 			    seq, orig_seq, ack, pd->p_len, ackskew,
4740 			    (unsigned long long)(*state)->packets[0],
4741 			    (unsigned long long)(*state)->packets[1],
4742 			    pd->dir == PF_IN ? "in" : "out",
4743 			    pd->dir == (*state)->direction ? "fwd" : "rev");
4744 			printf("pf: State failure on: %c %c %c %c | %c %c\n",
4745 			    SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4746 			    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4747 			    ' ': '2',
4748 			    (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4749 			    (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4750 			    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4751 			    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4752 		}
4753 		REASON_SET(reason, PFRES_BADSTATE);
4754 		return (PF_DROP);
4755 	}
4756 
4757 	return (PF_PASS);
4758 }
4759 
4760 static int
4761 pf_tcp_track_sloppy(struct pf_kstate **state, struct pf_pdesc *pd, u_short *reason)
4762 {
4763 	struct tcphdr		*th = &pd->hdr.tcp;
4764 	struct pf_state_peer	*src, *dst;
4765 	u_int8_t		 psrc, pdst;
4766 
4767 	if (pd->dir == (*state)->direction) {
4768 		src = &(*state)->src;
4769 		dst = &(*state)->dst;
4770 		psrc = PF_PEER_SRC;
4771 		pdst = PF_PEER_DST;
4772 	} else {
4773 		src = &(*state)->dst;
4774 		dst = &(*state)->src;
4775 		psrc = PF_PEER_DST;
4776 		pdst = PF_PEER_SRC;
4777 	}
4778 
4779 	if (th->th_flags & TH_SYN)
4780 		if (src->state < TCPS_SYN_SENT)
4781 			pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
4782 	if (th->th_flags & TH_FIN)
4783 		if (src->state < TCPS_CLOSING)
4784 			pf_set_protostate(*state, psrc, TCPS_CLOSING);
4785 	if (th->th_flags & TH_ACK) {
4786 		if (dst->state == TCPS_SYN_SENT) {
4787 			pf_set_protostate(*state, pdst, TCPS_ESTABLISHED);
4788 			if (src->state == TCPS_ESTABLISHED &&
4789 			    (*state)->src_node != NULL &&
4790 			    pf_src_connlimit(state)) {
4791 				REASON_SET(reason, PFRES_SRCLIMIT);
4792 				return (PF_DROP);
4793 			}
4794 		} else if (dst->state == TCPS_CLOSING) {
4795 			pf_set_protostate(*state, pdst, TCPS_FIN_WAIT_2);
4796 		} else if (src->state == TCPS_SYN_SENT &&
4797 		    dst->state < TCPS_SYN_SENT) {
4798 			/*
4799 			 * Handle a special sloppy case where we only see one
4800 			 * half of the connection. If there is a ACK after
4801 			 * the initial SYN without ever seeing a packet from
4802 			 * the destination, set the connection to established.
4803 			 */
4804 			pf_set_protostate(*state, PF_PEER_BOTH,
4805 			    TCPS_ESTABLISHED);
4806 			dst->state = src->state = TCPS_ESTABLISHED;
4807 			if ((*state)->src_node != NULL &&
4808 			    pf_src_connlimit(state)) {
4809 				REASON_SET(reason, PFRES_SRCLIMIT);
4810 				return (PF_DROP);
4811 			}
4812 		} else if (src->state == TCPS_CLOSING &&
4813 		    dst->state == TCPS_ESTABLISHED &&
4814 		    dst->seqlo == 0) {
4815 			/*
4816 			 * Handle the closing of half connections where we
4817 			 * don't see the full bidirectional FIN/ACK+ACK
4818 			 * handshake.
4819 			 */
4820 			pf_set_protostate(*state, pdst, TCPS_CLOSING);
4821 		}
4822 	}
4823 	if (th->th_flags & TH_RST)
4824 		pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
4825 
4826 	/* update expire time */
4827 	(*state)->expire = time_uptime;
4828 	if (src->state >= TCPS_FIN_WAIT_2 &&
4829 	    dst->state >= TCPS_FIN_WAIT_2)
4830 		(*state)->timeout = PFTM_TCP_CLOSED;
4831 	else if (src->state >= TCPS_CLOSING &&
4832 	    dst->state >= TCPS_CLOSING)
4833 		(*state)->timeout = PFTM_TCP_FIN_WAIT;
4834 	else if (src->state < TCPS_ESTABLISHED ||
4835 	    dst->state < TCPS_ESTABLISHED)
4836 		(*state)->timeout = PFTM_TCP_OPENING;
4837 	else if (src->state >= TCPS_CLOSING ||
4838 	    dst->state >= TCPS_CLOSING)
4839 		(*state)->timeout = PFTM_TCP_CLOSING;
4840 	else
4841 		(*state)->timeout = PFTM_TCP_ESTABLISHED;
4842 
4843 	return (PF_PASS);
4844 }
4845 
4846 static int
4847 pf_synproxy(struct pf_pdesc *pd, struct pf_kstate **state, u_short *reason)
4848 {
4849 	struct pf_state_key	*sk = (*state)->key[pd->didx];
4850 	struct tcphdr		*th = &pd->hdr.tcp;
4851 
4852 	if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4853 		if (pd->dir != (*state)->direction) {
4854 			REASON_SET(reason, PFRES_SYNPROXY);
4855 			return (PF_SYNPROXY_DROP);
4856 		}
4857 		if (th->th_flags & TH_SYN) {
4858 			if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4859 				REASON_SET(reason, PFRES_SYNPROXY);
4860 				return (PF_DROP);
4861 			}
4862 			pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
4863 			    pd->src, th->th_dport, th->th_sport,
4864 			    (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4865 			    TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0);
4866 			REASON_SET(reason, PFRES_SYNPROXY);
4867 			return (PF_SYNPROXY_DROP);
4868 		} else if ((th->th_flags & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
4869 		    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4870 		    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4871 			REASON_SET(reason, PFRES_SYNPROXY);
4872 			return (PF_DROP);
4873 		} else if ((*state)->src_node != NULL &&
4874 		    pf_src_connlimit(state)) {
4875 			REASON_SET(reason, PFRES_SRCLIMIT);
4876 			return (PF_DROP);
4877 		} else
4878 			pf_set_protostate(*state, PF_PEER_SRC,
4879 			    PF_TCPS_PROXY_DST);
4880 	}
4881 	if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4882 		if (pd->dir == (*state)->direction) {
4883 			if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4884 			    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4885 			    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4886 				REASON_SET(reason, PFRES_SYNPROXY);
4887 				return (PF_DROP);
4888 			}
4889 			(*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4890 			if ((*state)->dst.seqhi == 1)
4891 				(*state)->dst.seqhi = htonl(arc4random());
4892 			pf_send_tcp((*state)->rule.ptr, pd->af,
4893 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
4894 			    sk->port[pd->sidx], sk->port[pd->didx],
4895 			    (*state)->dst.seqhi, 0, TH_SYN, 0,
4896 			    (*state)->src.mss, 0, 0, (*state)->tag);
4897 			REASON_SET(reason, PFRES_SYNPROXY);
4898 			return (PF_SYNPROXY_DROP);
4899 		} else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4900 		    (TH_SYN|TH_ACK)) ||
4901 		    (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4902 			REASON_SET(reason, PFRES_SYNPROXY);
4903 			return (PF_DROP);
4904 		} else {
4905 			(*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4906 			(*state)->dst.seqlo = ntohl(th->th_seq);
4907 			pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
4908 			    pd->src, th->th_dport, th->th_sport,
4909 			    ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4910 			    TH_ACK, (*state)->src.max_win, 0, 0, 0,
4911 			    (*state)->tag);
4912 			pf_send_tcp((*state)->rule.ptr, pd->af,
4913 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
4914 			    sk->port[pd->sidx], sk->port[pd->didx],
4915 			    (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4916 			    TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0);
4917 			(*state)->src.seqdiff = (*state)->dst.seqhi -
4918 			    (*state)->src.seqlo;
4919 			(*state)->dst.seqdiff = (*state)->src.seqhi -
4920 			    (*state)->dst.seqlo;
4921 			(*state)->src.seqhi = (*state)->src.seqlo +
4922 			    (*state)->dst.max_win;
4923 			(*state)->dst.seqhi = (*state)->dst.seqlo +
4924 			    (*state)->src.max_win;
4925 			(*state)->src.wscale = (*state)->dst.wscale = 0;
4926 			pf_set_protostate(*state, PF_PEER_BOTH,
4927 			    TCPS_ESTABLISHED);
4928 			REASON_SET(reason, PFRES_SYNPROXY);
4929 			return (PF_SYNPROXY_DROP);
4930 		}
4931 	}
4932 
4933 	return (PF_PASS);
4934 }
4935 
4936 static int
4937 pf_test_state_tcp(struct pf_kstate **state, int direction, struct pfi_kkif *kif,
4938     struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4939     u_short *reason)
4940 {
4941 	struct pf_state_key_cmp	 key;
4942 	struct tcphdr		*th = &pd->hdr.tcp;
4943 	int			 copyback = 0;
4944 	int			 action;
4945 	struct pf_state_peer	*src, *dst;
4946 	struct pf_state_key	*sk;
4947 
4948 	bzero(&key, sizeof(key));
4949 	key.af = pd->af;
4950 	key.proto = IPPROTO_TCP;
4951 	if (direction == PF_IN)	{	/* wire side, straight */
4952 		PF_ACPY(&key.addr[0], pd->src, key.af);
4953 		PF_ACPY(&key.addr[1], pd->dst, key.af);
4954 		key.port[0] = th->th_sport;
4955 		key.port[1] = th->th_dport;
4956 	} else {			/* stack side, reverse */
4957 		PF_ACPY(&key.addr[1], pd->src, key.af);
4958 		PF_ACPY(&key.addr[0], pd->dst, key.af);
4959 		key.port[1] = th->th_sport;
4960 		key.port[0] = th->th_dport;
4961 	}
4962 
4963 	STATE_LOOKUP(kif, &key, direction, *state, pd);
4964 
4965 	if (direction == (*state)->direction) {
4966 		src = &(*state)->src;
4967 		dst = &(*state)->dst;
4968 	} else {
4969 		src = &(*state)->dst;
4970 		dst = &(*state)->src;
4971 	}
4972 
4973 	sk = (*state)->key[pd->didx];
4974 
4975 	if ((action = pf_synproxy(pd, state, reason)) != PF_PASS)
4976 		return (action);
4977 
4978 	if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4979 	    dst->state >= TCPS_FIN_WAIT_2 &&
4980 	    src->state >= TCPS_FIN_WAIT_2) {
4981 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
4982 			printf("pf: state reuse ");
4983 			pf_print_state(*state);
4984 			pf_print_flags(th->th_flags);
4985 			printf("\n");
4986 		}
4987 		/* XXX make sure it's the same direction ?? */
4988 		pf_set_protostate(*state, PF_PEER_BOTH, TCPS_CLOSED);
4989 		pf_unlink_state(*state, PF_ENTER_LOCKED);
4990 		*state = NULL;
4991 		return (PF_DROP);
4992 	}
4993 
4994 	if ((*state)->state_flags & PFSTATE_SLOPPY) {
4995 		if (pf_tcp_track_sloppy(state, pd, reason) == PF_DROP)
4996 			return (PF_DROP);
4997 	} else {
4998 		if (pf_tcp_track_full(state, kif, m, off, pd, reason,
4999 		    &copyback) == PF_DROP)
5000 			return (PF_DROP);
5001 	}
5002 
5003 	/* translate source/destination address, if necessary */
5004 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5005 		struct pf_state_key *nk = (*state)->key[pd->didx];
5006 
5007 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
5008 		    nk->port[pd->sidx] != th->th_sport)
5009 			pf_change_ap(m, pd->src, &th->th_sport,
5010 			    pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
5011 			    nk->port[pd->sidx], 0, pd->af);
5012 
5013 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
5014 		    nk->port[pd->didx] != th->th_dport)
5015 			pf_change_ap(m, pd->dst, &th->th_dport,
5016 			    pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
5017 			    nk->port[pd->didx], 0, pd->af);
5018 		copyback = 1;
5019 	}
5020 
5021 	/* Copyback sequence modulation or stateful scrub changes if needed */
5022 	if (copyback)
5023 		m_copyback(m, off, sizeof(*th), (caddr_t)th);
5024 
5025 	return (PF_PASS);
5026 }
5027 
5028 static int
5029 pf_test_state_udp(struct pf_kstate **state, int direction, struct pfi_kkif *kif,
5030     struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
5031 {
5032 	struct pf_state_peer	*src, *dst;
5033 	struct pf_state_key_cmp	 key;
5034 	struct udphdr		*uh = &pd->hdr.udp;
5035 	uint8_t			 psrc, pdst;
5036 
5037 	bzero(&key, sizeof(key));
5038 	key.af = pd->af;
5039 	key.proto = IPPROTO_UDP;
5040 	if (direction == PF_IN)	{	/* wire side, straight */
5041 		PF_ACPY(&key.addr[0], pd->src, key.af);
5042 		PF_ACPY(&key.addr[1], pd->dst, key.af);
5043 		key.port[0] = uh->uh_sport;
5044 		key.port[1] = uh->uh_dport;
5045 	} else {			/* stack side, reverse */
5046 		PF_ACPY(&key.addr[1], pd->src, key.af);
5047 		PF_ACPY(&key.addr[0], pd->dst, key.af);
5048 		key.port[1] = uh->uh_sport;
5049 		key.port[0] = uh->uh_dport;
5050 	}
5051 
5052 	STATE_LOOKUP(kif, &key, direction, *state, pd);
5053 
5054 	if (direction == (*state)->direction) {
5055 		src = &(*state)->src;
5056 		dst = &(*state)->dst;
5057 		psrc = PF_PEER_SRC;
5058 		pdst = PF_PEER_DST;
5059 	} else {
5060 		src = &(*state)->dst;
5061 		dst = &(*state)->src;
5062 		psrc = PF_PEER_DST;
5063 		pdst = PF_PEER_SRC;
5064 	}
5065 
5066 	/* update states */
5067 	if (src->state < PFUDPS_SINGLE)
5068 		pf_set_protostate(*state, psrc, PFUDPS_SINGLE);
5069 	if (dst->state == PFUDPS_SINGLE)
5070 		pf_set_protostate(*state, pdst, PFUDPS_MULTIPLE);
5071 
5072 	/* update expire time */
5073 	(*state)->expire = time_uptime;
5074 	if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
5075 		(*state)->timeout = PFTM_UDP_MULTIPLE;
5076 	else
5077 		(*state)->timeout = PFTM_UDP_SINGLE;
5078 
5079 	/* translate source/destination address, if necessary */
5080 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5081 		struct pf_state_key *nk = (*state)->key[pd->didx];
5082 
5083 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
5084 		    nk->port[pd->sidx] != uh->uh_sport)
5085 			pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
5086 			    &uh->uh_sum, &nk->addr[pd->sidx],
5087 			    nk->port[pd->sidx], 1, pd->af);
5088 
5089 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
5090 		    nk->port[pd->didx] != uh->uh_dport)
5091 			pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
5092 			    &uh->uh_sum, &nk->addr[pd->didx],
5093 			    nk->port[pd->didx], 1, pd->af);
5094 		m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
5095 	}
5096 
5097 	return (PF_PASS);
5098 }
5099 
5100 static int
5101 pf_test_state_icmp(struct pf_kstate **state, int direction, struct pfi_kkif *kif,
5102     struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
5103 {
5104 	struct pf_addr  *saddr = pd->src, *daddr = pd->dst;
5105 	u_int16_t	 icmpid = 0, *icmpsum;
5106 	u_int8_t	 icmptype, icmpcode;
5107 	int		 state_icmp = 0;
5108 	struct pf_state_key_cmp key;
5109 
5110 	bzero(&key, sizeof(key));
5111 	switch (pd->proto) {
5112 #ifdef INET
5113 	case IPPROTO_ICMP:
5114 		icmptype = pd->hdr.icmp.icmp_type;
5115 		icmpcode = pd->hdr.icmp.icmp_code;
5116 		icmpid = pd->hdr.icmp.icmp_id;
5117 		icmpsum = &pd->hdr.icmp.icmp_cksum;
5118 
5119 		if (icmptype == ICMP_UNREACH ||
5120 		    icmptype == ICMP_SOURCEQUENCH ||
5121 		    icmptype == ICMP_REDIRECT ||
5122 		    icmptype == ICMP_TIMXCEED ||
5123 		    icmptype == ICMP_PARAMPROB)
5124 			state_icmp++;
5125 		break;
5126 #endif /* INET */
5127 #ifdef INET6
5128 	case IPPROTO_ICMPV6:
5129 		icmptype = pd->hdr.icmp6.icmp6_type;
5130 		icmpcode = pd->hdr.icmp6.icmp6_code;
5131 		icmpid = pd->hdr.icmp6.icmp6_id;
5132 		icmpsum = &pd->hdr.icmp6.icmp6_cksum;
5133 
5134 		if (icmptype == ICMP6_DST_UNREACH ||
5135 		    icmptype == ICMP6_PACKET_TOO_BIG ||
5136 		    icmptype == ICMP6_TIME_EXCEEDED ||
5137 		    icmptype == ICMP6_PARAM_PROB)
5138 			state_icmp++;
5139 		break;
5140 #endif /* INET6 */
5141 	}
5142 
5143 	if (!state_icmp) {
5144 		/*
5145 		 * ICMP query/reply message not related to a TCP/UDP packet.
5146 		 * Search for an ICMP state.
5147 		 */
5148 		key.af = pd->af;
5149 		key.proto = pd->proto;
5150 		key.port[0] = key.port[1] = icmpid;
5151 		if (direction == PF_IN)	{	/* wire side, straight */
5152 			PF_ACPY(&key.addr[0], pd->src, key.af);
5153 			PF_ACPY(&key.addr[1], pd->dst, key.af);
5154 		} else {			/* stack side, reverse */
5155 			PF_ACPY(&key.addr[1], pd->src, key.af);
5156 			PF_ACPY(&key.addr[0], pd->dst, key.af);
5157 		}
5158 
5159 		STATE_LOOKUP(kif, &key, direction, *state, pd);
5160 
5161 		(*state)->expire = time_uptime;
5162 		(*state)->timeout = PFTM_ICMP_ERROR_REPLY;
5163 
5164 		/* translate source/destination address, if necessary */
5165 		if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5166 			struct pf_state_key *nk = (*state)->key[pd->didx];
5167 
5168 			switch (pd->af) {
5169 #ifdef INET
5170 			case AF_INET:
5171 				if (PF_ANEQ(pd->src,
5172 				    &nk->addr[pd->sidx], AF_INET))
5173 					pf_change_a(&saddr->v4.s_addr,
5174 					    pd->ip_sum,
5175 					    nk->addr[pd->sidx].v4.s_addr, 0);
5176 
5177 				if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
5178 				    AF_INET))
5179 					pf_change_a(&daddr->v4.s_addr,
5180 					    pd->ip_sum,
5181 					    nk->addr[pd->didx].v4.s_addr, 0);
5182 
5183 				if (nk->port[0] !=
5184 				    pd->hdr.icmp.icmp_id) {
5185 					pd->hdr.icmp.icmp_cksum =
5186 					    pf_cksum_fixup(
5187 					    pd->hdr.icmp.icmp_cksum, icmpid,
5188 					    nk->port[pd->sidx], 0);
5189 					pd->hdr.icmp.icmp_id =
5190 					    nk->port[pd->sidx];
5191 				}
5192 
5193 				m_copyback(m, off, ICMP_MINLEN,
5194 				    (caddr_t )&pd->hdr.icmp);
5195 				break;
5196 #endif /* INET */
5197 #ifdef INET6
5198 			case AF_INET6:
5199 				if (PF_ANEQ(pd->src,
5200 				    &nk->addr[pd->sidx], AF_INET6))
5201 					pf_change_a6(saddr,
5202 					    &pd->hdr.icmp6.icmp6_cksum,
5203 					    &nk->addr[pd->sidx], 0);
5204 
5205 				if (PF_ANEQ(pd->dst,
5206 				    &nk->addr[pd->didx], AF_INET6))
5207 					pf_change_a6(daddr,
5208 					    &pd->hdr.icmp6.icmp6_cksum,
5209 					    &nk->addr[pd->didx], 0);
5210 
5211 				m_copyback(m, off, sizeof(struct icmp6_hdr),
5212 				    (caddr_t )&pd->hdr.icmp6);
5213 				break;
5214 #endif /* INET6 */
5215 			}
5216 		}
5217 		return (PF_PASS);
5218 
5219 	} else {
5220 		/*
5221 		 * ICMP error message in response to a TCP/UDP packet.
5222 		 * Extract the inner TCP/UDP header and search for that state.
5223 		 */
5224 
5225 		struct pf_pdesc	pd2;
5226 		bzero(&pd2, sizeof pd2);
5227 #ifdef INET
5228 		struct ip	h2;
5229 #endif /* INET */
5230 #ifdef INET6
5231 		struct ip6_hdr	h2_6;
5232 		int		terminal = 0;
5233 #endif /* INET6 */
5234 		int		ipoff2 = 0;
5235 		int		off2 = 0;
5236 
5237 		pd2.af = pd->af;
5238 		/* Payload packet is from the opposite direction. */
5239 		pd2.sidx = (direction == PF_IN) ? 1 : 0;
5240 		pd2.didx = (direction == PF_IN) ? 0 : 1;
5241 		switch (pd->af) {
5242 #ifdef INET
5243 		case AF_INET:
5244 			/* offset of h2 in mbuf chain */
5245 			ipoff2 = off + ICMP_MINLEN;
5246 
5247 			if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
5248 			    NULL, reason, pd2.af)) {
5249 				DPFPRINTF(PF_DEBUG_MISC,
5250 				    ("pf: ICMP error message too short "
5251 				    "(ip)\n"));
5252 				return (PF_DROP);
5253 			}
5254 			/*
5255 			 * ICMP error messages don't refer to non-first
5256 			 * fragments
5257 			 */
5258 			if (h2.ip_off & htons(IP_OFFMASK)) {
5259 				REASON_SET(reason, PFRES_FRAG);
5260 				return (PF_DROP);
5261 			}
5262 
5263 			/* offset of protocol header that follows h2 */
5264 			off2 = ipoff2 + (h2.ip_hl << 2);
5265 
5266 			pd2.proto = h2.ip_p;
5267 			pd2.src = (struct pf_addr *)&h2.ip_src;
5268 			pd2.dst = (struct pf_addr *)&h2.ip_dst;
5269 			pd2.ip_sum = &h2.ip_sum;
5270 			break;
5271 #endif /* INET */
5272 #ifdef INET6
5273 		case AF_INET6:
5274 			ipoff2 = off + sizeof(struct icmp6_hdr);
5275 
5276 			if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
5277 			    NULL, reason, pd2.af)) {
5278 				DPFPRINTF(PF_DEBUG_MISC,
5279 				    ("pf: ICMP error message too short "
5280 				    "(ip6)\n"));
5281 				return (PF_DROP);
5282 			}
5283 			pd2.proto = h2_6.ip6_nxt;
5284 			pd2.src = (struct pf_addr *)&h2_6.ip6_src;
5285 			pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
5286 			pd2.ip_sum = NULL;
5287 			off2 = ipoff2 + sizeof(h2_6);
5288 			do {
5289 				switch (pd2.proto) {
5290 				case IPPROTO_FRAGMENT:
5291 					/*
5292 					 * ICMPv6 error messages for
5293 					 * non-first fragments
5294 					 */
5295 					REASON_SET(reason, PFRES_FRAG);
5296 					return (PF_DROP);
5297 				case IPPROTO_AH:
5298 				case IPPROTO_HOPOPTS:
5299 				case IPPROTO_ROUTING:
5300 				case IPPROTO_DSTOPTS: {
5301 					/* get next header and header length */
5302 					struct ip6_ext opt6;
5303 
5304 					if (!pf_pull_hdr(m, off2, &opt6,
5305 					    sizeof(opt6), NULL, reason,
5306 					    pd2.af)) {
5307 						DPFPRINTF(PF_DEBUG_MISC,
5308 						    ("pf: ICMPv6 short opt\n"));
5309 						return (PF_DROP);
5310 					}
5311 					if (pd2.proto == IPPROTO_AH)
5312 						off2 += (opt6.ip6e_len + 2) * 4;
5313 					else
5314 						off2 += (opt6.ip6e_len + 1) * 8;
5315 					pd2.proto = opt6.ip6e_nxt;
5316 					/* goto the next header */
5317 					break;
5318 				}
5319 				default:
5320 					terminal++;
5321 					break;
5322 				}
5323 			} while (!terminal);
5324 			break;
5325 #endif /* INET6 */
5326 		}
5327 
5328 		if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
5329 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
5330 				printf("pf: BAD ICMP %d:%d outer dst: ",
5331 				    icmptype, icmpcode);
5332 				pf_print_host(pd->src, 0, pd->af);
5333 				printf(" -> ");
5334 				pf_print_host(pd->dst, 0, pd->af);
5335 				printf(" inner src: ");
5336 				pf_print_host(pd2.src, 0, pd2.af);
5337 				printf(" -> ");
5338 				pf_print_host(pd2.dst, 0, pd2.af);
5339 				printf("\n");
5340 			}
5341 			REASON_SET(reason, PFRES_BADSTATE);
5342 			return (PF_DROP);
5343 		}
5344 
5345 		switch (pd2.proto) {
5346 		case IPPROTO_TCP: {
5347 			struct tcphdr		 th;
5348 			u_int32_t		 seq;
5349 			struct pf_state_peer	*src, *dst;
5350 			u_int8_t		 dws;
5351 			int			 copyback = 0;
5352 
5353 			/*
5354 			 * Only the first 8 bytes of the TCP header can be
5355 			 * expected. Don't access any TCP header fields after
5356 			 * th_seq, an ackskew test is not possible.
5357 			 */
5358 			if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
5359 			    pd2.af)) {
5360 				DPFPRINTF(PF_DEBUG_MISC,
5361 				    ("pf: ICMP error message too short "
5362 				    "(tcp)\n"));
5363 				return (PF_DROP);
5364 			}
5365 
5366 			key.af = pd2.af;
5367 			key.proto = IPPROTO_TCP;
5368 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5369 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5370 			key.port[pd2.sidx] = th.th_sport;
5371 			key.port[pd2.didx] = th.th_dport;
5372 
5373 			STATE_LOOKUP(kif, &key, direction, *state, pd);
5374 
5375 			if (direction == (*state)->direction) {
5376 				src = &(*state)->dst;
5377 				dst = &(*state)->src;
5378 			} else {
5379 				src = &(*state)->src;
5380 				dst = &(*state)->dst;
5381 			}
5382 
5383 			if (src->wscale && dst->wscale)
5384 				dws = dst->wscale & PF_WSCALE_MASK;
5385 			else
5386 				dws = 0;
5387 
5388 			/* Demodulate sequence number */
5389 			seq = ntohl(th.th_seq) - src->seqdiff;
5390 			if (src->seqdiff) {
5391 				pf_change_a(&th.th_seq, icmpsum,
5392 				    htonl(seq), 0);
5393 				copyback = 1;
5394 			}
5395 
5396 			if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
5397 			    (!SEQ_GEQ(src->seqhi, seq) ||
5398 			    !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
5399 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
5400 					printf("pf: BAD ICMP %d:%d ",
5401 					    icmptype, icmpcode);
5402 					pf_print_host(pd->src, 0, pd->af);
5403 					printf(" -> ");
5404 					pf_print_host(pd->dst, 0, pd->af);
5405 					printf(" state: ");
5406 					pf_print_state(*state);
5407 					printf(" seq=%u\n", seq);
5408 				}
5409 				REASON_SET(reason, PFRES_BADSTATE);
5410 				return (PF_DROP);
5411 			} else {
5412 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
5413 					printf("pf: OK ICMP %d:%d ",
5414 					    icmptype, icmpcode);
5415 					pf_print_host(pd->src, 0, pd->af);
5416 					printf(" -> ");
5417 					pf_print_host(pd->dst, 0, pd->af);
5418 					printf(" state: ");
5419 					pf_print_state(*state);
5420 					printf(" seq=%u\n", seq);
5421 				}
5422 			}
5423 
5424 			/* translate source/destination address, if necessary */
5425 			if ((*state)->key[PF_SK_WIRE] !=
5426 			    (*state)->key[PF_SK_STACK]) {
5427 				struct pf_state_key *nk =
5428 				    (*state)->key[pd->didx];
5429 
5430 				if (PF_ANEQ(pd2.src,
5431 				    &nk->addr[pd2.sidx], pd2.af) ||
5432 				    nk->port[pd2.sidx] != th.th_sport)
5433 					pf_change_icmp(pd2.src, &th.th_sport,
5434 					    daddr, &nk->addr[pd2.sidx],
5435 					    nk->port[pd2.sidx], NULL,
5436 					    pd2.ip_sum, icmpsum,
5437 					    pd->ip_sum, 0, pd2.af);
5438 
5439 				if (PF_ANEQ(pd2.dst,
5440 				    &nk->addr[pd2.didx], pd2.af) ||
5441 				    nk->port[pd2.didx] != th.th_dport)
5442 					pf_change_icmp(pd2.dst, &th.th_dport,
5443 					    saddr, &nk->addr[pd2.didx],
5444 					    nk->port[pd2.didx], NULL,
5445 					    pd2.ip_sum, icmpsum,
5446 					    pd->ip_sum, 0, pd2.af);
5447 				copyback = 1;
5448 			}
5449 
5450 			if (copyback) {
5451 				switch (pd2.af) {
5452 #ifdef INET
5453 				case AF_INET:
5454 					m_copyback(m, off, ICMP_MINLEN,
5455 					    (caddr_t )&pd->hdr.icmp);
5456 					m_copyback(m, ipoff2, sizeof(h2),
5457 					    (caddr_t )&h2);
5458 					break;
5459 #endif /* INET */
5460 #ifdef INET6
5461 				case AF_INET6:
5462 					m_copyback(m, off,
5463 					    sizeof(struct icmp6_hdr),
5464 					    (caddr_t )&pd->hdr.icmp6);
5465 					m_copyback(m, ipoff2, sizeof(h2_6),
5466 					    (caddr_t )&h2_6);
5467 					break;
5468 #endif /* INET6 */
5469 				}
5470 				m_copyback(m, off2, 8, (caddr_t)&th);
5471 			}
5472 
5473 			return (PF_PASS);
5474 			break;
5475 		}
5476 		case IPPROTO_UDP: {
5477 			struct udphdr		uh;
5478 
5479 			if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
5480 			    NULL, reason, pd2.af)) {
5481 				DPFPRINTF(PF_DEBUG_MISC,
5482 				    ("pf: ICMP error message too short "
5483 				    "(udp)\n"));
5484 				return (PF_DROP);
5485 			}
5486 
5487 			key.af = pd2.af;
5488 			key.proto = IPPROTO_UDP;
5489 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5490 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5491 			key.port[pd2.sidx] = uh.uh_sport;
5492 			key.port[pd2.didx] = uh.uh_dport;
5493 
5494 			STATE_LOOKUP(kif, &key, direction, *state, pd);
5495 
5496 			/* translate source/destination address, if necessary */
5497 			if ((*state)->key[PF_SK_WIRE] !=
5498 			    (*state)->key[PF_SK_STACK]) {
5499 				struct pf_state_key *nk =
5500 				    (*state)->key[pd->didx];
5501 
5502 				if (PF_ANEQ(pd2.src,
5503 				    &nk->addr[pd2.sidx], pd2.af) ||
5504 				    nk->port[pd2.sidx] != uh.uh_sport)
5505 					pf_change_icmp(pd2.src, &uh.uh_sport,
5506 					    daddr, &nk->addr[pd2.sidx],
5507 					    nk->port[pd2.sidx], &uh.uh_sum,
5508 					    pd2.ip_sum, icmpsum,
5509 					    pd->ip_sum, 1, pd2.af);
5510 
5511 				if (PF_ANEQ(pd2.dst,
5512 				    &nk->addr[pd2.didx], pd2.af) ||
5513 				    nk->port[pd2.didx] != uh.uh_dport)
5514 					pf_change_icmp(pd2.dst, &uh.uh_dport,
5515 					    saddr, &nk->addr[pd2.didx],
5516 					    nk->port[pd2.didx], &uh.uh_sum,
5517 					    pd2.ip_sum, icmpsum,
5518 					    pd->ip_sum, 1, pd2.af);
5519 
5520 				switch (pd2.af) {
5521 #ifdef INET
5522 				case AF_INET:
5523 					m_copyback(m, off, ICMP_MINLEN,
5524 					    (caddr_t )&pd->hdr.icmp);
5525 					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5526 					break;
5527 #endif /* INET */
5528 #ifdef INET6
5529 				case AF_INET6:
5530 					m_copyback(m, off,
5531 					    sizeof(struct icmp6_hdr),
5532 					    (caddr_t )&pd->hdr.icmp6);
5533 					m_copyback(m, ipoff2, sizeof(h2_6),
5534 					    (caddr_t )&h2_6);
5535 					break;
5536 #endif /* INET6 */
5537 				}
5538 				m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5539 			}
5540 			return (PF_PASS);
5541 			break;
5542 		}
5543 #ifdef INET
5544 		case IPPROTO_ICMP: {
5545 			struct icmp		iih;
5546 
5547 			if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5548 			    NULL, reason, pd2.af)) {
5549 				DPFPRINTF(PF_DEBUG_MISC,
5550 				    ("pf: ICMP error message too short i"
5551 				    "(icmp)\n"));
5552 				return (PF_DROP);
5553 			}
5554 
5555 			key.af = pd2.af;
5556 			key.proto = IPPROTO_ICMP;
5557 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5558 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5559 			key.port[0] = key.port[1] = iih.icmp_id;
5560 
5561 			STATE_LOOKUP(kif, &key, direction, *state, pd);
5562 
5563 			/* translate source/destination address, if necessary */
5564 			if ((*state)->key[PF_SK_WIRE] !=
5565 			    (*state)->key[PF_SK_STACK]) {
5566 				struct pf_state_key *nk =
5567 				    (*state)->key[pd->didx];
5568 
5569 				if (PF_ANEQ(pd2.src,
5570 				    &nk->addr[pd2.sidx], pd2.af) ||
5571 				    nk->port[pd2.sidx] != iih.icmp_id)
5572 					pf_change_icmp(pd2.src, &iih.icmp_id,
5573 					    daddr, &nk->addr[pd2.sidx],
5574 					    nk->port[pd2.sidx], NULL,
5575 					    pd2.ip_sum, icmpsum,
5576 					    pd->ip_sum, 0, AF_INET);
5577 
5578 				if (PF_ANEQ(pd2.dst,
5579 				    &nk->addr[pd2.didx], pd2.af) ||
5580 				    nk->port[pd2.didx] != iih.icmp_id)
5581 					pf_change_icmp(pd2.dst, &iih.icmp_id,
5582 					    saddr, &nk->addr[pd2.didx],
5583 					    nk->port[pd2.didx], NULL,
5584 					    pd2.ip_sum, icmpsum,
5585 					    pd->ip_sum, 0, AF_INET);
5586 
5587 				m_copyback(m, off, ICMP_MINLEN, (caddr_t)&pd->hdr.icmp);
5588 				m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5589 				m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5590 			}
5591 			return (PF_PASS);
5592 			break;
5593 		}
5594 #endif /* INET */
5595 #ifdef INET6
5596 		case IPPROTO_ICMPV6: {
5597 			struct icmp6_hdr	iih;
5598 
5599 			if (!pf_pull_hdr(m, off2, &iih,
5600 			    sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5601 				DPFPRINTF(PF_DEBUG_MISC,
5602 				    ("pf: ICMP error message too short "
5603 				    "(icmp6)\n"));
5604 				return (PF_DROP);
5605 			}
5606 
5607 			key.af = pd2.af;
5608 			key.proto = IPPROTO_ICMPV6;
5609 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5610 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5611 			key.port[0] = key.port[1] = iih.icmp6_id;
5612 
5613 			STATE_LOOKUP(kif, &key, direction, *state, pd);
5614 
5615 			/* translate source/destination address, if necessary */
5616 			if ((*state)->key[PF_SK_WIRE] !=
5617 			    (*state)->key[PF_SK_STACK]) {
5618 				struct pf_state_key *nk =
5619 				    (*state)->key[pd->didx];
5620 
5621 				if (PF_ANEQ(pd2.src,
5622 				    &nk->addr[pd2.sidx], pd2.af) ||
5623 				    nk->port[pd2.sidx] != iih.icmp6_id)
5624 					pf_change_icmp(pd2.src, &iih.icmp6_id,
5625 					    daddr, &nk->addr[pd2.sidx],
5626 					    nk->port[pd2.sidx], NULL,
5627 					    pd2.ip_sum, icmpsum,
5628 					    pd->ip_sum, 0, AF_INET6);
5629 
5630 				if (PF_ANEQ(pd2.dst,
5631 				    &nk->addr[pd2.didx], pd2.af) ||
5632 				    nk->port[pd2.didx] != iih.icmp6_id)
5633 					pf_change_icmp(pd2.dst, &iih.icmp6_id,
5634 					    saddr, &nk->addr[pd2.didx],
5635 					    nk->port[pd2.didx], NULL,
5636 					    pd2.ip_sum, icmpsum,
5637 					    pd->ip_sum, 0, AF_INET6);
5638 
5639 				m_copyback(m, off, sizeof(struct icmp6_hdr),
5640 				    (caddr_t)&pd->hdr.icmp6);
5641 				m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5642 				m_copyback(m, off2, sizeof(struct icmp6_hdr),
5643 				    (caddr_t)&iih);
5644 			}
5645 			return (PF_PASS);
5646 			break;
5647 		}
5648 #endif /* INET6 */
5649 		default: {
5650 			key.af = pd2.af;
5651 			key.proto = pd2.proto;
5652 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5653 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5654 			key.port[0] = key.port[1] = 0;
5655 
5656 			STATE_LOOKUP(kif, &key, direction, *state, pd);
5657 
5658 			/* translate source/destination address, if necessary */
5659 			if ((*state)->key[PF_SK_WIRE] !=
5660 			    (*state)->key[PF_SK_STACK]) {
5661 				struct pf_state_key *nk =
5662 				    (*state)->key[pd->didx];
5663 
5664 				if (PF_ANEQ(pd2.src,
5665 				    &nk->addr[pd2.sidx], pd2.af))
5666 					pf_change_icmp(pd2.src, NULL, daddr,
5667 					    &nk->addr[pd2.sidx], 0, NULL,
5668 					    pd2.ip_sum, icmpsum,
5669 					    pd->ip_sum, 0, pd2.af);
5670 
5671 				if (PF_ANEQ(pd2.dst,
5672 				    &nk->addr[pd2.didx], pd2.af))
5673 					pf_change_icmp(pd2.dst, NULL, saddr,
5674 					    &nk->addr[pd2.didx], 0, NULL,
5675 					    pd2.ip_sum, icmpsum,
5676 					    pd->ip_sum, 0, pd2.af);
5677 
5678 				switch (pd2.af) {
5679 #ifdef INET
5680 				case AF_INET:
5681 					m_copyback(m, off, ICMP_MINLEN,
5682 					    (caddr_t)&pd->hdr.icmp);
5683 					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5684 					break;
5685 #endif /* INET */
5686 #ifdef INET6
5687 				case AF_INET6:
5688 					m_copyback(m, off,
5689 					    sizeof(struct icmp6_hdr),
5690 					    (caddr_t )&pd->hdr.icmp6);
5691 					m_copyback(m, ipoff2, sizeof(h2_6),
5692 					    (caddr_t )&h2_6);
5693 					break;
5694 #endif /* INET6 */
5695 				}
5696 			}
5697 			return (PF_PASS);
5698 			break;
5699 		}
5700 		}
5701 	}
5702 }
5703 
5704 static int
5705 pf_test_state_other(struct pf_kstate **state, int direction, struct pfi_kkif *kif,
5706     struct mbuf *m, struct pf_pdesc *pd)
5707 {
5708 	struct pf_state_peer	*src, *dst;
5709 	struct pf_state_key_cmp	 key;
5710 	uint8_t			 psrc, pdst;
5711 
5712 	bzero(&key, sizeof(key));
5713 	key.af = pd->af;
5714 	key.proto = pd->proto;
5715 	if (direction == PF_IN)	{
5716 		PF_ACPY(&key.addr[0], pd->src, key.af);
5717 		PF_ACPY(&key.addr[1], pd->dst, key.af);
5718 		key.port[0] = key.port[1] = 0;
5719 	} else {
5720 		PF_ACPY(&key.addr[1], pd->src, key.af);
5721 		PF_ACPY(&key.addr[0], pd->dst, key.af);
5722 		key.port[1] = key.port[0] = 0;
5723 	}
5724 
5725 	STATE_LOOKUP(kif, &key, direction, *state, pd);
5726 
5727 	if (direction == (*state)->direction) {
5728 		src = &(*state)->src;
5729 		dst = &(*state)->dst;
5730 		psrc = PF_PEER_SRC;
5731 		pdst = PF_PEER_DST;
5732 	} else {
5733 		src = &(*state)->dst;
5734 		dst = &(*state)->src;
5735 		psrc = PF_PEER_DST;
5736 		pdst = PF_PEER_SRC;
5737 	}
5738 
5739 	/* update states */
5740 	if (src->state < PFOTHERS_SINGLE)
5741 		pf_set_protostate(*state, psrc, PFOTHERS_SINGLE);
5742 	if (dst->state == PFOTHERS_SINGLE)
5743 		pf_set_protostate(*state, pdst, PFOTHERS_MULTIPLE);
5744 
5745 	/* update expire time */
5746 	(*state)->expire = time_uptime;
5747 	if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5748 		(*state)->timeout = PFTM_OTHER_MULTIPLE;
5749 	else
5750 		(*state)->timeout = PFTM_OTHER_SINGLE;
5751 
5752 	/* translate source/destination address, if necessary */
5753 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5754 		struct pf_state_key *nk = (*state)->key[pd->didx];
5755 
5756 		KASSERT(nk, ("%s: nk is null", __func__));
5757 		KASSERT(pd, ("%s: pd is null", __func__));
5758 		KASSERT(pd->src, ("%s: pd->src is null", __func__));
5759 		KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5760 		switch (pd->af) {
5761 #ifdef INET
5762 		case AF_INET:
5763 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5764 				pf_change_a(&pd->src->v4.s_addr,
5765 				    pd->ip_sum,
5766 				    nk->addr[pd->sidx].v4.s_addr,
5767 				    0);
5768 
5769 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5770 				pf_change_a(&pd->dst->v4.s_addr,
5771 				    pd->ip_sum,
5772 				    nk->addr[pd->didx].v4.s_addr,
5773 				    0);
5774 
5775 			break;
5776 #endif /* INET */
5777 #ifdef INET6
5778 		case AF_INET6:
5779 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5780 				PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5781 
5782 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5783 				PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5784 #endif /* INET6 */
5785 		}
5786 	}
5787 	return (PF_PASS);
5788 }
5789 
5790 /*
5791  * ipoff and off are measured from the start of the mbuf chain.
5792  * h must be at "ipoff" on the mbuf chain.
5793  */
5794 void *
5795 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5796     u_short *actionp, u_short *reasonp, sa_family_t af)
5797 {
5798 	switch (af) {
5799 #ifdef INET
5800 	case AF_INET: {
5801 		struct ip	*h = mtod(m, struct ip *);
5802 		u_int16_t	 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5803 
5804 		if (fragoff) {
5805 			if (fragoff >= len)
5806 				ACTION_SET(actionp, PF_PASS);
5807 			else {
5808 				ACTION_SET(actionp, PF_DROP);
5809 				REASON_SET(reasonp, PFRES_FRAG);
5810 			}
5811 			return (NULL);
5812 		}
5813 		if (m->m_pkthdr.len < off + len ||
5814 		    ntohs(h->ip_len) < off + len) {
5815 			ACTION_SET(actionp, PF_DROP);
5816 			REASON_SET(reasonp, PFRES_SHORT);
5817 			return (NULL);
5818 		}
5819 		break;
5820 	}
5821 #endif /* INET */
5822 #ifdef INET6
5823 	case AF_INET6: {
5824 		struct ip6_hdr	*h = mtod(m, struct ip6_hdr *);
5825 
5826 		if (m->m_pkthdr.len < off + len ||
5827 		    (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5828 		    (unsigned)(off + len)) {
5829 			ACTION_SET(actionp, PF_DROP);
5830 			REASON_SET(reasonp, PFRES_SHORT);
5831 			return (NULL);
5832 		}
5833 		break;
5834 	}
5835 #endif /* INET6 */
5836 	}
5837 	m_copydata(m, off, len, p);
5838 	return (p);
5839 }
5840 
5841 int
5842 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kkif *kif,
5843     int rtableid)
5844 {
5845 	struct ifnet		*ifp;
5846 
5847 	/*
5848 	 * Skip check for addresses with embedded interface scope,
5849 	 * as they would always match anyway.
5850 	 */
5851 	if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
5852 		return (1);
5853 
5854 	if (af != AF_INET && af != AF_INET6)
5855 		return (0);
5856 
5857 	/* Skip checks for ipsec interfaces */
5858 	if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5859 		return (1);
5860 
5861 	ifp = (kif != NULL) ? kif->pfik_ifp : NULL;
5862 
5863 	switch (af) {
5864 #ifdef INET6
5865 	case AF_INET6:
5866 		return (fib6_check_urpf(rtableid, &addr->v6, 0, NHR_NONE,
5867 		    ifp));
5868 #endif
5869 #ifdef INET
5870 	case AF_INET:
5871 		return (fib4_check_urpf(rtableid, addr->v4, 0, NHR_NONE,
5872 		    ifp));
5873 #endif
5874 	}
5875 
5876 	return (0);
5877 }
5878 
5879 #ifdef INET
5880 static void
5881 pf_route(struct mbuf **m, struct pf_krule *r, int dir, struct ifnet *oifp,
5882     struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
5883 {
5884 	struct mbuf		*m0, *m1;
5885 	struct sockaddr_in	dst;
5886 	struct ip		*ip;
5887 	struct ifnet		*ifp = NULL;
5888 	struct pf_addr		 naddr;
5889 	struct pf_ksrc_node	*sn = NULL;
5890 	int			 error = 0;
5891 	uint16_t		 ip_len, ip_off;
5892 
5893 	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5894 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5895 	    __func__));
5896 
5897 	if ((pd->pf_mtag == NULL &&
5898 	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5899 	    pd->pf_mtag->routed++ > 3) {
5900 		m0 = *m;
5901 		*m = NULL;
5902 		goto bad_locked;
5903 	}
5904 
5905 	if (r->rt == PF_DUPTO) {
5906 		if ((pd->pf_mtag->flags & PF_DUPLICATED)) {
5907 			if (s == NULL) {
5908 				ifp = r->rpool.cur->kif ?
5909 				    r->rpool.cur->kif->pfik_ifp : NULL;
5910 			} else {
5911 				ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5912 				PF_STATE_UNLOCK(s);
5913 			}
5914 			if (ifp == oifp) {
5915 				/* When the 2nd interface is not skipped */
5916 				return;
5917 			} else {
5918 				m0 = *m;
5919 				*m = NULL;
5920 				goto bad;
5921 			}
5922 		} else {
5923 			pd->pf_mtag->flags |= PF_DUPLICATED;
5924 			if (((m0 = m_dup(*m, M_NOWAIT)) == NULL)) {
5925 				if (s)
5926 					PF_STATE_UNLOCK(s);
5927 				return;
5928 			}
5929 		}
5930 	} else {
5931 		if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5932 			if (s)
5933 				PF_STATE_UNLOCK(s);
5934 			return;
5935 		}
5936 		m0 = *m;
5937 	}
5938 
5939 	ip = mtod(m0, struct ip *);
5940 
5941 	bzero(&dst, sizeof(dst));
5942 	dst.sin_family = AF_INET;
5943 	dst.sin_len = sizeof(dst);
5944 	dst.sin_addr = ip->ip_dst;
5945 
5946 	bzero(&naddr, sizeof(naddr));
5947 
5948 	if (s == NULL) {
5949 		if (TAILQ_EMPTY(&r->rpool.list)) {
5950 			DPFPRINTF(PF_DEBUG_URGENT,
5951 			    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5952 			goto bad_locked;
5953 		}
5954 		pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5955 		    &naddr, NULL, &sn);
5956 		if (!PF_AZERO(&naddr, AF_INET))
5957 			dst.sin_addr.s_addr = naddr.v4.s_addr;
5958 		ifp = r->rpool.cur->kif ?
5959 		    r->rpool.cur->kif->pfik_ifp : NULL;
5960 	} else {
5961 		if (!PF_AZERO(&s->rt_addr, AF_INET))
5962 			dst.sin_addr.s_addr =
5963 			    s->rt_addr.v4.s_addr;
5964 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5965 		PF_STATE_UNLOCK(s);
5966 	}
5967 	if (ifp == NULL)
5968 		goto bad;
5969 
5970 	if (dir == PF_IN) {
5971 		if (pf_test(PF_OUT, 0, ifp, &m0, inp) != PF_PASS)
5972 			goto bad;
5973 		else if (m0 == NULL)
5974 			goto done;
5975 		if (m0->m_len < sizeof(struct ip)) {
5976 			DPFPRINTF(PF_DEBUG_URGENT,
5977 			    ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5978 			goto bad;
5979 		}
5980 		ip = mtod(m0, struct ip *);
5981 	}
5982 
5983 	if (ifp->if_flags & IFF_LOOPBACK)
5984 		m0->m_flags |= M_SKIP_FIREWALL;
5985 
5986 	ip_len = ntohs(ip->ip_len);
5987 	ip_off = ntohs(ip->ip_off);
5988 
5989 	/* Copied from FreeBSD 10.0-CURRENT ip_output. */
5990 	m0->m_pkthdr.csum_flags |= CSUM_IP;
5991 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5992 		m0 = mb_unmapped_to_ext(m0);
5993 		if (m0 == NULL)
5994 			goto done;
5995 		in_delayed_cksum(m0);
5996 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5997 	}
5998 #if defined(SCTP) || defined(SCTP_SUPPORT)
5999 	if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
6000 		m0 = mb_unmapped_to_ext(m0);
6001 		if (m0 == NULL)
6002 			goto done;
6003 		sctp_delayed_cksum(m0, (uint32_t)(ip->ip_hl << 2));
6004 		m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
6005 	}
6006 #endif
6007 
6008 	/*
6009 	 * If small enough for interface, or the interface will take
6010 	 * care of the fragmentation for us, we can just send directly.
6011 	 */
6012 	if (ip_len <= ifp->if_mtu ||
6013 	    (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
6014 		ip->ip_sum = 0;
6015 		if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
6016 			ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
6017 			m0->m_pkthdr.csum_flags &= ~CSUM_IP;
6018 		}
6019 		m_clrprotoflags(m0);	/* Avoid confusing lower layers. */
6020 		error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
6021 		goto done;
6022 	}
6023 
6024 	/* Balk when DF bit is set or the interface didn't support TSO. */
6025 	if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
6026 		error = EMSGSIZE;
6027 		KMOD_IPSTAT_INC(ips_cantfrag);
6028 		if (r->rt != PF_DUPTO) {
6029 			if (s && pd->nat_rule != NULL)
6030 				PACKET_UNDO_NAT(m0, pd,
6031 				    (ip->ip_hl << 2) + (ip_off & IP_OFFMASK),
6032 				    s, dir);
6033 
6034 			icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
6035 			    ifp->if_mtu);
6036 			goto done;
6037 		} else
6038 			goto bad;
6039 	}
6040 
6041 	error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
6042 	if (error)
6043 		goto bad;
6044 
6045 	for (; m0; m0 = m1) {
6046 		m1 = m0->m_nextpkt;
6047 		m0->m_nextpkt = NULL;
6048 		if (error == 0) {
6049 			m_clrprotoflags(m0);
6050 			error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
6051 		} else
6052 			m_freem(m0);
6053 	}
6054 
6055 	if (error == 0)
6056 		KMOD_IPSTAT_INC(ips_fragmented);
6057 
6058 done:
6059 	if (r->rt != PF_DUPTO)
6060 		*m = NULL;
6061 	return;
6062 
6063 bad_locked:
6064 	if (s)
6065 		PF_STATE_UNLOCK(s);
6066 bad:
6067 	m_freem(m0);
6068 	goto done;
6069 }
6070 #endif /* INET */
6071 
6072 #ifdef INET6
6073 static void
6074 pf_route6(struct mbuf **m, struct pf_krule *r, int dir, struct ifnet *oifp,
6075     struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
6076 {
6077 	struct mbuf		*m0;
6078 	struct sockaddr_in6	dst;
6079 	struct ip6_hdr		*ip6;
6080 	struct ifnet		*ifp = NULL;
6081 	struct pf_addr		 naddr;
6082 	struct pf_ksrc_node	*sn = NULL;
6083 
6084 	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
6085 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
6086 	    __func__));
6087 
6088 	if ((pd->pf_mtag == NULL &&
6089 	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
6090 	    pd->pf_mtag->routed++ > 3) {
6091 		m0 = *m;
6092 		*m = NULL;
6093 		goto bad_locked;
6094 	}
6095 
6096 	if (r->rt == PF_DUPTO) {
6097 		if ((pd->pf_mtag->flags & PF_DUPLICATED)) {
6098 			if (s == NULL) {
6099 				ifp = r->rpool.cur->kif ?
6100 				    r->rpool.cur->kif->pfik_ifp : NULL;
6101 			} else {
6102 				ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
6103 				PF_STATE_UNLOCK(s);
6104 			}
6105 			if (ifp == oifp) {
6106 				/* When the 2nd interface is not skipped */
6107 				return;
6108 			} else {
6109 				m0 = *m;
6110 				*m = NULL;
6111 				goto bad;
6112 			}
6113 		} else {
6114 			pd->pf_mtag->flags |= PF_DUPLICATED;
6115 			if (((m0 = m_dup(*m, M_NOWAIT)) == NULL)) {
6116 				if (s)
6117 					PF_STATE_UNLOCK(s);
6118 				return;
6119 			}
6120 		}
6121 	} else {
6122 		if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
6123 			if (s)
6124 				PF_STATE_UNLOCK(s);
6125 			return;
6126 		}
6127 		m0 = *m;
6128 	}
6129 
6130 	ip6 = mtod(m0, struct ip6_hdr *);
6131 
6132 	bzero(&dst, sizeof(dst));
6133 	dst.sin6_family = AF_INET6;
6134 	dst.sin6_len = sizeof(dst);
6135 	dst.sin6_addr = ip6->ip6_dst;
6136 
6137 	bzero(&naddr, sizeof(naddr));
6138 
6139 	if (s == NULL) {
6140 		if (TAILQ_EMPTY(&r->rpool.list)) {
6141 			DPFPRINTF(PF_DEBUG_URGENT,
6142 			    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
6143 			goto bad_locked;
6144 		}
6145 		pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
6146 		    &naddr, NULL, &sn);
6147 		if (!PF_AZERO(&naddr, AF_INET6))
6148 			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
6149 			    &naddr, AF_INET6);
6150 		ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
6151 	} else {
6152 		if (!PF_AZERO(&s->rt_addr, AF_INET6))
6153 			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
6154 			    &s->rt_addr, AF_INET6);
6155 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
6156 	}
6157 
6158 	if (s)
6159 		PF_STATE_UNLOCK(s);
6160 
6161 	if (ifp == NULL)
6162 		goto bad;
6163 
6164 	if (dir == PF_IN) {
6165 		if (pf_test6(PF_OUT, PFIL_FWD, ifp, &m0, inp) != PF_PASS)
6166 			goto bad;
6167 		else if (m0 == NULL)
6168 			goto done;
6169 		if (m0->m_len < sizeof(struct ip6_hdr)) {
6170 			DPFPRINTF(PF_DEBUG_URGENT,
6171 			    ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
6172 			    __func__));
6173 			goto bad;
6174 		}
6175 		ip6 = mtod(m0, struct ip6_hdr *);
6176 	}
6177 
6178 	if (ifp->if_flags & IFF_LOOPBACK)
6179 		m0->m_flags |= M_SKIP_FIREWALL;
6180 
6181 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
6182 	    ~ifp->if_hwassist) {
6183 		uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
6184 		m0 = mb_unmapped_to_ext(m0);
6185 		if (m0 == NULL)
6186 			goto done;
6187 		in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
6188 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
6189 	}
6190 
6191 	/*
6192 	 * If the packet is too large for the outgoing interface,
6193 	 * send back an icmp6 error.
6194 	 */
6195 	if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
6196 		dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
6197 	if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
6198 		nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
6199 	else {
6200 		in6_ifstat_inc(ifp, ifs6_in_toobig);
6201 		if (r->rt != PF_DUPTO) {
6202 			if (s && pd->nat_rule != NULL)
6203 				PACKET_UNDO_NAT(m0, pd,
6204 				    ((caddr_t)ip6 - m0->m_data) +
6205 				    sizeof(struct ip6_hdr), s, dir);
6206 
6207 			icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
6208 		} else
6209 			goto bad;
6210 	}
6211 
6212 done:
6213 	if (r->rt != PF_DUPTO)
6214 		*m = NULL;
6215 	return;
6216 
6217 bad_locked:
6218 	if (s)
6219 		PF_STATE_UNLOCK(s);
6220 bad:
6221 	m_freem(m0);
6222 	goto done;
6223 }
6224 #endif /* INET6 */
6225 
6226 /*
6227  * FreeBSD supports cksum offloads for the following drivers.
6228  *  em(4), fxp(4), lge(4), nge(4), re(4), ti(4), txp(4), xl(4)
6229  *
6230  * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
6231  *  network driver performed cksum including pseudo header, need to verify
6232  *   csum_data
6233  * CSUM_DATA_VALID :
6234  *  network driver performed cksum, needs to additional pseudo header
6235  *  cksum computation with partial csum_data(i.e. lack of H/W support for
6236  *  pseudo header, for instance sk(4) and possibly gem(4))
6237  *
6238  * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
6239  * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
6240  * TCP/UDP layer.
6241  * Also, set csum_data to 0xffff to force cksum validation.
6242  */
6243 static int
6244 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
6245 {
6246 	u_int16_t sum = 0;
6247 	int hw_assist = 0;
6248 	struct ip *ip;
6249 
6250 	if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
6251 		return (1);
6252 	if (m->m_pkthdr.len < off + len)
6253 		return (1);
6254 
6255 	switch (p) {
6256 	case IPPROTO_TCP:
6257 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
6258 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
6259 				sum = m->m_pkthdr.csum_data;
6260 			} else {
6261 				ip = mtod(m, struct ip *);
6262 				sum = in_pseudo(ip->ip_src.s_addr,
6263 				ip->ip_dst.s_addr, htonl((u_short)len +
6264 				m->m_pkthdr.csum_data + IPPROTO_TCP));
6265 			}
6266 			sum ^= 0xffff;
6267 			++hw_assist;
6268 		}
6269 		break;
6270 	case IPPROTO_UDP:
6271 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
6272 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
6273 				sum = m->m_pkthdr.csum_data;
6274 			} else {
6275 				ip = mtod(m, struct ip *);
6276 				sum = in_pseudo(ip->ip_src.s_addr,
6277 				ip->ip_dst.s_addr, htonl((u_short)len +
6278 				m->m_pkthdr.csum_data + IPPROTO_UDP));
6279 			}
6280 			sum ^= 0xffff;
6281 			++hw_assist;
6282 		}
6283 		break;
6284 	case IPPROTO_ICMP:
6285 #ifdef INET6
6286 	case IPPROTO_ICMPV6:
6287 #endif /* INET6 */
6288 		break;
6289 	default:
6290 		return (1);
6291 	}
6292 
6293 	if (!hw_assist) {
6294 		switch (af) {
6295 		case AF_INET:
6296 			if (p == IPPROTO_ICMP) {
6297 				if (m->m_len < off)
6298 					return (1);
6299 				m->m_data += off;
6300 				m->m_len -= off;
6301 				sum = in_cksum(m, len);
6302 				m->m_data -= off;
6303 				m->m_len += off;
6304 			} else {
6305 				if (m->m_len < sizeof(struct ip))
6306 					return (1);
6307 				sum = in4_cksum(m, p, off, len);
6308 			}
6309 			break;
6310 #ifdef INET6
6311 		case AF_INET6:
6312 			if (m->m_len < sizeof(struct ip6_hdr))
6313 				return (1);
6314 			sum = in6_cksum(m, p, off, len);
6315 			break;
6316 #endif /* INET6 */
6317 		default:
6318 			return (1);
6319 		}
6320 	}
6321 	if (sum) {
6322 		switch (p) {
6323 		case IPPROTO_TCP:
6324 		    {
6325 			KMOD_TCPSTAT_INC(tcps_rcvbadsum);
6326 			break;
6327 		    }
6328 		case IPPROTO_UDP:
6329 		    {
6330 			KMOD_UDPSTAT_INC(udps_badsum);
6331 			break;
6332 		    }
6333 #ifdef INET
6334 		case IPPROTO_ICMP:
6335 		    {
6336 			KMOD_ICMPSTAT_INC(icps_checksum);
6337 			break;
6338 		    }
6339 #endif
6340 #ifdef INET6
6341 		case IPPROTO_ICMPV6:
6342 		    {
6343 			KMOD_ICMP6STAT_INC(icp6s_checksum);
6344 			break;
6345 		    }
6346 #endif /* INET6 */
6347 		}
6348 		return (1);
6349 	} else {
6350 		if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
6351 			m->m_pkthdr.csum_flags |=
6352 			    (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
6353 			m->m_pkthdr.csum_data = 0xffff;
6354 		}
6355 	}
6356 	return (0);
6357 }
6358 
6359 static bool
6360 pf_pdesc_to_dnflow(int dir, const struct pf_pdesc *pd,
6361     const struct pf_krule *r, const struct pf_kstate *s,
6362     struct ip_fw_args *dnflow)
6363 {
6364 	int dndir = r->direction;
6365 
6366 	if (s && dndir == PF_INOUT)
6367 		dndir = s->direction;
6368 
6369 	memset(dnflow, 0, sizeof(*dnflow));
6370 
6371 	if (pd->dport != NULL)
6372 		dnflow->f_id.dst_port = ntohs(*pd->dport);
6373 	if (pd->sport != NULL)
6374 		dnflow->f_id.src_port = ntohs(*pd->sport);
6375 
6376 	if (dir == PF_IN)
6377 		dnflow->flags |= IPFW_ARGS_IN;
6378 	else
6379 		dnflow->flags |= IPFW_ARGS_OUT;
6380 
6381 	if (dir != dndir && pd->act.dnrpipe) {
6382 		dnflow->rule.info = pd->act.dnrpipe;
6383 	}
6384 	else if (dir == dndir) {
6385 		dnflow->rule.info = pd->act.dnpipe;
6386 	}
6387 	else {
6388 		return (false);
6389 	}
6390 
6391 	dnflow->rule.info |= IPFW_IS_DUMMYNET;
6392 	if (r->free_flags & PFRULE_DN_IS_PIPE)
6393 		dnflow->rule.info |= IPFW_IS_PIPE;
6394 
6395 	dnflow->f_id.proto = pd->proto;
6396 	dnflow->f_id.extra = dnflow->rule.info;
6397 	switch (pd->af) {
6398 	case AF_INET:
6399 		dnflow->f_id.addr_type = 4;
6400 		dnflow->f_id.src_ip = ntohl(pd->src->v4.s_addr);
6401 		dnflow->f_id.dst_ip = ntohl(pd->dst->v4.s_addr);
6402 		break;
6403 	case AF_INET6:
6404 		dnflow->flags |= IPFW_ARGS_IP6;
6405 		dnflow->f_id.addr_type = 6;
6406 		dnflow->f_id.src_ip6 = pd->src->v6;
6407 		dnflow->f_id.dst_ip6 = pd->dst->v6;
6408 		break;
6409 	default:
6410 		panic("Invalid AF");
6411 		break;
6412 	}
6413 
6414 	return (true);
6415 }
6416 
6417 #ifdef INET
6418 int
6419 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6420 {
6421 	struct pfi_kkif		*kif;
6422 	u_short			 action, reason = 0, log = 0;
6423 	struct mbuf		*m = *m0;
6424 	struct ip		*h = NULL;
6425 	struct m_tag		*ipfwtag;
6426 	struct pf_krule		*a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6427 	struct pf_kstate	*s = NULL;
6428 	struct pf_kruleset	*ruleset = NULL;
6429 	struct pf_pdesc		 pd;
6430 	int			 off, dirndx, pqid = 0;
6431 
6432 	PF_RULES_RLOCK_TRACKER;
6433 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: bad direction %d\n", __func__, dir));
6434 	M_ASSERTPKTHDR(m);
6435 
6436 	if (!V_pf_status.running)
6437 		return (PF_PASS);
6438 
6439 	memset(&pd, 0, sizeof(pd));
6440 
6441 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
6442 
6443 	if (kif == NULL) {
6444 		DPFPRINTF(PF_DEBUG_URGENT,
6445 		    ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
6446 		return (PF_DROP);
6447 	}
6448 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
6449 		return (PF_PASS);
6450 
6451 	if (m->m_flags & M_SKIP_FIREWALL)
6452 		return (PF_PASS);
6453 
6454 	pd.pf_mtag = pf_find_mtag(m);
6455 
6456 	PF_RULES_RLOCK();
6457 
6458 	if ((__predict_false(ip_divert_ptr != NULL) || ip_dn_io_ptr != NULL) &&
6459 	    ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
6460 		struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
6461 		if ((rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) ||
6462 		    (rr->info & IPFW_IS_DUMMYNET)) {
6463 			if (pd.pf_mtag == NULL &&
6464 			    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6465 				action = PF_DROP;
6466 				goto done;
6467 			}
6468 			pd.pf_mtag->flags |= PF_PACKET_LOOPED;
6469 			m_tag_delete(m, ipfwtag);
6470 		}
6471 		if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
6472 			m->m_flags |= M_FASTFWD_OURS;
6473 			pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
6474 		}
6475 	} else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
6476 		/* We do IP header normalization and packet reassembly here */
6477 		action = PF_DROP;
6478 		goto done;
6479 	}
6480 	m = *m0;	/* pf_normalize messes with m0 */
6481 	h = mtod(m, struct ip *);
6482 
6483 	off = h->ip_hl << 2;
6484 	if (off < (int)sizeof(struct ip)) {
6485 		action = PF_DROP;
6486 		REASON_SET(&reason, PFRES_SHORT);
6487 		log = 1;
6488 		goto done;
6489 	}
6490 
6491 	pd.src = (struct pf_addr *)&h->ip_src;
6492 	pd.dst = (struct pf_addr *)&h->ip_dst;
6493 	pd.sport = pd.dport = NULL;
6494 	pd.ip_sum = &h->ip_sum;
6495 	pd.proto_sum = NULL;
6496 	pd.proto = h->ip_p;
6497 	pd.dir = dir;
6498 	pd.sidx = (dir == PF_IN) ? 0 : 1;
6499 	pd.didx = (dir == PF_IN) ? 1 : 0;
6500 	pd.af = AF_INET;
6501 	pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
6502 	pd.tot_len = ntohs(h->ip_len);
6503 
6504 	/* handle fragments that didn't get reassembled by normalization */
6505 	if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
6506 		action = pf_test_fragment(&r, dir, kif, m, h,
6507 		    &pd, &a, &ruleset);
6508 		goto done;
6509 	}
6510 
6511 	switch (h->ip_p) {
6512 	case IPPROTO_TCP: {
6513 		if (!pf_pull_hdr(m, off, &pd.hdr.tcp, sizeof(pd.hdr.tcp),
6514 		    &action, &reason, AF_INET)) {
6515 			log = action != PF_PASS;
6516 			goto done;
6517 		}
6518 		pd.p_len = pd.tot_len - off - (pd.hdr.tcp.th_off << 2);
6519 
6520 		pd.sport = &pd.hdr.tcp.th_sport;
6521 		pd.dport = &pd.hdr.tcp.th_dport;
6522 
6523 		/* Respond to SYN with a syncookie. */
6524 		if ((pd.hdr.tcp.th_flags & (TH_SYN|TH_ACK|TH_RST)) == TH_SYN &&
6525 		    pd.dir == PF_IN && pf_synflood_check(&pd)) {
6526 			pf_syncookie_send(m, off, &pd);
6527 			action = PF_DROP;
6528 			break;
6529 		}
6530 
6531 		if ((pd.hdr.tcp.th_flags & TH_ACK) && pd.p_len == 0)
6532 			pqid = 1;
6533 		action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6534 		if (action == PF_DROP)
6535 			goto done;
6536 		action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6537 		    &reason);
6538 		if (action == PF_PASS) {
6539 			if (V_pfsync_update_state_ptr != NULL)
6540 				V_pfsync_update_state_ptr(s);
6541 			r = s->rule.ptr;
6542 			a = s->anchor.ptr;
6543 			log = s->log;
6544 		} else if (s == NULL) {
6545 			/* Validate remote SYN|ACK, re-create original SYN if
6546 			 * valid. */
6547 			if ((pd.hdr.tcp.th_flags & (TH_SYN|TH_ACK|TH_RST)) ==
6548 			    TH_ACK && pf_syncookie_validate(&pd) &&
6549 			    pd.dir == PF_IN) {
6550 				struct mbuf *msyn;
6551 
6552 				msyn = pf_syncookie_recreate_syn(h->ip_ttl,
6553 				    off,&pd);
6554 				if (msyn == NULL) {
6555 					action = PF_DROP;
6556 					break;
6557 				}
6558 
6559 				action = pf_test(dir, pflags, ifp, &msyn, inp);
6560 				m_freem(msyn);
6561 
6562 				if (action == PF_PASS) {
6563 					action = pf_test_state_tcp(&s, dir,
6564 					    kif, m, off, h, &pd, &reason);
6565 					if (action != PF_PASS || s == NULL) {
6566 						action = PF_DROP;
6567 						break;
6568 					}
6569 
6570 					s->src.seqhi = ntohl(pd.hdr.tcp.th_ack)
6571 					    - 1;
6572 					s->src.seqlo = ntohl(pd.hdr.tcp.th_seq)
6573 					    - 1;
6574 					pf_set_protostate(s, PF_PEER_SRC,
6575 					    PF_TCPS_PROXY_DST);
6576 
6577 					action = pf_synproxy(&pd, &s, &reason);
6578 					if (action != PF_PASS)
6579 						break;
6580 				}
6581 				break;
6582 			}
6583 			else {
6584 				action = pf_test_rule(&r, &s, dir, kif, m, off,
6585 				    &pd, &a, &ruleset, inp);
6586 			}
6587 		}
6588 		break;
6589 	}
6590 
6591 	case IPPROTO_UDP: {
6592 		if (!pf_pull_hdr(m, off, &pd.hdr.udp, sizeof(pd.hdr.udp),
6593 		    &action, &reason, AF_INET)) {
6594 			log = action != PF_PASS;
6595 			goto done;
6596 		}
6597 		pd.sport = &pd.hdr.udp.uh_sport;
6598 		pd.dport = &pd.hdr.udp.uh_dport;
6599 		if (pd.hdr.udp.uh_dport == 0 ||
6600 		    ntohs(pd.hdr.udp.uh_ulen) > m->m_pkthdr.len - off ||
6601 		    ntohs(pd.hdr.udp.uh_ulen) < sizeof(struct udphdr)) {
6602 			action = PF_DROP;
6603 			REASON_SET(&reason, PFRES_SHORT);
6604 			goto done;
6605 		}
6606 		action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6607 		if (action == PF_PASS) {
6608 			if (V_pfsync_update_state_ptr != NULL)
6609 				V_pfsync_update_state_ptr(s);
6610 			r = s->rule.ptr;
6611 			a = s->anchor.ptr;
6612 			log = s->log;
6613 		} else if (s == NULL)
6614 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6615 			    &a, &ruleset, inp);
6616 		break;
6617 	}
6618 
6619 	case IPPROTO_ICMP: {
6620 		if (!pf_pull_hdr(m, off, &pd.hdr.icmp, ICMP_MINLEN,
6621 		    &action, &reason, AF_INET)) {
6622 			log = action != PF_PASS;
6623 			goto done;
6624 		}
6625 		action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6626 		    &reason);
6627 		if (action == PF_PASS) {
6628 			if (V_pfsync_update_state_ptr != NULL)
6629 				V_pfsync_update_state_ptr(s);
6630 			r = s->rule.ptr;
6631 			a = s->anchor.ptr;
6632 			log = s->log;
6633 		} else if (s == NULL)
6634 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6635 			    &a, &ruleset, inp);
6636 		break;
6637 	}
6638 
6639 #ifdef INET6
6640 	case IPPROTO_ICMPV6: {
6641 		action = PF_DROP;
6642 		DPFPRINTF(PF_DEBUG_MISC,
6643 		    ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
6644 		goto done;
6645 	}
6646 #endif
6647 
6648 	default:
6649 		action = pf_test_state_other(&s, dir, kif, m, &pd);
6650 		if (action == PF_PASS) {
6651 			if (V_pfsync_update_state_ptr != NULL)
6652 				V_pfsync_update_state_ptr(s);
6653 			r = s->rule.ptr;
6654 			a = s->anchor.ptr;
6655 			log = s->log;
6656 		} else if (s == NULL)
6657 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6658 			    &a, &ruleset, inp);
6659 		break;
6660 	}
6661 
6662 done:
6663 	PF_RULES_RUNLOCK();
6664 	if (action == PF_PASS && h->ip_hl > 5 &&
6665 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6666 		action = PF_DROP;
6667 		REASON_SET(&reason, PFRES_IPOPTIONS);
6668 		log = r->log;
6669 		DPFPRINTF(PF_DEBUG_MISC,
6670 		    ("pf: dropping packet with ip options\n"));
6671 	}
6672 
6673 	if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6674 		action = PF_DROP;
6675 		REASON_SET(&reason, PFRES_MEMORY);
6676 	}
6677 	if (r->rtableid >= 0)
6678 		M_SETFIB(m, r->rtableid);
6679 
6680 	if (r->scrub_flags & PFSTATE_SETPRIO) {
6681 		if (pd.tos & IPTOS_LOWDELAY)
6682 			pqid = 1;
6683 		if (vlan_set_pcp(m, r->set_prio[pqid])) {
6684 			action = PF_DROP;
6685 			REASON_SET(&reason, PFRES_MEMORY);
6686 			log = 1;
6687 			DPFPRINTF(PF_DEBUG_MISC,
6688 			    ("pf: failed to allocate 802.1q mtag\n"));
6689 		}
6690 	}
6691 
6692 #ifdef ALTQ
6693 	if (s && s->qid) {
6694 		pd.act.pqid = s->pqid;
6695 		pd.act.qid = s->qid;
6696 	} else if (r->qid) {
6697 		pd.act.pqid = r->pqid;
6698 		pd.act.qid = r->qid;
6699 	}
6700 	if (action == PF_PASS && pd.act.qid) {
6701 		if (pd.pf_mtag == NULL &&
6702 		    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6703 			action = PF_DROP;
6704 			REASON_SET(&reason, PFRES_MEMORY);
6705 		} else {
6706 			if (s != NULL)
6707 				pd.pf_mtag->qid_hash = pf_state_hash(s);
6708 			if (pqid || (pd.tos & IPTOS_LOWDELAY))
6709 				pd.pf_mtag->qid = pd.act.pqid;
6710 			else
6711 				pd.pf_mtag->qid = pd.act.qid;
6712 			/* Add hints for ecn. */
6713 			pd.pf_mtag->hdr = h;
6714 		}
6715 	}
6716 #endif /* ALTQ */
6717 
6718 	if (s && (s->dnpipe || s->dnrpipe)) {
6719 		pd.act.dnpipe = s->dnpipe;
6720 		pd.act.dnrpipe = s->dnrpipe;
6721 		pd.act.flags = s->state_flags;
6722 	} else if (r->dnpipe || r->dnrpipe) {
6723 		pd.act.dnpipe = r->dnpipe;
6724 		pd.act.dnrpipe = r->dnrpipe;
6725 		pd.act.flags = r->free_flags;
6726 	}
6727 	if ((pd.act.dnpipe || pd.act.dnrpipe) && !PACKET_LOOPED(&pd)) {
6728 		if (ip_dn_io_ptr == NULL) {
6729 			action = PF_DROP;
6730 			REASON_SET(&reason, PFRES_MEMORY);
6731 		} else {
6732 			struct ip_fw_args dnflow;
6733 
6734 			if (pd.pf_mtag == NULL &&
6735 			    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6736 				action = PF_DROP;
6737 				REASON_SET(&reason, PFRES_MEMORY);
6738 				if (s)
6739 					PF_STATE_UNLOCK(s);
6740 				return (action);
6741 			}
6742 
6743 			if (pf_pdesc_to_dnflow(dir, &pd, r, s, &dnflow)) {
6744 				ip_dn_io_ptr(m0, &dnflow);
6745 
6746 				if (*m0 == NULL) {
6747 					if (s)
6748 						PF_STATE_UNLOCK(s);
6749 					return (action);
6750 				} else {
6751 					/* This is dummynet fast io processing */
6752 					m_tag_delete(*m0, m_tag_first(*m0));
6753 					pd.pf_mtag->flags &= ~PF_PACKET_LOOPED;
6754 				}
6755 			}
6756 		}
6757 	}
6758 
6759 	/*
6760 	 * connections redirected to loopback should not match sockets
6761 	 * bound specifically to loopback due to security implications,
6762 	 * see tcp_input() and in_pcblookup_listen().
6763 	 */
6764 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6765 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6766 	    (s->nat_rule.ptr->action == PF_RDR ||
6767 	    s->nat_rule.ptr->action == PF_BINAT) &&
6768 	    IN_LOOPBACK(ntohl(pd.dst->v4.s_addr)))
6769 		m->m_flags |= M_SKIP_FIREWALL;
6770 
6771 	if (__predict_false(ip_divert_ptr != NULL) && action == PF_PASS &&
6772 	    r->divert.port && !PACKET_LOOPED(&pd)) {
6773 		ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6774 		    sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6775 		if (ipfwtag != NULL) {
6776 			((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6777 			    ntohs(r->divert.port);
6778 			((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6779 
6780 			if (s)
6781 				PF_STATE_UNLOCK(s);
6782 
6783 			m_tag_prepend(m, ipfwtag);
6784 			if (m->m_flags & M_FASTFWD_OURS) {
6785 				if (pd.pf_mtag == NULL &&
6786 				    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6787 					action = PF_DROP;
6788 					REASON_SET(&reason, PFRES_MEMORY);
6789 					log = 1;
6790 					DPFPRINTF(PF_DEBUG_MISC,
6791 					    ("pf: failed to allocate tag\n"));
6792 				} else {
6793 					pd.pf_mtag->flags |=
6794 					    PF_FASTFWD_OURS_PRESENT;
6795 					m->m_flags &= ~M_FASTFWD_OURS;
6796 				}
6797 			}
6798 			ip_divert_ptr(*m0, dir == PF_IN);
6799 			*m0 = NULL;
6800 
6801 			return (action);
6802 		} else {
6803 			/* XXX: ipfw has the same behaviour! */
6804 			action = PF_DROP;
6805 			REASON_SET(&reason, PFRES_MEMORY);
6806 			log = 1;
6807 			DPFPRINTF(PF_DEBUG_MISC,
6808 			    ("pf: failed to allocate divert tag\n"));
6809 		}
6810 	}
6811 
6812 	if (log) {
6813 		struct pf_krule *lr;
6814 
6815 		if (s != NULL && s->nat_rule.ptr != NULL &&
6816 		    s->nat_rule.ptr->log & PF_LOG_ALL)
6817 			lr = s->nat_rule.ptr;
6818 		else
6819 			lr = r;
6820 		PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6821 		    (s == NULL));
6822 	}
6823 
6824 	pf_counter_u64_critical_enter();
6825 	pf_counter_u64_add_protected(&kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS],
6826 	    pd.tot_len);
6827 	pf_counter_u64_add_protected(&kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS],
6828 	    1);
6829 
6830 	if (action == PF_PASS || r->action == PF_DROP) {
6831 		dirndx = (dir == PF_OUT);
6832 		pf_counter_u64_add_protected(&r->packets[dirndx], 1);
6833 		pf_counter_u64_add_protected(&r->bytes[dirndx], pd.tot_len);
6834 		if (a != NULL) {
6835 			pf_counter_u64_add_protected(&a->packets[dirndx], 1);
6836 			pf_counter_u64_add_protected(&a->bytes[dirndx], pd.tot_len);
6837 		}
6838 		if (s != NULL) {
6839 			if (s->nat_rule.ptr != NULL) {
6840 				pf_counter_u64_add_protected(&s->nat_rule.ptr->packets[dirndx],
6841 				    1);
6842 				pf_counter_u64_add_protected(&s->nat_rule.ptr->bytes[dirndx],
6843 				    pd.tot_len);
6844 			}
6845 			if (s->src_node != NULL) {
6846 				counter_u64_add(s->src_node->packets[dirndx],
6847 				    1);
6848 				counter_u64_add(s->src_node->bytes[dirndx],
6849 				    pd.tot_len);
6850 			}
6851 			if (s->nat_src_node != NULL) {
6852 				counter_u64_add(s->nat_src_node->packets[dirndx],
6853 				    1);
6854 				counter_u64_add(s->nat_src_node->bytes[dirndx],
6855 				    pd.tot_len);
6856 			}
6857 			dirndx = (dir == s->direction) ? 0 : 1;
6858 			s->packets[dirndx]++;
6859 			s->bytes[dirndx] += pd.tot_len;
6860 		}
6861 		tr = r;
6862 		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6863 		if (nr != NULL && r == &V_pf_default_rule)
6864 			tr = nr;
6865 		if (tr->src.addr.type == PF_ADDR_TABLE)
6866 			pfr_update_stats(tr->src.addr.p.tbl,
6867 			    (s == NULL) ? pd.src :
6868 			    &s->key[(s->direction == PF_IN)]->
6869 				addr[(s->direction == PF_OUT)],
6870 			    pd.af, pd.tot_len, dir == PF_OUT,
6871 			    r->action == PF_PASS, tr->src.neg);
6872 		if (tr->dst.addr.type == PF_ADDR_TABLE)
6873 			pfr_update_stats(tr->dst.addr.p.tbl,
6874 			    (s == NULL) ? pd.dst :
6875 			    &s->key[(s->direction == PF_IN)]->
6876 				addr[(s->direction == PF_IN)],
6877 			    pd.af, pd.tot_len, dir == PF_OUT,
6878 			    r->action == PF_PASS, tr->dst.neg);
6879 	}
6880 	pf_counter_u64_critical_exit();
6881 
6882 	switch (action) {
6883 	case PF_SYNPROXY_DROP:
6884 		m_freem(*m0);
6885 	case PF_DEFER:
6886 		*m0 = NULL;
6887 		action = PF_PASS;
6888 		break;
6889 	case PF_DROP:
6890 		m_freem(*m0);
6891 		*m0 = NULL;
6892 		break;
6893 	default:
6894 		/* pf_route() returns unlocked. */
6895 		if (r->rt) {
6896 			pf_route(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6897 			return (action);
6898 		}
6899 		break;
6900 	}
6901 
6902 	SDT_PROBE4(pf, ip, test, done, action, reason, r, s);
6903 
6904 	if (s)
6905 		PF_STATE_UNLOCK(s);
6906 
6907 	return (action);
6908 }
6909 #endif /* INET */
6910 
6911 #ifdef INET6
6912 int
6913 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6914 {
6915 	struct pfi_kkif		*kif;
6916 	u_short			 action, reason = 0, log = 0;
6917 	struct mbuf		*m = *m0, *n = NULL;
6918 	struct m_tag		*mtag;
6919 	struct m_tag		*ipfwtag;
6920 	struct ip6_hdr		*h = NULL;
6921 	struct pf_krule		*a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6922 	struct pf_kstate	*s = NULL;
6923 	struct pf_kruleset	*ruleset = NULL;
6924 	struct pf_pdesc		 pd;
6925 	int			 off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
6926 
6927 	PF_RULES_RLOCK_TRACKER;
6928 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: bad direction %d\n", __func__, dir));
6929 	M_ASSERTPKTHDR(m);
6930 
6931 	if (!V_pf_status.running)
6932 		return (PF_PASS);
6933 
6934 	memset(&pd, 0, sizeof(pd));
6935 	pd.pf_mtag = pf_find_mtag(m);
6936 
6937 	if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6938 		return (PF_PASS);
6939 
6940 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
6941 	if (kif == NULL) {
6942 		DPFPRINTF(PF_DEBUG_URGENT,
6943 		    ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6944 		return (PF_DROP);
6945 	}
6946 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
6947 		return (PF_PASS);
6948 
6949 	if (m->m_flags & M_SKIP_FIREWALL)
6950 		return (PF_PASS);
6951 
6952 	PF_RULES_RLOCK();
6953 
6954 	/* We do IP header normalization and packet reassembly here */
6955 	if (ip_dn_io_ptr != NULL &&
6956 	    ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
6957 		struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
6958 		if (rr->info & IPFW_IS_DUMMYNET) {
6959 			if (pd.pf_mtag == NULL &&
6960 			    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6961 				action = PF_DROP;
6962 				goto done;
6963 			}
6964 			pd.pf_mtag->flags |= PF_PACKET_LOOPED;
6965 			m_tag_delete(m, ipfwtag);
6966 		}
6967 	} else if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6968 		action = PF_DROP;
6969 		goto done;
6970 	}
6971 	m = *m0;	/* pf_normalize messes with m0 */
6972 	h = mtod(m, struct ip6_hdr *);
6973 
6974 	/*
6975 	 * we do not support jumbogram.  if we keep going, zero ip6_plen
6976 	 * will do something bad, so drop the packet for now.
6977 	 */
6978 	if (htons(h->ip6_plen) == 0) {
6979 		action = PF_DROP;
6980 		REASON_SET(&reason, PFRES_NORM);	/*XXX*/
6981 		goto done;
6982 	}
6983 
6984 	pd.src = (struct pf_addr *)&h->ip6_src;
6985 	pd.dst = (struct pf_addr *)&h->ip6_dst;
6986 	pd.sport = pd.dport = NULL;
6987 	pd.ip_sum = NULL;
6988 	pd.proto_sum = NULL;
6989 	pd.dir = dir;
6990 	pd.sidx = (dir == PF_IN) ? 0 : 1;
6991 	pd.didx = (dir == PF_IN) ? 1 : 0;
6992 	pd.af = AF_INET6;
6993 	pd.tos = IPV6_DSCP(h);
6994 	pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6995 
6996 	off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6997 	pd.proto = h->ip6_nxt;
6998 	do {
6999 		switch (pd.proto) {
7000 		case IPPROTO_FRAGMENT:
7001 			action = pf_test_fragment(&r, dir, kif, m, h,
7002 			    &pd, &a, &ruleset);
7003 			if (action == PF_DROP)
7004 				REASON_SET(&reason, PFRES_FRAG);
7005 			goto done;
7006 		case IPPROTO_ROUTING: {
7007 			struct ip6_rthdr rthdr;
7008 
7009 			if (rh_cnt++) {
7010 				DPFPRINTF(PF_DEBUG_MISC,
7011 				    ("pf: IPv6 more than one rthdr\n"));
7012 				action = PF_DROP;
7013 				REASON_SET(&reason, PFRES_IPOPTIONS);
7014 				log = 1;
7015 				goto done;
7016 			}
7017 			if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
7018 			    &reason, pd.af)) {
7019 				DPFPRINTF(PF_DEBUG_MISC,
7020 				    ("pf: IPv6 short rthdr\n"));
7021 				action = PF_DROP;
7022 				REASON_SET(&reason, PFRES_SHORT);
7023 				log = 1;
7024 				goto done;
7025 			}
7026 			if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
7027 				DPFPRINTF(PF_DEBUG_MISC,
7028 				    ("pf: IPv6 rthdr0\n"));
7029 				action = PF_DROP;
7030 				REASON_SET(&reason, PFRES_IPOPTIONS);
7031 				log = 1;
7032 				goto done;
7033 			}
7034 			/* FALLTHROUGH */
7035 		}
7036 		case IPPROTO_AH:
7037 		case IPPROTO_HOPOPTS:
7038 		case IPPROTO_DSTOPTS: {
7039 			/* get next header and header length */
7040 			struct ip6_ext	opt6;
7041 
7042 			if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
7043 			    NULL, &reason, pd.af)) {
7044 				DPFPRINTF(PF_DEBUG_MISC,
7045 				    ("pf: IPv6 short opt\n"));
7046 				action = PF_DROP;
7047 				log = 1;
7048 				goto done;
7049 			}
7050 			if (pd.proto == IPPROTO_AH)
7051 				off += (opt6.ip6e_len + 2) * 4;
7052 			else
7053 				off += (opt6.ip6e_len + 1) * 8;
7054 			pd.proto = opt6.ip6e_nxt;
7055 			/* goto the next header */
7056 			break;
7057 		}
7058 		default:
7059 			terminal++;
7060 			break;
7061 		}
7062 	} while (!terminal);
7063 
7064 	/* if there's no routing header, use unmodified mbuf for checksumming */
7065 	if (!n)
7066 		n = m;
7067 
7068 	switch (pd.proto) {
7069 	case IPPROTO_TCP: {
7070 		if (!pf_pull_hdr(m, off, &pd.hdr.tcp, sizeof(pd.hdr.tcp),
7071 		    &action, &reason, AF_INET6)) {
7072 			log = action != PF_PASS;
7073 			goto done;
7074 		}
7075 		pd.p_len = pd.tot_len - off - (pd.hdr.tcp.th_off << 2);
7076 		pd.sport = &pd.hdr.tcp.th_sport;
7077 		pd.dport = &pd.hdr.tcp.th_dport;
7078 		action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
7079 		if (action == PF_DROP)
7080 			goto done;
7081 		action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
7082 		    &reason);
7083 		if (action == PF_PASS) {
7084 			if (V_pfsync_update_state_ptr != NULL)
7085 				V_pfsync_update_state_ptr(s);
7086 			r = s->rule.ptr;
7087 			a = s->anchor.ptr;
7088 			log = s->log;
7089 		} else if (s == NULL)
7090 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7091 			    &a, &ruleset, inp);
7092 		break;
7093 	}
7094 
7095 	case IPPROTO_UDP: {
7096 		if (!pf_pull_hdr(m, off, &pd.hdr.udp, sizeof(pd.hdr.udp),
7097 		    &action, &reason, AF_INET6)) {
7098 			log = action != PF_PASS;
7099 			goto done;
7100 		}
7101 		pd.sport = &pd.hdr.udp.uh_sport;
7102 		pd.dport = &pd.hdr.udp.uh_dport;
7103 		if (pd.hdr.udp.uh_dport == 0 ||
7104 		    ntohs(pd.hdr.udp.uh_ulen) > m->m_pkthdr.len - off ||
7105 		    ntohs(pd.hdr.udp.uh_ulen) < sizeof(struct udphdr)) {
7106 			action = PF_DROP;
7107 			REASON_SET(&reason, PFRES_SHORT);
7108 			goto done;
7109 		}
7110 		action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
7111 		if (action == PF_PASS) {
7112 			if (V_pfsync_update_state_ptr != NULL)
7113 				V_pfsync_update_state_ptr(s);
7114 			r = s->rule.ptr;
7115 			a = s->anchor.ptr;
7116 			log = s->log;
7117 		} else if (s == NULL)
7118 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7119 			    &a, &ruleset, inp);
7120 		break;
7121 	}
7122 
7123 	case IPPROTO_ICMP: {
7124 		action = PF_DROP;
7125 		DPFPRINTF(PF_DEBUG_MISC,
7126 		    ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
7127 		goto done;
7128 	}
7129 
7130 	case IPPROTO_ICMPV6: {
7131 		if (!pf_pull_hdr(m, off, &pd.hdr.icmp6, sizeof(pd.hdr.icmp6),
7132 		    &action, &reason, AF_INET6)) {
7133 			log = action != PF_PASS;
7134 			goto done;
7135 		}
7136 		action = pf_test_state_icmp(&s, dir, kif,
7137 		    m, off, h, &pd, &reason);
7138 		if (action == PF_PASS) {
7139 			if (V_pfsync_update_state_ptr != NULL)
7140 				V_pfsync_update_state_ptr(s);
7141 			r = s->rule.ptr;
7142 			a = s->anchor.ptr;
7143 			log = s->log;
7144 		} else if (s == NULL)
7145 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7146 			    &a, &ruleset, inp);
7147 		break;
7148 	}
7149 
7150 	default:
7151 		action = pf_test_state_other(&s, dir, kif, m, &pd);
7152 		if (action == PF_PASS) {
7153 			if (V_pfsync_update_state_ptr != NULL)
7154 				V_pfsync_update_state_ptr(s);
7155 			r = s->rule.ptr;
7156 			a = s->anchor.ptr;
7157 			log = s->log;
7158 		} else if (s == NULL)
7159 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7160 			    &a, &ruleset, inp);
7161 		break;
7162 	}
7163 
7164 done:
7165 	PF_RULES_RUNLOCK();
7166 	if (n != m) {
7167 		m_freem(n);
7168 		n = NULL;
7169 	}
7170 
7171 	/* handle dangerous IPv6 extension headers. */
7172 	if (action == PF_PASS && rh_cnt &&
7173 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
7174 		action = PF_DROP;
7175 		REASON_SET(&reason, PFRES_IPOPTIONS);
7176 		log = r->log;
7177 		DPFPRINTF(PF_DEBUG_MISC,
7178 		    ("pf: dropping packet with dangerous v6 headers\n"));
7179 	}
7180 
7181 	if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
7182 		action = PF_DROP;
7183 		REASON_SET(&reason, PFRES_MEMORY);
7184 	}
7185 	if (r->rtableid >= 0)
7186 		M_SETFIB(m, r->rtableid);
7187 
7188 	if (r->scrub_flags & PFSTATE_SETPRIO) {
7189 		if (pd.tos & IPTOS_LOWDELAY)
7190 			pqid = 1;
7191 		if (vlan_set_pcp(m, r->set_prio[pqid])) {
7192 			action = PF_DROP;
7193 			REASON_SET(&reason, PFRES_MEMORY);
7194 			log = 1;
7195 			DPFPRINTF(PF_DEBUG_MISC,
7196 			    ("pf: failed to allocate 802.1q mtag\n"));
7197 		}
7198 	}
7199 
7200 #ifdef ALTQ
7201 	if (s && s->qid) {
7202 		pd.act.pqid = s->pqid;
7203 		pd.act.qid = s->qid;
7204 	} else if (r->qid) {
7205 		pd.act.pqid = r->pqid;
7206 		pd.act.qid = r->qid;
7207 	}
7208 	if (action == PF_PASS && pd.act.qid) {
7209 		if (pd.pf_mtag == NULL &&
7210 		    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
7211 			action = PF_DROP;
7212 			REASON_SET(&reason, PFRES_MEMORY);
7213 		} else {
7214 			if (s != NULL)
7215 				pd.pf_mtag->qid_hash = pf_state_hash(s);
7216 			if (pd.tos & IPTOS_LOWDELAY)
7217 				pd.pf_mtag->qid = pd.act.pqid;
7218 			else
7219 				pd.pf_mtag->qid = pd.act.qid;
7220 			/* Add hints for ecn. */
7221 			pd.pf_mtag->hdr = h;
7222 		}
7223 	}
7224 #endif /* ALTQ */
7225 
7226 	if (s && (s->dnpipe || s->dnrpipe)) {
7227 		pd.act.dnpipe = s->dnpipe;
7228 		pd.act.dnrpipe = s->dnrpipe;
7229 		pd.act.flags = s->state_flags;
7230 	} else {
7231 		pd.act.dnpipe = r->dnpipe;
7232 		pd.act.dnrpipe = r->dnrpipe;
7233 		pd.act.flags = r->free_flags;
7234 	}
7235 	if ((pd.act.dnpipe || pd.act.dnrpipe) && !PACKET_LOOPED(&pd)) {
7236 		if (ip_dn_io_ptr == NULL) {
7237 			action = PF_DROP;
7238 			REASON_SET(&reason, PFRES_MEMORY);
7239 		} else {
7240 			struct ip_fw_args dnflow;
7241 
7242 			if (pd.pf_mtag == NULL &&
7243 			    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
7244 				action = PF_DROP;
7245 				REASON_SET(&reason, PFRES_MEMORY);
7246 				if (s)
7247 					PF_STATE_UNLOCK(s);
7248 				return (action);
7249 			}
7250 
7251 			if (pf_pdesc_to_dnflow(dir, &pd, r, s, &dnflow)) {
7252 				ip_dn_io_ptr(m0, &dnflow);
7253 
7254 				if (*m0 == NULL) {
7255 					if (s)
7256 						PF_STATE_UNLOCK(s);
7257 					return (action);
7258 				} else {
7259 					/* This is dummynet fast io processing */
7260 					m_tag_delete(*m0, m_tag_first(*m0));
7261 					pd.pf_mtag->flags &= ~PF_PACKET_LOOPED;
7262 				}
7263 			}
7264 		}
7265 	}
7266 
7267 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
7268 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
7269 	    (s->nat_rule.ptr->action == PF_RDR ||
7270 	    s->nat_rule.ptr->action == PF_BINAT) &&
7271 	    IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
7272 		m->m_flags |= M_SKIP_FIREWALL;
7273 
7274 	/* XXX: Anybody working on it?! */
7275 	if (r->divert.port)
7276 		printf("pf: divert(9) is not supported for IPv6\n");
7277 
7278 	if (log) {
7279 		struct pf_krule *lr;
7280 
7281 		if (s != NULL && s->nat_rule.ptr != NULL &&
7282 		    s->nat_rule.ptr->log & PF_LOG_ALL)
7283 			lr = s->nat_rule.ptr;
7284 		else
7285 			lr = r;
7286 		PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
7287 		    &pd, (s == NULL));
7288 	}
7289 
7290 	pf_counter_u64_critical_enter();
7291 	pf_counter_u64_add_protected(&kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS],
7292 	    pd.tot_len);
7293 	pf_counter_u64_add_protected(&kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS],
7294 	    1);
7295 
7296 	if (action == PF_PASS || r->action == PF_DROP) {
7297 		dirndx = (dir == PF_OUT);
7298 		pf_counter_u64_add_protected(&r->packets[dirndx], 1);
7299 		pf_counter_u64_add_protected(&r->bytes[dirndx], pd.tot_len);
7300 		if (a != NULL) {
7301 			pf_counter_u64_add_protected(&a->packets[dirndx], 1);
7302 			pf_counter_u64_add_protected(&a->bytes[dirndx], pd.tot_len);
7303 		}
7304 		if (s != NULL) {
7305 			if (s->nat_rule.ptr != NULL) {
7306 				pf_counter_u64_add_protected(&s->nat_rule.ptr->packets[dirndx],
7307 				    1);
7308 				pf_counter_u64_add_protected(&s->nat_rule.ptr->bytes[dirndx],
7309 				    pd.tot_len);
7310 			}
7311 			if (s->src_node != NULL) {
7312 				counter_u64_add(s->src_node->packets[dirndx],
7313 				    1);
7314 				counter_u64_add(s->src_node->bytes[dirndx],
7315 				    pd.tot_len);
7316 			}
7317 			if (s->nat_src_node != NULL) {
7318 				counter_u64_add(s->nat_src_node->packets[dirndx],
7319 				    1);
7320 				counter_u64_add(s->nat_src_node->bytes[dirndx],
7321 				    pd.tot_len);
7322 			}
7323 			dirndx = (dir == s->direction) ? 0 : 1;
7324 			s->packets[dirndx]++;
7325 			s->bytes[dirndx] += pd.tot_len;
7326 		}
7327 		tr = r;
7328 		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
7329 		if (nr != NULL && r == &V_pf_default_rule)
7330 			tr = nr;
7331 		if (tr->src.addr.type == PF_ADDR_TABLE)
7332 			pfr_update_stats(tr->src.addr.p.tbl,
7333 			    (s == NULL) ? pd.src :
7334 			    &s->key[(s->direction == PF_IN)]->addr[0],
7335 			    pd.af, pd.tot_len, dir == PF_OUT,
7336 			    r->action == PF_PASS, tr->src.neg);
7337 		if (tr->dst.addr.type == PF_ADDR_TABLE)
7338 			pfr_update_stats(tr->dst.addr.p.tbl,
7339 			    (s == NULL) ? pd.dst :
7340 			    &s->key[(s->direction == PF_IN)]->addr[1],
7341 			    pd.af, pd.tot_len, dir == PF_OUT,
7342 			    r->action == PF_PASS, tr->dst.neg);
7343 	}
7344 	pf_counter_u64_critical_exit();
7345 
7346 	switch (action) {
7347 	case PF_SYNPROXY_DROP:
7348 		m_freem(*m0);
7349 	case PF_DEFER:
7350 		*m0 = NULL;
7351 		action = PF_PASS;
7352 		break;
7353 	case PF_DROP:
7354 		m_freem(*m0);
7355 		*m0 = NULL;
7356 		break;
7357 	default:
7358 		/* pf_route6() returns unlocked. */
7359 		if (r->rt) {
7360 			pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
7361 			return (action);
7362 		}
7363 		break;
7364 	}
7365 
7366 	if (s)
7367 		PF_STATE_UNLOCK(s);
7368 
7369 	/* If reassembled packet passed, create new fragments. */
7370 	if (action == PF_PASS && *m0 && (pflags & PFIL_FWD) &&
7371 	    (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
7372 		action = pf_refragment6(ifp, m0, mtag);
7373 
7374 	SDT_PROBE4(pf, ip, test6, done, action, reason, r, s);
7375 
7376 	return (action);
7377 }
7378 #endif /* INET6 */
7379