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