xref: /freebsd/sys/netpfil/pf/pf.c (revision 357378bbdedf24ce2b90e9bd831af4a9db3ec70a)
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);
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 	/* Track state. */
6143 	if (pd->sctp_flags & PFDESC_SCTP_INIT) {
6144 		if (src->state < SCTP_COOKIE_WAIT) {
6145 			pf_set_protostate(*state, psrc, SCTP_COOKIE_WAIT);
6146 			(*state)->timeout = PFTM_SCTP_OPENING;
6147 		}
6148 	}
6149 	if (pd->sctp_flags & PFDESC_SCTP_INIT_ACK) {
6150 		MPASS(dst->scrub != NULL);
6151 		if (dst->scrub->pfss_v_tag == 0)
6152 			dst->scrub->pfss_v_tag = pd->sctp_initiate_tag;
6153 	}
6154 
6155 	if (pd->sctp_flags & (PFDESC_SCTP_COOKIE | PFDESC_SCTP_HEARTBEAT_ACK)) {
6156 		if (src->state < SCTP_ESTABLISHED) {
6157 			pf_set_protostate(*state, psrc, SCTP_ESTABLISHED);
6158 			(*state)->timeout = PFTM_SCTP_ESTABLISHED;
6159 		}
6160 	}
6161 	if (pd->sctp_flags & (PFDESC_SCTP_SHUTDOWN | PFDESC_SCTP_ABORT |
6162 	    PFDESC_SCTP_SHUTDOWN_COMPLETE)) {
6163 		if (src->state < SCTP_SHUTDOWN_PENDING) {
6164 			pf_set_protostate(*state, psrc, SCTP_SHUTDOWN_PENDING);
6165 			(*state)->timeout = PFTM_SCTP_CLOSING;
6166 		}
6167 	}
6168 	if (pd->sctp_flags & (PFDESC_SCTP_SHUTDOWN_COMPLETE)) {
6169 		pf_set_protostate(*state, psrc, SCTP_CLOSED);
6170 		(*state)->timeout = PFTM_SCTP_CLOSED;
6171 	}
6172 
6173 	if (src->scrub != NULL) {
6174 		if (src->scrub->pfss_v_tag == 0) {
6175 			src->scrub->pfss_v_tag = pd->hdr.sctp.v_tag;
6176 		} else  if (src->scrub->pfss_v_tag != pd->hdr.sctp.v_tag)
6177 			return (PF_DROP);
6178 	}
6179 
6180 	(*state)->expire = pf_get_uptime();
6181 
6182 	/* translate source/destination address, if necessary */
6183 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
6184 		uint16_t checksum = 0;
6185 		struct pf_state_key *nk = (*state)->key[pd->didx];
6186 
6187 		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
6188 		    nk->port[pd->sidx] != pd->hdr.sctp.src_port) {
6189 			pf_change_ap(m, pd->src, &pd->hdr.sctp.src_port,
6190 			    pd->ip_sum, &checksum, &nk->addr[pd->sidx],
6191 			    nk->port[pd->sidx], 1, pd->af);
6192 		}
6193 
6194 		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
6195 		    nk->port[pd->didx] != pd->hdr.sctp.dest_port) {
6196 			pf_change_ap(m, pd->dst, &pd->hdr.sctp.dest_port,
6197 			    pd->ip_sum, &checksum, &nk->addr[pd->didx],
6198 			    nk->port[pd->didx], 1, pd->af);
6199 		}
6200 	}
6201 
6202 	return (PF_PASS);
6203 }
6204 
6205 static void
6206 pf_sctp_multihome_detach_addr(const struct pf_kstate *s)
6207 {
6208 	struct pf_sctp_endpoint key;
6209 	struct pf_sctp_endpoint *ep;
6210 	struct pf_state_key *sks = s->key[PF_SK_STACK];
6211 	struct pf_sctp_source *i, *tmp;
6212 
6213 	if (sks == NULL || sks->proto != IPPROTO_SCTP || s->dst.scrub == NULL)
6214 		return;
6215 
6216 	PF_SCTP_ENDPOINTS_LOCK();
6217 
6218 	key.v_tag = s->dst.scrub->pfss_v_tag;
6219 	ep  = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
6220 	if (ep != NULL) {
6221 		TAILQ_FOREACH_SAFE(i, &ep->sources, entry, tmp) {
6222 			if (pf_addr_cmp(&i->addr,
6223 			    &s->key[PF_SK_WIRE]->addr[s->direction == PF_OUT],
6224 			    s->key[PF_SK_WIRE]->af) == 0) {
6225 				SDT_PROBE3(pf, sctp, multihome, remove,
6226 				    key.v_tag, s, i);
6227 				TAILQ_REMOVE(&ep->sources, i, entry);
6228 				free(i, M_PFTEMP);
6229 				break;
6230 			}
6231 		}
6232 
6233 		if (TAILQ_EMPTY(&ep->sources)) {
6234 			RB_REMOVE(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
6235 			free(ep, M_PFTEMP);
6236 		}
6237 	}
6238 
6239 	/* Other direction. */
6240 	key.v_tag = s->src.scrub->pfss_v_tag;
6241 	ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
6242 	if (ep != NULL) {
6243 		TAILQ_FOREACH_SAFE(i, &ep->sources, entry, tmp) {
6244 			if (pf_addr_cmp(&i->addr,
6245 			    &s->key[PF_SK_WIRE]->addr[s->direction == PF_IN],
6246 			    s->key[PF_SK_WIRE]->af) == 0) {
6247 				SDT_PROBE3(pf, sctp, multihome, remove,
6248 				    key.v_tag, s, i);
6249 				TAILQ_REMOVE(&ep->sources, i, entry);
6250 				free(i, M_PFTEMP);
6251 				break;
6252 			}
6253 		}
6254 
6255 		if (TAILQ_EMPTY(&ep->sources)) {
6256 			RB_REMOVE(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
6257 			free(ep, M_PFTEMP);
6258 		}
6259 	}
6260 
6261 	PF_SCTP_ENDPOINTS_UNLOCK();
6262 }
6263 
6264 static void
6265 pf_sctp_multihome_add_addr(struct pf_pdesc *pd, struct pf_addr *a, uint32_t v_tag)
6266 {
6267 	struct pf_sctp_endpoint key = {
6268 		.v_tag = v_tag,
6269 	};
6270 	struct pf_sctp_source *i;
6271 	struct pf_sctp_endpoint *ep;
6272 
6273 	PF_SCTP_ENDPOINTS_LOCK();
6274 
6275 	ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
6276 	if (ep == NULL) {
6277 		ep = malloc(sizeof(struct pf_sctp_endpoint),
6278 		    M_PFTEMP, M_NOWAIT);
6279 		if (ep == NULL) {
6280 			PF_SCTP_ENDPOINTS_UNLOCK();
6281 			return;
6282 		}
6283 
6284 		ep->v_tag = v_tag;
6285 		TAILQ_INIT(&ep->sources);
6286 		RB_INSERT(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
6287 	}
6288 
6289 	/* Avoid inserting duplicates. */
6290 	TAILQ_FOREACH(i, &ep->sources, entry) {
6291 		if (pf_addr_cmp(&i->addr, a, pd->af) == 0) {
6292 			PF_SCTP_ENDPOINTS_UNLOCK();
6293 			return;
6294 		}
6295 	}
6296 
6297 	i = malloc(sizeof(*i), M_PFTEMP, M_NOWAIT);
6298 	if (i == NULL) {
6299 		PF_SCTP_ENDPOINTS_UNLOCK();
6300 		return;
6301 	}
6302 
6303 	i->af = pd->af;
6304 	memcpy(&i->addr, a, sizeof(*a));
6305 	TAILQ_INSERT_TAIL(&ep->sources, i, entry);
6306 	SDT_PROBE2(pf, sctp, multihome, add, v_tag, i);
6307 
6308 	PF_SCTP_ENDPOINTS_UNLOCK();
6309 }
6310 
6311 static void
6312 pf_sctp_multihome_delayed(struct pf_pdesc *pd, int off, struct pfi_kkif *kif,
6313     struct pf_kstate *s, int action)
6314 {
6315 	struct pf_sctp_multihome_job	*j, *tmp;
6316 	struct pf_sctp_source		*i;
6317 	int			 ret __unused;
6318 	struct pf_kstate	*sm = NULL;
6319 	struct pf_krule		*ra = NULL;
6320 	struct pf_krule		*r = &V_pf_default_rule;
6321 	struct pf_kruleset	*rs = NULL;
6322 	bool do_extra = true;
6323 
6324 	PF_RULES_RLOCK_TRACKER;
6325 
6326 again:
6327 	TAILQ_FOREACH_SAFE(j, &pd->sctp_multihome_jobs, next, tmp) {
6328 		if (s == NULL || action != PF_PASS)
6329 			goto free;
6330 
6331 		/* Confirm we don't recurse here. */
6332 		MPASS(! (pd->sctp_flags & PFDESC_SCTP_ADD_IP));
6333 
6334 		switch (j->op) {
6335 		case  SCTP_ADD_IP_ADDRESS: {
6336 			uint32_t v_tag = pd->sctp_initiate_tag;
6337 
6338 			if (v_tag == 0) {
6339 				if (s->direction == pd->dir)
6340 					v_tag = s->src.scrub->pfss_v_tag;
6341 				else
6342 					v_tag = s->dst.scrub->pfss_v_tag;
6343 			}
6344 
6345 			/*
6346 			 * Avoid duplicating states. We'll already have
6347 			 * created a state based on the source address of
6348 			 * the packet, but SCTP endpoints may also list this
6349 			 * address again in the INIT(_ACK) parameters.
6350 			 */
6351 			if (pf_addr_cmp(&j->src, pd->src, pd->af) == 0) {
6352 				break;
6353 			}
6354 
6355 			j->pd.sctp_flags |= PFDESC_SCTP_ADD_IP;
6356 			PF_RULES_RLOCK();
6357 			sm = NULL;
6358 			/*
6359 			 * New connections need to be floating, because
6360 			 * we cannot know what interfaces it will use.
6361 			 * That's why we pass V_pfi_all rather than kif.
6362 			 */
6363 			ret = pf_test_rule(&r, &sm, V_pfi_all,
6364 			    j->m, off, &j->pd, &ra, &rs, NULL);
6365 			PF_RULES_RUNLOCK();
6366 			SDT_PROBE4(pf, sctp, multihome, test, kif, r, j->m, ret);
6367 			if (ret != PF_DROP && sm != NULL) {
6368 				/* Inherit v_tag values. */
6369 				if (sm->direction == s->direction) {
6370 					sm->src.scrub->pfss_v_tag = s->src.scrub->pfss_v_tag;
6371 					sm->dst.scrub->pfss_v_tag = s->dst.scrub->pfss_v_tag;
6372 				} else {
6373 					sm->src.scrub->pfss_v_tag = s->dst.scrub->pfss_v_tag;
6374 					sm->dst.scrub->pfss_v_tag = s->src.scrub->pfss_v_tag;
6375 				}
6376 				PF_STATE_UNLOCK(sm);
6377 			} else {
6378 				/* If we try duplicate inserts? */
6379 				break;
6380 			}
6381 
6382 			/* Only add the address if we've actually allowed the state. */
6383 			pf_sctp_multihome_add_addr(pd, &j->src, v_tag);
6384 
6385 			if (! do_extra) {
6386 				break;
6387 			}
6388 			/*
6389 			 * We need to do this for each of our source addresses.
6390 			 * Find those based on the verification tag.
6391 			 */
6392 			struct pf_sctp_endpoint key = {
6393 				.v_tag = pd->hdr.sctp.v_tag,
6394 			};
6395 			struct pf_sctp_endpoint *ep;
6396 
6397 			PF_SCTP_ENDPOINTS_LOCK();
6398 			ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
6399 			if (ep == NULL) {
6400 				PF_SCTP_ENDPOINTS_UNLOCK();
6401 				break;
6402 			}
6403 			MPASS(ep != NULL);
6404 
6405 			TAILQ_FOREACH(i, &ep->sources, entry) {
6406 				struct pf_sctp_multihome_job *nj;
6407 
6408 				/* SCTP can intermingle IPv4 and IPv6. */
6409 				if (i->af != pd->af)
6410 					continue;
6411 
6412 				nj = malloc(sizeof(*nj), M_PFTEMP, M_NOWAIT | M_ZERO);
6413 				if (! nj) {
6414 					continue;
6415 				}
6416 				memcpy(&nj->pd, &j->pd, sizeof(j->pd));
6417 				memcpy(&nj->src, &j->src, sizeof(nj->src));
6418 				nj->pd.src = &nj->src;
6419 				// New destination address!
6420 				memcpy(&nj->dst, &i->addr, sizeof(nj->dst));
6421 				nj->pd.dst = &nj->dst;
6422 				nj->m = j->m;
6423 				nj->op = j->op;
6424 
6425 				TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, nj, next);
6426 			}
6427 			PF_SCTP_ENDPOINTS_UNLOCK();
6428 
6429 			break;
6430 		}
6431 		case SCTP_DEL_IP_ADDRESS: {
6432 			struct pf_state_key_cmp key;
6433 			uint8_t psrc;
6434 
6435 			bzero(&key, sizeof(key));
6436 			key.af = j->pd.af;
6437 			key.proto = IPPROTO_SCTP;
6438 			if (j->pd.dir == PF_IN)	{	/* wire side, straight */
6439 				PF_ACPY(&key.addr[0], j->pd.src, key.af);
6440 				PF_ACPY(&key.addr[1], j->pd.dst, key.af);
6441 				key.port[0] = j->pd.hdr.sctp.src_port;
6442 				key.port[1] = j->pd.hdr.sctp.dest_port;
6443 			} else {			/* stack side, reverse */
6444 				PF_ACPY(&key.addr[1], j->pd.src, key.af);
6445 				PF_ACPY(&key.addr[0], j->pd.dst, key.af);
6446 				key.port[1] = j->pd.hdr.sctp.src_port;
6447 				key.port[0] = j->pd.hdr.sctp.dest_port;
6448 			}
6449 
6450 			sm = pf_find_state(kif, &key, j->pd.dir);
6451 			if (sm != NULL) {
6452 				PF_STATE_LOCK_ASSERT(sm);
6453 				if (j->pd.dir == sm->direction) {
6454 					psrc = PF_PEER_SRC;
6455 				} else {
6456 					psrc = PF_PEER_DST;
6457 				}
6458 				pf_set_protostate(sm, psrc, SCTP_SHUTDOWN_PENDING);
6459 				sm->timeout = PFTM_SCTP_CLOSING;
6460 				PF_STATE_UNLOCK(sm);
6461 			}
6462 			break;
6463 		default:
6464 			panic("Unknown op %#x", j->op);
6465 		}
6466 	}
6467 
6468 	free:
6469 		TAILQ_REMOVE(&pd->sctp_multihome_jobs, j, next);
6470 		free(j, M_PFTEMP);
6471 	}
6472 
6473 	/* We may have inserted extra work while processing the list. */
6474 	if (! TAILQ_EMPTY(&pd->sctp_multihome_jobs)) {
6475 		do_extra = false;
6476 		goto again;
6477 	}
6478 }
6479 
6480 static int
6481 pf_multihome_scan(struct mbuf *m, int start, int len, struct pf_pdesc *pd,
6482     struct pfi_kkif *kif, int op)
6483 {
6484 	int			 off = 0;
6485 	struct pf_sctp_multihome_job	*job;
6486 
6487 	while (off < len) {
6488 		struct sctp_paramhdr h;
6489 
6490 		if (!pf_pull_hdr(m, start + off, &h, sizeof(h), NULL, NULL,
6491 		    pd->af))
6492 			return (PF_DROP);
6493 
6494 		/* Parameters are at least 4 bytes. */
6495 		if (ntohs(h.param_length) < 4)
6496 			return (PF_DROP);
6497 
6498 		switch (ntohs(h.param_type)) {
6499 		case  SCTP_IPV4_ADDRESS: {
6500 			struct in_addr t;
6501 
6502 			if (ntohs(h.param_length) !=
6503 			    (sizeof(struct sctp_paramhdr) + sizeof(t)))
6504 				return (PF_DROP);
6505 
6506 			if (!pf_pull_hdr(m, start + off + sizeof(h), &t, sizeof(t),
6507 			    NULL, NULL, pd->af))
6508 				return (PF_DROP);
6509 
6510 			if (in_nullhost(t))
6511 				t.s_addr = pd->src->v4.s_addr;
6512 
6513 			/*
6514 			 * We hold the state lock (idhash) here, which means
6515 			 * that we can't acquire the keyhash, or we'll get a
6516 			 * LOR (and potentially double-lock things too). We also
6517 			 * can't release the state lock here, so instead we'll
6518 			 * enqueue this for async handling.
6519 			 * There's a relatively small race here, in that a
6520 			 * packet using the new addresses could arrive already,
6521 			 * but that's just though luck for it.
6522 			 */
6523 			job = malloc(sizeof(*job), M_PFTEMP, M_NOWAIT | M_ZERO);
6524 			if (! job)
6525 				return (PF_DROP);
6526 
6527 			memcpy(&job->pd, pd, sizeof(*pd));
6528 
6529 			// New source address!
6530 			memcpy(&job->src, &t, sizeof(t));
6531 			job->pd.src = &job->src;
6532 			memcpy(&job->dst, pd->dst, sizeof(job->dst));
6533 			job->pd.dst = &job->dst;
6534 			job->m = m;
6535 			job->op = op;
6536 
6537 			TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, job, next);
6538 			break;
6539 		}
6540 #ifdef INET6
6541 		case SCTP_IPV6_ADDRESS: {
6542 			struct in6_addr t;
6543 
6544 			if (ntohs(h.param_length) !=
6545 			    (sizeof(struct sctp_paramhdr) + sizeof(t)))
6546 				return (PF_DROP);
6547 
6548 			if (!pf_pull_hdr(m, start + off + sizeof(h), &t, sizeof(t),
6549 			    NULL, NULL, pd->af))
6550 				return (PF_DROP);
6551 			if (memcmp(&t, &pd->src->v6, sizeof(t)) == 0)
6552 				break;
6553 			if (memcmp(&t, &in6addr_any, sizeof(t)) == 0)
6554 				memcpy(&t, &pd->src->v6, sizeof(t));
6555 
6556 			job = malloc(sizeof(*job), M_PFTEMP, M_NOWAIT | M_ZERO);
6557 			if (! job)
6558 				return (PF_DROP);
6559 
6560 			memcpy(&job->pd, pd, sizeof(*pd));
6561 			memcpy(&job->src, &t, sizeof(t));
6562 			job->pd.src = &job->src;
6563 			memcpy(&job->dst, pd->dst, sizeof(job->dst));
6564 			job->pd.dst = &job->dst;
6565 			job->m = m;
6566 			job->op = op;
6567 
6568 			TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, job, next);
6569 			break;
6570 		}
6571 #endif
6572 		case SCTP_ADD_IP_ADDRESS: {
6573 			int ret;
6574 			struct sctp_asconf_paramhdr ah;
6575 
6576 			if (!pf_pull_hdr(m, start + off, &ah, sizeof(ah),
6577 			    NULL, NULL, pd->af))
6578 				return (PF_DROP);
6579 
6580 			ret = pf_multihome_scan(m, start + off + sizeof(ah),
6581 			    ntohs(ah.ph.param_length) - sizeof(ah), pd, kif,
6582 			    SCTP_ADD_IP_ADDRESS);
6583 			if (ret != PF_PASS)
6584 				return (ret);
6585 			break;
6586 		}
6587 		case SCTP_DEL_IP_ADDRESS: {
6588 			int ret;
6589 			struct sctp_asconf_paramhdr ah;
6590 
6591 			if (!pf_pull_hdr(m, start + off, &ah, sizeof(ah),
6592 			    NULL, NULL, pd->af))
6593 				return (PF_DROP);
6594 			ret = pf_multihome_scan(m, start + off + sizeof(ah),
6595 			    ntohs(ah.ph.param_length) - sizeof(ah), pd, kif,
6596 			    SCTP_DEL_IP_ADDRESS);
6597 			if (ret != PF_PASS)
6598 				return (ret);
6599 			break;
6600 		}
6601 		default:
6602 			break;
6603 		}
6604 
6605 		off += roundup(ntohs(h.param_length), 4);
6606 	}
6607 
6608 	return (PF_PASS);
6609 }
6610 int
6611 pf_multihome_scan_init(struct mbuf *m, int start, int len, struct pf_pdesc *pd,
6612     struct pfi_kkif *kif)
6613 {
6614 	start += sizeof(struct sctp_init_chunk);
6615 	len -= sizeof(struct sctp_init_chunk);
6616 
6617 	return (pf_multihome_scan(m, start, len, pd, kif, SCTP_ADD_IP_ADDRESS));
6618 }
6619 
6620 int
6621 pf_multihome_scan_asconf(struct mbuf *m, int start, int len,
6622     struct pf_pdesc *pd, struct pfi_kkif *kif)
6623 {
6624 	start += sizeof(struct sctp_asconf_chunk);
6625 	len -= sizeof(struct sctp_asconf_chunk);
6626 
6627 	return (pf_multihome_scan(m, start, len, pd, kif, SCTP_ADD_IP_ADDRESS));
6628 }
6629 
6630 int
6631 pf_icmp_state_lookup(struct pf_state_key_cmp *key, struct pf_pdesc *pd,
6632     struct pf_kstate **state, struct mbuf *m, int direction, struct pfi_kkif *kif,
6633     u_int16_t icmpid, u_int16_t type, int icmp_dir, int *iidx, int multi)
6634 {
6635 	key->af = pd->af;
6636 	key->proto = pd->proto;
6637 	if (icmp_dir == PF_IN) {
6638 		*iidx = pd->sidx;
6639 		key->port[pd->sidx] = icmpid;
6640 		key->port[pd->didx] = type;
6641 	} else {
6642 		*iidx = pd->didx;
6643 		key->port[pd->sidx] = type;
6644 		key->port[pd->didx] = icmpid;
6645 	}
6646 	if (pd->af == AF_INET6 && multi != PF_ICMP_MULTI_NONE) {
6647 		switch (multi) {
6648 		case PF_ICMP_MULTI_SOLICITED:
6649 			key->addr[pd->sidx].addr32[0] = IPV6_ADDR_INT32_MLL;
6650 			key->addr[pd->sidx].addr32[1] = 0;
6651 			key->addr[pd->sidx].addr32[2] = IPV6_ADDR_INT32_ONE;
6652 			key->addr[pd->sidx].addr32[3] = pd->src->addr32[3];
6653 			key->addr[pd->sidx].addr8[12] = 0xff;
6654 			break;
6655 		case PF_ICMP_MULTI_LINK:
6656 			key->addr[pd->sidx].addr32[0] = IPV6_ADDR_INT32_MLL;
6657 			key->addr[pd->sidx].addr32[1] = 0;
6658 			key->addr[pd->sidx].addr32[2] = 0;
6659 			key->addr[pd->sidx].addr32[3] = IPV6_ADDR_INT32_ONE;
6660 			break;
6661 		}
6662 	} else
6663 		PF_ACPY(&key->addr[pd->sidx], pd->src, key->af);
6664 	PF_ACPY(&key->addr[pd->didx], pd->dst, key->af);
6665 
6666 	STATE_LOOKUP(kif, key, *state, pd);
6667 
6668 	/* Is this ICMP message flowing in right direction? */
6669 	if ((*state)->rule.ptr->type &&
6670 	    (((*state)->direction == direction) ?
6671 	    PF_IN : PF_OUT) != icmp_dir) {
6672 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
6673 			printf("pf: icmp type %d in wrong direction (%d): ",
6674 			    icmp_dir, pd->dir);
6675 			pf_print_state(*state);
6676 			printf("\n");
6677 		}
6678 		return (PF_DROP);
6679 	}
6680 	return (-1);
6681 }
6682 
6683 static int
6684 pf_test_state_icmp(struct pf_kstate **state, struct pfi_kkif *kif,
6685     struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
6686 {
6687 	struct pf_addr  *saddr = pd->src, *daddr = pd->dst;
6688 	u_int16_t	*icmpsum, virtual_id, virtual_type;
6689 	u_int8_t	 icmptype, icmpcode;
6690 	int		 icmp_dir, iidx, ret, multi;
6691 	struct pf_state_key_cmp key;
6692 #ifdef INET
6693 	u_int16_t	 icmpid;
6694 #endif
6695 
6696 	MPASS(*state == NULL);
6697 
6698 	bzero(&key, sizeof(key));
6699 	switch (pd->proto) {
6700 #ifdef INET
6701 	case IPPROTO_ICMP:
6702 		icmptype = pd->hdr.icmp.icmp_type;
6703 		icmpcode = pd->hdr.icmp.icmp_code;
6704 		icmpid = pd->hdr.icmp.icmp_id;
6705 		icmpsum = &pd->hdr.icmp.icmp_cksum;
6706 		break;
6707 #endif /* INET */
6708 #ifdef INET6
6709 	case IPPROTO_ICMPV6:
6710 		icmptype = pd->hdr.icmp6.icmp6_type;
6711 		icmpcode = pd->hdr.icmp6.icmp6_code;
6712 #ifdef INET
6713 		icmpid = pd->hdr.icmp6.icmp6_id;
6714 #endif
6715 		icmpsum = &pd->hdr.icmp6.icmp6_cksum;
6716 		break;
6717 #endif /* INET6 */
6718 	}
6719 
6720 	if (pf_icmp_mapping(pd, icmptype, &icmp_dir, &multi,
6721 	    &virtual_id, &virtual_type) == 0) {
6722 		/*
6723 		 * ICMP query/reply message not related to a TCP/UDP packet.
6724 		 * Search for an ICMP state.
6725 		 */
6726 		ret = pf_icmp_state_lookup(&key, pd, state, m, pd->dir,
6727 		    kif, virtual_id, virtual_type, icmp_dir, &iidx,
6728 		    PF_ICMP_MULTI_NONE);
6729 		if (ret >= 0) {
6730 			if (ret == PF_DROP && pd->af == AF_INET6 &&
6731 			    icmp_dir == PF_OUT) {
6732 				if (*state != NULL)
6733 					PF_STATE_UNLOCK((*state));
6734 				ret = pf_icmp_state_lookup(&key, pd, state, m,
6735 				    pd->dir, kif, virtual_id, virtual_type,
6736 				    icmp_dir, &iidx, multi);
6737 				if (ret >= 0)
6738 					return (ret);
6739 			} else
6740 				return (ret);
6741 		}
6742 
6743 		(*state)->expire = pf_get_uptime();
6744 		(*state)->timeout = PFTM_ICMP_ERROR_REPLY;
6745 
6746 		/* translate source/destination address, if necessary */
6747 		if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
6748 			struct pf_state_key *nk = (*state)->key[pd->didx];
6749 
6750 			switch (pd->af) {
6751 #ifdef INET
6752 			case AF_INET:
6753 				if (PF_ANEQ(pd->src,
6754 				    &nk->addr[pd->sidx], AF_INET))
6755 					pf_change_a(&saddr->v4.s_addr,
6756 					    pd->ip_sum,
6757 					    nk->addr[pd->sidx].v4.s_addr, 0);
6758 
6759 				if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
6760 				    AF_INET))
6761 					pf_change_a(&daddr->v4.s_addr,
6762 					    pd->ip_sum,
6763 					    nk->addr[pd->didx].v4.s_addr, 0);
6764 
6765 				if (nk->port[iidx] !=
6766 				    pd->hdr.icmp.icmp_id) {
6767 					pd->hdr.icmp.icmp_cksum =
6768 					    pf_cksum_fixup(
6769 					    pd->hdr.icmp.icmp_cksum, icmpid,
6770 					    nk->port[iidx], 0);
6771 					pd->hdr.icmp.icmp_id =
6772 					    nk->port[iidx];
6773 				}
6774 
6775 				m_copyback(m, off, ICMP_MINLEN,
6776 				    (caddr_t )&pd->hdr.icmp);
6777 				break;
6778 #endif /* INET */
6779 #ifdef INET6
6780 			case AF_INET6:
6781 				if (PF_ANEQ(pd->src,
6782 				    &nk->addr[pd->sidx], AF_INET6))
6783 					pf_change_a6(saddr,
6784 					    &pd->hdr.icmp6.icmp6_cksum,
6785 					    &nk->addr[pd->sidx], 0);
6786 
6787 				if (PF_ANEQ(pd->dst,
6788 				    &nk->addr[pd->didx], AF_INET6))
6789 					pf_change_a6(daddr,
6790 					    &pd->hdr.icmp6.icmp6_cksum,
6791 					    &nk->addr[pd->didx], 0);
6792 
6793 				m_copyback(m, off, sizeof(struct icmp6_hdr),
6794 				    (caddr_t )&pd->hdr.icmp6);
6795 				break;
6796 #endif /* INET6 */
6797 			}
6798 		}
6799 		return (PF_PASS);
6800 
6801 	} else {
6802 		/*
6803 		 * ICMP error message in response to a TCP/UDP packet.
6804 		 * Extract the inner TCP/UDP header and search for that state.
6805 		 */
6806 
6807 		struct pf_pdesc	pd2;
6808 		bzero(&pd2, sizeof pd2);
6809 #ifdef INET
6810 		struct ip	h2;
6811 #endif /* INET */
6812 #ifdef INET6
6813 		struct ip6_hdr	h2_6;
6814 		int		terminal = 0;
6815 #endif /* INET6 */
6816 		int		ipoff2 = 0;
6817 		int		off2 = 0;
6818 
6819 		pd2.af = pd->af;
6820 		/* Payload packet is from the opposite direction. */
6821 		pd2.sidx = (pd->dir == PF_IN) ? 1 : 0;
6822 		pd2.didx = (pd->dir == PF_IN) ? 0 : 1;
6823 		switch (pd->af) {
6824 #ifdef INET
6825 		case AF_INET:
6826 			/* offset of h2 in mbuf chain */
6827 			ipoff2 = off + ICMP_MINLEN;
6828 
6829 			if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
6830 			    NULL, reason, pd2.af)) {
6831 				DPFPRINTF(PF_DEBUG_MISC,
6832 				    ("pf: ICMP error message too short "
6833 				    "(ip)\n"));
6834 				return (PF_DROP);
6835 			}
6836 			/*
6837 			 * ICMP error messages don't refer to non-first
6838 			 * fragments
6839 			 */
6840 			if (h2.ip_off & htons(IP_OFFMASK)) {
6841 				REASON_SET(reason, PFRES_FRAG);
6842 				return (PF_DROP);
6843 			}
6844 
6845 			/* offset of protocol header that follows h2 */
6846 			off2 = ipoff2 + (h2.ip_hl << 2);
6847 
6848 			pd2.proto = h2.ip_p;
6849 			pd2.src = (struct pf_addr *)&h2.ip_src;
6850 			pd2.dst = (struct pf_addr *)&h2.ip_dst;
6851 			pd2.ip_sum = &h2.ip_sum;
6852 			break;
6853 #endif /* INET */
6854 #ifdef INET6
6855 		case AF_INET6:
6856 			ipoff2 = off + sizeof(struct icmp6_hdr);
6857 
6858 			if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
6859 			    NULL, reason, pd2.af)) {
6860 				DPFPRINTF(PF_DEBUG_MISC,
6861 				    ("pf: ICMP error message too short "
6862 				    "(ip6)\n"));
6863 				return (PF_DROP);
6864 			}
6865 			pd2.proto = h2_6.ip6_nxt;
6866 			pd2.src = (struct pf_addr *)&h2_6.ip6_src;
6867 			pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
6868 			pd2.ip_sum = NULL;
6869 			off2 = ipoff2 + sizeof(h2_6);
6870 			do {
6871 				switch (pd2.proto) {
6872 				case IPPROTO_FRAGMENT:
6873 					/*
6874 					 * ICMPv6 error messages for
6875 					 * non-first fragments
6876 					 */
6877 					REASON_SET(reason, PFRES_FRAG);
6878 					return (PF_DROP);
6879 				case IPPROTO_AH:
6880 				case IPPROTO_HOPOPTS:
6881 				case IPPROTO_ROUTING:
6882 				case IPPROTO_DSTOPTS: {
6883 					/* get next header and header length */
6884 					struct ip6_ext opt6;
6885 
6886 					if (!pf_pull_hdr(m, off2, &opt6,
6887 					    sizeof(opt6), NULL, reason,
6888 					    pd2.af)) {
6889 						DPFPRINTF(PF_DEBUG_MISC,
6890 						    ("pf: ICMPv6 short opt\n"));
6891 						return (PF_DROP);
6892 					}
6893 					if (pd2.proto == IPPROTO_AH)
6894 						off2 += (opt6.ip6e_len + 2) * 4;
6895 					else
6896 						off2 += (opt6.ip6e_len + 1) * 8;
6897 					pd2.proto = opt6.ip6e_nxt;
6898 					/* goto the next header */
6899 					break;
6900 				}
6901 				default:
6902 					terminal++;
6903 					break;
6904 				}
6905 			} while (!terminal);
6906 			break;
6907 #endif /* INET6 */
6908 		}
6909 
6910 		if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
6911 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
6912 				printf("pf: BAD ICMP %d:%d outer dst: ",
6913 				    icmptype, icmpcode);
6914 				pf_print_host(pd->src, 0, pd->af);
6915 				printf(" -> ");
6916 				pf_print_host(pd->dst, 0, pd->af);
6917 				printf(" inner src: ");
6918 				pf_print_host(pd2.src, 0, pd2.af);
6919 				printf(" -> ");
6920 				pf_print_host(pd2.dst, 0, pd2.af);
6921 				printf("\n");
6922 			}
6923 			REASON_SET(reason, PFRES_BADSTATE);
6924 			return (PF_DROP);
6925 		}
6926 
6927 		switch (pd2.proto) {
6928 		case IPPROTO_TCP: {
6929 			struct tcphdr		 th;
6930 			u_int32_t		 seq;
6931 			struct pf_state_peer	*src, *dst;
6932 			u_int8_t		 dws;
6933 			int			 copyback = 0;
6934 
6935 			/*
6936 			 * Only the first 8 bytes of the TCP header can be
6937 			 * expected. Don't access any TCP header fields after
6938 			 * th_seq, an ackskew test is not possible.
6939 			 */
6940 			if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
6941 			    pd2.af)) {
6942 				DPFPRINTF(PF_DEBUG_MISC,
6943 				    ("pf: ICMP error message too short "
6944 				    "(tcp)\n"));
6945 				return (PF_DROP);
6946 			}
6947 
6948 			key.af = pd2.af;
6949 			key.proto = IPPROTO_TCP;
6950 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
6951 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
6952 			key.port[pd2.sidx] = th.th_sport;
6953 			key.port[pd2.didx] = th.th_dport;
6954 
6955 			STATE_LOOKUP(kif, &key, *state, pd);
6956 
6957 			if (pd->dir == (*state)->direction) {
6958 				src = &(*state)->dst;
6959 				dst = &(*state)->src;
6960 			} else {
6961 				src = &(*state)->src;
6962 				dst = &(*state)->dst;
6963 			}
6964 
6965 			if (src->wscale && dst->wscale)
6966 				dws = dst->wscale & PF_WSCALE_MASK;
6967 			else
6968 				dws = 0;
6969 
6970 			/* Demodulate sequence number */
6971 			seq = ntohl(th.th_seq) - src->seqdiff;
6972 			if (src->seqdiff) {
6973 				pf_change_a(&th.th_seq, icmpsum,
6974 				    htonl(seq), 0);
6975 				copyback = 1;
6976 			}
6977 
6978 			if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
6979 			    (!SEQ_GEQ(src->seqhi, seq) ||
6980 			    !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
6981 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
6982 					printf("pf: BAD ICMP %d:%d ",
6983 					    icmptype, icmpcode);
6984 					pf_print_host(pd->src, 0, pd->af);
6985 					printf(" -> ");
6986 					pf_print_host(pd->dst, 0, pd->af);
6987 					printf(" state: ");
6988 					pf_print_state(*state);
6989 					printf(" seq=%u\n", seq);
6990 				}
6991 				REASON_SET(reason, PFRES_BADSTATE);
6992 				return (PF_DROP);
6993 			} else {
6994 				if (V_pf_status.debug >= PF_DEBUG_MISC) {
6995 					printf("pf: OK ICMP %d:%d ",
6996 					    icmptype, icmpcode);
6997 					pf_print_host(pd->src, 0, pd->af);
6998 					printf(" -> ");
6999 					pf_print_host(pd->dst, 0, pd->af);
7000 					printf(" state: ");
7001 					pf_print_state(*state);
7002 					printf(" seq=%u\n", seq);
7003 				}
7004 			}
7005 
7006 			/* translate source/destination address, if necessary */
7007 			if ((*state)->key[PF_SK_WIRE] !=
7008 			    (*state)->key[PF_SK_STACK]) {
7009 				struct pf_state_key *nk =
7010 				    (*state)->key[pd->didx];
7011 
7012 				if (PF_ANEQ(pd2.src,
7013 				    &nk->addr[pd2.sidx], pd2.af) ||
7014 				    nk->port[pd2.sidx] != th.th_sport)
7015 					pf_change_icmp(pd2.src, &th.th_sport,
7016 					    daddr, &nk->addr[pd2.sidx],
7017 					    nk->port[pd2.sidx], NULL,
7018 					    pd2.ip_sum, icmpsum,
7019 					    pd->ip_sum, 0, pd2.af);
7020 
7021 				if (PF_ANEQ(pd2.dst,
7022 				    &nk->addr[pd2.didx], pd2.af) ||
7023 				    nk->port[pd2.didx] != th.th_dport)
7024 					pf_change_icmp(pd2.dst, &th.th_dport,
7025 					    saddr, &nk->addr[pd2.didx],
7026 					    nk->port[pd2.didx], NULL,
7027 					    pd2.ip_sum, icmpsum,
7028 					    pd->ip_sum, 0, pd2.af);
7029 				copyback = 1;
7030 			}
7031 
7032 			if (copyback) {
7033 				switch (pd2.af) {
7034 #ifdef INET
7035 				case AF_INET:
7036 					m_copyback(m, off, ICMP_MINLEN,
7037 					    (caddr_t )&pd->hdr.icmp);
7038 					m_copyback(m, ipoff2, sizeof(h2),
7039 					    (caddr_t )&h2);
7040 					break;
7041 #endif /* INET */
7042 #ifdef INET6
7043 				case AF_INET6:
7044 					m_copyback(m, off,
7045 					    sizeof(struct icmp6_hdr),
7046 					    (caddr_t )&pd->hdr.icmp6);
7047 					m_copyback(m, ipoff2, sizeof(h2_6),
7048 					    (caddr_t )&h2_6);
7049 					break;
7050 #endif /* INET6 */
7051 				}
7052 				m_copyback(m, off2, 8, (caddr_t)&th);
7053 			}
7054 
7055 			return (PF_PASS);
7056 			break;
7057 		}
7058 		case IPPROTO_UDP: {
7059 			struct udphdr		uh;
7060 
7061 			if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
7062 			    NULL, reason, pd2.af)) {
7063 				DPFPRINTF(PF_DEBUG_MISC,
7064 				    ("pf: ICMP error message too short "
7065 				    "(udp)\n"));
7066 				return (PF_DROP);
7067 			}
7068 
7069 			key.af = pd2.af;
7070 			key.proto = IPPROTO_UDP;
7071 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
7072 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
7073 			key.port[pd2.sidx] = uh.uh_sport;
7074 			key.port[pd2.didx] = uh.uh_dport;
7075 
7076 			STATE_LOOKUP(kif, &key, *state, pd);
7077 
7078 			/* translate source/destination address, if necessary */
7079 			if ((*state)->key[PF_SK_WIRE] !=
7080 			    (*state)->key[PF_SK_STACK]) {
7081 				struct pf_state_key *nk =
7082 				    (*state)->key[pd->didx];
7083 
7084 				if (PF_ANEQ(pd2.src,
7085 				    &nk->addr[pd2.sidx], pd2.af) ||
7086 				    nk->port[pd2.sidx] != uh.uh_sport)
7087 					pf_change_icmp(pd2.src, &uh.uh_sport,
7088 					    daddr, &nk->addr[pd2.sidx],
7089 					    nk->port[pd2.sidx], &uh.uh_sum,
7090 					    pd2.ip_sum, icmpsum,
7091 					    pd->ip_sum, 1, pd2.af);
7092 
7093 				if (PF_ANEQ(pd2.dst,
7094 				    &nk->addr[pd2.didx], pd2.af) ||
7095 				    nk->port[pd2.didx] != uh.uh_dport)
7096 					pf_change_icmp(pd2.dst, &uh.uh_dport,
7097 					    saddr, &nk->addr[pd2.didx],
7098 					    nk->port[pd2.didx], &uh.uh_sum,
7099 					    pd2.ip_sum, icmpsum,
7100 					    pd->ip_sum, 1, pd2.af);
7101 
7102 				switch (pd2.af) {
7103 #ifdef INET
7104 				case AF_INET:
7105 					m_copyback(m, off, ICMP_MINLEN,
7106 					    (caddr_t )&pd->hdr.icmp);
7107 					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
7108 					break;
7109 #endif /* INET */
7110 #ifdef INET6
7111 				case AF_INET6:
7112 					m_copyback(m, off,
7113 					    sizeof(struct icmp6_hdr),
7114 					    (caddr_t )&pd->hdr.icmp6);
7115 					m_copyback(m, ipoff2, sizeof(h2_6),
7116 					    (caddr_t )&h2_6);
7117 					break;
7118 #endif /* INET6 */
7119 				}
7120 				m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
7121 			}
7122 			return (PF_PASS);
7123 			break;
7124 		}
7125 #ifdef INET
7126 		case IPPROTO_ICMP: {
7127 			struct icmp		iih;
7128 
7129 			if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
7130 			    NULL, reason, pd2.af)) {
7131 				DPFPRINTF(PF_DEBUG_MISC,
7132 				    ("pf: ICMP error message too short i"
7133 				    "(icmp)\n"));
7134 				return (PF_DROP);
7135 			}
7136 
7137 			icmpid = iih.icmp_id;
7138 			pf_icmp_mapping(&pd2, iih.icmp_type,
7139 			    &icmp_dir, &multi, &virtual_id, &virtual_type);
7140 
7141 			ret = pf_icmp_state_lookup(&key, &pd2, state, m,
7142 			    pd->dir, kif, virtual_id, virtual_type,
7143 			    icmp_dir, &iidx, PF_ICMP_MULTI_NONE);
7144 			if (ret >= 0)
7145 				return (ret);
7146 
7147 			/* translate source/destination address, if necessary */
7148 			if ((*state)->key[PF_SK_WIRE] !=
7149 			    (*state)->key[PF_SK_STACK]) {
7150 				struct pf_state_key *nk =
7151 				    (*state)->key[pd->didx];
7152 
7153 				if (PF_ANEQ(pd2.src,
7154 				    &nk->addr[pd2.sidx], pd2.af) ||
7155 				    (virtual_type == htons(ICMP_ECHO) &&
7156 				    nk->port[iidx] != iih.icmp_id))
7157 					pf_change_icmp(pd2.src,
7158 					    (virtual_type == htons(ICMP_ECHO)) ?
7159 					    &iih.icmp_id : NULL,
7160 					    daddr, &nk->addr[pd2.sidx],
7161 					    (virtual_type == htons(ICMP_ECHO)) ?
7162 					    nk->port[iidx] : 0, NULL,
7163 					    pd2.ip_sum, icmpsum,
7164 					    pd->ip_sum, 0, AF_INET);
7165 
7166 				if (PF_ANEQ(pd2.dst,
7167 				    &nk->addr[pd2.didx], pd2.af))
7168 					pf_change_icmp(pd2.dst, NULL, NULL,
7169 					    &nk->addr[pd2.didx], 0, NULL,
7170 					    pd2.ip_sum, icmpsum, pd->ip_sum, 0,
7171 					    AF_INET);
7172 
7173 				m_copyback(m, off, ICMP_MINLEN, (caddr_t)&pd->hdr.icmp);
7174 				m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
7175 				m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
7176 			}
7177 			return (PF_PASS);
7178 			break;
7179 		}
7180 #endif /* INET */
7181 #ifdef INET6
7182 		case IPPROTO_ICMPV6: {
7183 			struct icmp6_hdr	iih;
7184 
7185 			if (!pf_pull_hdr(m, off2, &iih,
7186 			    sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
7187 				DPFPRINTF(PF_DEBUG_MISC,
7188 				    ("pf: ICMP error message too short "
7189 				    "(icmp6)\n"));
7190 				return (PF_DROP);
7191 			}
7192 
7193 			pf_icmp_mapping(&pd2, iih.icmp6_type,
7194 			    &icmp_dir, &multi, &virtual_id, &virtual_type);
7195 			ret = pf_icmp_state_lookup(&key, &pd2, state, m,
7196 			    pd->dir, kif, virtual_id, virtual_type,
7197 			    icmp_dir, &iidx, PF_ICMP_MULTI_NONE);
7198 			if (ret >= 0) {
7199 				if (ret == PF_DROP && pd->af == AF_INET6 &&
7200 				    icmp_dir == PF_OUT) {
7201 					if (*state != NULL)
7202 						PF_STATE_UNLOCK((*state));
7203 					ret = pf_icmp_state_lookup(&key, pd,
7204 					    state, m, pd->dir, kif,
7205 					    virtual_id, virtual_type,
7206 					    icmp_dir, &iidx, multi);
7207 					if (ret >= 0)
7208 						return (ret);
7209 				} else
7210 					return (ret);
7211 			}
7212 
7213 			/* translate source/destination address, if necessary */
7214 			if ((*state)->key[PF_SK_WIRE] !=
7215 			    (*state)->key[PF_SK_STACK]) {
7216 				struct pf_state_key *nk =
7217 				    (*state)->key[pd->didx];
7218 
7219 				if (PF_ANEQ(pd2.src,
7220 				    &nk->addr[pd2.sidx], pd2.af) ||
7221 				    ((virtual_type == htons(ICMP6_ECHO_REQUEST)) &&
7222 				    nk->port[pd2.sidx] != iih.icmp6_id))
7223 					pf_change_icmp(pd2.src,
7224 					    (virtual_type == htons(ICMP6_ECHO_REQUEST))
7225 					    ? &iih.icmp6_id : NULL,
7226 					    daddr, &nk->addr[pd2.sidx],
7227 					    (virtual_type == htons(ICMP6_ECHO_REQUEST))
7228 					    ? nk->port[iidx] : 0, NULL,
7229 					    pd2.ip_sum, icmpsum,
7230 					    pd->ip_sum, 0, AF_INET6);
7231 
7232 				if (PF_ANEQ(pd2.dst,
7233 				    &nk->addr[pd2.didx], pd2.af))
7234 					pf_change_icmp(pd2.dst, NULL, NULL,
7235 					    &nk->addr[pd2.didx], 0, NULL,
7236 					    pd2.ip_sum, icmpsum,
7237 					    pd->ip_sum, 0, AF_INET6);
7238 
7239 				m_copyback(m, off, sizeof(struct icmp6_hdr),
7240 				    (caddr_t)&pd->hdr.icmp6);
7241 				m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
7242 				m_copyback(m, off2, sizeof(struct icmp6_hdr),
7243 				    (caddr_t)&iih);
7244 			}
7245 			return (PF_PASS);
7246 			break;
7247 		}
7248 #endif /* INET6 */
7249 		default: {
7250 			key.af = pd2.af;
7251 			key.proto = pd2.proto;
7252 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
7253 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
7254 			key.port[0] = key.port[1] = 0;
7255 
7256 			STATE_LOOKUP(kif, &key, *state, pd);
7257 
7258 			/* translate source/destination address, if necessary */
7259 			if ((*state)->key[PF_SK_WIRE] !=
7260 			    (*state)->key[PF_SK_STACK]) {
7261 				struct pf_state_key *nk =
7262 				    (*state)->key[pd->didx];
7263 
7264 				if (PF_ANEQ(pd2.src,
7265 				    &nk->addr[pd2.sidx], pd2.af))
7266 					pf_change_icmp(pd2.src, NULL, daddr,
7267 					    &nk->addr[pd2.sidx], 0, NULL,
7268 					    pd2.ip_sum, icmpsum,
7269 					    pd->ip_sum, 0, pd2.af);
7270 
7271 				if (PF_ANEQ(pd2.dst,
7272 				    &nk->addr[pd2.didx], pd2.af))
7273 					pf_change_icmp(pd2.dst, NULL, saddr,
7274 					    &nk->addr[pd2.didx], 0, NULL,
7275 					    pd2.ip_sum, icmpsum,
7276 					    pd->ip_sum, 0, pd2.af);
7277 
7278 				switch (pd2.af) {
7279 #ifdef INET
7280 				case AF_INET:
7281 					m_copyback(m, off, ICMP_MINLEN,
7282 					    (caddr_t)&pd->hdr.icmp);
7283 					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
7284 					break;
7285 #endif /* INET */
7286 #ifdef INET6
7287 				case AF_INET6:
7288 					m_copyback(m, off,
7289 					    sizeof(struct icmp6_hdr),
7290 					    (caddr_t )&pd->hdr.icmp6);
7291 					m_copyback(m, ipoff2, sizeof(h2_6),
7292 					    (caddr_t )&h2_6);
7293 					break;
7294 #endif /* INET6 */
7295 				}
7296 			}
7297 			return (PF_PASS);
7298 			break;
7299 		}
7300 		}
7301 	}
7302 }
7303 
7304 static int
7305 pf_test_state_other(struct pf_kstate **state, struct pfi_kkif *kif,
7306     struct mbuf *m, struct pf_pdesc *pd)
7307 {
7308 	struct pf_state_peer	*src, *dst;
7309 	struct pf_state_key_cmp	 key;
7310 	uint8_t			 psrc, pdst;
7311 
7312 	bzero(&key, sizeof(key));
7313 	key.af = pd->af;
7314 	key.proto = pd->proto;
7315 	if (pd->dir == PF_IN)	{
7316 		PF_ACPY(&key.addr[0], pd->src, key.af);
7317 		PF_ACPY(&key.addr[1], pd->dst, key.af);
7318 		key.port[0] = key.port[1] = 0;
7319 	} else {
7320 		PF_ACPY(&key.addr[1], pd->src, key.af);
7321 		PF_ACPY(&key.addr[0], pd->dst, key.af);
7322 		key.port[1] = key.port[0] = 0;
7323 	}
7324 
7325 	STATE_LOOKUP(kif, &key, *state, pd);
7326 
7327 	if (pd->dir == (*state)->direction) {
7328 		src = &(*state)->src;
7329 		dst = &(*state)->dst;
7330 		psrc = PF_PEER_SRC;
7331 		pdst = PF_PEER_DST;
7332 	} else {
7333 		src = &(*state)->dst;
7334 		dst = &(*state)->src;
7335 		psrc = PF_PEER_DST;
7336 		pdst = PF_PEER_SRC;
7337 	}
7338 
7339 	/* update states */
7340 	if (src->state < PFOTHERS_SINGLE)
7341 		pf_set_protostate(*state, psrc, PFOTHERS_SINGLE);
7342 	if (dst->state == PFOTHERS_SINGLE)
7343 		pf_set_protostate(*state, pdst, PFOTHERS_MULTIPLE);
7344 
7345 	/* update expire time */
7346 	(*state)->expire = pf_get_uptime();
7347 	if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
7348 		(*state)->timeout = PFTM_OTHER_MULTIPLE;
7349 	else
7350 		(*state)->timeout = PFTM_OTHER_SINGLE;
7351 
7352 	/* translate source/destination address, if necessary */
7353 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
7354 		struct pf_state_key *nk = (*state)->key[pd->didx];
7355 
7356 		KASSERT(nk, ("%s: nk is null", __func__));
7357 		KASSERT(pd, ("%s: pd is null", __func__));
7358 		KASSERT(pd->src, ("%s: pd->src is null", __func__));
7359 		KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
7360 		switch (pd->af) {
7361 #ifdef INET
7362 		case AF_INET:
7363 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
7364 				pf_change_a(&pd->src->v4.s_addr,
7365 				    pd->ip_sum,
7366 				    nk->addr[pd->sidx].v4.s_addr,
7367 				    0);
7368 
7369 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
7370 				pf_change_a(&pd->dst->v4.s_addr,
7371 				    pd->ip_sum,
7372 				    nk->addr[pd->didx].v4.s_addr,
7373 				    0);
7374 
7375 			break;
7376 #endif /* INET */
7377 #ifdef INET6
7378 		case AF_INET6:
7379 			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
7380 				PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
7381 
7382 			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
7383 				PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
7384 #endif /* INET6 */
7385 		}
7386 	}
7387 	return (PF_PASS);
7388 }
7389 
7390 /*
7391  * ipoff and off are measured from the start of the mbuf chain.
7392  * h must be at "ipoff" on the mbuf chain.
7393  */
7394 void *
7395 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
7396     u_short *actionp, u_short *reasonp, sa_family_t af)
7397 {
7398 	switch (af) {
7399 #ifdef INET
7400 	case AF_INET: {
7401 		struct ip	*h = mtod(m, struct ip *);
7402 		u_int16_t	 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
7403 
7404 		if (fragoff) {
7405 			if (fragoff >= len)
7406 				ACTION_SET(actionp, PF_PASS);
7407 			else {
7408 				ACTION_SET(actionp, PF_DROP);
7409 				REASON_SET(reasonp, PFRES_FRAG);
7410 			}
7411 			return (NULL);
7412 		}
7413 		if (m->m_pkthdr.len < off + len ||
7414 		    ntohs(h->ip_len) < off + len) {
7415 			ACTION_SET(actionp, PF_DROP);
7416 			REASON_SET(reasonp, PFRES_SHORT);
7417 			return (NULL);
7418 		}
7419 		break;
7420 	}
7421 #endif /* INET */
7422 #ifdef INET6
7423 	case AF_INET6: {
7424 		struct ip6_hdr	*h = mtod(m, struct ip6_hdr *);
7425 
7426 		if (m->m_pkthdr.len < off + len ||
7427 		    (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
7428 		    (unsigned)(off + len)) {
7429 			ACTION_SET(actionp, PF_DROP);
7430 			REASON_SET(reasonp, PFRES_SHORT);
7431 			return (NULL);
7432 		}
7433 		break;
7434 	}
7435 #endif /* INET6 */
7436 	}
7437 	m_copydata(m, off, len, p);
7438 	return (p);
7439 }
7440 
7441 int
7442 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kkif *kif,
7443     int rtableid)
7444 {
7445 	struct ifnet		*ifp;
7446 
7447 	/*
7448 	 * Skip check for addresses with embedded interface scope,
7449 	 * as they would always match anyway.
7450 	 */
7451 	if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
7452 		return (1);
7453 
7454 	if (af != AF_INET && af != AF_INET6)
7455 		return (0);
7456 
7457 	if (kif == V_pfi_all)
7458 		return (1);
7459 
7460 	/* Skip checks for ipsec interfaces */
7461 	if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
7462 		return (1);
7463 
7464 	ifp = (kif != NULL) ? kif->pfik_ifp : NULL;
7465 
7466 	switch (af) {
7467 #ifdef INET6
7468 	case AF_INET6:
7469 		return (fib6_check_urpf(rtableid, &addr->v6, 0, NHR_NONE,
7470 		    ifp));
7471 #endif
7472 #ifdef INET
7473 	case AF_INET:
7474 		return (fib4_check_urpf(rtableid, addr->v4, 0, NHR_NONE,
7475 		    ifp));
7476 #endif
7477 	}
7478 
7479 	return (0);
7480 }
7481 
7482 #ifdef INET
7483 static void
7484 pf_route(struct mbuf **m, struct pf_krule *r, struct ifnet *oifp,
7485     struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
7486 {
7487 	struct mbuf		*m0, *m1, *md;
7488 	struct sockaddr_in	dst;
7489 	struct ip		*ip;
7490 	struct pfi_kkif		*nkif = NULL;
7491 	struct ifnet		*ifp = NULL;
7492 	struct pf_addr		 naddr;
7493 	struct pf_ksrc_node	*sn = NULL;
7494 	int			 error = 0;
7495 	uint16_t		 ip_len, ip_off;
7496 	uint16_t		 tmp;
7497 	int			 r_rt, r_dir;
7498 
7499 	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
7500 
7501 	if (s) {
7502 		r_rt = s->rt;
7503 		r_dir = s->direction;
7504 	} else {
7505 		r_rt = r->rt;
7506 		r_dir = r->direction;
7507 	}
7508 
7509 	KASSERT(pd->dir == PF_IN || pd->dir == PF_OUT ||
7510 	    r_dir == PF_IN || r_dir == PF_OUT, ("%s: invalid direction",
7511 	    __func__));
7512 
7513 	if ((pd->pf_mtag == NULL &&
7514 	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
7515 	    pd->pf_mtag->routed++ > 3) {
7516 		m0 = *m;
7517 		*m = NULL;
7518 		goto bad_locked;
7519 	}
7520 
7521 	if (r_rt == PF_DUPTO) {
7522 		if ((pd->pf_mtag->flags & PF_MTAG_FLAG_DUPLICATED)) {
7523 			if (s == NULL) {
7524 				ifp = r->rpool.cur->kif ?
7525 				    r->rpool.cur->kif->pfik_ifp : NULL;
7526 			} else {
7527 				ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
7528 				/* If pfsync'd */
7529 				if (ifp == NULL && r->rpool.cur != NULL)
7530 					ifp = r->rpool.cur->kif ?
7531 					    r->rpool.cur->kif->pfik_ifp : NULL;
7532 				PF_STATE_UNLOCK(s);
7533 			}
7534 			if (ifp == oifp) {
7535 				/* When the 2nd interface is not skipped */
7536 				return;
7537 			} else {
7538 				m0 = *m;
7539 				*m = NULL;
7540 				goto bad;
7541 			}
7542 		} else {
7543 			pd->pf_mtag->flags |= PF_MTAG_FLAG_DUPLICATED;
7544 			if (((m0 = m_dup(*m, M_NOWAIT)) == NULL)) {
7545 				if (s)
7546 					PF_STATE_UNLOCK(s);
7547 				return;
7548 			}
7549 		}
7550 	} else {
7551 		if ((r_rt == PF_REPLYTO) == (r_dir == pd->dir)) {
7552 			pf_dummynet(pd, s, r, m);
7553 			if (s)
7554 				PF_STATE_UNLOCK(s);
7555 			return;
7556 		}
7557 		m0 = *m;
7558 	}
7559 
7560 	ip = mtod(m0, struct ip *);
7561 
7562 	bzero(&dst, sizeof(dst));
7563 	dst.sin_family = AF_INET;
7564 	dst.sin_len = sizeof(dst);
7565 	dst.sin_addr = ip->ip_dst;
7566 
7567 	bzero(&naddr, sizeof(naddr));
7568 
7569 	if (s == NULL) {
7570 		if (TAILQ_EMPTY(&r->rpool.list)) {
7571 			DPFPRINTF(PF_DEBUG_URGENT,
7572 			    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
7573 			goto bad_locked;
7574 		}
7575 		pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
7576 		    &naddr, &nkif, NULL, &sn);
7577 		if (!PF_AZERO(&naddr, AF_INET))
7578 			dst.sin_addr.s_addr = naddr.v4.s_addr;
7579 		ifp = nkif ? nkif->pfik_ifp : NULL;
7580 	} else {
7581 		struct pfi_kkif *kif;
7582 
7583 		if (!PF_AZERO(&s->rt_addr, AF_INET))
7584 			dst.sin_addr.s_addr =
7585 			    s->rt_addr.v4.s_addr;
7586 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
7587 		kif = s->rt_kif;
7588 		/* If pfsync'd */
7589 		if (ifp == NULL && r->rpool.cur != NULL) {
7590 			ifp = r->rpool.cur->kif ?
7591 			    r->rpool.cur->kif->pfik_ifp : NULL;
7592 			kif = r->rpool.cur->kif;
7593 		}
7594 		if (ifp != NULL && kif != NULL &&
7595 		    r->rule_flag & PFRULE_IFBOUND &&
7596 		    r->rt == PF_REPLYTO &&
7597 		    s->kif == V_pfi_all) {
7598 			s->kif = kif;
7599 			s->orig_kif = oifp->if_pf_kif;
7600 		}
7601 
7602 		PF_STATE_UNLOCK(s);
7603 	}
7604 
7605 	if (ifp == NULL)
7606 		goto bad;
7607 
7608 	if (pd->dir == PF_IN) {
7609 		if (pf_test(PF_OUT, PFIL_FWD, ifp, &m0, inp, &pd->act) != PF_PASS)
7610 			goto bad;
7611 		else if (m0 == NULL)
7612 			goto done;
7613 		if (m0->m_len < sizeof(struct ip)) {
7614 			DPFPRINTF(PF_DEBUG_URGENT,
7615 			    ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
7616 			goto bad;
7617 		}
7618 		ip = mtod(m0, struct ip *);
7619 	}
7620 
7621 	if (ifp->if_flags & IFF_LOOPBACK)
7622 		m0->m_flags |= M_SKIP_FIREWALL;
7623 
7624 	ip_len = ntohs(ip->ip_len);
7625 	ip_off = ntohs(ip->ip_off);
7626 
7627 	/* Copied from FreeBSD 10.0-CURRENT ip_output. */
7628 	m0->m_pkthdr.csum_flags |= CSUM_IP;
7629 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
7630 		in_delayed_cksum(m0);
7631 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
7632 	}
7633 	if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
7634 		pf_sctp_checksum(m0, (uint32_t)(ip->ip_hl << 2));
7635 		m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
7636 	}
7637 
7638 	if (pd->dir == PF_IN) {
7639 		/*
7640 		 * Make sure dummynet gets the correct direction, in case it needs to
7641 		 * re-inject later.
7642 		 */
7643 		pd->dir = PF_OUT;
7644 
7645 		/*
7646 		 * The following processing is actually the rest of the inbound processing, even
7647 		 * though we've marked it as outbound (so we don't look through dummynet) and it
7648 		 * happens after the outbound processing (pf_test(PF_OUT) above).
7649 		 * Swap the dummynet pipe numbers, because it's going to come to the wrong
7650 		 * conclusion about what direction it's processing, and we can't fix it or it
7651 		 * will re-inject incorrectly. Swapping the pipe numbers means that its incorrect
7652 		 * decision will pick the right pipe, and everything will mostly work as expected.
7653 		 */
7654 		tmp = pd->act.dnrpipe;
7655 		pd->act.dnrpipe = pd->act.dnpipe;
7656 		pd->act.dnpipe = tmp;
7657 	}
7658 
7659 	/*
7660 	 * If small enough for interface, or the interface will take
7661 	 * care of the fragmentation for us, we can just send directly.
7662 	 */
7663 	if (ip_len <= ifp->if_mtu ||
7664 	    (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
7665 		ip->ip_sum = 0;
7666 		if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
7667 			ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
7668 			m0->m_pkthdr.csum_flags &= ~CSUM_IP;
7669 		}
7670 		m_clrprotoflags(m0);	/* Avoid confusing lower layers. */
7671 
7672 		md = m0;
7673 		error = pf_dummynet_route(pd, s, r, ifp, sintosa(&dst), &md);
7674 		if (md != NULL)
7675 			error = (*ifp->if_output)(ifp, md, sintosa(&dst), NULL);
7676 		goto done;
7677 	}
7678 
7679 	/* Balk when DF bit is set or the interface didn't support TSO. */
7680 	if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
7681 		error = EMSGSIZE;
7682 		KMOD_IPSTAT_INC(ips_cantfrag);
7683 		if (r_rt != PF_DUPTO) {
7684 			if (s && pd->nat_rule != NULL)
7685 				PACKET_UNDO_NAT(m0, pd,
7686 				    (ip->ip_hl << 2) + (ip_off & IP_OFFMASK),
7687 				    s);
7688 
7689 			icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
7690 			    ifp->if_mtu);
7691 			goto done;
7692 		} else
7693 			goto bad;
7694 	}
7695 
7696 	error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
7697 	if (error)
7698 		goto bad;
7699 
7700 	for (; m0; m0 = m1) {
7701 		m1 = m0->m_nextpkt;
7702 		m0->m_nextpkt = NULL;
7703 		if (error == 0) {
7704 			m_clrprotoflags(m0);
7705 			md = m0;
7706 			pd->pf_mtag = pf_find_mtag(md);
7707 			error = pf_dummynet_route(pd, s, r, ifp,
7708 			    sintosa(&dst), &md);
7709 			if (md != NULL)
7710 				error = (*ifp->if_output)(ifp, md,
7711 				    sintosa(&dst), NULL);
7712 		} else
7713 			m_freem(m0);
7714 	}
7715 
7716 	if (error == 0)
7717 		KMOD_IPSTAT_INC(ips_fragmented);
7718 
7719 done:
7720 	if (r_rt != PF_DUPTO)
7721 		*m = NULL;
7722 	return;
7723 
7724 bad_locked:
7725 	if (s)
7726 		PF_STATE_UNLOCK(s);
7727 bad:
7728 	m_freem(m0);
7729 	goto done;
7730 }
7731 #endif /* INET */
7732 
7733 #ifdef INET6
7734 static void
7735 pf_route6(struct mbuf **m, struct pf_krule *r, struct ifnet *oifp,
7736     struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
7737 {
7738 	struct mbuf		*m0, *md;
7739 	struct sockaddr_in6	dst;
7740 	struct ip6_hdr		*ip6;
7741 	struct pfi_kkif		*nkif = NULL;
7742 	struct ifnet		*ifp = NULL;
7743 	struct pf_addr		 naddr;
7744 	struct pf_ksrc_node	*sn = NULL;
7745 	int			 r_rt, r_dir;
7746 
7747 	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
7748 
7749 	if (s) {
7750 		r_rt = s->rt;
7751 		r_dir = s->direction;
7752 	} else {
7753 		r_rt = r->rt;
7754 		r_dir = r->direction;
7755 	}
7756 
7757 	KASSERT(pd->dir == PF_IN || pd->dir == PF_OUT ||
7758 	    r_dir == PF_IN || r_dir == PF_OUT, ("%s: invalid direction",
7759 	    __func__));
7760 
7761 	if ((pd->pf_mtag == NULL &&
7762 	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
7763 	    pd->pf_mtag->routed++ > 3) {
7764 		m0 = *m;
7765 		*m = NULL;
7766 		goto bad_locked;
7767 	}
7768 
7769 	if (r_rt == PF_DUPTO) {
7770 		if ((pd->pf_mtag->flags & PF_MTAG_FLAG_DUPLICATED)) {
7771 			if (s == NULL) {
7772 				ifp = r->rpool.cur->kif ?
7773 				    r->rpool.cur->kif->pfik_ifp : NULL;
7774 			} else {
7775 				ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
7776 				/* If pfsync'd */
7777 				if (ifp == NULL && r->rpool.cur != NULL)
7778 					ifp = r->rpool.cur->kif ?
7779 					    r->rpool.cur->kif->pfik_ifp : NULL;
7780 				PF_STATE_UNLOCK(s);
7781 			}
7782 			if (ifp == oifp) {
7783 				/* When the 2nd interface is not skipped */
7784 				return;
7785 			} else {
7786 				m0 = *m;
7787 				*m = NULL;
7788 				goto bad;
7789 			}
7790 		} else {
7791 			pd->pf_mtag->flags |= PF_MTAG_FLAG_DUPLICATED;
7792 			if (((m0 = m_dup(*m, M_NOWAIT)) == NULL)) {
7793 				if (s)
7794 					PF_STATE_UNLOCK(s);
7795 				return;
7796 			}
7797 		}
7798 	} else {
7799 		if ((r_rt == PF_REPLYTO) == (r_dir == pd->dir)) {
7800 			pf_dummynet(pd, s, r, m);
7801 			if (s)
7802 				PF_STATE_UNLOCK(s);
7803 			return;
7804 		}
7805 		m0 = *m;
7806 	}
7807 
7808 	ip6 = mtod(m0, struct ip6_hdr *);
7809 
7810 	bzero(&dst, sizeof(dst));
7811 	dst.sin6_family = AF_INET6;
7812 	dst.sin6_len = sizeof(dst);
7813 	dst.sin6_addr = ip6->ip6_dst;
7814 
7815 	bzero(&naddr, sizeof(naddr));
7816 
7817 	if (s == NULL) {
7818 		if (TAILQ_EMPTY(&r->rpool.list)) {
7819 			DPFPRINTF(PF_DEBUG_URGENT,
7820 			    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
7821 			goto bad_locked;
7822 		}
7823 		pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
7824 		    &naddr, &nkif, NULL, &sn);
7825 		if (!PF_AZERO(&naddr, AF_INET6))
7826 			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
7827 			    &naddr, AF_INET6);
7828 		ifp = nkif ? nkif->pfik_ifp : NULL;
7829 	} else {
7830 		struct pfi_kkif *kif;
7831 
7832 		if (!PF_AZERO(&s->rt_addr, AF_INET6))
7833 			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
7834 			    &s->rt_addr, AF_INET6);
7835 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
7836 		kif = s->rt_kif;
7837 		/* If pfsync'd */
7838 		if (ifp == NULL && r->rpool.cur != NULL) {
7839 			ifp = r->rpool.cur->kif ?
7840 			    r->rpool.cur->kif->pfik_ifp : NULL;
7841 			kif = r->rpool.cur->kif;
7842 		}
7843 		if (ifp != NULL && kif != NULL &&
7844 		    r->rule_flag & PFRULE_IFBOUND &&
7845 		    r->rt == PF_REPLYTO &&
7846 		    s->kif == V_pfi_all) {
7847 			s->kif = kif;
7848 			s->orig_kif = oifp->if_pf_kif;
7849 		}
7850 	}
7851 
7852 	if (s)
7853 		PF_STATE_UNLOCK(s);
7854 
7855 	if (ifp == NULL)
7856 		goto bad;
7857 
7858 	if (pd->dir == PF_IN) {
7859 		if (pf_test6(PF_OUT, PFIL_FWD, ifp, &m0, inp, &pd->act) != PF_PASS)
7860 			goto bad;
7861 		else if (m0 == NULL)
7862 			goto done;
7863 		if (m0->m_len < sizeof(struct ip6_hdr)) {
7864 			DPFPRINTF(PF_DEBUG_URGENT,
7865 			    ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
7866 			    __func__));
7867 			goto bad;
7868 		}
7869 		ip6 = mtod(m0, struct ip6_hdr *);
7870 	}
7871 
7872 	if (ifp->if_flags & IFF_LOOPBACK)
7873 		m0->m_flags |= M_SKIP_FIREWALL;
7874 
7875 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
7876 	    ~ifp->if_hwassist) {
7877 		uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
7878 		in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
7879 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
7880 	}
7881 
7882 	/*
7883 	 * If the packet is too large for the outgoing interface,
7884 	 * send back an icmp6 error.
7885 	 */
7886 	if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
7887 		dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
7888 	if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu) {
7889 		md = m0;
7890 		pf_dummynet_route(pd, s, r, ifp, sintosa(&dst), &md);
7891 		if (md != NULL)
7892 			nd6_output_ifp(ifp, ifp, md, &dst, NULL);
7893 	}
7894 	else {
7895 		in6_ifstat_inc(ifp, ifs6_in_toobig);
7896 		if (r_rt != PF_DUPTO) {
7897 			if (s && pd->nat_rule != NULL)
7898 				PACKET_UNDO_NAT(m0, pd,
7899 				    ((caddr_t)ip6 - m0->m_data) +
7900 				    sizeof(struct ip6_hdr), s);
7901 
7902 			icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
7903 		} else
7904 			goto bad;
7905 	}
7906 
7907 done:
7908 	if (r_rt != PF_DUPTO)
7909 		*m = NULL;
7910 	return;
7911 
7912 bad_locked:
7913 	if (s)
7914 		PF_STATE_UNLOCK(s);
7915 bad:
7916 	m_freem(m0);
7917 	goto done;
7918 }
7919 #endif /* INET6 */
7920 
7921 /*
7922  * FreeBSD supports cksum offloads for the following drivers.
7923  *  em(4), fxp(4), lge(4), nge(4), re(4), ti(4), txp(4), xl(4)
7924  *
7925  * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
7926  *  network driver performed cksum including pseudo header, need to verify
7927  *   csum_data
7928  * CSUM_DATA_VALID :
7929  *  network driver performed cksum, needs to additional pseudo header
7930  *  cksum computation with partial csum_data(i.e. lack of H/W support for
7931  *  pseudo header, for instance sk(4) and possibly gem(4))
7932  *
7933  * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
7934  * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
7935  * TCP/UDP layer.
7936  * Also, set csum_data to 0xffff to force cksum validation.
7937  */
7938 static int
7939 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
7940 {
7941 	u_int16_t sum = 0;
7942 	int hw_assist = 0;
7943 	struct ip *ip;
7944 
7945 	if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
7946 		return (1);
7947 	if (m->m_pkthdr.len < off + len)
7948 		return (1);
7949 
7950 	switch (p) {
7951 	case IPPROTO_TCP:
7952 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
7953 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
7954 				sum = m->m_pkthdr.csum_data;
7955 			} else {
7956 				ip = mtod(m, struct ip *);
7957 				sum = in_pseudo(ip->ip_src.s_addr,
7958 				ip->ip_dst.s_addr, htonl((u_short)len +
7959 				m->m_pkthdr.csum_data + IPPROTO_TCP));
7960 			}
7961 			sum ^= 0xffff;
7962 			++hw_assist;
7963 		}
7964 		break;
7965 	case IPPROTO_UDP:
7966 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
7967 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
7968 				sum = m->m_pkthdr.csum_data;
7969 			} else {
7970 				ip = mtod(m, struct ip *);
7971 				sum = in_pseudo(ip->ip_src.s_addr,
7972 				ip->ip_dst.s_addr, htonl((u_short)len +
7973 				m->m_pkthdr.csum_data + IPPROTO_UDP));
7974 			}
7975 			sum ^= 0xffff;
7976 			++hw_assist;
7977 		}
7978 		break;
7979 	case IPPROTO_ICMP:
7980 #ifdef INET6
7981 	case IPPROTO_ICMPV6:
7982 #endif /* INET6 */
7983 		break;
7984 	default:
7985 		return (1);
7986 	}
7987 
7988 	if (!hw_assist) {
7989 		switch (af) {
7990 		case AF_INET:
7991 			if (p == IPPROTO_ICMP) {
7992 				if (m->m_len < off)
7993 					return (1);
7994 				m->m_data += off;
7995 				m->m_len -= off;
7996 				sum = in_cksum(m, len);
7997 				m->m_data -= off;
7998 				m->m_len += off;
7999 			} else {
8000 				if (m->m_len < sizeof(struct ip))
8001 					return (1);
8002 				sum = in4_cksum(m, p, off, len);
8003 			}
8004 			break;
8005 #ifdef INET6
8006 		case AF_INET6:
8007 			if (m->m_len < sizeof(struct ip6_hdr))
8008 				return (1);
8009 			sum = in6_cksum(m, p, off, len);
8010 			break;
8011 #endif /* INET6 */
8012 		default:
8013 			return (1);
8014 		}
8015 	}
8016 	if (sum) {
8017 		switch (p) {
8018 		case IPPROTO_TCP:
8019 		    {
8020 			KMOD_TCPSTAT_INC(tcps_rcvbadsum);
8021 			break;
8022 		    }
8023 		case IPPROTO_UDP:
8024 		    {
8025 			KMOD_UDPSTAT_INC(udps_badsum);
8026 			break;
8027 		    }
8028 #ifdef INET
8029 		case IPPROTO_ICMP:
8030 		    {
8031 			KMOD_ICMPSTAT_INC(icps_checksum);
8032 			break;
8033 		    }
8034 #endif
8035 #ifdef INET6
8036 		case IPPROTO_ICMPV6:
8037 		    {
8038 			KMOD_ICMP6STAT_INC(icp6s_checksum);
8039 			break;
8040 		    }
8041 #endif /* INET6 */
8042 		}
8043 		return (1);
8044 	} else {
8045 		if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
8046 			m->m_pkthdr.csum_flags |=
8047 			    (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
8048 			m->m_pkthdr.csum_data = 0xffff;
8049 		}
8050 	}
8051 	return (0);
8052 }
8053 
8054 static bool
8055 pf_pdesc_to_dnflow(const struct pf_pdesc *pd, const struct pf_krule *r,
8056     const struct pf_kstate *s, struct ip_fw_args *dnflow)
8057 {
8058 	int dndir = r->direction;
8059 
8060 	if (s && dndir == PF_INOUT) {
8061 		dndir = s->direction;
8062 	} else if (dndir == PF_INOUT) {
8063 		/* Assume primary direction. Happens when we've set dnpipe in
8064 		 * the ethernet level code. */
8065 		dndir = pd->dir;
8066 	}
8067 
8068 	if (pd->pf_mtag->flags & PF_MTAG_FLAG_DUMMYNETED)
8069 		return (false);
8070 
8071 	memset(dnflow, 0, sizeof(*dnflow));
8072 
8073 	if (pd->dport != NULL)
8074 		dnflow->f_id.dst_port = ntohs(*pd->dport);
8075 	if (pd->sport != NULL)
8076 		dnflow->f_id.src_port = ntohs(*pd->sport);
8077 
8078 	if (pd->dir == PF_IN)
8079 		dnflow->flags |= IPFW_ARGS_IN;
8080 	else
8081 		dnflow->flags |= IPFW_ARGS_OUT;
8082 
8083 	if (pd->dir != dndir && pd->act.dnrpipe) {
8084 		dnflow->rule.info = pd->act.dnrpipe;
8085 	}
8086 	else if (pd->dir == dndir && pd->act.dnpipe) {
8087 		dnflow->rule.info = pd->act.dnpipe;
8088 	}
8089 	else {
8090 		return (false);
8091 	}
8092 
8093 	dnflow->rule.info |= IPFW_IS_DUMMYNET;
8094 	if (r->free_flags & PFRULE_DN_IS_PIPE || pd->act.flags & PFSTATE_DN_IS_PIPE)
8095 		dnflow->rule.info |= IPFW_IS_PIPE;
8096 
8097 	dnflow->f_id.proto = pd->proto;
8098 	dnflow->f_id.extra = dnflow->rule.info;
8099 	switch (pd->af) {
8100 	case AF_INET:
8101 		dnflow->f_id.addr_type = 4;
8102 		dnflow->f_id.src_ip = ntohl(pd->src->v4.s_addr);
8103 		dnflow->f_id.dst_ip = ntohl(pd->dst->v4.s_addr);
8104 		break;
8105 	case AF_INET6:
8106 		dnflow->flags |= IPFW_ARGS_IP6;
8107 		dnflow->f_id.addr_type = 6;
8108 		dnflow->f_id.src_ip6 = pd->src->v6;
8109 		dnflow->f_id.dst_ip6 = pd->dst->v6;
8110 		break;
8111 	default:
8112 		panic("Invalid AF");
8113 		break;
8114 	}
8115 
8116 	return (true);
8117 }
8118 
8119 int
8120 pf_test_eth(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0,
8121     struct inpcb *inp)
8122 {
8123 	struct pfi_kkif		*kif;
8124 	struct mbuf		*m = *m0;
8125 
8126 	M_ASSERTPKTHDR(m);
8127 	MPASS(ifp->if_vnet == curvnet);
8128 	NET_EPOCH_ASSERT();
8129 
8130 	if (!V_pf_status.running)
8131 		return (PF_PASS);
8132 
8133 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
8134 
8135 	if (kif == NULL) {
8136 		DPFPRINTF(PF_DEBUG_URGENT,
8137 		    ("%s: kif == NULL, if_xname %s\n", __func__, ifp->if_xname));
8138 		return (PF_DROP);
8139 	}
8140 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
8141 		return (PF_PASS);
8142 
8143 	if (m->m_flags & M_SKIP_FIREWALL)
8144 		return (PF_PASS);
8145 
8146 	/* Stateless! */
8147 	return (pf_test_eth_rule(dir, kif, m0));
8148 }
8149 
8150 static __inline void
8151 pf_dummynet_flag_remove(struct mbuf *m, struct pf_mtag *pf_mtag)
8152 {
8153 	struct m_tag *mtag;
8154 
8155 	pf_mtag->flags &= ~PF_MTAG_FLAG_DUMMYNET;
8156 
8157 	/* dummynet adds this tag, but pf does not need it,
8158 	 * and keeping it creates unexpected behavior,
8159 	 * e.g. in case of divert(4) usage right after dummynet. */
8160 	mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
8161 	if (mtag != NULL)
8162 		m_tag_delete(m, mtag);
8163 }
8164 
8165 static int
8166 pf_dummynet(struct pf_pdesc *pd, struct pf_kstate *s,
8167     struct pf_krule *r, struct mbuf **m0)
8168 {
8169 	return (pf_dummynet_route(pd, s, r, NULL, NULL, m0));
8170 }
8171 
8172 static int
8173 pf_dummynet_route(struct pf_pdesc *pd, struct pf_kstate *s,
8174     struct pf_krule *r, struct ifnet *ifp, struct sockaddr *sa,
8175     struct mbuf **m0)
8176 {
8177 	NET_EPOCH_ASSERT();
8178 
8179 	if (pd->act.dnpipe || pd->act.dnrpipe) {
8180 		struct ip_fw_args dnflow;
8181 		if (ip_dn_io_ptr == NULL) {
8182 			m_freem(*m0);
8183 			*m0 = NULL;
8184 			return (ENOMEM);
8185 		}
8186 
8187 		if (pd->pf_mtag == NULL &&
8188 		    ((pd->pf_mtag = pf_get_mtag(*m0)) == NULL)) {
8189 			m_freem(*m0);
8190 			*m0 = NULL;
8191 			return (ENOMEM);
8192 		}
8193 
8194 		if (ifp != NULL) {
8195 			pd->pf_mtag->flags |= PF_MTAG_FLAG_ROUTE_TO;
8196 
8197 			pd->pf_mtag->if_index = ifp->if_index;
8198 			pd->pf_mtag->if_idxgen = ifp->if_idxgen;
8199 
8200 			MPASS(sa != NULL);
8201 
8202 			if (pd->af == AF_INET)
8203 				memcpy(&pd->pf_mtag->dst, sa,
8204 				    sizeof(struct sockaddr_in));
8205 			else
8206 				memcpy(&pd->pf_mtag->dst, sa,
8207 				    sizeof(struct sockaddr_in6));
8208 		}
8209 
8210 		if (s != NULL && s->nat_rule.ptr != NULL &&
8211 		    s->nat_rule.ptr->action == PF_RDR &&
8212 		    (
8213 #ifdef INET
8214 		    (pd->af == AF_INET && IN_LOOPBACK(ntohl(pd->dst->v4.s_addr))) ||
8215 #endif
8216 		    (pd->af == AF_INET6 && IN6_IS_ADDR_LOOPBACK(&pd->dst->v6)))) {
8217 			/*
8218 			 * If we're redirecting to loopback mark this packet
8219 			 * as being local. Otherwise it might get dropped
8220 			 * if dummynet re-injects.
8221 			 */
8222 			(*m0)->m_pkthdr.rcvif = V_loif;
8223 		}
8224 
8225 		if (pf_pdesc_to_dnflow(pd, r, s, &dnflow)) {
8226 			pd->pf_mtag->flags |= PF_MTAG_FLAG_DUMMYNET;
8227 			pd->pf_mtag->flags |= PF_MTAG_FLAG_DUMMYNETED;
8228 			ip_dn_io_ptr(m0, &dnflow);
8229 			if (*m0 != NULL) {
8230 				pd->pf_mtag->flags &= ~PF_MTAG_FLAG_ROUTE_TO;
8231 				pf_dummynet_flag_remove(*m0, pd->pf_mtag);
8232 			}
8233 		}
8234 	}
8235 
8236 	return (0);
8237 }
8238 
8239 #ifdef INET
8240 int
8241 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0,
8242     struct inpcb *inp, struct pf_rule_actions *default_actions)
8243 {
8244 	struct pfi_kkif		*kif;
8245 	u_short			 action, reason = 0;
8246 	struct mbuf		*m = *m0;
8247 	struct ip		*h = NULL;
8248 	struct m_tag		*mtag;
8249 	struct pf_krule		*a = NULL, *r = &V_pf_default_rule, *tr, *nr;
8250 	struct pf_kstate	*s = NULL;
8251 	struct pf_kruleset	*ruleset = NULL;
8252 	struct pf_pdesc		 pd;
8253 	int			 off, dirndx, use_2nd_queue = 0;
8254 	uint16_t		 tag;
8255 	uint8_t			 rt;
8256 
8257 	PF_RULES_RLOCK_TRACKER;
8258 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: bad direction %d\n", __func__, dir));
8259 	M_ASSERTPKTHDR(m);
8260 
8261 	if (!V_pf_status.running)
8262 		return (PF_PASS);
8263 
8264 	PF_RULES_RLOCK();
8265 
8266 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
8267 
8268 	if (__predict_false(kif == NULL)) {
8269 		DPFPRINTF(PF_DEBUG_URGENT,
8270 		    ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
8271 		PF_RULES_RUNLOCK();
8272 		return (PF_DROP);
8273 	}
8274 	if (kif->pfik_flags & PFI_IFLAG_SKIP) {
8275 		PF_RULES_RUNLOCK();
8276 		return (PF_PASS);
8277 	}
8278 
8279 	if (m->m_flags & M_SKIP_FIREWALL) {
8280 		PF_RULES_RUNLOCK();
8281 		return (PF_PASS);
8282 	}
8283 
8284 	memset(&pd, 0, sizeof(pd));
8285 	TAILQ_INIT(&pd.sctp_multihome_jobs);
8286 	if (default_actions != NULL)
8287 		memcpy(&pd.act, default_actions, sizeof(pd.act));
8288 	pd.pf_mtag = pf_find_mtag(m);
8289 
8290 	if (pd.pf_mtag != NULL && (pd.pf_mtag->flags & PF_MTAG_FLAG_ROUTE_TO)) {
8291 		pd.pf_mtag->flags &= ~PF_MTAG_FLAG_ROUTE_TO;
8292 
8293 		ifp = ifnet_byindexgen(pd.pf_mtag->if_index,
8294 		    pd.pf_mtag->if_idxgen);
8295 		if (ifp == NULL || ifp->if_flags & IFF_DYING) {
8296 			PF_RULES_RUNLOCK();
8297 			m_freem(*m0);
8298 			*m0 = NULL;
8299 			return (PF_PASS);
8300 		}
8301 		PF_RULES_RUNLOCK();
8302 		(ifp->if_output)(ifp, m, sintosa(&pd.pf_mtag->dst), NULL);
8303 		*m0 = NULL;
8304 		return (PF_PASS);
8305 	}
8306 
8307 	if (pd.pf_mtag && pd.pf_mtag->dnpipe) {
8308 		pd.act.dnpipe = pd.pf_mtag->dnpipe;
8309 		pd.act.flags = pd.pf_mtag->dnflags;
8310 	}
8311 
8312 	if (ip_dn_io_ptr != NULL && pd.pf_mtag != NULL &&
8313 	    pd.pf_mtag->flags & PF_MTAG_FLAG_DUMMYNET) {
8314 		/* Dummynet re-injects packets after they've
8315 		 * completed their delay. We've already
8316 		 * processed them, so pass unconditionally. */
8317 
8318 		/* But only once. We may see the packet multiple times (e.g.
8319 		 * PFIL_IN/PFIL_OUT). */
8320 		pf_dummynet_flag_remove(m, pd.pf_mtag);
8321 		PF_RULES_RUNLOCK();
8322 
8323 		return (PF_PASS);
8324 	}
8325 
8326 	pd.sport = pd.dport = NULL;
8327 	pd.proto_sum = NULL;
8328 	pd.dir = dir;
8329 	pd.sidx = (dir == PF_IN) ? 0 : 1;
8330 	pd.didx = (dir == PF_IN) ? 1 : 0;
8331 	pd.af = AF_INET;
8332 	pd.act.rtableid = -1;
8333 
8334 	if (m->m_len < sizeof(struct ip) &&
8335 	    (m = *m0 = m_pullup(*m0, sizeof(struct ip))) == NULL) {
8336 		DPFPRINTF(PF_DEBUG_URGENT,
8337 		    ("pf_test: m_len < sizeof(struct ip), pullup failed\n"));
8338 		PF_RULES_RUNLOCK();
8339 		return (PF_DROP);
8340 	}
8341 	h = mtod(m, struct ip *);
8342 	off = h->ip_hl << 2;
8343 
8344 	if (__predict_false(ip_divert_ptr != NULL) &&
8345 	    ((mtag = m_tag_locate(m, MTAG_PF_DIVERT, 0, NULL)) != NULL)) {
8346 		struct pf_divert_mtag *dt = (struct pf_divert_mtag *)(mtag+1);
8347 		if ((dt->idir == PF_DIVERT_MTAG_DIR_IN && dir == PF_IN) ||
8348 		    (dt->idir == PF_DIVERT_MTAG_DIR_OUT && dir == PF_OUT)) {
8349 			if (pd.pf_mtag == NULL &&
8350 			    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
8351 				action = PF_DROP;
8352 				goto done;
8353 			}
8354 			pd.pf_mtag->flags |= PF_MTAG_FLAG_PACKET_LOOPED;
8355 		}
8356 		if (pd.pf_mtag && pd.pf_mtag->flags & PF_MTAG_FLAG_FASTFWD_OURS_PRESENT) {
8357 			m->m_flags |= M_FASTFWD_OURS;
8358 			pd.pf_mtag->flags &= ~PF_MTAG_FLAG_FASTFWD_OURS_PRESENT;
8359 		}
8360 		m_tag_delete(m, mtag);
8361 
8362 		mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
8363 		if (mtag != NULL)
8364 			m_tag_delete(m, mtag);
8365 	} else if (pf_normalize_ip(m0, kif, &reason, &pd) != PF_PASS) {
8366 		/* We do IP header normalization and packet reassembly here */
8367 		action = PF_DROP;
8368 		goto done;
8369 	}
8370 	m = *m0;	/* pf_normalize messes with m0 */
8371 	h = mtod(m, struct ip *);
8372 
8373 	off = h->ip_hl << 2;
8374 	if (off < (int)sizeof(struct ip)) {
8375 		action = PF_DROP;
8376 		REASON_SET(&reason, PFRES_SHORT);
8377 		pd.act.log = PF_LOG_FORCE;
8378 		goto done;
8379 	}
8380 
8381 	pd.src = (struct pf_addr *)&h->ip_src;
8382 	pd.dst = (struct pf_addr *)&h->ip_dst;
8383 	pd.ip_sum = &h->ip_sum;
8384 	pd.proto = h->ip_p;
8385 	pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
8386 	pd.tot_len = ntohs(h->ip_len);
8387 
8388 	/* handle fragments that didn't get reassembled by normalization */
8389 	if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
8390 		action = pf_test_fragment(&r, kif, m, h, &pd, &a, &ruleset);
8391 		goto done;
8392 	}
8393 
8394 	switch (h->ip_p) {
8395 	case IPPROTO_TCP: {
8396 		if (!pf_pull_hdr(m, off, &pd.hdr.tcp, sizeof(pd.hdr.tcp),
8397 		    &action, &reason, AF_INET)) {
8398 			if (action != PF_PASS)
8399 				pd.act.log = PF_LOG_FORCE;
8400 			goto done;
8401 		}
8402 		pd.p_len = pd.tot_len - off - (pd.hdr.tcp.th_off << 2);
8403 
8404 		pd.sport = &pd.hdr.tcp.th_sport;
8405 		pd.dport = &pd.hdr.tcp.th_dport;
8406 
8407 		/* Respond to SYN with a syncookie. */
8408 		if ((pd.hdr.tcp.th_flags & (TH_SYN|TH_ACK|TH_RST)) == TH_SYN &&
8409 		    pd.dir == PF_IN && pf_synflood_check(&pd)) {
8410 			pf_syncookie_send(m, off, &pd);
8411 			action = PF_DROP;
8412 			break;
8413 		}
8414 
8415 		if ((pd.hdr.tcp.th_flags & TH_ACK) && pd.p_len == 0)
8416 			use_2nd_queue = 1;
8417 		action = pf_normalize_tcp(kif, m, 0, off, h, &pd);
8418 		if (action == PF_DROP)
8419 			goto done;
8420 		action = pf_test_state_tcp(&s, kif, m, off, h, &pd, &reason);
8421 		if (action == PF_PASS) {
8422 			if (V_pfsync_update_state_ptr != NULL)
8423 				V_pfsync_update_state_ptr(s);
8424 			r = s->rule.ptr;
8425 			a = s->anchor.ptr;
8426 		} else if (s == NULL) {
8427 			/* Validate remote SYN|ACK, re-create original SYN if
8428 			 * valid. */
8429 			if ((pd.hdr.tcp.th_flags & (TH_SYN|TH_ACK|TH_RST)) ==
8430 			    TH_ACK && pf_syncookie_validate(&pd) &&
8431 			    pd.dir == PF_IN) {
8432 				struct mbuf *msyn;
8433 
8434 				msyn = pf_syncookie_recreate_syn(h->ip_ttl, off,
8435 				    &pd);
8436 				if (msyn == NULL) {
8437 					action = PF_DROP;
8438 					break;
8439 				}
8440 
8441 				action = pf_test(dir, pflags, ifp, &msyn, inp,
8442 				    &pd.act);
8443 				m_freem(msyn);
8444 				if (action != PF_PASS)
8445 					break;
8446 
8447 				action = pf_test_state_tcp(&s, kif, m, off, h,
8448 				    &pd, &reason);
8449 				if (action != PF_PASS || s == NULL) {
8450 					action = PF_DROP;
8451 					break;
8452 				}
8453 
8454 				s->src.seqhi = ntohl(pd.hdr.tcp.th_ack) - 1;
8455 				s->src.seqlo = ntohl(pd.hdr.tcp.th_seq) - 1;
8456 				pf_set_protostate(s, PF_PEER_SRC, PF_TCPS_PROXY_DST);
8457 				action = pf_synproxy(&pd, &s, &reason);
8458 				break;
8459 			} else {
8460 				action = pf_test_rule(&r, &s, kif, m, off, &pd,
8461 				    &a, &ruleset, inp);
8462 			}
8463 		}
8464 		break;
8465 	}
8466 
8467 	case IPPROTO_UDP: {
8468 		if (!pf_pull_hdr(m, off, &pd.hdr.udp, sizeof(pd.hdr.udp),
8469 		    &action, &reason, AF_INET)) {
8470 			if (action != PF_PASS)
8471 				pd.act.log = PF_LOG_FORCE;
8472 			goto done;
8473 		}
8474 		pd.sport = &pd.hdr.udp.uh_sport;
8475 		pd.dport = &pd.hdr.udp.uh_dport;
8476 		if (pd.hdr.udp.uh_dport == 0 ||
8477 		    ntohs(pd.hdr.udp.uh_ulen) > m->m_pkthdr.len - off ||
8478 		    ntohs(pd.hdr.udp.uh_ulen) < sizeof(struct udphdr)) {
8479 			action = PF_DROP;
8480 			REASON_SET(&reason, PFRES_SHORT);
8481 			goto done;
8482 		}
8483 		action = pf_test_state_udp(&s, kif, m, off, h, &pd);
8484 		if (action == PF_PASS) {
8485 			if (V_pfsync_update_state_ptr != NULL)
8486 				V_pfsync_update_state_ptr(s);
8487 			r = s->rule.ptr;
8488 			a = s->anchor.ptr;
8489 		} else if (s == NULL)
8490 			action = pf_test_rule(&r, &s, kif, m, off, &pd,
8491 			    &a, &ruleset, inp);
8492 		break;
8493 	}
8494 
8495 	case IPPROTO_SCTP: {
8496 		if (!pf_pull_hdr(m, off, &pd.hdr.sctp, sizeof(pd.hdr.sctp),
8497 		    &action, &reason, AF_INET)) {
8498 			if (action != PF_PASS)
8499 				pd.act.log |= PF_LOG_FORCE;
8500 			goto done;
8501 		}
8502 		pd.p_len = pd.tot_len - off;
8503 
8504 		pd.sport = &pd.hdr.sctp.src_port;
8505 		pd.dport = &pd.hdr.sctp.dest_port;
8506 		if (pd.hdr.sctp.src_port == 0 || pd.hdr.sctp.dest_port == 0) {
8507 			action = PF_DROP;
8508 			REASON_SET(&reason, PFRES_SHORT);
8509 			goto done;
8510 		}
8511 		action = pf_normalize_sctp(dir, kif, m, 0, off, h, &pd);
8512 		if (action == PF_DROP)
8513 			goto done;
8514 		action = pf_test_state_sctp(&s, kif, m, off, h, &pd,
8515 		    &reason);
8516 		if (action == PF_PASS) {
8517 			if (V_pfsync_update_state_ptr != NULL)
8518 				V_pfsync_update_state_ptr(s);
8519 			r = s->rule.ptr;
8520 			a = s->anchor.ptr;
8521 		} else if (s == NULL) {
8522 			action = pf_test_rule(&r, &s, kif, m, off,
8523 			    &pd, &a, &ruleset, inp);
8524 		}
8525 		break;
8526 	}
8527 
8528 	case IPPROTO_ICMP: {
8529 		if (!pf_pull_hdr(m, off, &pd.hdr.icmp, ICMP_MINLEN,
8530 		    &action, &reason, AF_INET)) {
8531 			if (action != PF_PASS)
8532 				pd.act.log = PF_LOG_FORCE;
8533 			goto done;
8534 		}
8535 		action = pf_test_state_icmp(&s, kif, m, off, h, &pd, &reason);
8536 		if (action == PF_PASS) {
8537 			if (V_pfsync_update_state_ptr != NULL)
8538 				V_pfsync_update_state_ptr(s);
8539 			r = s->rule.ptr;
8540 			a = s->anchor.ptr;
8541 		} else if (s == NULL)
8542 			action = pf_test_rule(&r, &s, kif, m, off, &pd,
8543 			    &a, &ruleset, inp);
8544 		break;
8545 	}
8546 
8547 #ifdef INET6
8548 	case IPPROTO_ICMPV6: {
8549 		action = PF_DROP;
8550 		DPFPRINTF(PF_DEBUG_MISC,
8551 		    ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
8552 		goto done;
8553 	}
8554 #endif
8555 
8556 	default:
8557 		action = pf_test_state_other(&s, kif, m, &pd);
8558 		if (action == PF_PASS) {
8559 			if (V_pfsync_update_state_ptr != NULL)
8560 				V_pfsync_update_state_ptr(s);
8561 			r = s->rule.ptr;
8562 			a = s->anchor.ptr;
8563 		} else if (s == NULL)
8564 			action = pf_test_rule(&r, &s, kif, m, off, &pd,
8565 			    &a, &ruleset, inp);
8566 		break;
8567 	}
8568 
8569 done:
8570 	PF_RULES_RUNLOCK();
8571 	if (action == PF_PASS && h->ip_hl > 5 &&
8572 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
8573 		action = PF_DROP;
8574 		REASON_SET(&reason, PFRES_IPOPTIONS);
8575 		pd.act.log = PF_LOG_FORCE;
8576 		DPFPRINTF(PF_DEBUG_MISC,
8577 		    ("pf: dropping packet with ip options\n"));
8578 	}
8579 
8580 	if (s) {
8581 		uint8_t log = pd.act.log;
8582 		memcpy(&pd.act, &s->act, sizeof(struct pf_rule_actions));
8583 		pd.act.log |= log;
8584 		tag = s->tag;
8585 		rt = s->rt;
8586 	} else {
8587 		tag = r->tag;
8588 		rt = r->rt;
8589 	}
8590 
8591 	if (tag > 0 && pf_tag_packet(m, &pd, tag)) {
8592 		action = PF_DROP;
8593 		REASON_SET(&reason, PFRES_MEMORY);
8594 	}
8595 
8596 	pf_scrub_ip(&m, &pd);
8597 	if (pd.proto == IPPROTO_TCP && pd.act.max_mss)
8598 		pf_normalize_mss(m, off, &pd);
8599 
8600 	if (pd.act.rtableid >= 0)
8601 		M_SETFIB(m, pd.act.rtableid);
8602 
8603 	if (pd.act.flags & PFSTATE_SETPRIO) {
8604 		if (pd.tos & IPTOS_LOWDELAY)
8605 			use_2nd_queue = 1;
8606 		if (vlan_set_pcp(m, pd.act.set_prio[use_2nd_queue])) {
8607 			action = PF_DROP;
8608 			REASON_SET(&reason, PFRES_MEMORY);
8609 			pd.act.log = PF_LOG_FORCE;
8610 			DPFPRINTF(PF_DEBUG_MISC,
8611 			    ("pf: failed to allocate 802.1q mtag\n"));
8612 		}
8613 	}
8614 
8615 #ifdef ALTQ
8616 	if (action == PF_PASS && pd.act.qid) {
8617 		if (pd.pf_mtag == NULL &&
8618 		    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
8619 			action = PF_DROP;
8620 			REASON_SET(&reason, PFRES_MEMORY);
8621 		} else {
8622 			if (s != NULL)
8623 				pd.pf_mtag->qid_hash = pf_state_hash(s);
8624 			if (use_2nd_queue || (pd.tos & IPTOS_LOWDELAY))
8625 				pd.pf_mtag->qid = pd.act.pqid;
8626 			else
8627 				pd.pf_mtag->qid = pd.act.qid;
8628 			/* Add hints for ecn. */
8629 			pd.pf_mtag->hdr = h;
8630 		}
8631 	}
8632 #endif /* ALTQ */
8633 
8634 	/*
8635 	 * connections redirected to loopback should not match sockets
8636 	 * bound specifically to loopback due to security implications,
8637 	 * see tcp_input() and in_pcblookup_listen().
8638 	 */
8639 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
8640 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
8641 	    (s->nat_rule.ptr->action == PF_RDR ||
8642 	    s->nat_rule.ptr->action == PF_BINAT) &&
8643 	    IN_LOOPBACK(ntohl(pd.dst->v4.s_addr)))
8644 		m->m_flags |= M_SKIP_FIREWALL;
8645 
8646 	if (__predict_false(ip_divert_ptr != NULL) && action == PF_PASS &&
8647 	    r->divert.port && !PACKET_LOOPED(&pd)) {
8648 		mtag = m_tag_alloc(MTAG_PF_DIVERT, 0,
8649 		    sizeof(struct pf_divert_mtag), M_NOWAIT | M_ZERO);
8650 		if (mtag != NULL) {
8651 			((struct pf_divert_mtag *)(mtag+1))->port =
8652 			    ntohs(r->divert.port);
8653 			((struct pf_divert_mtag *)(mtag+1))->idir =
8654 			    (dir == PF_IN) ? PF_DIVERT_MTAG_DIR_IN :
8655 			    PF_DIVERT_MTAG_DIR_OUT;
8656 
8657 			if (s)
8658 				PF_STATE_UNLOCK(s);
8659 
8660 			m_tag_prepend(m, mtag);
8661 			if (m->m_flags & M_FASTFWD_OURS) {
8662 				if (pd.pf_mtag == NULL &&
8663 				    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
8664 					action = PF_DROP;
8665 					REASON_SET(&reason, PFRES_MEMORY);
8666 					pd.act.log = PF_LOG_FORCE;
8667 					DPFPRINTF(PF_DEBUG_MISC,
8668 					    ("pf: failed to allocate tag\n"));
8669 				} else {
8670 					pd.pf_mtag->flags |=
8671 					    PF_MTAG_FLAG_FASTFWD_OURS_PRESENT;
8672 					m->m_flags &= ~M_FASTFWD_OURS;
8673 				}
8674 			}
8675 			ip_divert_ptr(*m0, dir == PF_IN);
8676 			*m0 = NULL;
8677 
8678 			return (action);
8679 		} else {
8680 			/* XXX: ipfw has the same behaviour! */
8681 			action = PF_DROP;
8682 			REASON_SET(&reason, PFRES_MEMORY);
8683 			pd.act.log = PF_LOG_FORCE;
8684 			DPFPRINTF(PF_DEBUG_MISC,
8685 			    ("pf: failed to allocate divert tag\n"));
8686 		}
8687 	}
8688 	/* this flag will need revising if the pkt is forwarded */
8689 	if (pd.pf_mtag)
8690 		pd.pf_mtag->flags &= ~PF_MTAG_FLAG_PACKET_LOOPED;
8691 
8692 	if (pd.act.log) {
8693 		struct pf_krule		*lr;
8694 		struct pf_krule_item	*ri;
8695 
8696 		if (s != NULL && s->nat_rule.ptr != NULL &&
8697 		    s->nat_rule.ptr->log & PF_LOG_ALL)
8698 			lr = s->nat_rule.ptr;
8699 		else
8700 			lr = r;
8701 
8702 		if (pd.act.log & PF_LOG_FORCE || lr->log & PF_LOG_ALL)
8703 			PFLOG_PACKET(kif, m, AF_INET, action, reason, lr, a,
8704 			    ruleset, &pd, (s == NULL));
8705 		if (s) {
8706 			SLIST_FOREACH(ri, &s->match_rules, entry)
8707 				if (ri->r->log & PF_LOG_ALL)
8708 					PFLOG_PACKET(kif, m, AF_INET, action,
8709 					    reason, ri->r, a, ruleset, &pd, 0);
8710 		}
8711 	}
8712 
8713 	pf_counter_u64_critical_enter();
8714 	pf_counter_u64_add_protected(&kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS],
8715 	    pd.tot_len);
8716 	pf_counter_u64_add_protected(&kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS],
8717 	    1);
8718 
8719 	if (action == PF_PASS || r->action == PF_DROP) {
8720 		dirndx = (dir == PF_OUT);
8721 		pf_counter_u64_add_protected(&r->packets[dirndx], 1);
8722 		pf_counter_u64_add_protected(&r->bytes[dirndx], pd.tot_len);
8723 		pf_update_timestamp(r);
8724 
8725 		if (a != NULL) {
8726 			pf_counter_u64_add_protected(&a->packets[dirndx], 1);
8727 			pf_counter_u64_add_protected(&a->bytes[dirndx], pd.tot_len);
8728 		}
8729 		if (s != NULL) {
8730 			struct pf_krule_item	*ri;
8731 
8732 			if (s->nat_rule.ptr != NULL) {
8733 				pf_counter_u64_add_protected(&s->nat_rule.ptr->packets[dirndx],
8734 				    1);
8735 				pf_counter_u64_add_protected(&s->nat_rule.ptr->bytes[dirndx],
8736 				    pd.tot_len);
8737 			}
8738 			if (s->src_node != NULL) {
8739 				counter_u64_add(s->src_node->packets[dirndx],
8740 				    1);
8741 				counter_u64_add(s->src_node->bytes[dirndx],
8742 				    pd.tot_len);
8743 			}
8744 			if (s->nat_src_node != NULL) {
8745 				counter_u64_add(s->nat_src_node->packets[dirndx],
8746 				    1);
8747 				counter_u64_add(s->nat_src_node->bytes[dirndx],
8748 				    pd.tot_len);
8749 			}
8750 			dirndx = (dir == s->direction) ? 0 : 1;
8751 			s->packets[dirndx]++;
8752 			s->bytes[dirndx] += pd.tot_len;
8753 			SLIST_FOREACH(ri, &s->match_rules, entry) {
8754 				pf_counter_u64_add_protected(&ri->r->packets[dirndx], 1);
8755 				pf_counter_u64_add_protected(&ri->r->bytes[dirndx], pd.tot_len);
8756 			}
8757 		}
8758 		tr = r;
8759 		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
8760 		if (nr != NULL && r == &V_pf_default_rule)
8761 			tr = nr;
8762 		if (tr->src.addr.type == PF_ADDR_TABLE)
8763 			pfr_update_stats(tr->src.addr.p.tbl,
8764 			    (s == NULL) ? pd.src :
8765 			    &s->key[(s->direction == PF_IN)]->
8766 				addr[(s->direction == PF_OUT)],
8767 			    pd.af, pd.tot_len, dir == PF_OUT,
8768 			    r->action == PF_PASS, tr->src.neg);
8769 		if (tr->dst.addr.type == PF_ADDR_TABLE)
8770 			pfr_update_stats(tr->dst.addr.p.tbl,
8771 			    (s == NULL) ? pd.dst :
8772 			    &s->key[(s->direction == PF_IN)]->
8773 				addr[(s->direction == PF_IN)],
8774 			    pd.af, pd.tot_len, dir == PF_OUT,
8775 			    r->action == PF_PASS, tr->dst.neg);
8776 	}
8777 	pf_counter_u64_critical_exit();
8778 
8779 	switch (action) {
8780 	case PF_SYNPROXY_DROP:
8781 		m_freem(*m0);
8782 	case PF_DEFER:
8783 		*m0 = NULL;
8784 		action = PF_PASS;
8785 		break;
8786 	case PF_DROP:
8787 		m_freem(*m0);
8788 		*m0 = NULL;
8789 		break;
8790 	default:
8791 		/* pf_route() returns unlocked. */
8792 		if (rt) {
8793 			pf_route(m0, r, kif->pfik_ifp, s, &pd, inp);
8794 			goto out;
8795 		}
8796 		if (pf_dummynet(&pd, s, r, m0) != 0) {
8797 			action = PF_DROP;
8798 			REASON_SET(&reason, PFRES_MEMORY);
8799 		}
8800 		break;
8801 	}
8802 
8803 	SDT_PROBE4(pf, ip, test, done, action, reason, r, s);
8804 
8805 	if (s && action != PF_DROP) {
8806 		if (!s->if_index_in && dir == PF_IN)
8807 			s->if_index_in = ifp->if_index;
8808 		else if (!s->if_index_out && dir == PF_OUT)
8809 			s->if_index_out = ifp->if_index;
8810 	}
8811 
8812 	if (s)
8813 		PF_STATE_UNLOCK(s);
8814 
8815 out:
8816 	pf_sctp_multihome_delayed(&pd, off, kif, s, action);
8817 
8818 	return (action);
8819 }
8820 #endif /* INET */
8821 
8822 #ifdef INET6
8823 int
8824 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp,
8825     struct pf_rule_actions *default_actions)
8826 {
8827 	struct pfi_kkif		*kif;
8828 	u_short			 action, reason = 0;
8829 	struct mbuf		*m = *m0, *n = NULL;
8830 	struct m_tag		*mtag;
8831 	struct ip6_hdr		*h = NULL;
8832 	struct pf_krule		*a = NULL, *r = &V_pf_default_rule, *tr, *nr;
8833 	struct pf_kstate	*s = NULL;
8834 	struct pf_kruleset	*ruleset = NULL;
8835 	struct pf_pdesc		 pd;
8836 	int			 off, terminal = 0, dirndx, rh_cnt = 0, use_2nd_queue = 0;
8837 	uint16_t		 tag;
8838 	uint8_t			 rt;
8839 
8840 	PF_RULES_RLOCK_TRACKER;
8841 	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: bad direction %d\n", __func__, dir));
8842 	M_ASSERTPKTHDR(m);
8843 
8844 	if (!V_pf_status.running)
8845 		return (PF_PASS);
8846 
8847 	PF_RULES_RLOCK();
8848 
8849 	kif = (struct pfi_kkif *)ifp->if_pf_kif;
8850 	if (__predict_false(kif == NULL)) {
8851 		DPFPRINTF(PF_DEBUG_URGENT,
8852 		    ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
8853 		PF_RULES_RUNLOCK();
8854 		return (PF_DROP);
8855 	}
8856 	if (kif->pfik_flags & PFI_IFLAG_SKIP) {
8857 		PF_RULES_RUNLOCK();
8858 		return (PF_PASS);
8859 	}
8860 
8861 	if (m->m_flags & M_SKIP_FIREWALL) {
8862 		PF_RULES_RUNLOCK();
8863 		return (PF_PASS);
8864 	}
8865 
8866 	/*
8867 	 * If we end up changing IP addresses (e.g. binat) the stack may get
8868 	 * confused and fail to send the icmp6 packet too big error. Just send
8869 	 * it here, before we do any NAT.
8870 	 */
8871 	if (dir == PF_OUT && pflags & PFIL_FWD && IN6_LINKMTU(ifp) < pf_max_frag_size(m)) {
8872 		PF_RULES_RUNLOCK();
8873 		*m0 = NULL;
8874 		icmp6_error(m, ICMP6_PACKET_TOO_BIG, 0, IN6_LINKMTU(ifp));
8875 		return (PF_DROP);
8876 	}
8877 
8878 	memset(&pd, 0, sizeof(pd));
8879 	TAILQ_INIT(&pd.sctp_multihome_jobs);
8880 	if (default_actions != NULL)
8881 		memcpy(&pd.act, default_actions, sizeof(pd.act));
8882 	pd.pf_mtag = pf_find_mtag(m);
8883 
8884 	if (pd.pf_mtag != NULL && (pd.pf_mtag->flags & PF_MTAG_FLAG_ROUTE_TO)) {
8885 		pd.pf_mtag->flags &= ~PF_MTAG_FLAG_ROUTE_TO;
8886 
8887 		ifp = ifnet_byindexgen(pd.pf_mtag->if_index,
8888 		    pd.pf_mtag->if_idxgen);
8889 		if (ifp == NULL || ifp->if_flags & IFF_DYING) {
8890 			PF_RULES_RUNLOCK();
8891 			m_freem(*m0);
8892 			*m0 = NULL;
8893 			return (PF_PASS);
8894 		}
8895 		PF_RULES_RUNLOCK();
8896 		nd6_output_ifp(ifp, ifp, m,
8897                     (struct sockaddr_in6 *)&pd.pf_mtag->dst, NULL);
8898 		*m0 = NULL;
8899 		return (PF_PASS);
8900 	}
8901 
8902 	if (pd.pf_mtag && pd.pf_mtag->dnpipe) {
8903 		pd.act.dnpipe = pd.pf_mtag->dnpipe;
8904 		pd.act.flags = pd.pf_mtag->dnflags;
8905 	}
8906 
8907 	if (ip_dn_io_ptr != NULL && pd.pf_mtag != NULL &&
8908 	    pd.pf_mtag->flags & PF_MTAG_FLAG_DUMMYNET) {
8909 		pf_dummynet_flag_remove(m, pd.pf_mtag);
8910 		/* Dummynet re-injects packets after they've
8911 		 * completed their delay. We've already
8912 		 * processed them, so pass unconditionally. */
8913 		PF_RULES_RUNLOCK();
8914 		return (PF_PASS);
8915 	}
8916 
8917 	pd.sport = pd.dport = NULL;
8918 	pd.ip_sum = NULL;
8919 	pd.proto_sum = NULL;
8920 	pd.dir = dir;
8921 	pd.sidx = (dir == PF_IN) ? 0 : 1;
8922 	pd.didx = (dir == PF_IN) ? 1 : 0;
8923 	pd.af = AF_INET6;
8924 	pd.act.rtableid = -1;
8925 
8926 	h = mtod(m, struct ip6_hdr *);
8927 	off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
8928 
8929 	/* We do IP header normalization and packet reassembly here */
8930 	if (pf_normalize_ip6(m0, kif, &reason, &pd) != PF_PASS) {
8931 		action = PF_DROP;
8932 		goto done;
8933 	}
8934 	m = *m0;	/* pf_normalize messes with m0 */
8935 	h = mtod(m, struct ip6_hdr *);
8936 	off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
8937 
8938 	/*
8939 	 * we do not support jumbogram.  if we keep going, zero ip6_plen
8940 	 * will do something bad, so drop the packet for now.
8941 	 */
8942 	if (htons(h->ip6_plen) == 0) {
8943 		action = PF_DROP;
8944 		REASON_SET(&reason, PFRES_NORM);	/*XXX*/
8945 		goto done;
8946 	}
8947 
8948 	pd.src = (struct pf_addr *)&h->ip6_src;
8949 	pd.dst = (struct pf_addr *)&h->ip6_dst;
8950 	pd.tos = IPV6_DSCP(h);
8951 	pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
8952 
8953 	pd.proto = h->ip6_nxt;
8954 	do {
8955 		switch (pd.proto) {
8956 		case IPPROTO_FRAGMENT:
8957 			action = pf_test_fragment(&r, kif, m, h, &pd, &a,
8958 			    &ruleset);
8959 			if (action == PF_DROP)
8960 				REASON_SET(&reason, PFRES_FRAG);
8961 			goto done;
8962 		case IPPROTO_ROUTING: {
8963 			struct ip6_rthdr rthdr;
8964 
8965 			if (rh_cnt++) {
8966 				DPFPRINTF(PF_DEBUG_MISC,
8967 				    ("pf: IPv6 more than one rthdr\n"));
8968 				action = PF_DROP;
8969 				REASON_SET(&reason, PFRES_IPOPTIONS);
8970 				pd.act.log = PF_LOG_FORCE;
8971 				goto done;
8972 			}
8973 			if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
8974 			    &reason, pd.af)) {
8975 				DPFPRINTF(PF_DEBUG_MISC,
8976 				    ("pf: IPv6 short rthdr\n"));
8977 				action = PF_DROP;
8978 				REASON_SET(&reason, PFRES_SHORT);
8979 				pd.act.log = PF_LOG_FORCE;
8980 				goto done;
8981 			}
8982 			if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
8983 				DPFPRINTF(PF_DEBUG_MISC,
8984 				    ("pf: IPv6 rthdr0\n"));
8985 				action = PF_DROP;
8986 				REASON_SET(&reason, PFRES_IPOPTIONS);
8987 				pd.act.log = PF_LOG_FORCE;
8988 				goto done;
8989 			}
8990 			/* FALLTHROUGH */
8991 		}
8992 		case IPPROTO_AH:
8993 		case IPPROTO_HOPOPTS:
8994 		case IPPROTO_DSTOPTS: {
8995 			/* get next header and header length */
8996 			struct ip6_ext	opt6;
8997 
8998 			if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
8999 			    NULL, &reason, pd.af)) {
9000 				DPFPRINTF(PF_DEBUG_MISC,
9001 				    ("pf: IPv6 short opt\n"));
9002 				action = PF_DROP;
9003 				pd.act.log = PF_LOG_FORCE;
9004 				goto done;
9005 			}
9006 			if (pd.proto == IPPROTO_AH)
9007 				off += (opt6.ip6e_len + 2) * 4;
9008 			else
9009 				off += (opt6.ip6e_len + 1) * 8;
9010 			pd.proto = opt6.ip6e_nxt;
9011 			/* goto the next header */
9012 			break;
9013 		}
9014 		default:
9015 			terminal++;
9016 			break;
9017 		}
9018 	} while (!terminal);
9019 
9020 	/* if there's no routing header, use unmodified mbuf for checksumming */
9021 	if (!n)
9022 		n = m;
9023 
9024 	switch (pd.proto) {
9025 	case IPPROTO_TCP: {
9026 		if (!pf_pull_hdr(m, off, &pd.hdr.tcp, sizeof(pd.hdr.tcp),
9027 		    &action, &reason, AF_INET6)) {
9028 			if (action != PF_PASS)
9029 				pd.act.log |= PF_LOG_FORCE;
9030 			goto done;
9031 		}
9032 		pd.p_len = pd.tot_len - off - (pd.hdr.tcp.th_off << 2);
9033 		pd.sport = &pd.hdr.tcp.th_sport;
9034 		pd.dport = &pd.hdr.tcp.th_dport;
9035 
9036 		/* Respond to SYN with a syncookie. */
9037 		if ((pd.hdr.tcp.th_flags & (TH_SYN|TH_ACK|TH_RST)) == TH_SYN &&
9038 		    pd.dir == PF_IN && pf_synflood_check(&pd)) {
9039 			pf_syncookie_send(m, off, &pd);
9040 			action = PF_DROP;
9041 			break;
9042 		}
9043 
9044 		action = pf_normalize_tcp(kif, m, 0, off, h, &pd);
9045 		if (action == PF_DROP)
9046 			goto done;
9047 		action = pf_test_state_tcp(&s, kif, m, off, h, &pd, &reason);
9048 		if (action == PF_PASS) {
9049 			if (V_pfsync_update_state_ptr != NULL)
9050 				V_pfsync_update_state_ptr(s);
9051 			r = s->rule.ptr;
9052 			a = s->anchor.ptr;
9053 		} else if (s == NULL) {
9054 			/* Validate remote SYN|ACK, re-create original SYN if
9055 			 * valid. */
9056 			if ((pd.hdr.tcp.th_flags & (TH_SYN|TH_ACK|TH_RST)) ==
9057 			    TH_ACK && pf_syncookie_validate(&pd) &&
9058 			    pd.dir == PF_IN) {
9059 				struct mbuf *msyn;
9060 
9061 				msyn = pf_syncookie_recreate_syn(h->ip6_hlim,
9062 				    off, &pd);
9063 				if (msyn == NULL) {
9064 					action = PF_DROP;
9065 					break;
9066 				}
9067 
9068 				action = pf_test6(dir, pflags, ifp, &msyn, inp,
9069 				    &pd.act);
9070 				m_freem(msyn);
9071 				if (action != PF_PASS)
9072 					break;
9073 
9074 				action = pf_test_state_tcp(&s, kif, m, off, h,
9075 				    &pd, &reason);
9076 				if (action != PF_PASS || s == NULL) {
9077 					action = PF_DROP;
9078 					break;
9079 				}
9080 
9081 				s->src.seqhi = ntohl(pd.hdr.tcp.th_ack) - 1;
9082 				s->src.seqlo = ntohl(pd.hdr.tcp.th_seq) - 1;
9083 				pf_set_protostate(s, PF_PEER_SRC, PF_TCPS_PROXY_DST);
9084 
9085 				action = pf_synproxy(&pd, &s, &reason);
9086 				break;
9087 			} else {
9088 				action = pf_test_rule(&r, &s, kif, m, off, &pd,
9089 				    &a, &ruleset, inp);
9090 			}
9091 		}
9092 		break;
9093 	}
9094 
9095 	case IPPROTO_UDP: {
9096 		if (!pf_pull_hdr(m, off, &pd.hdr.udp, sizeof(pd.hdr.udp),
9097 		    &action, &reason, AF_INET6)) {
9098 			if (action != PF_PASS)
9099 				pd.act.log |= PF_LOG_FORCE;
9100 			goto done;
9101 		}
9102 		pd.sport = &pd.hdr.udp.uh_sport;
9103 		pd.dport = &pd.hdr.udp.uh_dport;
9104 		if (pd.hdr.udp.uh_dport == 0 ||
9105 		    ntohs(pd.hdr.udp.uh_ulen) > m->m_pkthdr.len - off ||
9106 		    ntohs(pd.hdr.udp.uh_ulen) < sizeof(struct udphdr)) {
9107 			action = PF_DROP;
9108 			REASON_SET(&reason, PFRES_SHORT);
9109 			goto done;
9110 		}
9111 		action = pf_test_state_udp(&s, kif, m, off, h, &pd);
9112 		if (action == PF_PASS) {
9113 			if (V_pfsync_update_state_ptr != NULL)
9114 				V_pfsync_update_state_ptr(s);
9115 			r = s->rule.ptr;
9116 			a = s->anchor.ptr;
9117 		} else if (s == NULL)
9118 			action = pf_test_rule(&r, &s, kif, m, off, &pd,
9119 			    &a, &ruleset, inp);
9120 		break;
9121 	}
9122 
9123 	case IPPROTO_SCTP: {
9124 		if (!pf_pull_hdr(m, off, &pd.hdr.sctp, sizeof(pd.hdr.sctp),
9125 		    &action, &reason, AF_INET6)) {
9126 			if (action != PF_PASS)
9127 				pd.act.log |= PF_LOG_FORCE;
9128 			goto done;
9129 		}
9130 		pd.sport = &pd.hdr.sctp.src_port;
9131 		pd.dport = &pd.hdr.sctp.dest_port;
9132 		if (pd.hdr.sctp.src_port == 0 || pd.hdr.sctp.dest_port == 0) {
9133 			action = PF_DROP;
9134 			REASON_SET(&reason, PFRES_SHORT);
9135 			goto done;
9136 		}
9137 		action = pf_normalize_sctp(dir, kif, m, 0, off, h, &pd);
9138 		if (action == PF_DROP)
9139 			goto done;
9140 		action = pf_test_state_sctp(&s, kif, m, off, h, &pd,
9141 		    &reason);
9142 		if (action == PF_PASS) {
9143 			if (V_pfsync_update_state_ptr != NULL)
9144 				V_pfsync_update_state_ptr(s);
9145 			r = s->rule.ptr;
9146 			a = s->anchor.ptr;
9147 		} else if (s == NULL) {
9148 			action = pf_test_rule(&r, &s, kif, m, off,
9149 			    &pd, &a, &ruleset, inp);
9150 		}
9151 		break;
9152 	}
9153 
9154 	case IPPROTO_ICMP: {
9155 		action = PF_DROP;
9156 		DPFPRINTF(PF_DEBUG_MISC,
9157 		    ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
9158 		goto done;
9159 	}
9160 
9161 	case IPPROTO_ICMPV6: {
9162 		if (!pf_pull_hdr(m, off, &pd.hdr.icmp6, sizeof(pd.hdr.icmp6),
9163 		    &action, &reason, AF_INET6)) {
9164 			if (action != PF_PASS)
9165 				pd.act.log |= PF_LOG_FORCE;
9166 			goto done;
9167 		}
9168 		action = pf_test_state_icmp(&s, kif, m, off, h, &pd, &reason);
9169 		if (action == PF_PASS) {
9170 			if (V_pfsync_update_state_ptr != NULL)
9171 				V_pfsync_update_state_ptr(s);
9172 			r = s->rule.ptr;
9173 			a = s->anchor.ptr;
9174 		} else if (s == NULL)
9175 			action = pf_test_rule(&r, &s, kif, m, off, &pd,
9176 			    &a, &ruleset, inp);
9177 		break;
9178 	}
9179 
9180 	default:
9181 		action = pf_test_state_other(&s, kif, m, &pd);
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 done:
9194 	PF_RULES_RUNLOCK();
9195 	if (n != m) {
9196 		m_freem(n);
9197 		n = NULL;
9198 	}
9199 
9200 	/* handle dangerous IPv6 extension headers. */
9201 	if (action == PF_PASS && rh_cnt &&
9202 	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
9203 		action = PF_DROP;
9204 		REASON_SET(&reason, PFRES_IPOPTIONS);
9205 		pd.act.log = r->log;
9206 		DPFPRINTF(PF_DEBUG_MISC,
9207 		    ("pf: dropping packet with dangerous v6 headers\n"));
9208 	}
9209 
9210 	if (s) {
9211 		uint8_t log = pd.act.log;
9212 		memcpy(&pd.act, &s->act, sizeof(struct pf_rule_actions));
9213 		pd.act.log |= log;
9214 		tag = s->tag;
9215 		rt = s->rt;
9216 	} else {
9217 		tag = r->tag;
9218 		rt = r->rt;
9219 	}
9220 
9221 	if (tag > 0 && pf_tag_packet(m, &pd, tag)) {
9222 		action = PF_DROP;
9223 		REASON_SET(&reason, PFRES_MEMORY);
9224 	}
9225 
9226 	pf_scrub_ip6(&m, &pd);
9227 	if (pd.proto == IPPROTO_TCP && pd.act.max_mss)
9228 		pf_normalize_mss(m, off, &pd);
9229 
9230 	if (pd.act.rtableid >= 0)
9231 		M_SETFIB(m, pd.act.rtableid);
9232 
9233 	if (pd.act.flags & PFSTATE_SETPRIO) {
9234 		if (pd.tos & IPTOS_LOWDELAY)
9235 			use_2nd_queue = 1;
9236 		if (vlan_set_pcp(m, pd.act.set_prio[use_2nd_queue])) {
9237 			action = PF_DROP;
9238 			REASON_SET(&reason, PFRES_MEMORY);
9239 			pd.act.log = PF_LOG_FORCE;
9240 			DPFPRINTF(PF_DEBUG_MISC,
9241 			    ("pf: failed to allocate 802.1q mtag\n"));
9242 		}
9243 	}
9244 
9245 #ifdef ALTQ
9246 	if (action == PF_PASS && pd.act.qid) {
9247 		if (pd.pf_mtag == NULL &&
9248 		    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
9249 			action = PF_DROP;
9250 			REASON_SET(&reason, PFRES_MEMORY);
9251 		} else {
9252 			if (s != NULL)
9253 				pd.pf_mtag->qid_hash = pf_state_hash(s);
9254 			if (pd.tos & IPTOS_LOWDELAY)
9255 				pd.pf_mtag->qid = pd.act.pqid;
9256 			else
9257 				pd.pf_mtag->qid = pd.act.qid;
9258 			/* Add hints for ecn. */
9259 			pd.pf_mtag->hdr = h;
9260 		}
9261 	}
9262 #endif /* ALTQ */
9263 
9264 	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
9265 	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
9266 	    (s->nat_rule.ptr->action == PF_RDR ||
9267 	    s->nat_rule.ptr->action == PF_BINAT) &&
9268 	    IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
9269 		m->m_flags |= M_SKIP_FIREWALL;
9270 
9271 	/* XXX: Anybody working on it?! */
9272 	if (r->divert.port)
9273 		printf("pf: divert(9) is not supported for IPv6\n");
9274 
9275 	if (pd.act.log) {
9276 		struct pf_krule		*lr;
9277 		struct pf_krule_item	*ri;
9278 
9279 		if (s != NULL && s->nat_rule.ptr != NULL &&
9280 		    s->nat_rule.ptr->log & PF_LOG_ALL)
9281 			lr = s->nat_rule.ptr;
9282 		else
9283 			lr = r;
9284 
9285 		if (pd.act.log & PF_LOG_FORCE || lr->log & PF_LOG_ALL)
9286 			PFLOG_PACKET(kif, m, AF_INET6, action, reason, lr, a, ruleset,
9287 			    &pd, (s == NULL));
9288 		if (s) {
9289 			SLIST_FOREACH(ri, &s->match_rules, entry)
9290 				if (ri->r->log & PF_LOG_ALL)
9291 					PFLOG_PACKET(kif, m, AF_INET6, action, reason,
9292 					    ri->r, a, ruleset, &pd, 0);
9293 		}
9294 	}
9295 
9296 	pf_counter_u64_critical_enter();
9297 	pf_counter_u64_add_protected(&kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS],
9298 	    pd.tot_len);
9299 	pf_counter_u64_add_protected(&kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS],
9300 	    1);
9301 
9302 	if (action == PF_PASS || r->action == PF_DROP) {
9303 		dirndx = (dir == PF_OUT);
9304 		pf_counter_u64_add_protected(&r->packets[dirndx], 1);
9305 		pf_counter_u64_add_protected(&r->bytes[dirndx], pd.tot_len);
9306 		if (a != NULL) {
9307 			pf_counter_u64_add_protected(&a->packets[dirndx], 1);
9308 			pf_counter_u64_add_protected(&a->bytes[dirndx], pd.tot_len);
9309 		}
9310 		if (s != NULL) {
9311 			if (s->nat_rule.ptr != NULL) {
9312 				pf_counter_u64_add_protected(&s->nat_rule.ptr->packets[dirndx],
9313 				    1);
9314 				pf_counter_u64_add_protected(&s->nat_rule.ptr->bytes[dirndx],
9315 				    pd.tot_len);
9316 			}
9317 			if (s->src_node != NULL) {
9318 				counter_u64_add(s->src_node->packets[dirndx],
9319 				    1);
9320 				counter_u64_add(s->src_node->bytes[dirndx],
9321 				    pd.tot_len);
9322 			}
9323 			if (s->nat_src_node != NULL) {
9324 				counter_u64_add(s->nat_src_node->packets[dirndx],
9325 				    1);
9326 				counter_u64_add(s->nat_src_node->bytes[dirndx],
9327 				    pd.tot_len);
9328 			}
9329 			dirndx = (dir == s->direction) ? 0 : 1;
9330 			s->packets[dirndx]++;
9331 			s->bytes[dirndx] += pd.tot_len;
9332 		}
9333 		tr = r;
9334 		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
9335 		if (nr != NULL && r == &V_pf_default_rule)
9336 			tr = nr;
9337 		if (tr->src.addr.type == PF_ADDR_TABLE)
9338 			pfr_update_stats(tr->src.addr.p.tbl,
9339 			    (s == NULL) ? pd.src :
9340 			    &s->key[(s->direction == PF_IN)]->addr[0],
9341 			    pd.af, pd.tot_len, dir == PF_OUT,
9342 			    r->action == PF_PASS, tr->src.neg);
9343 		if (tr->dst.addr.type == PF_ADDR_TABLE)
9344 			pfr_update_stats(tr->dst.addr.p.tbl,
9345 			    (s == NULL) ? pd.dst :
9346 			    &s->key[(s->direction == PF_IN)]->addr[1],
9347 			    pd.af, pd.tot_len, dir == PF_OUT,
9348 			    r->action == PF_PASS, tr->dst.neg);
9349 	}
9350 	pf_counter_u64_critical_exit();
9351 
9352 	switch (action) {
9353 	case PF_SYNPROXY_DROP:
9354 		m_freem(*m0);
9355 	case PF_DEFER:
9356 		*m0 = NULL;
9357 		action = PF_PASS;
9358 		break;
9359 	case PF_DROP:
9360 		m_freem(*m0);
9361 		*m0 = NULL;
9362 		break;
9363 	default:
9364 		/* pf_route6() returns unlocked. */
9365 		if (rt) {
9366 			pf_route6(m0, r, kif->pfik_ifp, s, &pd, inp);
9367 			goto out;
9368 		}
9369 		if (pf_dummynet(&pd, s, r, m0) != 0) {
9370 			action = PF_DROP;
9371 			REASON_SET(&reason, PFRES_MEMORY);
9372 		}
9373 		break;
9374 	}
9375 
9376 	if (s && action != PF_DROP) {
9377 		if (!s->if_index_in && dir == PF_IN)
9378 			s->if_index_in = ifp->if_index;
9379 		else if (!s->if_index_out && dir == PF_OUT)
9380 			s->if_index_out = ifp->if_index;
9381 	}
9382 
9383 	if (s)
9384 		PF_STATE_UNLOCK(s);
9385 
9386 	/* If reassembled packet passed, create new fragments. */
9387 	if (action == PF_PASS && *m0 && dir == PF_OUT &&
9388 	    (mtag = m_tag_find(m, PACKET_TAG_PF_REASSEMBLED, NULL)) != NULL)
9389 		action = pf_refragment6(ifp, m0, mtag, pflags & PFIL_FWD);
9390 
9391 out:
9392 	SDT_PROBE4(pf, ip, test6, done, action, reason, r, s);
9393 
9394 	pf_sctp_multihome_delayed(&pd, off, kif, s, action);
9395 
9396 	return (action);
9397 }
9398 #endif /* INET6 */
9399