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