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