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