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