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