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