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