xref: /freebsd/sys/netpfil/pf/pf.c (revision b85b9c88eb02298ea7fa3885619f54ac0e930ba4)
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 	SDT_PROBE3(pf, eth, test_rule, entry, dir, kif->pfik_ifp, m);
3849 
3850 	ruleset = V_pf_keth;
3851 	rules = ck_pr_load_ptr(&ruleset->active.rules);
3852 	r = TAILQ_FIRST(rules);
3853 	rm = NULL;
3854 
3855 	e = mtod(m, struct ether_header *);
3856 	proto = ntohs(e->ether_type);
3857 
3858 	switch (proto) {
3859 #ifdef INET
3860 	case ETHERTYPE_IP: {
3861 		struct ip *ip;
3862 		m = m_pullup(m, sizeof(struct ether_header) +
3863 		    sizeof(struct ip));
3864 		if (m == NULL) {
3865 			*m0 = NULL;
3866 			return (PF_DROP);
3867 		}
3868 		af = AF_INET;
3869 		ip = mtodo(m, sizeof(struct ether_header));
3870 		src = (struct pf_addr *)&ip->ip_src;
3871 		dst = (struct pf_addr *)&ip->ip_dst;
3872 		break;
3873 	}
3874 #endif /* INET */
3875 #ifdef INET6
3876 	case ETHERTYPE_IPV6: {
3877 		struct ip6_hdr *ip6;
3878 		m = m_pullup(m, sizeof(struct ether_header) +
3879 		    sizeof(struct ip6_hdr));
3880 		if (m == NULL) {
3881 			*m0 = NULL;
3882 			return (PF_DROP);
3883 		}
3884 		af = AF_INET6;
3885 		ip6 = mtodo(m, sizeof(struct ether_header));
3886 		src = (struct pf_addr *)&ip6->ip6_src;
3887 		dst = (struct pf_addr *)&ip6->ip6_dst;
3888 		break;
3889 	}
3890 #endif /* INET6 */
3891 	}
3892 	e = mtod(m, struct ether_header *);
3893 	*m0 = m;
3894 
3895 	while (r != NULL) {
3896 		counter_u64_add(r->evaluations, 1);
3897 		SDT_PROBE2(pf, eth, test_rule, test, r->nr, r);
3898 
3899 		if (pfi_kkif_match(r->kif, kif) == r->ifnot) {
3900 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
3901 			    "kif");
3902 			r = r->skip[PFE_SKIP_IFP].ptr;
3903 		}
3904 		else if (r->direction && r->direction != dir) {
3905 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
3906 			    "dir");
3907 			r = r->skip[PFE_SKIP_DIR].ptr;
3908 		}
3909 		else if (r->proto && r->proto != proto) {
3910 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
3911 			    "proto");
3912 			r = r->skip[PFE_SKIP_PROTO].ptr;
3913 		}
3914 		else if (! pf_match_eth_addr(e->ether_shost, &r->src)) {
3915 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
3916 			    "src");
3917 			r = r->skip[PFE_SKIP_SRC_ADDR].ptr;
3918 		}
3919 		else if (! pf_match_eth_addr(e->ether_dhost, &r->dst)) {
3920 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
3921 			    "dst");
3922 			r = TAILQ_NEXT(r, entries);
3923 		}
3924 		else if (af != 0 && PF_MISMATCHAW(&r->ipsrc.addr, src, af,
3925 		    r->ipsrc.neg, kif, M_GETFIB(m))) {
3926 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
3927 			    "ip_src");
3928 			r = TAILQ_NEXT(r, entries);
3929 		}
3930 		else if (af != 0 && PF_MISMATCHAW(&r->ipdst.addr, dst, af,
3931 		    r->ipdst.neg, kif, M_GETFIB(m))) {
3932 			SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
3933 			    "ip_dst");
3934 			r = TAILQ_NEXT(r, entries);
3935 		}
3936 		else {
3937 			if (r->anchor == NULL) {
3938 				/* Rule matches */
3939 				rm = r;
3940 
3941 				SDT_PROBE2(pf, eth, test_rule, match, r->nr, r);
3942 
3943 				if (r->quick)
3944 					break;
3945 
3946 				r = TAILQ_NEXT(r, entries);
3947 			} else {
3948 				pf_step_into_keth_anchor(anchor_stack, &asd,
3949 				    &ruleset, &r, &a, &match);
3950 			}
3951 		}
3952 		if (r == NULL && pf_step_out_of_keth_anchor(anchor_stack, &asd,
3953 		    &ruleset, &r, &a, &match))
3954 			break;
3955 	}
3956 
3957 	r = rm;
3958 
3959 	SDT_PROBE2(pf, eth, test_rule, final_match, (r != NULL ? r->nr : -1), r);
3960 
3961 	/* Default to pass. */
3962 	if (r == NULL)
3963 		return (PF_PASS);
3964 
3965 	/* Execute action. */
3966 	counter_u64_add(r->packets[dir == PF_OUT], 1);
3967 	counter_u64_add(r->bytes[dir == PF_OUT], m_length(m, NULL));
3968 
3969 	/* Shortcut. Don't tag if we're just going to drop anyway. */
3970 	if (r->action == PF_DROP)
3971 		return (PF_DROP);
3972 
3973 	if (r->tag > 0) {
3974 		mtag = pf_get_mtag(m);
3975 		if (mtag == NULL) {
3976 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
3977 			return (PF_DROP);
3978 		}
3979 		mtag->tag = r->tag;
3980 	}
3981 
3982 	if (r->qid != 0) {
3983 		mtag = pf_get_mtag(m);
3984 		if (mtag == NULL) {
3985 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
3986 			return (PF_DROP);
3987 		}
3988 		mtag->qid = r->qid;
3989 	}
3990 
3991 	/* Dummynet */
3992 	if (r->dnpipe) {
3993 		/** While dummynet supports handling Ethernet packets directly
3994 		 * it still wants some L3/L4 information, and we're not set up
3995 		 * to provide that here. Instead we'll do what we do for ALTQ
3996 		 * and merely mark the packet with the dummynet queue/pipe number.
3997 		 **/
3998 		mtag = pf_get_mtag(m);
3999 		if (mtag == NULL) {
4000 			counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
4001 			return (PF_DROP);
4002 		}
4003 		mtag->dnpipe = r->dnpipe;
4004 		mtag->dnflags = r->dnflags;
4005 	}
4006 
4007 	action = r->action;
4008 
4009 	return (action);
4010 }
4011 
4012 static int
4013 pf_test_rule(struct pf_krule **rm, struct pf_kstate **sm, int direction,
4014     struct pfi_kkif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
4015     struct pf_krule **am, struct pf_kruleset **rsm, struct inpcb *inp)
4016 {
4017 	struct pf_krule		*nr = NULL;
4018 	struct pf_addr		* const saddr = pd->src;
4019 	struct pf_addr		* const daddr = pd->dst;
4020 	sa_family_t		 af = pd->af;
4021 	struct pf_krule		*r, *a = NULL;
4022 	struct pf_kruleset	*ruleset = NULL;
4023 	struct pf_ksrc_node	*nsn = NULL;
4024 	struct tcphdr		*th = &pd->hdr.tcp;
4025 	struct pf_state_key	*sk = NULL, *nk = NULL;
4026 	u_short			 reason;
4027 	int			 rewrite = 0, hdrlen = 0;
4028 	int			 tag = -1, rtableid = -1;
4029 	int			 asd = 0;
4030 	int			 match = 0;
4031 	int			 state_icmp = 0;
4032 	u_int16_t		 sport = 0, dport = 0;
4033 	u_int16_t		 bproto_sum = 0, bip_sum = 0;
4034 	u_int8_t		 icmptype = 0, icmpcode = 0;
4035 	struct pf_kanchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
4036 
4037 	PF_RULES_RASSERT();
4038 
4039 	if (inp != NULL) {
4040 		INP_LOCK_ASSERT(inp);
4041 		pd->lookup.uid = inp->inp_cred->cr_uid;
4042 		pd->lookup.gid = inp->inp_cred->cr_groups[0];
4043 		pd->lookup.done = 1;
4044 	}
4045 
4046 	switch (pd->proto) {
4047 	case IPPROTO_TCP:
4048 		sport = th->th_sport;
4049 		dport = th->th_dport;
4050 		hdrlen = sizeof(*th);
4051 		break;
4052 	case IPPROTO_UDP:
4053 		sport = pd->hdr.udp.uh_sport;
4054 		dport = pd->hdr.udp.uh_dport;
4055 		hdrlen = sizeof(pd->hdr.udp);
4056 		break;
4057 #ifdef INET
4058 	case IPPROTO_ICMP:
4059 		if (pd->af != AF_INET)
4060 			break;
4061 		sport = dport = pd->hdr.icmp.icmp_id;
4062 		hdrlen = sizeof(pd->hdr.icmp);
4063 		icmptype = pd->hdr.icmp.icmp_type;
4064 		icmpcode = pd->hdr.icmp.icmp_code;
4065 
4066 		if (icmptype == ICMP_UNREACH ||
4067 		    icmptype == ICMP_SOURCEQUENCH ||
4068 		    icmptype == ICMP_REDIRECT ||
4069 		    icmptype == ICMP_TIMXCEED ||
4070 		    icmptype == ICMP_PARAMPROB)
4071 			state_icmp++;
4072 		break;
4073 #endif /* INET */
4074 #ifdef INET6
4075 	case IPPROTO_ICMPV6:
4076 		if (af != AF_INET6)
4077 			break;
4078 		sport = dport = pd->hdr.icmp6.icmp6_id;
4079 		hdrlen = sizeof(pd->hdr.icmp6);
4080 		icmptype = pd->hdr.icmp6.icmp6_type;
4081 		icmpcode = pd->hdr.icmp6.icmp6_code;
4082 
4083 		if (icmptype == ICMP6_DST_UNREACH ||
4084 		    icmptype == ICMP6_PACKET_TOO_BIG ||
4085 		    icmptype == ICMP6_TIME_EXCEEDED ||
4086 		    icmptype == ICMP6_PARAM_PROB)
4087 			state_icmp++;
4088 		break;
4089 #endif /* INET6 */
4090 	default:
4091 		sport = dport = hdrlen = 0;
4092 		break;
4093 	}
4094 
4095 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
4096 
4097 	/* check packet for BINAT/NAT/RDR */
4098 	if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
4099 	    &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
4100 		KASSERT(sk != NULL, ("%s: null sk", __func__));
4101 		KASSERT(nk != NULL, ("%s: null nk", __func__));
4102 
4103 		if (nr->log) {
4104 			PFLOG_PACKET(kif, m, af, direction, PFRES_MATCH, nr, a,
4105 			    ruleset, pd, 1);
4106 		}
4107 
4108 		if (pd->ip_sum)
4109 			bip_sum = *pd->ip_sum;
4110 
4111 		switch (pd->proto) {
4112 		case IPPROTO_TCP:
4113 			bproto_sum = th->th_sum;
4114 			pd->proto_sum = &th->th_sum;
4115 
4116 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
4117 			    nk->port[pd->sidx] != sport) {
4118 				pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
4119 				    &th->th_sum, &nk->addr[pd->sidx],
4120 				    nk->port[pd->sidx], 0, af);
4121 				pd->sport = &th->th_sport;
4122 				sport = th->th_sport;
4123 			}
4124 
4125 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
4126 			    nk->port[pd->didx] != dport) {
4127 				pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
4128 				    &th->th_sum, &nk->addr[pd->didx],
4129 				    nk->port[pd->didx], 0, af);
4130 				dport = th->th_dport;
4131 				pd->dport = &th->th_dport;
4132 			}
4133 			rewrite++;
4134 			break;
4135 		case IPPROTO_UDP:
4136 			bproto_sum = pd->hdr.udp.uh_sum;
4137 			pd->proto_sum = &pd->hdr.udp.uh_sum;
4138 
4139 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
4140 			    nk->port[pd->sidx] != sport) {
4141 				pf_change_ap(m, saddr, &pd->hdr.udp.uh_sport,
4142 				    pd->ip_sum, &pd->hdr.udp.uh_sum,
4143 				    &nk->addr[pd->sidx],
4144 				    nk->port[pd->sidx], 1, af);
4145 				sport = pd->hdr.udp.uh_sport;
4146 				pd->sport = &pd->hdr.udp.uh_sport;
4147 			}
4148 
4149 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
4150 			    nk->port[pd->didx] != dport) {
4151 				pf_change_ap(m, daddr, &pd->hdr.udp.uh_dport,
4152 				    pd->ip_sum, &pd->hdr.udp.uh_sum,
4153 				    &nk->addr[pd->didx],
4154 				    nk->port[pd->didx], 1, af);
4155 				dport = pd->hdr.udp.uh_dport;
4156 				pd->dport = &pd->hdr.udp.uh_dport;
4157 			}
4158 			rewrite++;
4159 			break;
4160 #ifdef INET
4161 		case IPPROTO_ICMP:
4162 			nk->port[0] = nk->port[1];
4163 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
4164 				pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
4165 				    nk->addr[pd->sidx].v4.s_addr, 0);
4166 
4167 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
4168 				pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
4169 				    nk->addr[pd->didx].v4.s_addr, 0);
4170 
4171 			if (nk->port[1] != pd->hdr.icmp.icmp_id) {
4172 				pd->hdr.icmp.icmp_cksum = pf_cksum_fixup(
4173 				    pd->hdr.icmp.icmp_cksum, sport,
4174 				    nk->port[1], 0);
4175 				pd->hdr.icmp.icmp_id = nk->port[1];
4176 				pd->sport = &pd->hdr.icmp.icmp_id;
4177 			}
4178 			m_copyback(m, off, ICMP_MINLEN, (caddr_t)&pd->hdr.icmp);
4179 			break;
4180 #endif /* INET */
4181 #ifdef INET6
4182 		case IPPROTO_ICMPV6:
4183 			nk->port[0] = nk->port[1];
4184 			if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
4185 				pf_change_a6(saddr, &pd->hdr.icmp6.icmp6_cksum,
4186 				    &nk->addr[pd->sidx], 0);
4187 
4188 			if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
4189 				pf_change_a6(daddr, &pd->hdr.icmp6.icmp6_cksum,
4190 				    &nk->addr[pd->didx], 0);
4191 			rewrite++;
4192 			break;
4193 #endif /* INET */
4194 		default:
4195 			switch (af) {
4196 #ifdef INET
4197 			case AF_INET:
4198 				if (PF_ANEQ(saddr,
4199 				    &nk->addr[pd->sidx], AF_INET))
4200 					pf_change_a(&saddr->v4.s_addr,
4201 					    pd->ip_sum,
4202 					    nk->addr[pd->sidx].v4.s_addr, 0);
4203 
4204 				if (PF_ANEQ(daddr,
4205 				    &nk->addr[pd->didx], AF_INET))
4206 					pf_change_a(&daddr->v4.s_addr,
4207 					    pd->ip_sum,
4208 					    nk->addr[pd->didx].v4.s_addr, 0);
4209 				break;
4210 #endif /* INET */
4211 #ifdef INET6
4212 			case AF_INET6:
4213 				if (PF_ANEQ(saddr,
4214 				    &nk->addr[pd->sidx], AF_INET6))
4215 					PF_ACPY(saddr, &nk->addr[pd->sidx], af);
4216 
4217 				if (PF_ANEQ(daddr,
4218 				    &nk->addr[pd->didx], AF_INET6))
4219 					PF_ACPY(daddr, &nk->addr[pd->didx], af);
4220 				break;
4221 #endif /* INET */
4222 			}
4223 			break;
4224 		}
4225 		if (nr->natpass)
4226 			r = NULL;
4227 		pd->nat_rule = nr;
4228 	}
4229 
4230 	while (r != NULL) {
4231 		pf_counter_u64_add(&r->evaluations, 1);
4232 		if (pfi_kkif_match(r->kif, kif) == r->ifnot)
4233 			r = r->skip[PF_SKIP_IFP].ptr;
4234 		else if (r->direction && r->direction != direction)
4235 			r = r->skip[PF_SKIP_DIR].ptr;
4236 		else if (r->af && r->af != af)
4237 			r = r->skip[PF_SKIP_AF].ptr;
4238 		else if (r->proto && r->proto != pd->proto)
4239 			r = r->skip[PF_SKIP_PROTO].ptr;
4240 		else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
4241 		    r->src.neg, kif, M_GETFIB(m)))
4242 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
4243 		/* tcp/udp only. port_op always 0 in other cases */
4244 		else if (r->src.port_op && !pf_match_port(r->src.port_op,
4245 		    r->src.port[0], r->src.port[1], sport))
4246 			r = r->skip[PF_SKIP_SRC_PORT].ptr;
4247 		else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
4248 		    r->dst.neg, NULL, M_GETFIB(m)))
4249 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
4250 		/* tcp/udp only. port_op always 0 in other cases */
4251 		else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
4252 		    r->dst.port[0], r->dst.port[1], dport))
4253 			r = r->skip[PF_SKIP_DST_PORT].ptr;
4254 		/* icmp only. type always 0 in other cases */
4255 		else if (r->type && r->type != icmptype + 1)
4256 			r = TAILQ_NEXT(r, entries);
4257 		/* icmp only. type always 0 in other cases */
4258 		else if (r->code && r->code != icmpcode + 1)
4259 			r = TAILQ_NEXT(r, entries);
4260 		else if (r->tos && !(r->tos == pd->tos))
4261 			r = TAILQ_NEXT(r, entries);
4262 		else if (r->rule_flag & PFRULE_FRAGMENT)
4263 			r = TAILQ_NEXT(r, entries);
4264 		else if (pd->proto == IPPROTO_TCP &&
4265 		    (r->flagset & th->th_flags) != r->flags)
4266 			r = TAILQ_NEXT(r, entries);
4267 		/* tcp/udp only. uid.op always 0 in other cases */
4268 		else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
4269 		    pf_socket_lookup(direction, pd, m), 1)) &&
4270 		    !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
4271 		    pd->lookup.uid))
4272 			r = TAILQ_NEXT(r, entries);
4273 		/* tcp/udp only. gid.op always 0 in other cases */
4274 		else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
4275 		    pf_socket_lookup(direction, pd, m), 1)) &&
4276 		    !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
4277 		    pd->lookup.gid))
4278 			r = TAILQ_NEXT(r, entries);
4279 		else if (r->prio &&
4280 		    !pf_match_ieee8021q_pcp(r->prio, m))
4281 			r = TAILQ_NEXT(r, entries);
4282 		else if (r->prob &&
4283 		    r->prob <= arc4random())
4284 			r = TAILQ_NEXT(r, entries);
4285 		else if (r->match_tag && !pf_match_tag(m, r, &tag,
4286 		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
4287 			r = TAILQ_NEXT(r, entries);
4288 		else if (r->os_fingerprint != PF_OSFP_ANY &&
4289 		    (pd->proto != IPPROTO_TCP || !pf_osfp_match(
4290 		    pf_osfp_fingerprint(pd, m, off, th),
4291 		    r->os_fingerprint)))
4292 			r = TAILQ_NEXT(r, entries);
4293 		else {
4294 			if (r->tag)
4295 				tag = r->tag;
4296 			if (r->rtableid >= 0)
4297 				rtableid = r->rtableid;
4298 			if (r->anchor == NULL) {
4299 				if (r->action == PF_MATCH) {
4300 					pf_counter_u64_critical_enter();
4301 					pf_counter_u64_add_protected(&r->packets[direction == PF_OUT], 1);
4302 					pf_counter_u64_add_protected(&r->bytes[direction == PF_OUT], pd->tot_len);
4303 					pf_counter_u64_critical_exit();
4304 					pf_rule_to_actions(r, &pd->act);
4305 					if (r->log)
4306 						PFLOG_PACKET(kif, m, af,
4307 						    direction, PFRES_MATCH, r,
4308 						    a, ruleset, pd, 1);
4309 				} else {
4310 					match = 1;
4311 					*rm = r;
4312 					*am = a;
4313 					*rsm = ruleset;
4314 				}
4315 				if ((*rm)->quick)
4316 					break;
4317 				r = TAILQ_NEXT(r, entries);
4318 			} else
4319 				pf_step_into_anchor(anchor_stack, &asd,
4320 				    &ruleset, PF_RULESET_FILTER, &r, &a,
4321 				    &match);
4322 		}
4323 		if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
4324 		    &ruleset, PF_RULESET_FILTER, &r, &a, &match))
4325 			break;
4326 	}
4327 	r = *rm;
4328 	a = *am;
4329 	ruleset = *rsm;
4330 
4331 	REASON_SET(&reason, PFRES_MATCH);
4332 
4333 	/* apply actions for last matching pass/block rule */
4334 	pf_rule_to_actions(r, &pd->act);
4335 
4336 	if (r->log) {
4337 		if (rewrite)
4338 			m_copyback(m, off, hdrlen, pd->hdr.any);
4339 		PFLOG_PACKET(kif, m, af, direction, reason, r, a,
4340 		    ruleset, pd, 1);
4341 	}
4342 
4343 	if ((r->action == PF_DROP) &&
4344 	    ((r->rule_flag & PFRULE_RETURNRST) ||
4345 	    (r->rule_flag & PFRULE_RETURNICMP) ||
4346 	    (r->rule_flag & PFRULE_RETURN))) {
4347 		pf_return(r, nr, pd, sk, off, m, th, kif, bproto_sum,
4348 		    bip_sum, hdrlen, &reason);
4349 	}
4350 
4351 	if (r->action == PF_DROP)
4352 		goto cleanup;
4353 
4354 	if (tag > 0 && pf_tag_packet(m, pd, tag)) {
4355 		REASON_SET(&reason, PFRES_MEMORY);
4356 		goto cleanup;
4357 	}
4358 	if (rtableid >= 0)
4359 		M_SETFIB(m, rtableid);
4360 
4361 	if (!state_icmp && (r->keep_state || nr != NULL ||
4362 	    (pd->flags & PFDESC_TCP_NORM))) {
4363 		int action;
4364 		action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
4365 		    sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
4366 		    hdrlen);
4367 		if (action != PF_PASS) {
4368 			if (action == PF_DROP &&
4369 			    (r->rule_flag & PFRULE_RETURN))
4370 				pf_return(r, nr, pd, sk, off, m, th, kif,
4371 				    bproto_sum, bip_sum, hdrlen, &reason);
4372 			return (action);
4373 		}
4374 	} else {
4375 		if (sk != NULL)
4376 			uma_zfree(V_pf_state_key_z, sk);
4377 		if (nk != NULL)
4378 			uma_zfree(V_pf_state_key_z, nk);
4379 	}
4380 
4381 	/* copy back packet headers if we performed NAT operations */
4382 	if (rewrite)
4383 		m_copyback(m, off, hdrlen, pd->hdr.any);
4384 
4385 	if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
4386 	    direction == PF_OUT &&
4387 	    V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, m))
4388 		/*
4389 		 * We want the state created, but we dont
4390 		 * want to send this in case a partner
4391 		 * firewall has to know about it to allow
4392 		 * replies through it.
4393 		 */
4394 		return (PF_DEFER);
4395 
4396 	return (PF_PASS);
4397 
4398 cleanup:
4399 	if (sk != NULL)
4400 		uma_zfree(V_pf_state_key_z, sk);
4401 	if (nk != NULL)
4402 		uma_zfree(V_pf_state_key_z, nk);
4403 	return (PF_DROP);
4404 }
4405 
4406 static int
4407 pf_create_state(struct pf_krule *r, struct pf_krule *nr, struct pf_krule *a,
4408     struct pf_pdesc *pd, struct pf_ksrc_node *nsn, struct pf_state_key *nk,
4409     struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
4410     u_int16_t dport, int *rewrite, struct pfi_kkif *kif, struct pf_kstate **sm,
4411     int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
4412 {
4413 	struct pf_kstate	*s = NULL;
4414 	struct pf_ksrc_node	*sn = NULL;
4415 	struct tcphdr		*th = &pd->hdr.tcp;
4416 	u_int16_t		 mss = V_tcp_mssdflt;
4417 	u_short			 reason;
4418 
4419 	/* check maximums */
4420 	if (r->max_states &&
4421 	    (counter_u64_fetch(r->states_cur) >= r->max_states)) {
4422 		counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
4423 		REASON_SET(&reason, PFRES_MAXSTATES);
4424 		goto csfailed;
4425 	}
4426 	/* src node for filter rule */
4427 	if ((r->rule_flag & PFRULE_SRCTRACK ||
4428 	    r->rpool.opts & PF_POOL_STICKYADDR) &&
4429 	    pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
4430 		REASON_SET(&reason, PFRES_SRCLIMIT);
4431 		goto csfailed;
4432 	}
4433 	/* src node for translation rule */
4434 	if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
4435 	    pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
4436 		REASON_SET(&reason, PFRES_SRCLIMIT);
4437 		goto csfailed;
4438 	}
4439 	s = pf_alloc_state(M_NOWAIT);
4440 	if (s == NULL) {
4441 		REASON_SET(&reason, PFRES_MEMORY);
4442 		goto csfailed;
4443 	}
4444 	s->rule.ptr = r;
4445 	s->nat_rule.ptr = nr;
4446 	s->anchor.ptr = a;
4447 	STATE_INC_COUNTERS(s);
4448 	if (r->allow_opts)
4449 		s->state_flags |= PFSTATE_ALLOWOPTS;
4450 	if (r->rule_flag & PFRULE_STATESLOPPY)
4451 		s->state_flags |= PFSTATE_SLOPPY;
4452 	s->log = r->log & PF_LOG_ALL;
4453 	s->sync_state = PFSYNC_S_NONE;
4454 	s->qid = pd->act.qid;
4455 	s->pqid = pd->act.pqid;
4456 	s->dnpipe = pd->act.dnpipe;
4457 	s->dnrpipe = pd->act.dnrpipe;
4458 	s->state_flags |= pd->act.flags;
4459 	if (nr != NULL)
4460 		s->log |= nr->log & PF_LOG_ALL;
4461 	switch (pd->proto) {
4462 	case IPPROTO_TCP:
4463 		s->src.seqlo = ntohl(th->th_seq);
4464 		s->src.seqhi = s->src.seqlo + pd->p_len + 1;
4465 		if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
4466 		    r->keep_state == PF_STATE_MODULATE) {
4467 			/* Generate sequence number modulator */
4468 			if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
4469 			    0)
4470 				s->src.seqdiff = 1;
4471 			pf_change_proto_a(m, &th->th_seq, &th->th_sum,
4472 			    htonl(s->src.seqlo + s->src.seqdiff), 0);
4473 			*rewrite = 1;
4474 		} else
4475 			s->src.seqdiff = 0;
4476 		if (th->th_flags & TH_SYN) {
4477 			s->src.seqhi++;
4478 			s->src.wscale = pf_get_wscale(m, off,
4479 			    th->th_off, pd->af);
4480 		}
4481 		s->src.max_win = MAX(ntohs(th->th_win), 1);
4482 		if (s->src.wscale & PF_WSCALE_MASK) {
4483 			/* Remove scale factor from initial window */
4484 			int win = s->src.max_win;
4485 			win += 1 << (s->src.wscale & PF_WSCALE_MASK);
4486 			s->src.max_win = (win - 1) >>
4487 			    (s->src.wscale & PF_WSCALE_MASK);
4488 		}
4489 		if (th->th_flags & TH_FIN)
4490 			s->src.seqhi++;
4491 		s->dst.seqhi = 1;
4492 		s->dst.max_win = 1;
4493 		pf_set_protostate(s, PF_PEER_SRC, TCPS_SYN_SENT);
4494 		pf_set_protostate(s, PF_PEER_DST, TCPS_CLOSED);
4495 		s->timeout = PFTM_TCP_FIRST_PACKET;
4496 		atomic_add_32(&V_pf_status.states_halfopen, 1);
4497 		break;
4498 	case IPPROTO_UDP:
4499 		pf_set_protostate(s, PF_PEER_SRC, PFUDPS_SINGLE);
4500 		pf_set_protostate(s, PF_PEER_DST, PFUDPS_NO_TRAFFIC);
4501 		s->timeout = PFTM_UDP_FIRST_PACKET;
4502 		break;
4503 	case IPPROTO_ICMP:
4504 #ifdef INET6
4505 	case IPPROTO_ICMPV6:
4506 #endif
4507 		s->timeout = PFTM_ICMP_FIRST_PACKET;
4508 		break;
4509 	default:
4510 		pf_set_protostate(s, PF_PEER_SRC, PFOTHERS_SINGLE);
4511 		pf_set_protostate(s, PF_PEER_DST, PFOTHERS_NO_TRAFFIC);
4512 		s->timeout = PFTM_OTHER_FIRST_PACKET;
4513 	}
4514 
4515 	if (r->rt) {
4516 		if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
4517 			REASON_SET(&reason, PFRES_MAPFAILED);
4518 			pf_src_tree_remove_state(s);
4519 			s->timeout = PFTM_UNLINKED;
4520 			STATE_DEC_COUNTERS(s);
4521 			pf_free_state(s);
4522 			goto csfailed;
4523 		}
4524 		s->rt_kif = r->rpool.cur->kif;
4525 	}
4526 
4527 	s->creation = time_uptime;
4528 	s->expire = time_uptime;
4529 
4530 	if (sn != NULL)
4531 		s->src_node = sn;
4532 	if (nsn != NULL) {
4533 		/* XXX We only modify one side for now. */
4534 		PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
4535 		s->nat_src_node = nsn;
4536 	}
4537 	if (pd->proto == IPPROTO_TCP) {
4538 		if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
4539 		    off, pd, th, &s->src, &s->dst)) {
4540 			REASON_SET(&reason, PFRES_MEMORY);
4541 			pf_src_tree_remove_state(s);
4542 			s->timeout = PFTM_UNLINKED;
4543 			STATE_DEC_COUNTERS(s);
4544 			pf_free_state(s);
4545 			return (PF_DROP);
4546 		}
4547 		if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
4548 		    pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
4549 		    &s->src, &s->dst, rewrite)) {
4550 			/* This really shouldn't happen!!! */
4551 			DPFPRINTF(PF_DEBUG_URGENT,
4552 			    ("pf_normalize_tcp_stateful failed on first "
4553 			     "pkt\n"));
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 	}
4561 	s->direction = pd->dir;
4562 
4563 	/*
4564 	 * sk/nk could already been setup by pf_get_translation().
4565 	 */
4566 	if (nr == NULL) {
4567 		KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
4568 		    __func__, nr, sk, nk));
4569 		sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
4570 		if (sk == NULL)
4571 			goto csfailed;
4572 		nk = sk;
4573 	} else
4574 		KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
4575 		    __func__, nr, sk, nk));
4576 
4577 	/* Swap sk/nk for PF_OUT. */
4578 	if (pf_state_insert(BOUND_IFACE(r, kif), kif,
4579 	    (pd->dir == PF_IN) ? sk : nk,
4580 	    (pd->dir == PF_IN) ? nk : sk, s)) {
4581 		REASON_SET(&reason, PFRES_STATEINS);
4582 		pf_src_tree_remove_state(s);
4583 		s->timeout = PFTM_UNLINKED;
4584 		STATE_DEC_COUNTERS(s);
4585 		pf_free_state(s);
4586 		return (PF_DROP);
4587 	} else
4588 		*sm = s;
4589 
4590 	if (tag > 0)
4591 		s->tag = tag;
4592 	if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
4593 	    TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
4594 		pf_set_protostate(s, PF_PEER_SRC, PF_TCPS_PROXY_SRC);
4595 		/* undo NAT changes, if they have taken place */
4596 		if (nr != NULL) {
4597 			struct pf_state_key *skt = s->key[PF_SK_WIRE];
4598 			if (pd->dir == PF_OUT)
4599 				skt = s->key[PF_SK_STACK];
4600 			PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
4601 			PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
4602 			if (pd->sport)
4603 				*pd->sport = skt->port[pd->sidx];
4604 			if (pd->dport)
4605 				*pd->dport = skt->port[pd->didx];
4606 			if (pd->proto_sum)
4607 				*pd->proto_sum = bproto_sum;
4608 			if (pd->ip_sum)
4609 				*pd->ip_sum = bip_sum;
4610 			m_copyback(m, off, hdrlen, pd->hdr.any);
4611 		}
4612 		s->src.seqhi = htonl(arc4random());
4613 		/* Find mss option */
4614 		int rtid = M_GETFIB(m);
4615 		mss = pf_get_mss(m, off, th->th_off, pd->af);
4616 		mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
4617 		mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
4618 		s->src.mss = mss;
4619 		pf_send_tcp(r, pd->af, pd->dst, pd->src, th->th_dport,
4620 		    th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
4621 		    TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0);
4622 		REASON_SET(&reason, PFRES_SYNPROXY);
4623 		return (PF_SYNPROXY_DROP);
4624 	}
4625 
4626 	return (PF_PASS);
4627 
4628 csfailed:
4629 	if (sk != NULL)
4630 		uma_zfree(V_pf_state_key_z, sk);
4631 	if (nk != NULL)
4632 		uma_zfree(V_pf_state_key_z, nk);
4633 
4634 	if (sn != NULL) {
4635 		struct pf_srchash *sh;
4636 
4637 		sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
4638 		PF_HASHROW_LOCK(sh);
4639 		if (--sn->states == 0 && sn->expire == 0) {
4640 			pf_unlink_src_node(sn);
4641 			uma_zfree(V_pf_sources_z, sn);
4642 			counter_u64_add(
4643 			    V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
4644 		}
4645 		PF_HASHROW_UNLOCK(sh);
4646 	}
4647 
4648 	if (nsn != sn && nsn != NULL) {
4649 		struct pf_srchash *sh;
4650 
4651 		sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
4652 		PF_HASHROW_LOCK(sh);
4653 		if (--nsn->states == 0 && nsn->expire == 0) {
4654 			pf_unlink_src_node(nsn);
4655 			uma_zfree(V_pf_sources_z, nsn);
4656 			counter_u64_add(
4657 			    V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
4658 		}
4659 		PF_HASHROW_UNLOCK(sh);
4660 	}
4661 
4662 	return (PF_DROP);
4663 }
4664 
4665 static int
4666 pf_test_fragment(struct pf_krule **rm, int direction, struct pfi_kkif *kif,
4667     struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_krule **am,
4668     struct pf_kruleset **rsm)
4669 {
4670 	struct pf_krule		*r, *a = NULL;
4671 	struct pf_kruleset	*ruleset = NULL;
4672 	sa_family_t		 af = pd->af;
4673 	u_short			 reason;
4674 	int			 tag = -1;
4675 	int			 asd = 0;
4676 	int			 match = 0;
4677 	struct pf_kanchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
4678 
4679 	PF_RULES_RASSERT();
4680 
4681 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
4682 	while (r != NULL) {
4683 		pf_counter_u64_add(&r->evaluations, 1);
4684 		if (pfi_kkif_match(r->kif, kif) == r->ifnot)
4685 			r = r->skip[PF_SKIP_IFP].ptr;
4686 		else if (r->direction && r->direction != direction)
4687 			r = r->skip[PF_SKIP_DIR].ptr;
4688 		else if (r->af && r->af != af)
4689 			r = r->skip[PF_SKIP_AF].ptr;
4690 		else if (r->proto && r->proto != pd->proto)
4691 			r = r->skip[PF_SKIP_PROTO].ptr;
4692 		else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
4693 		    r->src.neg, kif, M_GETFIB(m)))
4694 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
4695 		else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
4696 		    r->dst.neg, NULL, M_GETFIB(m)))
4697 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
4698 		else if (r->tos && !(r->tos == pd->tos))
4699 			r = TAILQ_NEXT(r, entries);
4700 		else if (r->os_fingerprint != PF_OSFP_ANY)
4701 			r = TAILQ_NEXT(r, entries);
4702 		else if (pd->proto == IPPROTO_UDP &&
4703 		    (r->src.port_op || r->dst.port_op))
4704 			r = TAILQ_NEXT(r, entries);
4705 		else if (pd->proto == IPPROTO_TCP &&
4706 		    (r->src.port_op || r->dst.port_op || r->flagset))
4707 			r = TAILQ_NEXT(r, entries);
4708 		else if ((pd->proto == IPPROTO_ICMP ||
4709 		    pd->proto == IPPROTO_ICMPV6) &&
4710 		    (r->type || r->code))
4711 			r = TAILQ_NEXT(r, entries);
4712 		else if (r->prio &&
4713 		    !pf_match_ieee8021q_pcp(r->prio, m))
4714 			r = TAILQ_NEXT(r, entries);
4715 		else if (r->prob && r->prob <=
4716 		    (arc4random() % (UINT_MAX - 1) + 1))
4717 			r = TAILQ_NEXT(r, entries);
4718 		else if (r->match_tag && !pf_match_tag(m, r, &tag,
4719 		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
4720 			r = TAILQ_NEXT(r, entries);
4721 		else {
4722 			if (r->anchor == NULL) {
4723 				if (r->action == PF_MATCH) {
4724 					pf_counter_u64_critical_enter();
4725 					pf_counter_u64_add_protected(&r->packets[direction == PF_OUT], 1);
4726 					pf_counter_u64_add_protected(&r->bytes[direction == PF_OUT], pd->tot_len);
4727 					pf_counter_u64_critical_exit();
4728 					pf_rule_to_actions(r, &pd->act);
4729 					if (r->log)
4730 						PFLOG_PACKET(kif, m, af,
4731 						    direction, PFRES_MATCH, r,
4732 						    a, ruleset, pd, 1);
4733 				} else {
4734 					match = 1;
4735 					*rm = r;
4736 					*am = a;
4737 					*rsm = ruleset;
4738 				}
4739 				if ((*rm)->quick)
4740 					break;
4741 				r = TAILQ_NEXT(r, entries);
4742 			} else
4743 				pf_step_into_anchor(anchor_stack, &asd,
4744 				    &ruleset, PF_RULESET_FILTER, &r, &a,
4745 				    &match);
4746 		}
4747 		if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
4748 		    &ruleset, PF_RULESET_FILTER, &r, &a, &match))
4749 			break;
4750 	}
4751 	r = *rm;
4752 	a = *am;
4753 	ruleset = *rsm;
4754 
4755 	REASON_SET(&reason, PFRES_MATCH);
4756 
4757 	/* apply actions for last matching pass/block rule */
4758 	pf_rule_to_actions(r, &pd->act);
4759 
4760 	if (r->log)
4761 		PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
4762 		    1);
4763 
4764 	if (r->action != PF_PASS)
4765 		return (PF_DROP);
4766 
4767 	if (tag > 0 && pf_tag_packet(m, pd, tag)) {
4768 		REASON_SET(&reason, PFRES_MEMORY);
4769 		return (PF_DROP);
4770 	}
4771 
4772 	return (PF_PASS);
4773 }
4774 
4775 static int
4776 pf_tcp_track_full(struct pf_kstate **state, struct pfi_kkif *kif,
4777     struct mbuf *m, int off, struct pf_pdesc *pd, u_short *reason,
4778     int *copyback)
4779 {
4780 	struct tcphdr		*th = &pd->hdr.tcp;
4781 	struct pf_state_peer	*src, *dst;
4782 	u_int16_t		 win = ntohs(th->th_win);
4783 	u_int32_t		 ack, end, seq, orig_seq;
4784 	u_int8_t		 sws, dws, psrc, pdst;
4785 	int			 ackskew;
4786 
4787 	if (pd->dir == (*state)->direction) {
4788 		src = &(*state)->src;
4789 		dst = &(*state)->dst;
4790 		psrc = PF_PEER_SRC;
4791 		pdst = PF_PEER_DST;
4792 	} else {
4793 		src = &(*state)->dst;
4794 		dst = &(*state)->src;
4795 		psrc = PF_PEER_DST;
4796 		pdst = PF_PEER_SRC;
4797 	}
4798 
4799 	if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
4800 		sws = src->wscale & PF_WSCALE_MASK;
4801 		dws = dst->wscale & PF_WSCALE_MASK;
4802 	} else
4803 		sws = dws = 0;
4804 
4805 	/*
4806 	 * Sequence tracking algorithm from Guido van Rooij's paper:
4807 	 *   http://www.madison-gurkha.com/publications/tcp_filtering/
4808 	 *	tcp_filtering.ps
4809 	 */
4810 
4811 	orig_seq = seq = ntohl(th->th_seq);
4812 	if (src->seqlo == 0) {
4813 		/* First packet from this end. Set its state */
4814 
4815 		if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
4816 		    src->scrub == NULL) {
4817 			if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
4818 				REASON_SET(reason, PFRES_MEMORY);
4819 				return (PF_DROP);
4820 			}
4821 		}
4822 
4823 		/* Deferred generation of sequence number modulator */
4824 		if (dst->seqdiff && !src->seqdiff) {
4825 			/* use random iss for the TCP server */
4826 			while ((src->seqdiff = arc4random() - seq) == 0)
4827 				;
4828 			ack = ntohl(th->th_ack) - dst->seqdiff;
4829 			pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4830 			    src->seqdiff), 0);
4831 			pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4832 			*copyback = 1;
4833 		} else {
4834 			ack = ntohl(th->th_ack);
4835 		}
4836 
4837 		end = seq + pd->p_len;
4838 		if (th->th_flags & TH_SYN) {
4839 			end++;
4840 			if (dst->wscale & PF_WSCALE_FLAG) {
4841 				src->wscale = pf_get_wscale(m, off, th->th_off,
4842 				    pd->af);
4843 				if (src->wscale & PF_WSCALE_FLAG) {
4844 					/* Remove scale factor from initial
4845 					 * window */
4846 					sws = src->wscale & PF_WSCALE_MASK;
4847 					win = ((u_int32_t)win + (1 << sws) - 1)
4848 					    >> sws;
4849 					dws = dst->wscale & PF_WSCALE_MASK;
4850 				} else {
4851 					/* fixup other window */
4852 					dst->max_win <<= dst->wscale &
4853 					    PF_WSCALE_MASK;
4854 					/* in case of a retrans SYN|ACK */
4855 					dst->wscale = 0;
4856 				}
4857 			}
4858 		}
4859 		if (th->th_flags & TH_FIN)
4860 			end++;
4861 
4862 		src->seqlo = seq;
4863 		if (src->state < TCPS_SYN_SENT)
4864 			pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
4865 
4866 		/*
4867 		 * May need to slide the window (seqhi may have been set by
4868 		 * the crappy stack check or if we picked up the connection
4869 		 * after establishment)
4870 		 */
4871 		if (src->seqhi == 1 ||
4872 		    SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4873 			src->seqhi = end + MAX(1, dst->max_win << dws);
4874 		if (win > src->max_win)
4875 			src->max_win = win;
4876 
4877 	} else {
4878 		ack = ntohl(th->th_ack) - dst->seqdiff;
4879 		if (src->seqdiff) {
4880 			/* Modulate sequence numbers */
4881 			pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4882 			    src->seqdiff), 0);
4883 			pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4884 			*copyback = 1;
4885 		}
4886 		end = seq + pd->p_len;
4887 		if (th->th_flags & TH_SYN)
4888 			end++;
4889 		if (th->th_flags & TH_FIN)
4890 			end++;
4891 	}
4892 
4893 	if ((th->th_flags & TH_ACK) == 0) {
4894 		/* Let it pass through the ack skew check */
4895 		ack = dst->seqlo;
4896 	} else if ((ack == 0 &&
4897 	    (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4898 	    /* broken tcp stacks do not set ack */
4899 	    (dst->state < TCPS_SYN_SENT)) {
4900 		/*
4901 		 * Many stacks (ours included) will set the ACK number in an
4902 		 * FIN|ACK if the SYN times out -- no sequence to ACK.
4903 		 */
4904 		ack = dst->seqlo;
4905 	}
4906 
4907 	if (seq == end) {
4908 		/* Ease sequencing restrictions on no data packets */
4909 		seq = src->seqlo;
4910 		end = seq;
4911 	}
4912 
4913 	ackskew = dst->seqlo - ack;
4914 
4915 	/*
4916 	 * Need to demodulate the sequence numbers in any TCP SACK options
4917 	 * (Selective ACK). We could optionally validate the SACK values
4918 	 * against the current ACK window, either forwards or backwards, but
4919 	 * I'm not confident that SACK has been implemented properly
4920 	 * everywhere. It wouldn't surprise me if several stacks accidentally
4921 	 * SACK too far backwards of previously ACKed data. There really aren't
4922 	 * any security implications of bad SACKing unless the target stack
4923 	 * doesn't validate the option length correctly. Someone trying to
4924 	 * spoof into a TCP connection won't bother blindly sending SACK
4925 	 * options anyway.
4926 	 */
4927 	if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4928 		if (pf_modulate_sack(m, off, pd, th, dst))
4929 			*copyback = 1;
4930 	}
4931 
4932 #define	MAXACKWINDOW (0xffff + 1500)	/* 1500 is an arbitrary fudge factor */
4933 	if (SEQ_GEQ(src->seqhi, end) &&
4934 	    /* Last octet inside other's window space */
4935 	    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4936 	    /* Retrans: not more than one window back */
4937 	    (ackskew >= -MAXACKWINDOW) &&
4938 	    /* Acking not more than one reassembled fragment backwards */
4939 	    (ackskew <= (MAXACKWINDOW << sws)) &&
4940 	    /* Acking not more than one window forward */
4941 	    ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4942 	    (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4943 	    (pd->flags & PFDESC_IP_REAS) == 0)) {
4944 	    /* Require an exact/+1 sequence match on resets when possible */
4945 
4946 		if (dst->scrub || src->scrub) {
4947 			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4948 			    *state, src, dst, copyback))
4949 				return (PF_DROP);
4950 		}
4951 
4952 		/* update max window */
4953 		if (src->max_win < win)
4954 			src->max_win = win;
4955 		/* synchronize sequencing */
4956 		if (SEQ_GT(end, src->seqlo))
4957 			src->seqlo = end;
4958 		/* slide the window of what the other end can send */
4959 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4960 			dst->seqhi = ack + MAX((win << sws), 1);
4961 
4962 		/* update states */
4963 		if (th->th_flags & TH_SYN)
4964 			if (src->state < TCPS_SYN_SENT)
4965 				pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
4966 		if (th->th_flags & TH_FIN)
4967 			if (src->state < TCPS_CLOSING)
4968 				pf_set_protostate(*state, psrc, TCPS_CLOSING);
4969 		if (th->th_flags & TH_ACK) {
4970 			if (dst->state == TCPS_SYN_SENT) {
4971 				pf_set_protostate(*state, pdst,
4972 				    TCPS_ESTABLISHED);
4973 				if (src->state == TCPS_ESTABLISHED &&
4974 				    (*state)->src_node != NULL &&
4975 				    pf_src_connlimit(state)) {
4976 					REASON_SET(reason, PFRES_SRCLIMIT);
4977 					return (PF_DROP);
4978 				}
4979 			} else if (dst->state == TCPS_CLOSING)
4980 				pf_set_protostate(*state, pdst,
4981 				    TCPS_FIN_WAIT_2);
4982 		}
4983 		if (th->th_flags & TH_RST)
4984 			pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
4985 
4986 		/* update expire time */
4987 		(*state)->expire = time_uptime;
4988 		if (src->state >= TCPS_FIN_WAIT_2 &&
4989 		    dst->state >= TCPS_FIN_WAIT_2)
4990 			(*state)->timeout = PFTM_TCP_CLOSED;
4991 		else if (src->state >= TCPS_CLOSING &&
4992 		    dst->state >= TCPS_CLOSING)
4993 			(*state)->timeout = PFTM_TCP_FIN_WAIT;
4994 		else if (src->state < TCPS_ESTABLISHED ||
4995 		    dst->state < TCPS_ESTABLISHED)
4996 			(*state)->timeout = PFTM_TCP_OPENING;
4997 		else if (src->state >= TCPS_CLOSING ||
4998 		    dst->state >= TCPS_CLOSING)
4999 			(*state)->timeout = PFTM_TCP_CLOSING;
5000 		else
5001 			(*state)->timeout = PFTM_TCP_ESTABLISHED;
5002 
5003 		/* Fall through to PASS packet */
5004 
5005 	} else if ((dst->state < TCPS_SYN_SENT ||
5006 		dst->state >= TCPS_FIN_WAIT_2 ||
5007 		src->state >= TCPS_FIN_WAIT_2) &&
5008 	    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
5009 	    /* Within a window forward of the originating packet */
5010 	    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
5011 	    /* Within a window backward of the originating packet */
5012 
5013 		/*
5014 		 * This currently handles three situations:
5015 		 *  1) Stupid stacks will shotgun SYNs before their peer
5016 		 *     replies.
5017 		 *  2) When PF catches an already established stream (the
5018 		 *     firewall rebooted, the state table was flushed, routes
5019 		 *     changed...)
5020 		 *  3) Packets get funky immediately after the connection
5021 		 *     closes (this should catch Solaris spurious ACK|FINs
5022 		 *     that web servers like to spew after a close)
5023 		 *
5024 		 * This must be a little more careful than the above code
5025 		 * since packet floods will also be caught here. We don't
5026 		 * update the TTL here to mitigate the damage of a packet
5027 		 * flood and so the same code can handle awkward establishment
5028 		 * and a loosened connection close.
5029 		 * In the establishment case, a correct peer response will
5030 		 * validate the connection, go through the normal state code
5031 		 * and keep updating the state TTL.
5032 		 */
5033 
5034 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
5035 			printf("pf: loose state match: ");
5036 			pf_print_state(*state);
5037 			pf_print_flags(th->th_flags);
5038 			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
5039 			    "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
5040 			    pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
5041 			    (unsigned long long)(*state)->packets[1],
5042 			    pd->dir == PF_IN ? "in" : "out",
5043 			    pd->dir == (*state)->direction ? "fwd" : "rev");
5044 		}
5045 
5046 		if (dst->scrub || src->scrub) {
5047 			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
5048 			    *state, src, dst, copyback))
5049 				return (PF_DROP);
5050 		}
5051 
5052 		/* update max window */
5053 		if (src->max_win < win)
5054 			src->max_win = win;
5055 		/* synchronize sequencing */
5056 		if (SEQ_GT(end, src->seqlo))
5057 			src->seqlo = end;
5058 		/* slide the window of what the other end can send */
5059 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
5060 			dst->seqhi = ack + MAX((win << sws), 1);
5061 
5062 		/*
5063 		 * Cannot set dst->seqhi here since this could be a shotgunned
5064 		 * SYN and not an already established connection.
5065 		 */
5066 
5067 		if (th->th_flags & TH_FIN)
5068 			if (src->state < TCPS_CLOSING)
5069 				pf_set_protostate(*state, psrc, TCPS_CLOSING);
5070 		if (th->th_flags & TH_RST)
5071 			pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
5072 
5073 		/* Fall through to PASS packet */
5074 
5075 	} else {
5076 		if ((*state)->dst.state == TCPS_SYN_SENT &&
5077 		    (*state)->src.state == TCPS_SYN_SENT) {
5078 			/* Send RST for state mismatches during handshake */
5079 			if (!(th->th_flags & TH_RST))
5080 				pf_send_tcp((*state)->rule.ptr, pd->af,
5081 				    pd->dst, pd->src, th->th_dport,
5082 				    th->th_sport, ntohl(th->th_ack), 0,
5083 				    TH_RST, 0, 0,
5084 				    (*state)->rule.ptr->return_ttl, 1, 0);
5085 			src->seqlo = 0;
5086 			src->seqhi = 1;
5087 			src->max_win = 1;
5088 		} else if (V_pf_status.debug >= PF_DEBUG_MISC) {
5089 			printf("pf: BAD state: ");
5090 			pf_print_state(*state);
5091 			pf_print_flags(th->th_flags);
5092 			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
5093 			    "pkts=%llu:%llu dir=%s,%s\n",
5094 			    seq, orig_seq, ack, pd->p_len, ackskew,
5095 			    (unsigned long long)(*state)->packets[0],
5096 			    (unsigned long long)(*state)->packets[1],
5097 			    pd->dir == PF_IN ? "in" : "out",
5098 			    pd->dir == (*state)->direction ? "fwd" : "rev");
5099 			printf("pf: State failure on: %c %c %c %c | %c %c\n",
5100 			    SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
5101 			    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
5102 			    ' ': '2',
5103 			    (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
5104 			    (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
5105 			    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
5106 			    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
5107 		}
5108 		REASON_SET(reason, PFRES_BADSTATE);
5109 		return (PF_DROP);
5110 	}
5111 
5112 	return (PF_PASS);
5113 }
5114 
5115 static int
5116 pf_tcp_track_sloppy(struct pf_kstate **state, struct pf_pdesc *pd, u_short *reason)
5117 {
5118 	struct tcphdr		*th = &pd->hdr.tcp;
5119 	struct pf_state_peer	*src, *dst;
5120 	u_int8_t		 psrc, pdst;
5121 
5122 	if (pd->dir == (*state)->direction) {
5123 		src = &(*state)->src;
5124 		dst = &(*state)->dst;
5125 		psrc = PF_PEER_SRC;
5126 		pdst = PF_PEER_DST;
5127 	} else {
5128 		src = &(*state)->dst;
5129 		dst = &(*state)->src;
5130 		psrc = PF_PEER_DST;
5131 		pdst = PF_PEER_SRC;
5132 	}
5133 
5134 	if (th->th_flags & TH_SYN)
5135 		if (src->state < TCPS_SYN_SENT)
5136 			pf_set_protostate(*state, psrc, TCPS_SYN_SENT);
5137 	if (th->th_flags & TH_FIN)
5138 		if (src->state < TCPS_CLOSING)
5139 			pf_set_protostate(*state, psrc, TCPS_CLOSING);
5140 	if (th->th_flags & TH_ACK) {
5141 		if (dst->state == TCPS_SYN_SENT) {
5142 			pf_set_protostate(*state, pdst, TCPS_ESTABLISHED);
5143 			if (src->state == TCPS_ESTABLISHED &&
5144 			    (*state)->src_node != NULL &&
5145 			    pf_src_connlimit(state)) {
5146 				REASON_SET(reason, PFRES_SRCLIMIT);
5147 				return (PF_DROP);
5148 			}
5149 		} else if (dst->state == TCPS_CLOSING) {
5150 			pf_set_protostate(*state, pdst, TCPS_FIN_WAIT_2);
5151 		} else if (src->state == TCPS_SYN_SENT &&
5152 		    dst->state < TCPS_SYN_SENT) {
5153 			/*
5154 			 * Handle a special sloppy case where we only see one
5155 			 * half of the connection. If there is a ACK after
5156 			 * the initial SYN without ever seeing a packet from
5157 			 * the destination, set the connection to established.
5158 			 */
5159 			pf_set_protostate(*state, PF_PEER_BOTH,
5160 			    TCPS_ESTABLISHED);
5161 			dst->state = src->state = TCPS_ESTABLISHED;
5162 			if ((*state)->src_node != NULL &&
5163 			    pf_src_connlimit(state)) {
5164 				REASON_SET(reason, PFRES_SRCLIMIT);
5165 				return (PF_DROP);
5166 			}
5167 		} else if (src->state == TCPS_CLOSING &&
5168 		    dst->state == TCPS_ESTABLISHED &&
5169 		    dst->seqlo == 0) {
5170 			/*
5171 			 * Handle the closing of half connections where we
5172 			 * don't see the full bidirectional FIN/ACK+ACK
5173 			 * handshake.
5174 			 */
5175 			pf_set_protostate(*state, pdst, TCPS_CLOSING);
5176 		}
5177 	}
5178 	if (th->th_flags & TH_RST)
5179 		pf_set_protostate(*state, PF_PEER_BOTH, TCPS_TIME_WAIT);
5180 
5181 	/* update expire time */
5182 	(*state)->expire = time_uptime;
5183 	if (src->state >= TCPS_FIN_WAIT_2 &&
5184 	    dst->state >= TCPS_FIN_WAIT_2)
5185 		(*state)->timeout = PFTM_TCP_CLOSED;
5186 	else if (src->state >= TCPS_CLOSING &&
5187 	    dst->state >= TCPS_CLOSING)
5188 		(*state)->timeout = PFTM_TCP_FIN_WAIT;
5189 	else if (src->state < TCPS_ESTABLISHED ||
5190 	    dst->state < TCPS_ESTABLISHED)
5191 		(*state)->timeout = PFTM_TCP_OPENING;
5192 	else if (src->state >= TCPS_CLOSING ||
5193 	    dst->state >= TCPS_CLOSING)
5194 		(*state)->timeout = PFTM_TCP_CLOSING;
5195 	else
5196 		(*state)->timeout = PFTM_TCP_ESTABLISHED;
5197 
5198 	return (PF_PASS);
5199 }
5200 
5201 static int
5202 pf_synproxy(struct pf_pdesc *pd, struct pf_kstate **state, u_short *reason)
5203 {
5204 	struct pf_state_key	*sk = (*state)->key[pd->didx];
5205 	struct tcphdr		*th = &pd->hdr.tcp;
5206 
5207 	if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
5208 		if (pd->dir != (*state)->direction) {
5209 			REASON_SET(reason, PFRES_SYNPROXY);
5210 			return (PF_SYNPROXY_DROP);
5211 		}
5212 		if (th->th_flags & TH_SYN) {
5213 			if (ntohl(th->th_seq) != (*state)->src.seqlo) {
5214 				REASON_SET(reason, PFRES_SYNPROXY);
5215 				return (PF_DROP);
5216 			}
5217 			pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
5218 			    pd->src, th->th_dport, th->th_sport,
5219 			    (*state)->src.seqhi, ntohl(th->th_seq) + 1,
5220 			    TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0);
5221 			REASON_SET(reason, PFRES_SYNPROXY);
5222 			return (PF_SYNPROXY_DROP);
5223 		} else if ((th->th_flags & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
5224 		    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
5225 		    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
5226 			REASON_SET(reason, PFRES_SYNPROXY);
5227 			return (PF_DROP);
5228 		} else if ((*state)->src_node != NULL &&
5229 		    pf_src_connlimit(state)) {
5230 			REASON_SET(reason, PFRES_SRCLIMIT);
5231 			return (PF_DROP);
5232 		} else
5233 			pf_set_protostate(*state, PF_PEER_SRC,
5234 			    PF_TCPS_PROXY_DST);
5235 	}
5236 	if ((*state)->src.state == PF_TCPS_PROXY_DST) {
5237 		if (pd->dir == (*state)->direction) {
5238 			if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
5239 			    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
5240 			    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
5241 				REASON_SET(reason, PFRES_SYNPROXY);
5242 				return (PF_DROP);
5243 			}
5244 			(*state)->src.max_win = MAX(ntohs(th->th_win), 1);
5245 			if ((*state)->dst.seqhi == 1)
5246 				(*state)->dst.seqhi = htonl(arc4random());
5247 			pf_send_tcp((*state)->rule.ptr, pd->af,
5248 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
5249 			    sk->port[pd->sidx], sk->port[pd->didx],
5250 			    (*state)->dst.seqhi, 0, TH_SYN, 0,
5251 			    (*state)->src.mss, 0, 0, (*state)->tag);
5252 			REASON_SET(reason, PFRES_SYNPROXY);
5253 			return (PF_SYNPROXY_DROP);
5254 		} else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
5255 		    (TH_SYN|TH_ACK)) ||
5256 		    (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
5257 			REASON_SET(reason, PFRES_SYNPROXY);
5258 			return (PF_DROP);
5259 		} else {
5260 			(*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
5261 			(*state)->dst.seqlo = ntohl(th->th_seq);
5262 			pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
5263 			    pd->src, th->th_dport, th->th_sport,
5264 			    ntohl(th->th_ack), ntohl(th->th_seq) + 1,
5265 			    TH_ACK, (*state)->src.max_win, 0, 0, 0,
5266 			    (*state)->tag);
5267 			pf_send_tcp((*state)->rule.ptr, pd->af,
5268 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
5269 			    sk->port[pd->sidx], sk->port[pd->didx],
5270 			    (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
5271 			    TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0);
5272 			(*state)->src.seqdiff = (*state)->dst.seqhi -
5273 			    (*state)->src.seqlo;
5274 			(*state)->dst.seqdiff = (*state)->src.seqhi -
5275 			    (*state)->dst.seqlo;
5276 			(*state)->src.seqhi = (*state)->src.seqlo +
5277 			    (*state)->dst.max_win;
5278 			(*state)->dst.seqhi = (*state)->dst.seqlo +
5279 			    (*state)->src.max_win;
5280 			(*state)->src.wscale = (*state)->dst.wscale = 0;
5281 			pf_set_protostate(*state, PF_PEER_BOTH,
5282 			    TCPS_ESTABLISHED);
5283 			REASON_SET(reason, PFRES_SYNPROXY);
5284 			return (PF_SYNPROXY_DROP);
5285 		}
5286 	}
5287 
5288 	return (PF_PASS);
5289 }
5290 
5291 static int
5292 pf_test_state_tcp(struct pf_kstate **state, int direction, struct pfi_kkif *kif,
5293     struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
5294     u_short *reason)
5295 {
5296 	struct pf_state_key_cmp	 key;
5297 	struct tcphdr		*th = &pd->hdr.tcp;
5298 	int			 copyback = 0;
5299 	int			 action;
5300 	struct pf_state_peer	*src, *dst;
5301 
5302 	bzero(&key, sizeof(key));
5303 	key.af = pd->af;
5304 	key.proto = IPPROTO_TCP;
5305 	if (direction == PF_IN)	{	/* wire side, straight */
5306 		PF_ACPY(&key.addr[0], pd->src, key.af);
5307 		PF_ACPY(&key.addr[1], pd->dst, key.af);
5308 		key.port[0] = th->th_sport;
5309 		key.port[1] = th->th_dport;
5310 	} else {			/* stack side, reverse */
5311 		PF_ACPY(&key.addr[1], pd->src, key.af);
5312 		PF_ACPY(&key.addr[0], pd->dst, key.af);
5313 		key.port[1] = th->th_sport;
5314 		key.port[0] = th->th_dport;
5315 	}
5316 
5317 	STATE_LOOKUP(kif, &key, direction, *state, pd);
5318 
5319 	if (direction == (*state)->direction) {
5320 		src = &(*state)->src;
5321 		dst = &(*state)->dst;
5322 	} else {
5323 		src = &(*state)->dst;
5324 		dst = &(*state)->src;
5325 	}
5326 
5327 	if ((action = pf_synproxy(pd, state, reason)) != PF_PASS)
5328 		return (action);
5329 
5330 	if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
5331 	    dst->state >= TCPS_FIN_WAIT_2 &&
5332 	    src->state >= TCPS_FIN_WAIT_2) {
5333 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
5334 			printf("pf: state reuse ");
5335 			pf_print_state(*state);
5336 			pf_print_flags(th->th_flags);
5337 			printf("\n");
5338 		}
5339 		/* XXX make sure it's the same direction ?? */
5340 		pf_set_protostate(*state, PF_PEER_BOTH, TCPS_CLOSED);
5341 		pf_unlink_state(*state);
5342 		*state = NULL;
5343 		return (PF_DROP);
5344 	}
5345 
5346 	if ((*state)->state_flags & PFSTATE_SLOPPY) {
5347 		if (pf_tcp_track_sloppy(state, pd, reason) == PF_DROP)
5348 			return (PF_DROP);
5349 	} else {
5350 		if (pf_tcp_track_full(state, kif, m, off, pd, reason,
5351 		    &copyback) == PF_DROP)
5352 			return (PF_DROP);
5353 	}
5354 
5355 	/* translate source/destination address, if necessary */
5356 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5357 		struct pf_state_key *nk = (*state)->key[pd->didx];
5358 
5359 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
5360 		    nk->port[pd->sidx] != th->th_sport)
5361 			pf_change_ap(m, pd->src, &th->th_sport,
5362 			    pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
5363 			    nk->port[pd->sidx], 0, pd->af);
5364 
5365 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
5366 		    nk->port[pd->didx] != th->th_dport)
5367 			pf_change_ap(m, pd->dst, &th->th_dport,
5368 			    pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
5369 			    nk->port[pd->didx], 0, pd->af);
5370 		copyback = 1;
5371 	}
5372 
5373 	/* Copyback sequence modulation or stateful scrub changes if needed */
5374 	if (copyback)
5375 		m_copyback(m, off, sizeof(*th), (caddr_t)th);
5376 
5377 	return (PF_PASS);
5378 }
5379 
5380 static int
5381 pf_test_state_udp(struct pf_kstate **state, int direction, struct pfi_kkif *kif,
5382     struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
5383 {
5384 	struct pf_state_peer	*src, *dst;
5385 	struct pf_state_key_cmp	 key;
5386 	struct udphdr		*uh = &pd->hdr.udp;
5387 	uint8_t			 psrc, pdst;
5388 
5389 	bzero(&key, sizeof(key));
5390 	key.af = pd->af;
5391 	key.proto = IPPROTO_UDP;
5392 	if (direction == PF_IN)	{	/* wire side, straight */
5393 		PF_ACPY(&key.addr[0], pd->src, key.af);
5394 		PF_ACPY(&key.addr[1], pd->dst, key.af);
5395 		key.port[0] = uh->uh_sport;
5396 		key.port[1] = uh->uh_dport;
5397 	} else {			/* stack side, reverse */
5398 		PF_ACPY(&key.addr[1], pd->src, key.af);
5399 		PF_ACPY(&key.addr[0], pd->dst, key.af);
5400 		key.port[1] = uh->uh_sport;
5401 		key.port[0] = uh->uh_dport;
5402 	}
5403 
5404 	STATE_LOOKUP(kif, &key, direction, *state, pd);
5405 
5406 	if (direction == (*state)->direction) {
5407 		src = &(*state)->src;
5408 		dst = &(*state)->dst;
5409 		psrc = PF_PEER_SRC;
5410 		pdst = PF_PEER_DST;
5411 	} else {
5412 		src = &(*state)->dst;
5413 		dst = &(*state)->src;
5414 		psrc = PF_PEER_DST;
5415 		pdst = PF_PEER_SRC;
5416 	}
5417 
5418 	/* update states */
5419 	if (src->state < PFUDPS_SINGLE)
5420 		pf_set_protostate(*state, psrc, PFUDPS_SINGLE);
5421 	if (dst->state == PFUDPS_SINGLE)
5422 		pf_set_protostate(*state, pdst, PFUDPS_MULTIPLE);
5423 
5424 	/* update expire time */
5425 	(*state)->expire = time_uptime;
5426 	if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
5427 		(*state)->timeout = PFTM_UDP_MULTIPLE;
5428 	else
5429 		(*state)->timeout = PFTM_UDP_SINGLE;
5430 
5431 	/* translate source/destination address, if necessary */
5432 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5433 		struct pf_state_key *nk = (*state)->key[pd->didx];
5434 
5435 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
5436 		    nk->port[pd->sidx] != uh->uh_sport)
5437 			pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
5438 			    &uh->uh_sum, &nk->addr[pd->sidx],
5439 			    nk->port[pd->sidx], 1, pd->af);
5440 
5441 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
5442 		    nk->port[pd->didx] != uh->uh_dport)
5443 			pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
5444 			    &uh->uh_sum, &nk->addr[pd->didx],
5445 			    nk->port[pd->didx], 1, pd->af);
5446 		m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
5447 	}
5448 
5449 	return (PF_PASS);
5450 }
5451 
5452 static int
5453 pf_test_state_icmp(struct pf_kstate **state, int direction, struct pfi_kkif *kif,
5454     struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
5455 {
5456 	struct pf_addr  *saddr = pd->src, *daddr = pd->dst;
5457 	u_int16_t	 icmpid = 0, *icmpsum;
5458 	u_int8_t	 icmptype, icmpcode;
5459 	int		 state_icmp = 0;
5460 	struct pf_state_key_cmp key;
5461 
5462 	bzero(&key, sizeof(key));
5463 	switch (pd->proto) {
5464 #ifdef INET
5465 	case IPPROTO_ICMP:
5466 		icmptype = pd->hdr.icmp.icmp_type;
5467 		icmpcode = pd->hdr.icmp.icmp_code;
5468 		icmpid = pd->hdr.icmp.icmp_id;
5469 		icmpsum = &pd->hdr.icmp.icmp_cksum;
5470 
5471 		if (icmptype == ICMP_UNREACH ||
5472 		    icmptype == ICMP_SOURCEQUENCH ||
5473 		    icmptype == ICMP_REDIRECT ||
5474 		    icmptype == ICMP_TIMXCEED ||
5475 		    icmptype == ICMP_PARAMPROB)
5476 			state_icmp++;
5477 		break;
5478 #endif /* INET */
5479 #ifdef INET6
5480 	case IPPROTO_ICMPV6:
5481 		icmptype = pd->hdr.icmp6.icmp6_type;
5482 		icmpcode = pd->hdr.icmp6.icmp6_code;
5483 		icmpid = pd->hdr.icmp6.icmp6_id;
5484 		icmpsum = &pd->hdr.icmp6.icmp6_cksum;
5485 
5486 		if (icmptype == ICMP6_DST_UNREACH ||
5487 		    icmptype == ICMP6_PACKET_TOO_BIG ||
5488 		    icmptype == ICMP6_TIME_EXCEEDED ||
5489 		    icmptype == ICMP6_PARAM_PROB)
5490 			state_icmp++;
5491 		break;
5492 #endif /* INET6 */
5493 	}
5494 
5495 	if (!state_icmp) {
5496 		/*
5497 		 * ICMP query/reply message not related to a TCP/UDP packet.
5498 		 * Search for an ICMP state.
5499 		 */
5500 		key.af = pd->af;
5501 		key.proto = pd->proto;
5502 		key.port[0] = key.port[1] = icmpid;
5503 		if (direction == PF_IN)	{	/* wire side, straight */
5504 			PF_ACPY(&key.addr[0], pd->src, key.af);
5505 			PF_ACPY(&key.addr[1], pd->dst, key.af);
5506 		} else {			/* stack side, reverse */
5507 			PF_ACPY(&key.addr[1], pd->src, key.af);
5508 			PF_ACPY(&key.addr[0], pd->dst, key.af);
5509 		}
5510 
5511 		STATE_LOOKUP(kif, &key, direction, *state, pd);
5512 
5513 		(*state)->expire = time_uptime;
5514 		(*state)->timeout = PFTM_ICMP_ERROR_REPLY;
5515 
5516 		/* translate source/destination address, if necessary */
5517 		if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5518 			struct pf_state_key *nk = (*state)->key[pd->didx];
5519 
5520 			switch (pd->af) {
5521 #ifdef INET
5522 			case AF_INET:
5523 				if (PF_ANEQ(pd->src,
5524 				    &nk->addr[pd->sidx], AF_INET))
5525 					pf_change_a(&saddr->v4.s_addr,
5526 					    pd->ip_sum,
5527 					    nk->addr[pd->sidx].v4.s_addr, 0);
5528 
5529 				if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
5530 				    AF_INET))
5531 					pf_change_a(&daddr->v4.s_addr,
5532 					    pd->ip_sum,
5533 					    nk->addr[pd->didx].v4.s_addr, 0);
5534 
5535 				if (nk->port[0] !=
5536 				    pd->hdr.icmp.icmp_id) {
5537 					pd->hdr.icmp.icmp_cksum =
5538 					    pf_cksum_fixup(
5539 					    pd->hdr.icmp.icmp_cksum, icmpid,
5540 					    nk->port[pd->sidx], 0);
5541 					pd->hdr.icmp.icmp_id =
5542 					    nk->port[pd->sidx];
5543 				}
5544 
5545 				m_copyback(m, off, ICMP_MINLEN,
5546 				    (caddr_t )&pd->hdr.icmp);
5547 				break;
5548 #endif /* INET */
5549 #ifdef INET6
5550 			case AF_INET6:
5551 				if (PF_ANEQ(pd->src,
5552 				    &nk->addr[pd->sidx], AF_INET6))
5553 					pf_change_a6(saddr,
5554 					    &pd->hdr.icmp6.icmp6_cksum,
5555 					    &nk->addr[pd->sidx], 0);
5556 
5557 				if (PF_ANEQ(pd->dst,
5558 				    &nk->addr[pd->didx], AF_INET6))
5559 					pf_change_a6(daddr,
5560 					    &pd->hdr.icmp6.icmp6_cksum,
5561 					    &nk->addr[pd->didx], 0);
5562 
5563 				m_copyback(m, off, sizeof(struct icmp6_hdr),
5564 				    (caddr_t )&pd->hdr.icmp6);
5565 				break;
5566 #endif /* INET6 */
5567 			}
5568 		}
5569 		return (PF_PASS);
5570 
5571 	} else {
5572 		/*
5573 		 * ICMP error message in response to a TCP/UDP packet.
5574 		 * Extract the inner TCP/UDP header and search for that state.
5575 		 */
5576 
5577 		struct pf_pdesc	pd2;
5578 		bzero(&pd2, sizeof pd2);
5579 #ifdef INET
5580 		struct ip	h2;
5581 #endif /* INET */
5582 #ifdef INET6
5583 		struct ip6_hdr	h2_6;
5584 		int		terminal = 0;
5585 #endif /* INET6 */
5586 		int		ipoff2 = 0;
5587 		int		off2 = 0;
5588 
5589 		pd2.af = pd->af;
5590 		/* Payload packet is from the opposite direction. */
5591 		pd2.sidx = (direction == PF_IN) ? 1 : 0;
5592 		pd2.didx = (direction == PF_IN) ? 0 : 1;
5593 		switch (pd->af) {
5594 #ifdef INET
5595 		case AF_INET:
5596 			/* offset of h2 in mbuf chain */
5597 			ipoff2 = off + ICMP_MINLEN;
5598 
5599 			if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
5600 			    NULL, reason, pd2.af)) {
5601 				DPFPRINTF(PF_DEBUG_MISC,
5602 				    ("pf: ICMP error message too short "
5603 				    "(ip)\n"));
5604 				return (PF_DROP);
5605 			}
5606 			/*
5607 			 * ICMP error messages don't refer to non-first
5608 			 * fragments
5609 			 */
5610 			if (h2.ip_off & htons(IP_OFFMASK)) {
5611 				REASON_SET(reason, PFRES_FRAG);
5612 				return (PF_DROP);
5613 			}
5614 
5615 			/* offset of protocol header that follows h2 */
5616 			off2 = ipoff2 + (h2.ip_hl << 2);
5617 
5618 			pd2.proto = h2.ip_p;
5619 			pd2.src = (struct pf_addr *)&h2.ip_src;
5620 			pd2.dst = (struct pf_addr *)&h2.ip_dst;
5621 			pd2.ip_sum = &h2.ip_sum;
5622 			break;
5623 #endif /* INET */
5624 #ifdef INET6
5625 		case AF_INET6:
5626 			ipoff2 = off + sizeof(struct icmp6_hdr);
5627 
5628 			if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
5629 			    NULL, reason, pd2.af)) {
5630 				DPFPRINTF(PF_DEBUG_MISC,
5631 				    ("pf: ICMP error message too short "
5632 				    "(ip6)\n"));
5633 				return (PF_DROP);
5634 			}
5635 			pd2.proto = h2_6.ip6_nxt;
5636 			pd2.src = (struct pf_addr *)&h2_6.ip6_src;
5637 			pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
5638 			pd2.ip_sum = NULL;
5639 			off2 = ipoff2 + sizeof(h2_6);
5640 			do {
5641 				switch (pd2.proto) {
5642 				case IPPROTO_FRAGMENT:
5643 					/*
5644 					 * ICMPv6 error messages for
5645 					 * non-first fragments
5646 					 */
5647 					REASON_SET(reason, PFRES_FRAG);
5648 					return (PF_DROP);
5649 				case IPPROTO_AH:
5650 				case IPPROTO_HOPOPTS:
5651 				case IPPROTO_ROUTING:
5652 				case IPPROTO_DSTOPTS: {
5653 					/* get next header and header length */
5654 					struct ip6_ext opt6;
5655 
5656 					if (!pf_pull_hdr(m, off2, &opt6,
5657 					    sizeof(opt6), NULL, reason,
5658 					    pd2.af)) {
5659 						DPFPRINTF(PF_DEBUG_MISC,
5660 						    ("pf: ICMPv6 short opt\n"));
5661 						return (PF_DROP);
5662 					}
5663 					if (pd2.proto == IPPROTO_AH)
5664 						off2 += (opt6.ip6e_len + 2) * 4;
5665 					else
5666 						off2 += (opt6.ip6e_len + 1) * 8;
5667 					pd2.proto = opt6.ip6e_nxt;
5668 					/* goto the next header */
5669 					break;
5670 				}
5671 				default:
5672 					terminal++;
5673 					break;
5674 				}
5675 			} while (!terminal);
5676 			break;
5677 #endif /* INET6 */
5678 		}
5679 
5680 		if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
5681 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
5682 				printf("pf: BAD ICMP %d:%d outer dst: ",
5683 				    icmptype, icmpcode);
5684 				pf_print_host(pd->src, 0, pd->af);
5685 				printf(" -> ");
5686 				pf_print_host(pd->dst, 0, pd->af);
5687 				printf(" inner src: ");
5688 				pf_print_host(pd2.src, 0, pd2.af);
5689 				printf(" -> ");
5690 				pf_print_host(pd2.dst, 0, pd2.af);
5691 				printf("\n");
5692 			}
5693 			REASON_SET(reason, PFRES_BADSTATE);
5694 			return (PF_DROP);
5695 		}
5696 
5697 		switch (pd2.proto) {
5698 		case IPPROTO_TCP: {
5699 			struct tcphdr		 th;
5700 			u_int32_t		 seq;
5701 			struct pf_state_peer	*src, *dst;
5702 			u_int8_t		 dws;
5703 			int			 copyback = 0;
5704 
5705 			/*
5706 			 * Only the first 8 bytes of the TCP header can be
5707 			 * expected. Don't access any TCP header fields after
5708 			 * th_seq, an ackskew test is not possible.
5709 			 */
5710 			if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
5711 			    pd2.af)) {
5712 				DPFPRINTF(PF_DEBUG_MISC,
5713 				    ("pf: ICMP error message too short "
5714 				    "(tcp)\n"));
5715 				return (PF_DROP);
5716 			}
5717 
5718 			key.af = pd2.af;
5719 			key.proto = IPPROTO_TCP;
5720 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5721 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5722 			key.port[pd2.sidx] = th.th_sport;
5723 			key.port[pd2.didx] = th.th_dport;
5724 
5725 			STATE_LOOKUP(kif, &key, direction, *state, pd);
5726 
5727 			if (direction == (*state)->direction) {
5728 				src = &(*state)->dst;
5729 				dst = &(*state)->src;
5730 			} else {
5731 				src = &(*state)->src;
5732 				dst = &(*state)->dst;
5733 			}
5734 
5735 			if (src->wscale && dst->wscale)
5736 				dws = dst->wscale & PF_WSCALE_MASK;
5737 			else
5738 				dws = 0;
5739 
5740 			/* Demodulate sequence number */
5741 			seq = ntohl(th.th_seq) - src->seqdiff;
5742 			if (src->seqdiff) {
5743 				pf_change_a(&th.th_seq, icmpsum,
5744 				    htonl(seq), 0);
5745 				copyback = 1;
5746 			}
5747 
5748 			if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
5749 			    (!SEQ_GEQ(src->seqhi, seq) ||
5750 			    !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
5751 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
5752 					printf("pf: BAD ICMP %d:%d ",
5753 					    icmptype, icmpcode);
5754 					pf_print_host(pd->src, 0, pd->af);
5755 					printf(" -> ");
5756 					pf_print_host(pd->dst, 0, pd->af);
5757 					printf(" state: ");
5758 					pf_print_state(*state);
5759 					printf(" seq=%u\n", seq);
5760 				}
5761 				REASON_SET(reason, PFRES_BADSTATE);
5762 				return (PF_DROP);
5763 			} else {
5764 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
5765 					printf("pf: OK 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 			}
5775 
5776 			/* translate source/destination address, if necessary */
5777 			if ((*state)->key[PF_SK_WIRE] !=
5778 			    (*state)->key[PF_SK_STACK]) {
5779 				struct pf_state_key *nk =
5780 				    (*state)->key[pd->didx];
5781 
5782 				if (PF_ANEQ(pd2.src,
5783 				    &nk->addr[pd2.sidx], pd2.af) ||
5784 				    nk->port[pd2.sidx] != th.th_sport)
5785 					pf_change_icmp(pd2.src, &th.th_sport,
5786 					    daddr, &nk->addr[pd2.sidx],
5787 					    nk->port[pd2.sidx], NULL,
5788 					    pd2.ip_sum, icmpsum,
5789 					    pd->ip_sum, 0, pd2.af);
5790 
5791 				if (PF_ANEQ(pd2.dst,
5792 				    &nk->addr[pd2.didx], pd2.af) ||
5793 				    nk->port[pd2.didx] != th.th_dport)
5794 					pf_change_icmp(pd2.dst, &th.th_dport,
5795 					    saddr, &nk->addr[pd2.didx],
5796 					    nk->port[pd2.didx], NULL,
5797 					    pd2.ip_sum, icmpsum,
5798 					    pd->ip_sum, 0, pd2.af);
5799 				copyback = 1;
5800 			}
5801 
5802 			if (copyback) {
5803 				switch (pd2.af) {
5804 #ifdef INET
5805 				case AF_INET:
5806 					m_copyback(m, off, ICMP_MINLEN,
5807 					    (caddr_t )&pd->hdr.icmp);
5808 					m_copyback(m, ipoff2, sizeof(h2),
5809 					    (caddr_t )&h2);
5810 					break;
5811 #endif /* INET */
5812 #ifdef INET6
5813 				case AF_INET6:
5814 					m_copyback(m, off,
5815 					    sizeof(struct icmp6_hdr),
5816 					    (caddr_t )&pd->hdr.icmp6);
5817 					m_copyback(m, ipoff2, sizeof(h2_6),
5818 					    (caddr_t )&h2_6);
5819 					break;
5820 #endif /* INET6 */
5821 				}
5822 				m_copyback(m, off2, 8, (caddr_t)&th);
5823 			}
5824 
5825 			return (PF_PASS);
5826 			break;
5827 		}
5828 		case IPPROTO_UDP: {
5829 			struct udphdr		uh;
5830 
5831 			if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
5832 			    NULL, reason, pd2.af)) {
5833 				DPFPRINTF(PF_DEBUG_MISC,
5834 				    ("pf: ICMP error message too short "
5835 				    "(udp)\n"));
5836 				return (PF_DROP);
5837 			}
5838 
5839 			key.af = pd2.af;
5840 			key.proto = IPPROTO_UDP;
5841 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5842 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5843 			key.port[pd2.sidx] = uh.uh_sport;
5844 			key.port[pd2.didx] = uh.uh_dport;
5845 
5846 			STATE_LOOKUP(kif, &key, direction, *state, pd);
5847 
5848 			/* translate source/destination address, if necessary */
5849 			if ((*state)->key[PF_SK_WIRE] !=
5850 			    (*state)->key[PF_SK_STACK]) {
5851 				struct pf_state_key *nk =
5852 				    (*state)->key[pd->didx];
5853 
5854 				if (PF_ANEQ(pd2.src,
5855 				    &nk->addr[pd2.sidx], pd2.af) ||
5856 				    nk->port[pd2.sidx] != uh.uh_sport)
5857 					pf_change_icmp(pd2.src, &uh.uh_sport,
5858 					    daddr, &nk->addr[pd2.sidx],
5859 					    nk->port[pd2.sidx], &uh.uh_sum,
5860 					    pd2.ip_sum, icmpsum,
5861 					    pd->ip_sum, 1, pd2.af);
5862 
5863 				if (PF_ANEQ(pd2.dst,
5864 				    &nk->addr[pd2.didx], pd2.af) ||
5865 				    nk->port[pd2.didx] != uh.uh_dport)
5866 					pf_change_icmp(pd2.dst, &uh.uh_dport,
5867 					    saddr, &nk->addr[pd2.didx],
5868 					    nk->port[pd2.didx], &uh.uh_sum,
5869 					    pd2.ip_sum, icmpsum,
5870 					    pd->ip_sum, 1, pd2.af);
5871 
5872 				switch (pd2.af) {
5873 #ifdef INET
5874 				case AF_INET:
5875 					m_copyback(m, off, ICMP_MINLEN,
5876 					    (caddr_t )&pd->hdr.icmp);
5877 					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5878 					break;
5879 #endif /* INET */
5880 #ifdef INET6
5881 				case AF_INET6:
5882 					m_copyback(m, off,
5883 					    sizeof(struct icmp6_hdr),
5884 					    (caddr_t )&pd->hdr.icmp6);
5885 					m_copyback(m, ipoff2, sizeof(h2_6),
5886 					    (caddr_t )&h2_6);
5887 					break;
5888 #endif /* INET6 */
5889 				}
5890 				m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5891 			}
5892 			return (PF_PASS);
5893 			break;
5894 		}
5895 #ifdef INET
5896 		case IPPROTO_ICMP: {
5897 			struct icmp		iih;
5898 
5899 			if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5900 			    NULL, reason, pd2.af)) {
5901 				DPFPRINTF(PF_DEBUG_MISC,
5902 				    ("pf: ICMP error message too short i"
5903 				    "(icmp)\n"));
5904 				return (PF_DROP);
5905 			}
5906 
5907 			key.af = pd2.af;
5908 			key.proto = IPPROTO_ICMP;
5909 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5910 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5911 			key.port[0] = key.port[1] = iih.icmp_id;
5912 
5913 			STATE_LOOKUP(kif, &key, direction, *state, pd);
5914 
5915 			/* translate source/destination address, if necessary */
5916 			if ((*state)->key[PF_SK_WIRE] !=
5917 			    (*state)->key[PF_SK_STACK]) {
5918 				struct pf_state_key *nk =
5919 				    (*state)->key[pd->didx];
5920 
5921 				if (PF_ANEQ(pd2.src,
5922 				    &nk->addr[pd2.sidx], pd2.af) ||
5923 				    nk->port[pd2.sidx] != iih.icmp_id)
5924 					pf_change_icmp(pd2.src, &iih.icmp_id,
5925 					    daddr, &nk->addr[pd2.sidx],
5926 					    nk->port[pd2.sidx], NULL,
5927 					    pd2.ip_sum, icmpsum,
5928 					    pd->ip_sum, 0, AF_INET);
5929 
5930 				if (PF_ANEQ(pd2.dst,
5931 				    &nk->addr[pd2.didx], pd2.af) ||
5932 				    nk->port[pd2.didx] != iih.icmp_id)
5933 					pf_change_icmp(pd2.dst, &iih.icmp_id,
5934 					    saddr, &nk->addr[pd2.didx],
5935 					    nk->port[pd2.didx], NULL,
5936 					    pd2.ip_sum, icmpsum,
5937 					    pd->ip_sum, 0, AF_INET);
5938 
5939 				m_copyback(m, off, ICMP_MINLEN, (caddr_t)&pd->hdr.icmp);
5940 				m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5941 				m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5942 			}
5943 			return (PF_PASS);
5944 			break;
5945 		}
5946 #endif /* INET */
5947 #ifdef INET6
5948 		case IPPROTO_ICMPV6: {
5949 			struct icmp6_hdr	iih;
5950 
5951 			if (!pf_pull_hdr(m, off2, &iih,
5952 			    sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5953 				DPFPRINTF(PF_DEBUG_MISC,
5954 				    ("pf: ICMP error message too short "
5955 				    "(icmp6)\n"));
5956 				return (PF_DROP);
5957 			}
5958 
5959 			key.af = pd2.af;
5960 			key.proto = IPPROTO_ICMPV6;
5961 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5962 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5963 			key.port[0] = key.port[1] = iih.icmp6_id;
5964 
5965 			STATE_LOOKUP(kif, &key, direction, *state, pd);
5966 
5967 			/* translate source/destination address, if necessary */
5968 			if ((*state)->key[PF_SK_WIRE] !=
5969 			    (*state)->key[PF_SK_STACK]) {
5970 				struct pf_state_key *nk =
5971 				    (*state)->key[pd->didx];
5972 
5973 				if (PF_ANEQ(pd2.src,
5974 				    &nk->addr[pd2.sidx], pd2.af) ||
5975 				    nk->port[pd2.sidx] != iih.icmp6_id)
5976 					pf_change_icmp(pd2.src, &iih.icmp6_id,
5977 					    daddr, &nk->addr[pd2.sidx],
5978 					    nk->port[pd2.sidx], NULL,
5979 					    pd2.ip_sum, icmpsum,
5980 					    pd->ip_sum, 0, AF_INET6);
5981 
5982 				if (PF_ANEQ(pd2.dst,
5983 				    &nk->addr[pd2.didx], pd2.af) ||
5984 				    nk->port[pd2.didx] != iih.icmp6_id)
5985 					pf_change_icmp(pd2.dst, &iih.icmp6_id,
5986 					    saddr, &nk->addr[pd2.didx],
5987 					    nk->port[pd2.didx], NULL,
5988 					    pd2.ip_sum, icmpsum,
5989 					    pd->ip_sum, 0, AF_INET6);
5990 
5991 				m_copyback(m, off, sizeof(struct icmp6_hdr),
5992 				    (caddr_t)&pd->hdr.icmp6);
5993 				m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5994 				m_copyback(m, off2, sizeof(struct icmp6_hdr),
5995 				    (caddr_t)&iih);
5996 			}
5997 			return (PF_PASS);
5998 			break;
5999 		}
6000 #endif /* INET6 */
6001 		default: {
6002 			key.af = pd2.af;
6003 			key.proto = pd2.proto;
6004 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
6005 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
6006 			key.port[0] = key.port[1] = 0;
6007 
6008 			STATE_LOOKUP(kif, &key, direction, *state, pd);
6009 
6010 			/* translate source/destination address, if necessary */
6011 			if ((*state)->key[PF_SK_WIRE] !=
6012 			    (*state)->key[PF_SK_STACK]) {
6013 				struct pf_state_key *nk =
6014 				    (*state)->key[pd->didx];
6015 
6016 				if (PF_ANEQ(pd2.src,
6017 				    &nk->addr[pd2.sidx], pd2.af))
6018 					pf_change_icmp(pd2.src, NULL, daddr,
6019 					    &nk->addr[pd2.sidx], 0, NULL,
6020 					    pd2.ip_sum, icmpsum,
6021 					    pd->ip_sum, 0, pd2.af);
6022 
6023 				if (PF_ANEQ(pd2.dst,
6024 				    &nk->addr[pd2.didx], pd2.af))
6025 					pf_change_icmp(pd2.dst, NULL, saddr,
6026 					    &nk->addr[pd2.didx], 0, NULL,
6027 					    pd2.ip_sum, icmpsum,
6028 					    pd->ip_sum, 0, pd2.af);
6029 
6030 				switch (pd2.af) {
6031 #ifdef INET
6032 				case AF_INET:
6033 					m_copyback(m, off, ICMP_MINLEN,
6034 					    (caddr_t)&pd->hdr.icmp);
6035 					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
6036 					break;
6037 #endif /* INET */
6038 #ifdef INET6
6039 				case AF_INET6:
6040 					m_copyback(m, off,
6041 					    sizeof(struct icmp6_hdr),
6042 					    (caddr_t )&pd->hdr.icmp6);
6043 					m_copyback(m, ipoff2, sizeof(h2_6),
6044 					    (caddr_t )&h2_6);
6045 					break;
6046 #endif /* INET6 */
6047 				}
6048 			}
6049 			return (PF_PASS);
6050 			break;
6051 		}
6052 		}
6053 	}
6054 }
6055 
6056 static int
6057 pf_test_state_other(struct pf_kstate **state, int direction, struct pfi_kkif *kif,
6058     struct mbuf *m, struct pf_pdesc *pd)
6059 {
6060 	struct pf_state_peer	*src, *dst;
6061 	struct pf_state_key_cmp	 key;
6062 	uint8_t			 psrc, pdst;
6063 
6064 	bzero(&key, sizeof(key));
6065 	key.af = pd->af;
6066 	key.proto = pd->proto;
6067 	if (direction == PF_IN)	{
6068 		PF_ACPY(&key.addr[0], pd->src, key.af);
6069 		PF_ACPY(&key.addr[1], pd->dst, key.af);
6070 		key.port[0] = key.port[1] = 0;
6071 	} else {
6072 		PF_ACPY(&key.addr[1], pd->src, key.af);
6073 		PF_ACPY(&key.addr[0], pd->dst, key.af);
6074 		key.port[1] = key.port[0] = 0;
6075 	}
6076 
6077 	STATE_LOOKUP(kif, &key, direction, *state, pd);
6078 
6079 	if (direction == (*state)->direction) {
6080 		src = &(*state)->src;
6081 		dst = &(*state)->dst;
6082 		psrc = PF_PEER_SRC;
6083 		pdst = PF_PEER_DST;
6084 	} else {
6085 		src = &(*state)->dst;
6086 		dst = &(*state)->src;
6087 		psrc = PF_PEER_DST;
6088 		pdst = PF_PEER_SRC;
6089 	}
6090 
6091 	/* update states */
6092 	if (src->state < PFOTHERS_SINGLE)
6093 		pf_set_protostate(*state, psrc, PFOTHERS_SINGLE);
6094 	if (dst->state == PFOTHERS_SINGLE)
6095 		pf_set_protostate(*state, pdst, PFOTHERS_MULTIPLE);
6096 
6097 	/* update expire time */
6098 	(*state)->expire = time_uptime;
6099 	if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
6100 		(*state)->timeout = PFTM_OTHER_MULTIPLE;
6101 	else
6102 		(*state)->timeout = PFTM_OTHER_SINGLE;
6103 
6104 	/* translate source/destination address, if necessary */
6105 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
6106 		struct pf_state_key *nk = (*state)->key[pd->didx];
6107 
6108 		KASSERT(nk, ("%s: nk is null", __func__));
6109 		KASSERT(pd, ("%s: pd is null", __func__));
6110 		KASSERT(pd->src, ("%s: pd->src is null", __func__));
6111 		KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
6112 		switch (pd->af) {
6113 #ifdef INET
6114 		case AF_INET:
6115 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
6116 				pf_change_a(&pd->src->v4.s_addr,
6117 				    pd->ip_sum,
6118 				    nk->addr[pd->sidx].v4.s_addr,
6119 				    0);
6120 
6121 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
6122 				pf_change_a(&pd->dst->v4.s_addr,
6123 				    pd->ip_sum,
6124 				    nk->addr[pd->didx].v4.s_addr,
6125 				    0);
6126 
6127 			break;
6128 #endif /* INET */
6129 #ifdef INET6
6130 		case AF_INET6:
6131 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
6132 				PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
6133 
6134 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
6135 				PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
6136 #endif /* INET6 */
6137 		}
6138 	}
6139 	return (PF_PASS);
6140 }
6141 
6142 /*
6143  * ipoff and off are measured from the start of the mbuf chain.
6144  * h must be at "ipoff" on the mbuf chain.
6145  */
6146 void *
6147 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
6148     u_short *actionp, u_short *reasonp, sa_family_t af)
6149 {
6150 	switch (af) {
6151 #ifdef INET
6152 	case AF_INET: {
6153 		struct ip	*h = mtod(m, struct ip *);
6154 		u_int16_t	 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
6155 
6156 		if (fragoff) {
6157 			if (fragoff >= len)
6158 				ACTION_SET(actionp, PF_PASS);
6159 			else {
6160 				ACTION_SET(actionp, PF_DROP);
6161 				REASON_SET(reasonp, PFRES_FRAG);
6162 			}
6163 			return (NULL);
6164 		}
6165 		if (m->m_pkthdr.len < off + len ||
6166 		    ntohs(h->ip_len) < off + len) {
6167 			ACTION_SET(actionp, PF_DROP);
6168 			REASON_SET(reasonp, PFRES_SHORT);
6169 			return (NULL);
6170 		}
6171 		break;
6172 	}
6173 #endif /* INET */
6174 #ifdef INET6
6175 	case AF_INET6: {
6176 		struct ip6_hdr	*h = mtod(m, struct ip6_hdr *);
6177 
6178 		if (m->m_pkthdr.len < off + len ||
6179 		    (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
6180 		    (unsigned)(off + len)) {
6181 			ACTION_SET(actionp, PF_DROP);
6182 			REASON_SET(reasonp, PFRES_SHORT);
6183 			return (NULL);
6184 		}
6185 		break;
6186 	}
6187 #endif /* INET6 */
6188 	}
6189 	m_copydata(m, off, len, p);
6190 	return (p);
6191 }
6192 
6193 int
6194 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kkif *kif,
6195     int rtableid)
6196 {
6197 	struct ifnet		*ifp;
6198 
6199 	/*
6200 	 * Skip check for addresses with embedded interface scope,
6201 	 * as they would always match anyway.
6202 	 */
6203 	if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
6204 		return (1);
6205 
6206 	if (af != AF_INET && af != AF_INET6)
6207 		return (0);
6208 
6209 	/* Skip checks for ipsec interfaces */
6210 	if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
6211 		return (1);
6212 
6213 	ifp = (kif != NULL) ? kif->pfik_ifp : NULL;
6214 
6215 	switch (af) {
6216 #ifdef INET6
6217 	case AF_INET6:
6218 		return (fib6_check_urpf(rtableid, &addr->v6, 0, NHR_NONE,
6219 		    ifp));
6220 #endif
6221 #ifdef INET
6222 	case AF_INET:
6223 		return (fib4_check_urpf(rtableid, addr->v4, 0, NHR_NONE,
6224 		    ifp));
6225 #endif
6226 	}
6227 
6228 	return (0);
6229 }
6230 
6231 #ifdef INET
6232 static void
6233 pf_route(struct mbuf **m, struct pf_krule *r, int dir, struct ifnet *oifp,
6234     struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
6235 {
6236 	struct mbuf		*m0, *m1;
6237 	struct sockaddr_in	dst;
6238 	struct ip		*ip;
6239 	struct ifnet		*ifp = NULL;
6240 	struct pf_addr		 naddr;
6241 	struct pf_ksrc_node	*sn = NULL;
6242 	int			 error = 0;
6243 	uint16_t		 ip_len, ip_off;
6244 
6245 	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
6246 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
6247 	    __func__));
6248 
6249 	if ((pd->pf_mtag == NULL &&
6250 	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
6251 	    pd->pf_mtag->routed++ > 3) {
6252 		m0 = *m;
6253 		*m = NULL;
6254 		goto bad_locked;
6255 	}
6256 
6257 	if (r->rt == PF_DUPTO) {
6258 		if ((pd->pf_mtag->flags & PF_DUPLICATED)) {
6259 			if (s == NULL) {
6260 				ifp = r->rpool.cur->kif ?
6261 				    r->rpool.cur->kif->pfik_ifp : NULL;
6262 			} else {
6263 				ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
6264 				PF_STATE_UNLOCK(s);
6265 			}
6266 			if (ifp == oifp) {
6267 				/* When the 2nd interface is not skipped */
6268 				return;
6269 			} else {
6270 				m0 = *m;
6271 				*m = NULL;
6272 				goto bad;
6273 			}
6274 		} else {
6275 			pd->pf_mtag->flags |= PF_DUPLICATED;
6276 			if (((m0 = m_dup(*m, M_NOWAIT)) == NULL)) {
6277 				if (s)
6278 					PF_STATE_UNLOCK(s);
6279 				return;
6280 			}
6281 		}
6282 	} else {
6283 		if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
6284 			if (s)
6285 				PF_STATE_UNLOCK(s);
6286 			return;
6287 		}
6288 		m0 = *m;
6289 	}
6290 
6291 	ip = mtod(m0, struct ip *);
6292 
6293 	bzero(&dst, sizeof(dst));
6294 	dst.sin_family = AF_INET;
6295 	dst.sin_len = sizeof(dst);
6296 	dst.sin_addr = ip->ip_dst;
6297 
6298 	bzero(&naddr, sizeof(naddr));
6299 
6300 	if (s == NULL) {
6301 		if (TAILQ_EMPTY(&r->rpool.list)) {
6302 			DPFPRINTF(PF_DEBUG_URGENT,
6303 			    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
6304 			goto bad_locked;
6305 		}
6306 		pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
6307 		    &naddr, NULL, &sn);
6308 		if (!PF_AZERO(&naddr, AF_INET))
6309 			dst.sin_addr.s_addr = naddr.v4.s_addr;
6310 		ifp = r->rpool.cur->kif ?
6311 		    r->rpool.cur->kif->pfik_ifp : NULL;
6312 	} else {
6313 		if (!PF_AZERO(&s->rt_addr, AF_INET))
6314 			dst.sin_addr.s_addr =
6315 			    s->rt_addr.v4.s_addr;
6316 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
6317 		PF_STATE_UNLOCK(s);
6318 	}
6319 	if (ifp == NULL)
6320 		goto bad;
6321 
6322 	if (dir == PF_IN) {
6323 		if (pf_test(PF_OUT, 0, ifp, &m0, inp) != PF_PASS)
6324 			goto bad;
6325 		else if (m0 == NULL)
6326 			goto done;
6327 		if (m0->m_len < sizeof(struct ip)) {
6328 			DPFPRINTF(PF_DEBUG_URGENT,
6329 			    ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
6330 			goto bad;
6331 		}
6332 		ip = mtod(m0, struct ip *);
6333 	}
6334 
6335 	if (ifp->if_flags & IFF_LOOPBACK)
6336 		m0->m_flags |= M_SKIP_FIREWALL;
6337 
6338 	ip_len = ntohs(ip->ip_len);
6339 	ip_off = ntohs(ip->ip_off);
6340 
6341 	/* Copied from FreeBSD 10.0-CURRENT ip_output. */
6342 	m0->m_pkthdr.csum_flags |= CSUM_IP;
6343 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
6344 		in_delayed_cksum(m0);
6345 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
6346 	}
6347 #if defined(SCTP) || defined(SCTP_SUPPORT)
6348 	if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
6349 		sctp_delayed_cksum(m0, (uint32_t)(ip->ip_hl << 2));
6350 		m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
6351 	}
6352 #endif
6353 
6354 	/*
6355 	 * If small enough for interface, or the interface will take
6356 	 * care of the fragmentation for us, we can just send directly.
6357 	 */
6358 	if (ip_len <= ifp->if_mtu ||
6359 	    (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
6360 		ip->ip_sum = 0;
6361 		if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
6362 			ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
6363 			m0->m_pkthdr.csum_flags &= ~CSUM_IP;
6364 		}
6365 		m_clrprotoflags(m0);	/* Avoid confusing lower layers. */
6366 		error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
6367 		goto done;
6368 	}
6369 
6370 	/* Balk when DF bit is set or the interface didn't support TSO. */
6371 	if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
6372 		error = EMSGSIZE;
6373 		KMOD_IPSTAT_INC(ips_cantfrag);
6374 		if (r->rt != PF_DUPTO) {
6375 			if (s && pd->nat_rule != NULL)
6376 				PACKET_UNDO_NAT(m0, pd,
6377 				    (ip->ip_hl << 2) + (ip_off & IP_OFFMASK),
6378 				    s, dir);
6379 
6380 			icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
6381 			    ifp->if_mtu);
6382 			goto done;
6383 		} else
6384 			goto bad;
6385 	}
6386 
6387 	error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
6388 	if (error)
6389 		goto bad;
6390 
6391 	for (; m0; m0 = m1) {
6392 		m1 = m0->m_nextpkt;
6393 		m0->m_nextpkt = NULL;
6394 		if (error == 0) {
6395 			m_clrprotoflags(m0);
6396 			error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
6397 		} else
6398 			m_freem(m0);
6399 	}
6400 
6401 	if (error == 0)
6402 		KMOD_IPSTAT_INC(ips_fragmented);
6403 
6404 done:
6405 	if (r->rt != PF_DUPTO)
6406 		*m = NULL;
6407 	return;
6408 
6409 bad_locked:
6410 	if (s)
6411 		PF_STATE_UNLOCK(s);
6412 bad:
6413 	m_freem(m0);
6414 	goto done;
6415 }
6416 #endif /* INET */
6417 
6418 #ifdef INET6
6419 static void
6420 pf_route6(struct mbuf **m, struct pf_krule *r, int dir, struct ifnet *oifp,
6421     struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
6422 {
6423 	struct mbuf		*m0;
6424 	struct sockaddr_in6	dst;
6425 	struct ip6_hdr		*ip6;
6426 	struct ifnet		*ifp = NULL;
6427 	struct pf_addr		 naddr;
6428 	struct pf_ksrc_node	*sn = NULL;
6429 
6430 	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
6431 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
6432 	    __func__));
6433 
6434 	if ((pd->pf_mtag == NULL &&
6435 	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
6436 	    pd->pf_mtag->routed++ > 3) {
6437 		m0 = *m;
6438 		*m = NULL;
6439 		goto bad_locked;
6440 	}
6441 
6442 	if (r->rt == PF_DUPTO) {
6443 		if ((pd->pf_mtag->flags & PF_DUPLICATED)) {
6444 			if (s == NULL) {
6445 				ifp = r->rpool.cur->kif ?
6446 				    r->rpool.cur->kif->pfik_ifp : NULL;
6447 			} else {
6448 				ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
6449 				PF_STATE_UNLOCK(s);
6450 			}
6451 			if (ifp == oifp) {
6452 				/* When the 2nd interface is not skipped */
6453 				return;
6454 			} else {
6455 				m0 = *m;
6456 				*m = NULL;
6457 				goto bad;
6458 			}
6459 		} else {
6460 			pd->pf_mtag->flags |= PF_DUPLICATED;
6461 			if (((m0 = m_dup(*m, M_NOWAIT)) == NULL)) {
6462 				if (s)
6463 					PF_STATE_UNLOCK(s);
6464 				return;
6465 			}
6466 		}
6467 	} else {
6468 		if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
6469 			if (s)
6470 				PF_STATE_UNLOCK(s);
6471 			return;
6472 		}
6473 		m0 = *m;
6474 	}
6475 
6476 	ip6 = mtod(m0, struct ip6_hdr *);
6477 
6478 	bzero(&dst, sizeof(dst));
6479 	dst.sin6_family = AF_INET6;
6480 	dst.sin6_len = sizeof(dst);
6481 	dst.sin6_addr = ip6->ip6_dst;
6482 
6483 	bzero(&naddr, sizeof(naddr));
6484 
6485 	if (s == NULL) {
6486 		if (TAILQ_EMPTY(&r->rpool.list)) {
6487 			DPFPRINTF(PF_DEBUG_URGENT,
6488 			    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
6489 			goto bad_locked;
6490 		}
6491 		pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
6492 		    &naddr, NULL, &sn);
6493 		if (!PF_AZERO(&naddr, AF_INET6))
6494 			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
6495 			    &naddr, AF_INET6);
6496 		ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
6497 	} else {
6498 		if (!PF_AZERO(&s->rt_addr, AF_INET6))
6499 			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
6500 			    &s->rt_addr, AF_INET6);
6501 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
6502 	}
6503 
6504 	if (s)
6505 		PF_STATE_UNLOCK(s);
6506 
6507 	if (ifp == NULL)
6508 		goto bad;
6509 
6510 	if (dir == PF_IN) {
6511 		if (pf_test6(PF_OUT, PFIL_FWD, ifp, &m0, inp) != PF_PASS)
6512 			goto bad;
6513 		else if (m0 == NULL)
6514 			goto done;
6515 		if (m0->m_len < sizeof(struct ip6_hdr)) {
6516 			DPFPRINTF(PF_DEBUG_URGENT,
6517 			    ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
6518 			    __func__));
6519 			goto bad;
6520 		}
6521 		ip6 = mtod(m0, struct ip6_hdr *);
6522 	}
6523 
6524 	if (ifp->if_flags & IFF_LOOPBACK)
6525 		m0->m_flags |= M_SKIP_FIREWALL;
6526 
6527 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
6528 	    ~ifp->if_hwassist) {
6529 		uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
6530 		in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
6531 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
6532 	}
6533 
6534 	/*
6535 	 * If the packet is too large for the outgoing interface,
6536 	 * send back an icmp6 error.
6537 	 */
6538 	if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
6539 		dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
6540 	if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
6541 		nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
6542 	else {
6543 		in6_ifstat_inc(ifp, ifs6_in_toobig);
6544 		if (r->rt != PF_DUPTO) {
6545 			if (s && pd->nat_rule != NULL)
6546 				PACKET_UNDO_NAT(m0, pd,
6547 				    ((caddr_t)ip6 - m0->m_data) +
6548 				    sizeof(struct ip6_hdr), s, dir);
6549 
6550 			icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
6551 		} else
6552 			goto bad;
6553 	}
6554 
6555 done:
6556 	if (r->rt != PF_DUPTO)
6557 		*m = NULL;
6558 	return;
6559 
6560 bad_locked:
6561 	if (s)
6562 		PF_STATE_UNLOCK(s);
6563 bad:
6564 	m_freem(m0);
6565 	goto done;
6566 }
6567 #endif /* INET6 */
6568 
6569 /*
6570  * FreeBSD supports cksum offloads for the following drivers.
6571  *  em(4), fxp(4), lge(4), nge(4), re(4), ti(4), txp(4), xl(4)
6572  *
6573  * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
6574  *  network driver performed cksum including pseudo header, need to verify
6575  *   csum_data
6576  * CSUM_DATA_VALID :
6577  *  network driver performed cksum, needs to additional pseudo header
6578  *  cksum computation with partial csum_data(i.e. lack of H/W support for
6579  *  pseudo header, for instance sk(4) and possibly gem(4))
6580  *
6581  * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
6582  * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
6583  * TCP/UDP layer.
6584  * Also, set csum_data to 0xffff to force cksum validation.
6585  */
6586 static int
6587 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
6588 {
6589 	u_int16_t sum = 0;
6590 	int hw_assist = 0;
6591 	struct ip *ip;
6592 
6593 	if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
6594 		return (1);
6595 	if (m->m_pkthdr.len < off + len)
6596 		return (1);
6597 
6598 	switch (p) {
6599 	case IPPROTO_TCP:
6600 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
6601 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
6602 				sum = m->m_pkthdr.csum_data;
6603 			} else {
6604 				ip = mtod(m, struct ip *);
6605 				sum = in_pseudo(ip->ip_src.s_addr,
6606 				ip->ip_dst.s_addr, htonl((u_short)len +
6607 				m->m_pkthdr.csum_data + IPPROTO_TCP));
6608 			}
6609 			sum ^= 0xffff;
6610 			++hw_assist;
6611 		}
6612 		break;
6613 	case IPPROTO_UDP:
6614 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
6615 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
6616 				sum = m->m_pkthdr.csum_data;
6617 			} else {
6618 				ip = mtod(m, struct ip *);
6619 				sum = in_pseudo(ip->ip_src.s_addr,
6620 				ip->ip_dst.s_addr, htonl((u_short)len +
6621 				m->m_pkthdr.csum_data + IPPROTO_UDP));
6622 			}
6623 			sum ^= 0xffff;
6624 			++hw_assist;
6625 		}
6626 		break;
6627 	case IPPROTO_ICMP:
6628 #ifdef INET6
6629 	case IPPROTO_ICMPV6:
6630 #endif /* INET6 */
6631 		break;
6632 	default:
6633 		return (1);
6634 	}
6635 
6636 	if (!hw_assist) {
6637 		switch (af) {
6638 		case AF_INET:
6639 			if (p == IPPROTO_ICMP) {
6640 				if (m->m_len < off)
6641 					return (1);
6642 				m->m_data += off;
6643 				m->m_len -= off;
6644 				sum = in_cksum(m, len);
6645 				m->m_data -= off;
6646 				m->m_len += off;
6647 			} else {
6648 				if (m->m_len < sizeof(struct ip))
6649 					return (1);
6650 				sum = in4_cksum(m, p, off, len);
6651 			}
6652 			break;
6653 #ifdef INET6
6654 		case AF_INET6:
6655 			if (m->m_len < sizeof(struct ip6_hdr))
6656 				return (1);
6657 			sum = in6_cksum(m, p, off, len);
6658 			break;
6659 #endif /* INET6 */
6660 		default:
6661 			return (1);
6662 		}
6663 	}
6664 	if (sum) {
6665 		switch (p) {
6666 		case IPPROTO_TCP:
6667 		    {
6668 			KMOD_TCPSTAT_INC(tcps_rcvbadsum);
6669 			break;
6670 		    }
6671 		case IPPROTO_UDP:
6672 		    {
6673 			KMOD_UDPSTAT_INC(udps_badsum);
6674 			break;
6675 		    }
6676 #ifdef INET
6677 		case IPPROTO_ICMP:
6678 		    {
6679 			KMOD_ICMPSTAT_INC(icps_checksum);
6680 			break;
6681 		    }
6682 #endif
6683 #ifdef INET6
6684 		case IPPROTO_ICMPV6:
6685 		    {
6686 			KMOD_ICMP6STAT_INC(icp6s_checksum);
6687 			break;
6688 		    }
6689 #endif /* INET6 */
6690 		}
6691 		return (1);
6692 	} else {
6693 		if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
6694 			m->m_pkthdr.csum_flags |=
6695 			    (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
6696 			m->m_pkthdr.csum_data = 0xffff;
6697 		}
6698 	}
6699 	return (0);
6700 }
6701 
6702 static bool
6703 pf_pdesc_to_dnflow(int dir, const struct pf_pdesc *pd,
6704     const struct pf_krule *r, const struct pf_kstate *s,
6705     struct ip_fw_args *dnflow)
6706 {
6707 	int dndir = r->direction;
6708 
6709 	if (s && dndir == PF_INOUT) {
6710 		dndir = s->direction;
6711 	} else if (dndir == PF_INOUT) {
6712 		/* Assume primary direction. Happens when we've set dnpipe in
6713 		 * the ethernet level code. */
6714 		dndir = dir;
6715 	}
6716 
6717 	memset(dnflow, 0, sizeof(*dnflow));
6718 
6719 	if (pd->dport != NULL)
6720 		dnflow->f_id.dst_port = ntohs(*pd->dport);
6721 	if (pd->sport != NULL)
6722 		dnflow->f_id.src_port = ntohs(*pd->sport);
6723 
6724 	if (dir == PF_IN)
6725 		dnflow->flags |= IPFW_ARGS_IN;
6726 	else
6727 		dnflow->flags |= IPFW_ARGS_OUT;
6728 
6729 	if (dir != dndir && pd->act.dnrpipe) {
6730 		dnflow->rule.info = pd->act.dnrpipe;
6731 	}
6732 	else if (dir == dndir) {
6733 		dnflow->rule.info = pd->act.dnpipe;
6734 	}
6735 	else {
6736 		return (false);
6737 	}
6738 
6739 	dnflow->rule.info |= IPFW_IS_DUMMYNET;
6740 	if (r->free_flags & PFRULE_DN_IS_PIPE || pd->act.flags & PFRULE_DN_IS_PIPE)
6741 		dnflow->rule.info |= IPFW_IS_PIPE;
6742 
6743 	dnflow->f_id.proto = pd->proto;
6744 	dnflow->f_id.extra = dnflow->rule.info;
6745 	switch (pd->af) {
6746 	case AF_INET:
6747 		dnflow->f_id.addr_type = 4;
6748 		dnflow->f_id.src_ip = ntohl(pd->src->v4.s_addr);
6749 		dnflow->f_id.dst_ip = ntohl(pd->dst->v4.s_addr);
6750 		break;
6751 	case AF_INET6:
6752 		dnflow->flags |= IPFW_ARGS_IP6;
6753 		dnflow->f_id.addr_type = 6;
6754 		dnflow->f_id.src_ip6 = pd->src->v6;
6755 		dnflow->f_id.dst_ip6 = pd->dst->v6;
6756 		break;
6757 	default:
6758 		panic("Invalid AF");
6759 		break;
6760 	}
6761 
6762 	return (true);
6763 }
6764 
6765 int
6766 pf_test_eth(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0,
6767     struct inpcb *inp)
6768 {
6769 	struct pfi_kkif		*kif;
6770 	struct mbuf		*m = *m0;
6771 
6772 	M_ASSERTPKTHDR(m);
6773 	MPASS(ifp->if_vnet == curvnet);
6774 	NET_EPOCH_ASSERT();
6775 
6776 	if (!V_pf_status.running)
6777 		return (PF_PASS);
6778 
6779 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
6780 
6781 	if (kif == NULL) {
6782 		DPFPRINTF(PF_DEBUG_URGENT,
6783 		    ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
6784 		return (PF_DROP);
6785 	}
6786 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
6787 		return (PF_PASS);
6788 
6789 	if (m->m_flags & M_SKIP_FIREWALL)
6790 		return (PF_PASS);
6791 
6792 	/* Stateless! */
6793 	return (pf_test_eth_rule(dir, kif, m0));
6794 }
6795 
6796 #ifdef INET
6797 int
6798 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6799 {
6800 	struct pfi_kkif		*kif;
6801 	u_short			 action, reason = 0, log = 0;
6802 	struct mbuf		*m = *m0;
6803 	struct ip		*h = NULL;
6804 	struct m_tag		*ipfwtag;
6805 	struct pf_krule		*a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6806 	struct pf_kstate	*s = NULL;
6807 	struct pf_kruleset	*ruleset = NULL;
6808 	struct pf_pdesc		 pd;
6809 	int			 off, dirndx, pqid = 0;
6810 
6811 	PF_RULES_RLOCK_TRACKER;
6812 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: bad direction %d\n", __func__, dir));
6813 	M_ASSERTPKTHDR(m);
6814 
6815 	if (!V_pf_status.running)
6816 		return (PF_PASS);
6817 
6818 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
6819 
6820 	if (kif == NULL) {
6821 		DPFPRINTF(PF_DEBUG_URGENT,
6822 		    ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
6823 		return (PF_DROP);
6824 	}
6825 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
6826 		return (PF_PASS);
6827 
6828 	if (m->m_flags & M_SKIP_FIREWALL)
6829 		return (PF_PASS);
6830 
6831 	memset(&pd, 0, sizeof(pd));
6832 	pd.pf_mtag = pf_find_mtag(m);
6833 
6834 	if (pd.pf_mtag && pd.pf_mtag->dnpipe) {
6835 		pd.act.dnpipe = pd.pf_mtag->dnpipe;
6836 		pd.act.flags = pd.pf_mtag->dnflags;
6837 	}
6838 
6839 	if (ip_dn_io_ptr != NULL && pd.pf_mtag != NULL &&
6840 	    pd.pf_mtag->flags & PF_TAG_DUMMYNET) {
6841 		/* Dummynet re-injects packets after they've
6842 		 * completed their delay. We've already
6843 		 * processed them, so pass unconditionally. */
6844 
6845 		/* But only once. We may see the packet multiple times (e.g.
6846 		 * PFIL_IN/PFIL_OUT). */
6847 		pd.pf_mtag->flags &= ~PF_TAG_DUMMYNET;
6848 
6849 		return (PF_PASS);
6850 	}
6851 
6852 	PF_RULES_RLOCK();
6853 
6854 	if (__predict_false(ip_divert_ptr != NULL) &&
6855 	    ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
6856 		struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
6857 		if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
6858 			if (pd.pf_mtag == NULL &&
6859 			    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6860 				action = PF_DROP;
6861 				goto done;
6862 			}
6863 			pd.pf_mtag->flags |= PF_PACKET_LOOPED;
6864 			m_tag_delete(m, ipfwtag);
6865 		}
6866 		if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
6867 			m->m_flags |= M_FASTFWD_OURS;
6868 			pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
6869 		}
6870 	} else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
6871 		/* We do IP header normalization and packet reassembly here */
6872 		action = PF_DROP;
6873 		goto done;
6874 	}
6875 	m = *m0;	/* pf_normalize messes with m0 */
6876 	h = mtod(m, struct ip *);
6877 
6878 	off = h->ip_hl << 2;
6879 	if (off < (int)sizeof(struct ip)) {
6880 		action = PF_DROP;
6881 		REASON_SET(&reason, PFRES_SHORT);
6882 		log = 1;
6883 		goto done;
6884 	}
6885 
6886 	pd.src = (struct pf_addr *)&h->ip_src;
6887 	pd.dst = (struct pf_addr *)&h->ip_dst;
6888 	pd.sport = pd.dport = NULL;
6889 	pd.ip_sum = &h->ip_sum;
6890 	pd.proto_sum = NULL;
6891 	pd.proto = h->ip_p;
6892 	pd.dir = dir;
6893 	pd.sidx = (dir == PF_IN) ? 0 : 1;
6894 	pd.didx = (dir == PF_IN) ? 1 : 0;
6895 	pd.af = AF_INET;
6896 	pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
6897 	pd.tot_len = ntohs(h->ip_len);
6898 
6899 	/* handle fragments that didn't get reassembled by normalization */
6900 	if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
6901 		action = pf_test_fragment(&r, dir, kif, m, h,
6902 		    &pd, &a, &ruleset);
6903 		goto done;
6904 	}
6905 
6906 	switch (h->ip_p) {
6907 	case IPPROTO_TCP: {
6908 		if (!pf_pull_hdr(m, off, &pd.hdr.tcp, sizeof(pd.hdr.tcp),
6909 		    &action, &reason, AF_INET)) {
6910 			log = action != PF_PASS;
6911 			goto done;
6912 		}
6913 		pd.p_len = pd.tot_len - off - (pd.hdr.tcp.th_off << 2);
6914 
6915 		pd.sport = &pd.hdr.tcp.th_sport;
6916 		pd.dport = &pd.hdr.tcp.th_dport;
6917 
6918 		/* Respond to SYN with a syncookie. */
6919 		if ((pd.hdr.tcp.th_flags & (TH_SYN|TH_ACK|TH_RST)) == TH_SYN &&
6920 		    pd.dir == PF_IN && pf_synflood_check(&pd)) {
6921 			pf_syncookie_send(m, off, &pd);
6922 			action = PF_DROP;
6923 			break;
6924 		}
6925 
6926 		if ((pd.hdr.tcp.th_flags & TH_ACK) && pd.p_len == 0)
6927 			pqid = 1;
6928 		action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6929 		if (action == PF_DROP)
6930 			goto done;
6931 		action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6932 		    &reason);
6933 		if (action == PF_PASS) {
6934 			if (V_pfsync_update_state_ptr != NULL)
6935 				V_pfsync_update_state_ptr(s);
6936 			r = s->rule.ptr;
6937 			a = s->anchor.ptr;
6938 			log = s->log;
6939 		} else if (s == NULL) {
6940 			/* Validate remote SYN|ACK, re-create original SYN if
6941 			 * valid. */
6942 			if ((pd.hdr.tcp.th_flags & (TH_SYN|TH_ACK|TH_RST)) ==
6943 			    TH_ACK && pf_syncookie_validate(&pd) &&
6944 			    pd.dir == PF_IN) {
6945 				struct mbuf *msyn;
6946 
6947 				msyn = pf_syncookie_recreate_syn(h->ip_ttl,
6948 				    off,&pd);
6949 				if (msyn == NULL) {
6950 					action = PF_DROP;
6951 					break;
6952 				}
6953 
6954 				action = pf_test(dir, pflags, ifp, &msyn, inp);
6955 				m_freem(msyn);
6956 
6957 				if (action == PF_PASS) {
6958 					action = pf_test_state_tcp(&s, dir,
6959 					    kif, m, off, h, &pd, &reason);
6960 					if (action != PF_PASS || s == NULL) {
6961 						action = PF_DROP;
6962 						break;
6963 					}
6964 
6965 					s->src.seqhi = ntohl(pd.hdr.tcp.th_ack)
6966 					    - 1;
6967 					s->src.seqlo = ntohl(pd.hdr.tcp.th_seq)
6968 					    - 1;
6969 					pf_set_protostate(s, PF_PEER_SRC,
6970 					    PF_TCPS_PROXY_DST);
6971 
6972 					action = pf_synproxy(&pd, &s, &reason);
6973 					if (action != PF_PASS)
6974 						break;
6975 				}
6976 				break;
6977 			}
6978 			else {
6979 				action = pf_test_rule(&r, &s, dir, kif, m, off,
6980 				    &pd, &a, &ruleset, inp);
6981 			}
6982 		}
6983 		break;
6984 	}
6985 
6986 	case IPPROTO_UDP: {
6987 		if (!pf_pull_hdr(m, off, &pd.hdr.udp, sizeof(pd.hdr.udp),
6988 		    &action, &reason, AF_INET)) {
6989 			log = action != PF_PASS;
6990 			goto done;
6991 		}
6992 		pd.sport = &pd.hdr.udp.uh_sport;
6993 		pd.dport = &pd.hdr.udp.uh_dport;
6994 		if (pd.hdr.udp.uh_dport == 0 ||
6995 		    ntohs(pd.hdr.udp.uh_ulen) > m->m_pkthdr.len - off ||
6996 		    ntohs(pd.hdr.udp.uh_ulen) < sizeof(struct udphdr)) {
6997 			action = PF_DROP;
6998 			REASON_SET(&reason, PFRES_SHORT);
6999 			goto done;
7000 		}
7001 		action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
7002 		if (action == PF_PASS) {
7003 			if (V_pfsync_update_state_ptr != NULL)
7004 				V_pfsync_update_state_ptr(s);
7005 			r = s->rule.ptr;
7006 			a = s->anchor.ptr;
7007 			log = s->log;
7008 		} else if (s == NULL)
7009 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7010 			    &a, &ruleset, inp);
7011 		break;
7012 	}
7013 
7014 	case IPPROTO_ICMP: {
7015 		if (!pf_pull_hdr(m, off, &pd.hdr.icmp, ICMP_MINLEN,
7016 		    &action, &reason, AF_INET)) {
7017 			log = action != PF_PASS;
7018 			goto done;
7019 		}
7020 		action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
7021 		    &reason);
7022 		if (action == PF_PASS) {
7023 			if (V_pfsync_update_state_ptr != NULL)
7024 				V_pfsync_update_state_ptr(s);
7025 			r = s->rule.ptr;
7026 			a = s->anchor.ptr;
7027 			log = s->log;
7028 		} else if (s == NULL)
7029 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7030 			    &a, &ruleset, inp);
7031 		break;
7032 	}
7033 
7034 #ifdef INET6
7035 	case IPPROTO_ICMPV6: {
7036 		action = PF_DROP;
7037 		DPFPRINTF(PF_DEBUG_MISC,
7038 		    ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
7039 		goto done;
7040 	}
7041 #endif
7042 
7043 	default:
7044 		action = pf_test_state_other(&s, dir, kif, m, &pd);
7045 		if (action == PF_PASS) {
7046 			if (V_pfsync_update_state_ptr != NULL)
7047 				V_pfsync_update_state_ptr(s);
7048 			r = s->rule.ptr;
7049 			a = s->anchor.ptr;
7050 			log = s->log;
7051 		} else if (s == NULL)
7052 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7053 			    &a, &ruleset, inp);
7054 		break;
7055 	}
7056 
7057 done:
7058 	PF_RULES_RUNLOCK();
7059 	if (action == PF_PASS && h->ip_hl > 5 &&
7060 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
7061 		action = PF_DROP;
7062 		REASON_SET(&reason, PFRES_IPOPTIONS);
7063 		log = r->log;
7064 		DPFPRINTF(PF_DEBUG_MISC,
7065 		    ("pf: dropping packet with ip options\n"));
7066 	}
7067 
7068 	if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
7069 		action = PF_DROP;
7070 		REASON_SET(&reason, PFRES_MEMORY);
7071 	}
7072 	if (r->rtableid >= 0)
7073 		M_SETFIB(m, r->rtableid);
7074 
7075 	if (r->scrub_flags & PFSTATE_SETPRIO) {
7076 		if (pd.tos & IPTOS_LOWDELAY)
7077 			pqid = 1;
7078 		if (vlan_set_pcp(m, r->set_prio[pqid])) {
7079 			action = PF_DROP;
7080 			REASON_SET(&reason, PFRES_MEMORY);
7081 			log = 1;
7082 			DPFPRINTF(PF_DEBUG_MISC,
7083 			    ("pf: failed to allocate 802.1q mtag\n"));
7084 		}
7085 	}
7086 
7087 #ifdef ALTQ
7088 	if (s && s->qid) {
7089 		pd.act.pqid = s->pqid;
7090 		pd.act.qid = s->qid;
7091 	} else if (r->qid) {
7092 		pd.act.pqid = r->pqid;
7093 		pd.act.qid = r->qid;
7094 	}
7095 	if (action == PF_PASS && pd.act.qid) {
7096 		if (pd.pf_mtag == NULL &&
7097 		    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
7098 			action = PF_DROP;
7099 			REASON_SET(&reason, PFRES_MEMORY);
7100 		} else {
7101 			if (s != NULL)
7102 				pd.pf_mtag->qid_hash = pf_state_hash(s);
7103 			if (pqid || (pd.tos & IPTOS_LOWDELAY))
7104 				pd.pf_mtag->qid = pd.act.pqid;
7105 			else
7106 				pd.pf_mtag->qid = pd.act.qid;
7107 			/* Add hints for ecn. */
7108 			pd.pf_mtag->hdr = h;
7109 		}
7110 	}
7111 #endif /* ALTQ */
7112 
7113 	/*
7114 	 * connections redirected to loopback should not match sockets
7115 	 * bound specifically to loopback due to security implications,
7116 	 * see tcp_input() and in_pcblookup_listen().
7117 	 */
7118 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
7119 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
7120 	    (s->nat_rule.ptr->action == PF_RDR ||
7121 	    s->nat_rule.ptr->action == PF_BINAT) &&
7122 	    IN_LOOPBACK(ntohl(pd.dst->v4.s_addr)))
7123 		m->m_flags |= M_SKIP_FIREWALL;
7124 
7125 	if (__predict_false(ip_divert_ptr != NULL) && action == PF_PASS &&
7126 	    r->divert.port && !PACKET_LOOPED(&pd)) {
7127 		ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
7128 		    sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
7129 		if (ipfwtag != NULL) {
7130 			((struct ipfw_rule_ref *)(ipfwtag+1))->info =
7131 			    ntohs(r->divert.port);
7132 			((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
7133 
7134 			if (s)
7135 				PF_STATE_UNLOCK(s);
7136 
7137 			m_tag_prepend(m, ipfwtag);
7138 			if (m->m_flags & M_FASTFWD_OURS) {
7139 				if (pd.pf_mtag == NULL &&
7140 				    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
7141 					action = PF_DROP;
7142 					REASON_SET(&reason, PFRES_MEMORY);
7143 					log = 1;
7144 					DPFPRINTF(PF_DEBUG_MISC,
7145 					    ("pf: failed to allocate tag\n"));
7146 				} else {
7147 					pd.pf_mtag->flags |=
7148 					    PF_FASTFWD_OURS_PRESENT;
7149 					m->m_flags &= ~M_FASTFWD_OURS;
7150 				}
7151 			}
7152 			ip_divert_ptr(*m0, dir == PF_IN);
7153 			*m0 = NULL;
7154 
7155 			return (action);
7156 		} else {
7157 			/* XXX: ipfw has the same behaviour! */
7158 			action = PF_DROP;
7159 			REASON_SET(&reason, PFRES_MEMORY);
7160 			log = 1;
7161 			DPFPRINTF(PF_DEBUG_MISC,
7162 			    ("pf: failed to allocate divert tag\n"));
7163 		}
7164 	}
7165 
7166 	if (log) {
7167 		struct pf_krule *lr;
7168 
7169 		if (s != NULL && s->nat_rule.ptr != NULL &&
7170 		    s->nat_rule.ptr->log & PF_LOG_ALL)
7171 			lr = s->nat_rule.ptr;
7172 		else
7173 			lr = r;
7174 		PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
7175 		    (s == NULL));
7176 	}
7177 
7178 	pf_counter_u64_critical_enter();
7179 	pf_counter_u64_add_protected(&kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS],
7180 	    pd.tot_len);
7181 	pf_counter_u64_add_protected(&kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS],
7182 	    1);
7183 
7184 	if (action == PF_PASS || r->action == PF_DROP) {
7185 		dirndx = (dir == PF_OUT);
7186 		pf_counter_u64_add_protected(&r->packets[dirndx], 1);
7187 		pf_counter_u64_add_protected(&r->bytes[dirndx], pd.tot_len);
7188 		if (a != NULL) {
7189 			pf_counter_u64_add_protected(&a->packets[dirndx], 1);
7190 			pf_counter_u64_add_protected(&a->bytes[dirndx], pd.tot_len);
7191 		}
7192 		if (s != NULL) {
7193 			if (s->nat_rule.ptr != NULL) {
7194 				pf_counter_u64_add_protected(&s->nat_rule.ptr->packets[dirndx],
7195 				    1);
7196 				pf_counter_u64_add_protected(&s->nat_rule.ptr->bytes[dirndx],
7197 				    pd.tot_len);
7198 			}
7199 			if (s->src_node != NULL) {
7200 				counter_u64_add(s->src_node->packets[dirndx],
7201 				    1);
7202 				counter_u64_add(s->src_node->bytes[dirndx],
7203 				    pd.tot_len);
7204 			}
7205 			if (s->nat_src_node != NULL) {
7206 				counter_u64_add(s->nat_src_node->packets[dirndx],
7207 				    1);
7208 				counter_u64_add(s->nat_src_node->bytes[dirndx],
7209 				    pd.tot_len);
7210 			}
7211 			dirndx = (dir == s->direction) ? 0 : 1;
7212 			s->packets[dirndx]++;
7213 			s->bytes[dirndx] += pd.tot_len;
7214 		}
7215 		tr = r;
7216 		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
7217 		if (nr != NULL && r == &V_pf_default_rule)
7218 			tr = nr;
7219 		if (tr->src.addr.type == PF_ADDR_TABLE)
7220 			pfr_update_stats(tr->src.addr.p.tbl,
7221 			    (s == NULL) ? pd.src :
7222 			    &s->key[(s->direction == PF_IN)]->
7223 				addr[(s->direction == PF_OUT)],
7224 			    pd.af, pd.tot_len, dir == PF_OUT,
7225 			    r->action == PF_PASS, tr->src.neg);
7226 		if (tr->dst.addr.type == PF_ADDR_TABLE)
7227 			pfr_update_stats(tr->dst.addr.p.tbl,
7228 			    (s == NULL) ? pd.dst :
7229 			    &s->key[(s->direction == PF_IN)]->
7230 				addr[(s->direction == PF_IN)],
7231 			    pd.af, pd.tot_len, dir == PF_OUT,
7232 			    r->action == PF_PASS, tr->dst.neg);
7233 	}
7234 	pf_counter_u64_critical_exit();
7235 
7236 	switch (action) {
7237 	case PF_SYNPROXY_DROP:
7238 		m_freem(*m0);
7239 	case PF_DEFER:
7240 		*m0 = NULL;
7241 		action = PF_PASS;
7242 		break;
7243 	case PF_DROP:
7244 		m_freem(*m0);
7245 		*m0 = NULL;
7246 		break;
7247 	default:
7248 		/* pf_route() returns unlocked. */
7249 		if (r->rt) {
7250 			pf_route(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
7251 			return (action);
7252 		}
7253 		/* Dummynet processing. */
7254 		if (s && (s->dnpipe || s->dnrpipe)) {
7255 			pd.act.dnpipe = s->dnpipe;
7256 			pd.act.dnrpipe = s->dnrpipe;
7257 			pd.act.flags = s->state_flags;
7258 		} else if (r->dnpipe || r->dnrpipe) {
7259 			pd.act.dnpipe = r->dnpipe;
7260 			pd.act.dnrpipe = r->dnrpipe;
7261 			pd.act.flags = r->free_flags;
7262 		}
7263 		if (pd.act.dnpipe || pd.act.dnrpipe) {
7264 			struct ip_fw_args dnflow;
7265 			if (ip_dn_io_ptr == NULL) {
7266 				m_freem(*m0);
7267 				*m0 = NULL;
7268 				action = PF_DROP;
7269 				REASON_SET(&reason, PFRES_MEMORY);
7270 				break;
7271 			}
7272 
7273 			if (pd.pf_mtag == NULL &&
7274 			    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
7275 				m_freem(*m0);
7276 				*m0 = NULL;
7277 				action = PF_DROP;
7278 				REASON_SET(&reason, PFRES_MEMORY);
7279 				break;
7280 			}
7281 
7282 			if (pf_pdesc_to_dnflow(dir, &pd, r, s, &dnflow)) {
7283 				pd.pf_mtag->flags |= PF_TAG_DUMMYNET;
7284 				ip_dn_io_ptr(m0, &dnflow);
7285 				if (*m0 == NULL)
7286 					action = PF_DROP;
7287 			}
7288 		}
7289 		break;
7290 	}
7291 
7292 	SDT_PROBE4(pf, ip, test, done, action, reason, r, s);
7293 
7294 	if (s)
7295 		PF_STATE_UNLOCK(s);
7296 
7297 	return (action);
7298 }
7299 #endif /* INET */
7300 
7301 #ifdef INET6
7302 int
7303 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
7304 {
7305 	struct pfi_kkif		*kif;
7306 	u_short			 action, reason = 0, log = 0;
7307 	struct mbuf		*m = *m0, *n = NULL;
7308 	struct m_tag		*mtag;
7309 	struct ip6_hdr		*h = NULL;
7310 	struct pf_krule		*a = NULL, *r = &V_pf_default_rule, *tr, *nr;
7311 	struct pf_kstate	*s = NULL;
7312 	struct pf_kruleset	*ruleset = NULL;
7313 	struct pf_pdesc		 pd;
7314 	int			 off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
7315 
7316 	PF_RULES_RLOCK_TRACKER;
7317 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: bad direction %d\n", __func__, dir));
7318 	M_ASSERTPKTHDR(m);
7319 
7320 	if (!V_pf_status.running)
7321 		return (PF_PASS);
7322 
7323 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
7324 	if (kif == NULL) {
7325 		DPFPRINTF(PF_DEBUG_URGENT,
7326 		    ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
7327 		return (PF_DROP);
7328 	}
7329 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
7330 		return (PF_PASS);
7331 
7332 	if (m->m_flags & M_SKIP_FIREWALL)
7333 		return (PF_PASS);
7334 
7335 	memset(&pd, 0, sizeof(pd));
7336 	pd.pf_mtag = pf_find_mtag(m);
7337 
7338 	if (pd.pf_mtag && pd.pf_mtag->dnpipe) {
7339 		pd.act.dnpipe = pd.pf_mtag->dnpipe;
7340 		pd.act.flags = pd.pf_mtag->dnflags;
7341 	}
7342 
7343 	if (ip_dn_io_ptr != NULL && pd.pf_mtag != NULL &&
7344 	    pd.pf_mtag->flags & PF_TAG_DUMMYNET) {
7345 		pd.pf_mtag->flags &= ~PF_TAG_DUMMYNET;
7346 		/* Dummynet re-injects packets after they've
7347 		 * completed their delay. We've already
7348 		 * processed them, so pass unconditionally. */
7349 		return (PF_PASS);
7350 	}
7351 
7352 	PF_RULES_RLOCK();
7353 
7354 	/* We do IP header normalization and packet reassembly here */
7355 	if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
7356 		action = PF_DROP;
7357 		goto done;
7358 	}
7359 	m = *m0;	/* pf_normalize messes with m0 */
7360 	h = mtod(m, struct ip6_hdr *);
7361 
7362 	/*
7363 	 * we do not support jumbogram.  if we keep going, zero ip6_plen
7364 	 * will do something bad, so drop the packet for now.
7365 	 */
7366 	if (htons(h->ip6_plen) == 0) {
7367 		action = PF_DROP;
7368 		REASON_SET(&reason, PFRES_NORM);	/*XXX*/
7369 		goto done;
7370 	}
7371 
7372 	pd.src = (struct pf_addr *)&h->ip6_src;
7373 	pd.dst = (struct pf_addr *)&h->ip6_dst;
7374 	pd.sport = pd.dport = NULL;
7375 	pd.ip_sum = NULL;
7376 	pd.proto_sum = NULL;
7377 	pd.dir = dir;
7378 	pd.sidx = (dir == PF_IN) ? 0 : 1;
7379 	pd.didx = (dir == PF_IN) ? 1 : 0;
7380 	pd.af = AF_INET6;
7381 	pd.tos = IPV6_DSCP(h);
7382 	pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
7383 
7384 	off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
7385 	pd.proto = h->ip6_nxt;
7386 	do {
7387 		switch (pd.proto) {
7388 		case IPPROTO_FRAGMENT:
7389 			action = pf_test_fragment(&r, dir, kif, m, h,
7390 			    &pd, &a, &ruleset);
7391 			if (action == PF_DROP)
7392 				REASON_SET(&reason, PFRES_FRAG);
7393 			goto done;
7394 		case IPPROTO_ROUTING: {
7395 			struct ip6_rthdr rthdr;
7396 
7397 			if (rh_cnt++) {
7398 				DPFPRINTF(PF_DEBUG_MISC,
7399 				    ("pf: IPv6 more than one rthdr\n"));
7400 				action = PF_DROP;
7401 				REASON_SET(&reason, PFRES_IPOPTIONS);
7402 				log = 1;
7403 				goto done;
7404 			}
7405 			if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
7406 			    &reason, pd.af)) {
7407 				DPFPRINTF(PF_DEBUG_MISC,
7408 				    ("pf: IPv6 short rthdr\n"));
7409 				action = PF_DROP;
7410 				REASON_SET(&reason, PFRES_SHORT);
7411 				log = 1;
7412 				goto done;
7413 			}
7414 			if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
7415 				DPFPRINTF(PF_DEBUG_MISC,
7416 				    ("pf: IPv6 rthdr0\n"));
7417 				action = PF_DROP;
7418 				REASON_SET(&reason, PFRES_IPOPTIONS);
7419 				log = 1;
7420 				goto done;
7421 			}
7422 			/* FALLTHROUGH */
7423 		}
7424 		case IPPROTO_AH:
7425 		case IPPROTO_HOPOPTS:
7426 		case IPPROTO_DSTOPTS: {
7427 			/* get next header and header length */
7428 			struct ip6_ext	opt6;
7429 
7430 			if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
7431 			    NULL, &reason, pd.af)) {
7432 				DPFPRINTF(PF_DEBUG_MISC,
7433 				    ("pf: IPv6 short opt\n"));
7434 				action = PF_DROP;
7435 				log = 1;
7436 				goto done;
7437 			}
7438 			if (pd.proto == IPPROTO_AH)
7439 				off += (opt6.ip6e_len + 2) * 4;
7440 			else
7441 				off += (opt6.ip6e_len + 1) * 8;
7442 			pd.proto = opt6.ip6e_nxt;
7443 			/* goto the next header */
7444 			break;
7445 		}
7446 		default:
7447 			terminal++;
7448 			break;
7449 		}
7450 	} while (!terminal);
7451 
7452 	/* if there's no routing header, use unmodified mbuf for checksumming */
7453 	if (!n)
7454 		n = m;
7455 
7456 	switch (pd.proto) {
7457 	case IPPROTO_TCP: {
7458 		if (!pf_pull_hdr(m, off, &pd.hdr.tcp, sizeof(pd.hdr.tcp),
7459 		    &action, &reason, AF_INET6)) {
7460 			log = action != PF_PASS;
7461 			goto done;
7462 		}
7463 		pd.p_len = pd.tot_len - off - (pd.hdr.tcp.th_off << 2);
7464 		pd.sport = &pd.hdr.tcp.th_sport;
7465 		pd.dport = &pd.hdr.tcp.th_dport;
7466 		action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
7467 		if (action == PF_DROP)
7468 			goto done;
7469 		action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
7470 		    &reason);
7471 		if (action == PF_PASS) {
7472 			if (V_pfsync_update_state_ptr != NULL)
7473 				V_pfsync_update_state_ptr(s);
7474 			r = s->rule.ptr;
7475 			a = s->anchor.ptr;
7476 			log = s->log;
7477 		} else if (s == NULL)
7478 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7479 			    &a, &ruleset, inp);
7480 		break;
7481 	}
7482 
7483 	case IPPROTO_UDP: {
7484 		if (!pf_pull_hdr(m, off, &pd.hdr.udp, sizeof(pd.hdr.udp),
7485 		    &action, &reason, AF_INET6)) {
7486 			log = action != PF_PASS;
7487 			goto done;
7488 		}
7489 		pd.sport = &pd.hdr.udp.uh_sport;
7490 		pd.dport = &pd.hdr.udp.uh_dport;
7491 		if (pd.hdr.udp.uh_dport == 0 ||
7492 		    ntohs(pd.hdr.udp.uh_ulen) > m->m_pkthdr.len - off ||
7493 		    ntohs(pd.hdr.udp.uh_ulen) < sizeof(struct udphdr)) {
7494 			action = PF_DROP;
7495 			REASON_SET(&reason, PFRES_SHORT);
7496 			goto done;
7497 		}
7498 		action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
7499 		if (action == PF_PASS) {
7500 			if (V_pfsync_update_state_ptr != NULL)
7501 				V_pfsync_update_state_ptr(s);
7502 			r = s->rule.ptr;
7503 			a = s->anchor.ptr;
7504 			log = s->log;
7505 		} else if (s == NULL)
7506 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7507 			    &a, &ruleset, inp);
7508 		break;
7509 	}
7510 
7511 	case IPPROTO_ICMP: {
7512 		action = PF_DROP;
7513 		DPFPRINTF(PF_DEBUG_MISC,
7514 		    ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
7515 		goto done;
7516 	}
7517 
7518 	case IPPROTO_ICMPV6: {
7519 		if (!pf_pull_hdr(m, off, &pd.hdr.icmp6, sizeof(pd.hdr.icmp6),
7520 		    &action, &reason, AF_INET6)) {
7521 			log = action != PF_PASS;
7522 			goto done;
7523 		}
7524 		action = pf_test_state_icmp(&s, dir, kif,
7525 		    m, off, h, &pd, &reason);
7526 		if (action == PF_PASS) {
7527 			if (V_pfsync_update_state_ptr != NULL)
7528 				V_pfsync_update_state_ptr(s);
7529 			r = s->rule.ptr;
7530 			a = s->anchor.ptr;
7531 			log = s->log;
7532 		} else if (s == NULL)
7533 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7534 			    &a, &ruleset, inp);
7535 		break;
7536 	}
7537 
7538 	default:
7539 		action = pf_test_state_other(&s, dir, kif, m, &pd);
7540 		if (action == PF_PASS) {
7541 			if (V_pfsync_update_state_ptr != NULL)
7542 				V_pfsync_update_state_ptr(s);
7543 			r = s->rule.ptr;
7544 			a = s->anchor.ptr;
7545 			log = s->log;
7546 		} else if (s == NULL)
7547 			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
7548 			    &a, &ruleset, inp);
7549 		break;
7550 	}
7551 
7552 done:
7553 	PF_RULES_RUNLOCK();
7554 	if (n != m) {
7555 		m_freem(n);
7556 		n = NULL;
7557 	}
7558 
7559 	/* handle dangerous IPv6 extension headers. */
7560 	if (action == PF_PASS && rh_cnt &&
7561 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
7562 		action = PF_DROP;
7563 		REASON_SET(&reason, PFRES_IPOPTIONS);
7564 		log = r->log;
7565 		DPFPRINTF(PF_DEBUG_MISC,
7566 		    ("pf: dropping packet with dangerous v6 headers\n"));
7567 	}
7568 
7569 	if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
7570 		action = PF_DROP;
7571 		REASON_SET(&reason, PFRES_MEMORY);
7572 	}
7573 	if (r->rtableid >= 0)
7574 		M_SETFIB(m, r->rtableid);
7575 
7576 	if (r->scrub_flags & PFSTATE_SETPRIO) {
7577 		if (pd.tos & IPTOS_LOWDELAY)
7578 			pqid = 1;
7579 		if (vlan_set_pcp(m, r->set_prio[pqid])) {
7580 			action = PF_DROP;
7581 			REASON_SET(&reason, PFRES_MEMORY);
7582 			log = 1;
7583 			DPFPRINTF(PF_DEBUG_MISC,
7584 			    ("pf: failed to allocate 802.1q mtag\n"));
7585 		}
7586 	}
7587 
7588 #ifdef ALTQ
7589 	if (s && s->qid) {
7590 		pd.act.pqid = s->pqid;
7591 		pd.act.qid = s->qid;
7592 	} else if (r->qid) {
7593 		pd.act.pqid = r->pqid;
7594 		pd.act.qid = r->qid;
7595 	}
7596 	if (action == PF_PASS && pd.act.qid) {
7597 		if (pd.pf_mtag == NULL &&
7598 		    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
7599 			action = PF_DROP;
7600 			REASON_SET(&reason, PFRES_MEMORY);
7601 		} else {
7602 			if (s != NULL)
7603 				pd.pf_mtag->qid_hash = pf_state_hash(s);
7604 			if (pd.tos & IPTOS_LOWDELAY)
7605 				pd.pf_mtag->qid = pd.act.pqid;
7606 			else
7607 				pd.pf_mtag->qid = pd.act.qid;
7608 			/* Add hints for ecn. */
7609 			pd.pf_mtag->hdr = h;
7610 		}
7611 	}
7612 #endif /* ALTQ */
7613 
7614 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
7615 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
7616 	    (s->nat_rule.ptr->action == PF_RDR ||
7617 	    s->nat_rule.ptr->action == PF_BINAT) &&
7618 	    IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
7619 		m->m_flags |= M_SKIP_FIREWALL;
7620 
7621 	/* XXX: Anybody working on it?! */
7622 	if (r->divert.port)
7623 		printf("pf: divert(9) is not supported for IPv6\n");
7624 
7625 	if (log) {
7626 		struct pf_krule *lr;
7627 
7628 		if (s != NULL && s->nat_rule.ptr != NULL &&
7629 		    s->nat_rule.ptr->log & PF_LOG_ALL)
7630 			lr = s->nat_rule.ptr;
7631 		else
7632 			lr = r;
7633 		PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
7634 		    &pd, (s == NULL));
7635 	}
7636 
7637 	pf_counter_u64_critical_enter();
7638 	pf_counter_u64_add_protected(&kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS],
7639 	    pd.tot_len);
7640 	pf_counter_u64_add_protected(&kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS],
7641 	    1);
7642 
7643 	if (action == PF_PASS || r->action == PF_DROP) {
7644 		dirndx = (dir == PF_OUT);
7645 		pf_counter_u64_add_protected(&r->packets[dirndx], 1);
7646 		pf_counter_u64_add_protected(&r->bytes[dirndx], pd.tot_len);
7647 		if (a != NULL) {
7648 			pf_counter_u64_add_protected(&a->packets[dirndx], 1);
7649 			pf_counter_u64_add_protected(&a->bytes[dirndx], pd.tot_len);
7650 		}
7651 		if (s != NULL) {
7652 			if (s->nat_rule.ptr != NULL) {
7653 				pf_counter_u64_add_protected(&s->nat_rule.ptr->packets[dirndx],
7654 				    1);
7655 				pf_counter_u64_add_protected(&s->nat_rule.ptr->bytes[dirndx],
7656 				    pd.tot_len);
7657 			}
7658 			if (s->src_node != NULL) {
7659 				counter_u64_add(s->src_node->packets[dirndx],
7660 				    1);
7661 				counter_u64_add(s->src_node->bytes[dirndx],
7662 				    pd.tot_len);
7663 			}
7664 			if (s->nat_src_node != NULL) {
7665 				counter_u64_add(s->nat_src_node->packets[dirndx],
7666 				    1);
7667 				counter_u64_add(s->nat_src_node->bytes[dirndx],
7668 				    pd.tot_len);
7669 			}
7670 			dirndx = (dir == s->direction) ? 0 : 1;
7671 			s->packets[dirndx]++;
7672 			s->bytes[dirndx] += pd.tot_len;
7673 		}
7674 		tr = r;
7675 		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
7676 		if (nr != NULL && r == &V_pf_default_rule)
7677 			tr = nr;
7678 		if (tr->src.addr.type == PF_ADDR_TABLE)
7679 			pfr_update_stats(tr->src.addr.p.tbl,
7680 			    (s == NULL) ? pd.src :
7681 			    &s->key[(s->direction == PF_IN)]->addr[0],
7682 			    pd.af, pd.tot_len, dir == PF_OUT,
7683 			    r->action == PF_PASS, tr->src.neg);
7684 		if (tr->dst.addr.type == PF_ADDR_TABLE)
7685 			pfr_update_stats(tr->dst.addr.p.tbl,
7686 			    (s == NULL) ? pd.dst :
7687 			    &s->key[(s->direction == PF_IN)]->addr[1],
7688 			    pd.af, pd.tot_len, dir == PF_OUT,
7689 			    r->action == PF_PASS, tr->dst.neg);
7690 	}
7691 	pf_counter_u64_critical_exit();
7692 
7693 	switch (action) {
7694 	case PF_SYNPROXY_DROP:
7695 		m_freem(*m0);
7696 	case PF_DEFER:
7697 		*m0 = NULL;
7698 		action = PF_PASS;
7699 		break;
7700 	case PF_DROP:
7701 		m_freem(*m0);
7702 		*m0 = NULL;
7703 		break;
7704 	default:
7705 		/* pf_route6() returns unlocked. */
7706 		if (r->rt) {
7707 			pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
7708 			return (action);
7709 		}
7710 		/* Dummynet processing. */
7711 		if (s && (s->dnpipe || s->dnrpipe)) {
7712 			pd.act.dnpipe = s->dnpipe;
7713 			pd.act.dnrpipe = s->dnrpipe;
7714 			pd.act.flags = s->state_flags;
7715 		} else {
7716 			pd.act.dnpipe = r->dnpipe;
7717 			pd.act.dnrpipe = r->dnrpipe;
7718 			pd.act.flags = r->free_flags;
7719 		}
7720 		if (pd.act.dnpipe || pd.act.dnrpipe) {
7721 			struct ip_fw_args dnflow;
7722 
7723 			if (ip_dn_io_ptr == NULL) {
7724 				m_freem(*m0);
7725 				*m0 = NULL;
7726 				action = PF_DROP;
7727 				REASON_SET(&reason, PFRES_MEMORY);
7728 				break;
7729 			}
7730 
7731 			if (pd.pf_mtag == NULL &&
7732 					((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
7733 				m_freem(*m0);
7734 				*m0 = NULL;
7735 				action = PF_DROP;
7736 				REASON_SET(&reason, PFRES_MEMORY);
7737 				break;
7738 			}
7739 
7740 			if (pf_pdesc_to_dnflow(dir, &pd, r, s, &dnflow)) {
7741 				pd.pf_mtag->flags |= PF_TAG_DUMMYNET;
7742 				ip_dn_io_ptr(m0, &dnflow);
7743 				if (*m0 == NULL)
7744 					action = PF_DROP;
7745 			}
7746 		}
7747 		break;
7748 	}
7749 
7750 	if (s)
7751 		PF_STATE_UNLOCK(s);
7752 
7753 	/* If reassembled packet passed, create new fragments. */
7754 	if (action == PF_PASS && *m0 && (pflags & PFIL_FWD) &&
7755 	    (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
7756 		action = pf_refragment6(ifp, m0, mtag);
7757 
7758 	SDT_PROBE4(pf, ip, test6, done, action, reason, r, s);
7759 
7760 	return (action);
7761 }
7762 #endif /* INET6 */
7763