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