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