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