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