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