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