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