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