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