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