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