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