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