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