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