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