pf.c revision 270576
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 270576 2014-08-25 15:49:41Z 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		struct pf_src_node *sn = NULL;
3525
3526		if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3527			REASON_SET(&reason, PFRES_MAPFAILED);
3528			pf_src_tree_remove_state(s);
3529			STATE_DEC_COUNTERS(s);
3530			uma_zfree(V_pf_state_z, s);
3531			goto csfailed;
3532		}
3533		s->rt_kif = r->rpool.cur->kif;
3534	}
3535
3536	s->creation = time_uptime;
3537	s->expire = time_uptime;
3538
3539	if (sn != NULL) {
3540		s->src_node = sn;
3541		s->src_node->states++;
3542	}
3543	if (nsn != NULL) {
3544		/* XXX We only modify one side for now. */
3545		PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3546		s->nat_src_node = nsn;
3547		s->nat_src_node->states++;
3548	}
3549	if (pd->proto == IPPROTO_TCP) {
3550		if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3551		    off, pd, th, &s->src, &s->dst)) {
3552			REASON_SET(&reason, PFRES_MEMORY);
3553			pf_src_tree_remove_state(s);
3554			STATE_DEC_COUNTERS(s);
3555			uma_zfree(V_pf_state_z, s);
3556			return (PF_DROP);
3557		}
3558		if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3559		    pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3560		    &s->src, &s->dst, rewrite)) {
3561			/* This really shouldn't happen!!! */
3562			DPFPRINTF(PF_DEBUG_URGENT,
3563			    ("pf_normalize_tcp_stateful failed on first pkt"));
3564			pf_normalize_tcp_cleanup(s);
3565			pf_src_tree_remove_state(s);
3566			STATE_DEC_COUNTERS(s);
3567			uma_zfree(V_pf_state_z, s);
3568			return (PF_DROP);
3569		}
3570	}
3571	s->direction = pd->dir;
3572
3573	/*
3574	 * sk/nk could already been setup by pf_get_translation().
3575	 */
3576	if (nr == NULL) {
3577		KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3578		    __func__, nr, sk, nk));
3579		sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3580		if (sk == NULL)
3581			goto csfailed;
3582		nk = sk;
3583	} else
3584		KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3585		    __func__, nr, sk, nk));
3586
3587	/* Swap sk/nk for PF_OUT. */
3588	if (pf_state_insert(BOUND_IFACE(r, kif),
3589	    (pd->dir == PF_IN) ? sk : nk,
3590	    (pd->dir == PF_IN) ? nk : sk, s)) {
3591		if (pd->proto == IPPROTO_TCP)
3592			pf_normalize_tcp_cleanup(s);
3593		REASON_SET(&reason, PFRES_STATEINS);
3594		pf_src_tree_remove_state(s);
3595		STATE_DEC_COUNTERS(s);
3596		uma_zfree(V_pf_state_z, s);
3597		return (PF_DROP);
3598	} else
3599		*sm = s;
3600
3601	if (tag > 0)
3602		s->tag = tag;
3603	if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3604	    TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3605		s->src.state = PF_TCPS_PROXY_SRC;
3606		/* undo NAT changes, if they have taken place */
3607		if (nr != NULL) {
3608			struct pf_state_key *skt = s->key[PF_SK_WIRE];
3609			if (pd->dir == PF_OUT)
3610				skt = s->key[PF_SK_STACK];
3611			PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3612			PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3613			if (pd->sport)
3614				*pd->sport = skt->port[pd->sidx];
3615			if (pd->dport)
3616				*pd->dport = skt->port[pd->didx];
3617			if (pd->proto_sum)
3618				*pd->proto_sum = bproto_sum;
3619			if (pd->ip_sum)
3620				*pd->ip_sum = bip_sum;
3621			m_copyback(m, off, hdrlen, pd->hdr.any);
3622		}
3623		s->src.seqhi = htonl(arc4random());
3624		/* Find mss option */
3625		int rtid = M_GETFIB(m);
3626		mss = pf_get_mss(m, off, th->th_off, pd->af);
3627		mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3628		mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3629		s->src.mss = mss;
3630		pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3631		    th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3632		    TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3633		REASON_SET(&reason, PFRES_SYNPROXY);
3634		return (PF_SYNPROXY_DROP);
3635	}
3636
3637	return (PF_PASS);
3638
3639csfailed:
3640	if (sk != NULL)
3641		uma_zfree(V_pf_state_key_z, sk);
3642	if (nk != NULL)
3643		uma_zfree(V_pf_state_key_z, nk);
3644
3645	if (sn != NULL && sn->states == 0 && sn->expire == 0) {
3646		pf_unlink_src_node(sn);
3647		pf_free_src_node(sn);
3648	}
3649
3650	if (nsn != sn && nsn != NULL && nsn->states == 0 && nsn->expire == 0) {
3651		pf_unlink_src_node(nsn);
3652		pf_free_src_node(nsn);
3653	}
3654
3655	return (PF_DROP);
3656}
3657
3658static int
3659pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3660    struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3661    struct pf_ruleset **rsm)
3662{
3663	struct pf_rule		*r, *a = NULL;
3664	struct pf_ruleset	*ruleset = NULL;
3665	sa_family_t		 af = pd->af;
3666	u_short			 reason;
3667	int			 tag = -1;
3668	int			 asd = 0;
3669	int			 match = 0;
3670	struct pf_anchor_stackframe	anchor_stack[PF_ANCHOR_STACKSIZE];
3671
3672	PF_RULES_RASSERT();
3673
3674	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3675	while (r != NULL) {
3676		r->evaluations++;
3677		if (pfi_kif_match(r->kif, kif) == r->ifnot)
3678			r = r->skip[PF_SKIP_IFP].ptr;
3679		else if (r->direction && r->direction != direction)
3680			r = r->skip[PF_SKIP_DIR].ptr;
3681		else if (r->af && r->af != af)
3682			r = r->skip[PF_SKIP_AF].ptr;
3683		else if (r->proto && r->proto != pd->proto)
3684			r = r->skip[PF_SKIP_PROTO].ptr;
3685		else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3686		    r->src.neg, kif, M_GETFIB(m)))
3687			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3688		else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3689		    r->dst.neg, NULL, M_GETFIB(m)))
3690			r = r->skip[PF_SKIP_DST_ADDR].ptr;
3691		else if (r->tos && !(r->tos == pd->tos))
3692			r = TAILQ_NEXT(r, entries);
3693		else if (r->os_fingerprint != PF_OSFP_ANY)
3694			r = TAILQ_NEXT(r, entries);
3695		else if (pd->proto == IPPROTO_UDP &&
3696		    (r->src.port_op || r->dst.port_op))
3697			r = TAILQ_NEXT(r, entries);
3698		else if (pd->proto == IPPROTO_TCP &&
3699		    (r->src.port_op || r->dst.port_op || r->flagset))
3700			r = TAILQ_NEXT(r, entries);
3701		else if ((pd->proto == IPPROTO_ICMP ||
3702		    pd->proto == IPPROTO_ICMPV6) &&
3703		    (r->type || r->code))
3704			r = TAILQ_NEXT(r, entries);
3705		else if (r->prob && r->prob <=
3706		    (arc4random() % (UINT_MAX - 1) + 1))
3707			r = TAILQ_NEXT(r, entries);
3708		else if (r->match_tag && !pf_match_tag(m, r, &tag,
3709		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
3710			r = TAILQ_NEXT(r, entries);
3711		else {
3712			if (r->anchor == NULL) {
3713				match = 1;
3714				*rm = r;
3715				*am = a;
3716				*rsm = ruleset;
3717				if ((*rm)->quick)
3718					break;
3719				r = TAILQ_NEXT(r, entries);
3720			} else
3721				pf_step_into_anchor(anchor_stack, &asd,
3722				    &ruleset, PF_RULESET_FILTER, &r, &a,
3723				    &match);
3724		}
3725		if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3726		    &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3727			break;
3728	}
3729	r = *rm;
3730	a = *am;
3731	ruleset = *rsm;
3732
3733	REASON_SET(&reason, PFRES_MATCH);
3734
3735	if (r->log)
3736		PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3737		    1);
3738
3739	if (r->action != PF_PASS)
3740		return (PF_DROP);
3741
3742	if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3743		REASON_SET(&reason, PFRES_MEMORY);
3744		return (PF_DROP);
3745	}
3746
3747	return (PF_PASS);
3748}
3749
3750static int
3751pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3752	struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3753	struct pf_pdesc *pd, u_short *reason, int *copyback)
3754{
3755	struct tcphdr		*th = pd->hdr.tcp;
3756	u_int16_t		 win = ntohs(th->th_win);
3757	u_int32_t		 ack, end, seq, orig_seq;
3758	u_int8_t		 sws, dws;
3759	int			 ackskew;
3760
3761	if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3762		sws = src->wscale & PF_WSCALE_MASK;
3763		dws = dst->wscale & PF_WSCALE_MASK;
3764	} else
3765		sws = dws = 0;
3766
3767	/*
3768	 * Sequence tracking algorithm from Guido van Rooij's paper:
3769	 *   http://www.madison-gurkha.com/publications/tcp_filtering/
3770	 *	tcp_filtering.ps
3771	 */
3772
3773	orig_seq = seq = ntohl(th->th_seq);
3774	if (src->seqlo == 0) {
3775		/* First packet from this end. Set its state */
3776
3777		if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3778		    src->scrub == NULL) {
3779			if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3780				REASON_SET(reason, PFRES_MEMORY);
3781				return (PF_DROP);
3782			}
3783		}
3784
3785		/* Deferred generation of sequence number modulator */
3786		if (dst->seqdiff && !src->seqdiff) {
3787			/* use random iss for the TCP server */
3788			while ((src->seqdiff = arc4random() - seq) == 0)
3789				;
3790			ack = ntohl(th->th_ack) - dst->seqdiff;
3791			pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3792			    src->seqdiff), 0);
3793			pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3794			*copyback = 1;
3795		} else {
3796			ack = ntohl(th->th_ack);
3797		}
3798
3799		end = seq + pd->p_len;
3800		if (th->th_flags & TH_SYN) {
3801			end++;
3802			if (dst->wscale & PF_WSCALE_FLAG) {
3803				src->wscale = pf_get_wscale(m, off, th->th_off,
3804				    pd->af);
3805				if (src->wscale & PF_WSCALE_FLAG) {
3806					/* Remove scale factor from initial
3807					 * window */
3808					sws = src->wscale & PF_WSCALE_MASK;
3809					win = ((u_int32_t)win + (1 << sws) - 1)
3810					    >> sws;
3811					dws = dst->wscale & PF_WSCALE_MASK;
3812				} else {
3813					/* fixup other window */
3814					dst->max_win <<= dst->wscale &
3815					    PF_WSCALE_MASK;
3816					/* in case of a retrans SYN|ACK */
3817					dst->wscale = 0;
3818				}
3819			}
3820		}
3821		if (th->th_flags & TH_FIN)
3822			end++;
3823
3824		src->seqlo = seq;
3825		if (src->state < TCPS_SYN_SENT)
3826			src->state = TCPS_SYN_SENT;
3827
3828		/*
3829		 * May need to slide the window (seqhi may have been set by
3830		 * the crappy stack check or if we picked up the connection
3831		 * after establishment)
3832		 */
3833		if (src->seqhi == 1 ||
3834		    SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3835			src->seqhi = end + MAX(1, dst->max_win << dws);
3836		if (win > src->max_win)
3837			src->max_win = win;
3838
3839	} else {
3840		ack = ntohl(th->th_ack) - dst->seqdiff;
3841		if (src->seqdiff) {
3842			/* Modulate sequence numbers */
3843			pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3844			    src->seqdiff), 0);
3845			pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3846			*copyback = 1;
3847		}
3848		end = seq + pd->p_len;
3849		if (th->th_flags & TH_SYN)
3850			end++;
3851		if (th->th_flags & TH_FIN)
3852			end++;
3853	}
3854
3855	if ((th->th_flags & TH_ACK) == 0) {
3856		/* Let it pass through the ack skew check */
3857		ack = dst->seqlo;
3858	} else if ((ack == 0 &&
3859	    (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
3860	    /* broken tcp stacks do not set ack */
3861	    (dst->state < TCPS_SYN_SENT)) {
3862		/*
3863		 * Many stacks (ours included) will set the ACK number in an
3864		 * FIN|ACK if the SYN times out -- no sequence to ACK.
3865		 */
3866		ack = dst->seqlo;
3867	}
3868
3869	if (seq == end) {
3870		/* Ease sequencing restrictions on no data packets */
3871		seq = src->seqlo;
3872		end = seq;
3873	}
3874
3875	ackskew = dst->seqlo - ack;
3876
3877
3878	/*
3879	 * Need to demodulate the sequence numbers in any TCP SACK options
3880	 * (Selective ACK). We could optionally validate the SACK values
3881	 * against the current ACK window, either forwards or backwards, but
3882	 * I'm not confident that SACK has been implemented properly
3883	 * everywhere. It wouldn't surprise me if several stacks accidently
3884	 * SACK too far backwards of previously ACKed data. There really aren't
3885	 * any security implications of bad SACKing unless the target stack
3886	 * doesn't validate the option length correctly. Someone trying to
3887	 * spoof into a TCP connection won't bother blindly sending SACK
3888	 * options anyway.
3889	 */
3890	if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
3891		if (pf_modulate_sack(m, off, pd, th, dst))
3892			*copyback = 1;
3893	}
3894
3895
3896#define	MAXACKWINDOW (0xffff + 1500)	/* 1500 is an arbitrary fudge factor */
3897	if (SEQ_GEQ(src->seqhi, end) &&
3898	    /* Last octet inside other's window space */
3899	    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
3900	    /* Retrans: not more than one window back */
3901	    (ackskew >= -MAXACKWINDOW) &&
3902	    /* Acking not more than one reassembled fragment backwards */
3903	    (ackskew <= (MAXACKWINDOW << sws)) &&
3904	    /* Acking not more than one window forward */
3905	    ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
3906	    (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
3907	    (pd->flags & PFDESC_IP_REAS) == 0)) {
3908	    /* Require an exact/+1 sequence match on resets when possible */
3909
3910		if (dst->scrub || src->scrub) {
3911			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
3912			    *state, src, dst, copyback))
3913				return (PF_DROP);
3914		}
3915
3916		/* update max window */
3917		if (src->max_win < win)
3918			src->max_win = win;
3919		/* synchronize sequencing */
3920		if (SEQ_GT(end, src->seqlo))
3921			src->seqlo = end;
3922		/* slide the window of what the other end can send */
3923		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
3924			dst->seqhi = ack + MAX((win << sws), 1);
3925
3926
3927		/* update states */
3928		if (th->th_flags & TH_SYN)
3929			if (src->state < TCPS_SYN_SENT)
3930				src->state = TCPS_SYN_SENT;
3931		if (th->th_flags & TH_FIN)
3932			if (src->state < TCPS_CLOSING)
3933				src->state = TCPS_CLOSING;
3934		if (th->th_flags & TH_ACK) {
3935			if (dst->state == TCPS_SYN_SENT) {
3936				dst->state = TCPS_ESTABLISHED;
3937				if (src->state == TCPS_ESTABLISHED &&
3938				    (*state)->src_node != NULL &&
3939				    pf_src_connlimit(state)) {
3940					REASON_SET(reason, PFRES_SRCLIMIT);
3941					return (PF_DROP);
3942				}
3943			} else if (dst->state == TCPS_CLOSING)
3944				dst->state = TCPS_FIN_WAIT_2;
3945		}
3946		if (th->th_flags & TH_RST)
3947			src->state = dst->state = TCPS_TIME_WAIT;
3948
3949		/* update expire time */
3950		(*state)->expire = time_uptime;
3951		if (src->state >= TCPS_FIN_WAIT_2 &&
3952		    dst->state >= TCPS_FIN_WAIT_2)
3953			(*state)->timeout = PFTM_TCP_CLOSED;
3954		else if (src->state >= TCPS_CLOSING &&
3955		    dst->state >= TCPS_CLOSING)
3956			(*state)->timeout = PFTM_TCP_FIN_WAIT;
3957		else if (src->state < TCPS_ESTABLISHED ||
3958		    dst->state < TCPS_ESTABLISHED)
3959			(*state)->timeout = PFTM_TCP_OPENING;
3960		else if (src->state >= TCPS_CLOSING ||
3961		    dst->state >= TCPS_CLOSING)
3962			(*state)->timeout = PFTM_TCP_CLOSING;
3963		else
3964			(*state)->timeout = PFTM_TCP_ESTABLISHED;
3965
3966		/* Fall through to PASS packet */
3967
3968	} else if ((dst->state < TCPS_SYN_SENT ||
3969		dst->state >= TCPS_FIN_WAIT_2 ||
3970		src->state >= TCPS_FIN_WAIT_2) &&
3971	    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
3972	    /* Within a window forward of the originating packet */
3973	    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
3974	    /* Within a window backward of the originating packet */
3975
3976		/*
3977		 * This currently handles three situations:
3978		 *  1) Stupid stacks will shotgun SYNs before their peer
3979		 *     replies.
3980		 *  2) When PF catches an already established stream (the
3981		 *     firewall rebooted, the state table was flushed, routes
3982		 *     changed...)
3983		 *  3) Packets get funky immediately after the connection
3984		 *     closes (this should catch Solaris spurious ACK|FINs
3985		 *     that web servers like to spew after a close)
3986		 *
3987		 * This must be a little more careful than the above code
3988		 * since packet floods will also be caught here. We don't
3989		 * update the TTL here to mitigate the damage of a packet
3990		 * flood and so the same code can handle awkward establishment
3991		 * and a loosened connection close.
3992		 * In the establishment case, a correct peer response will
3993		 * validate the connection, go through the normal state code
3994		 * and keep updating the state TTL.
3995		 */
3996
3997		if (V_pf_status.debug >= PF_DEBUG_MISC) {
3998			printf("pf: loose state match: ");
3999			pf_print_state(*state);
4000			pf_print_flags(th->th_flags);
4001			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4002			    "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4003			    pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4004			    (unsigned long long)(*state)->packets[1],
4005			    pd->dir == PF_IN ? "in" : "out",
4006			    pd->dir == (*state)->direction ? "fwd" : "rev");
4007		}
4008
4009		if (dst->scrub || src->scrub) {
4010			if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4011			    *state, src, dst, copyback))
4012				return (PF_DROP);
4013		}
4014
4015		/* update max window */
4016		if (src->max_win < win)
4017			src->max_win = win;
4018		/* synchronize sequencing */
4019		if (SEQ_GT(end, src->seqlo))
4020			src->seqlo = end;
4021		/* slide the window of what the other end can send */
4022		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4023			dst->seqhi = ack + MAX((win << sws), 1);
4024
4025		/*
4026		 * Cannot set dst->seqhi here since this could be a shotgunned
4027		 * SYN and not an already established connection.
4028		 */
4029
4030		if (th->th_flags & TH_FIN)
4031			if (src->state < TCPS_CLOSING)
4032				src->state = TCPS_CLOSING;
4033		if (th->th_flags & TH_RST)
4034			src->state = dst->state = TCPS_TIME_WAIT;
4035
4036		/* Fall through to PASS packet */
4037
4038	} else {
4039		if ((*state)->dst.state == TCPS_SYN_SENT &&
4040		    (*state)->src.state == TCPS_SYN_SENT) {
4041			/* Send RST for state mismatches during handshake */
4042			if (!(th->th_flags & TH_RST))
4043				pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4044				    pd->dst, pd->src, th->th_dport,
4045				    th->th_sport, ntohl(th->th_ack), 0,
4046				    TH_RST, 0, 0,
4047				    (*state)->rule.ptr->return_ttl, 1, 0,
4048				    kif->pfik_ifp);
4049			src->seqlo = 0;
4050			src->seqhi = 1;
4051			src->max_win = 1;
4052		} else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4053			printf("pf: BAD state: ");
4054			pf_print_state(*state);
4055			pf_print_flags(th->th_flags);
4056			printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4057			    "pkts=%llu:%llu dir=%s,%s\n",
4058			    seq, orig_seq, ack, pd->p_len, ackskew,
4059			    (unsigned long long)(*state)->packets[0],
4060			    (unsigned long long)(*state)->packets[1],
4061			    pd->dir == PF_IN ? "in" : "out",
4062			    pd->dir == (*state)->direction ? "fwd" : "rev");
4063			printf("pf: State failure on: %c %c %c %c | %c %c\n",
4064			    SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4065			    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4066			    ' ': '2',
4067			    (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4068			    (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4069			    SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4070			    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4071		}
4072		REASON_SET(reason, PFRES_BADSTATE);
4073		return (PF_DROP);
4074	}
4075
4076	return (PF_PASS);
4077}
4078
4079static int
4080pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4081	struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4082{
4083	struct tcphdr		*th = pd->hdr.tcp;
4084
4085	if (th->th_flags & TH_SYN)
4086		if (src->state < TCPS_SYN_SENT)
4087			src->state = TCPS_SYN_SENT;
4088	if (th->th_flags & TH_FIN)
4089		if (src->state < TCPS_CLOSING)
4090			src->state = TCPS_CLOSING;
4091	if (th->th_flags & TH_ACK) {
4092		if (dst->state == TCPS_SYN_SENT) {
4093			dst->state = TCPS_ESTABLISHED;
4094			if (src->state == TCPS_ESTABLISHED &&
4095			    (*state)->src_node != NULL &&
4096			    pf_src_connlimit(state)) {
4097				REASON_SET(reason, PFRES_SRCLIMIT);
4098				return (PF_DROP);
4099			}
4100		} else if (dst->state == TCPS_CLOSING) {
4101			dst->state = TCPS_FIN_WAIT_2;
4102		} else if (src->state == TCPS_SYN_SENT &&
4103		    dst->state < TCPS_SYN_SENT) {
4104			/*
4105			 * Handle a special sloppy case where we only see one
4106			 * half of the connection. If there is a ACK after
4107			 * the initial SYN without ever seeing a packet from
4108			 * the destination, set the connection to established.
4109			 */
4110			dst->state = src->state = TCPS_ESTABLISHED;
4111			if ((*state)->src_node != NULL &&
4112			    pf_src_connlimit(state)) {
4113				REASON_SET(reason, PFRES_SRCLIMIT);
4114				return (PF_DROP);
4115			}
4116		} else if (src->state == TCPS_CLOSING &&
4117		    dst->state == TCPS_ESTABLISHED &&
4118		    dst->seqlo == 0) {
4119			/*
4120			 * Handle the closing of half connections where we
4121			 * don't see the full bidirectional FIN/ACK+ACK
4122			 * handshake.
4123			 */
4124			dst->state = TCPS_CLOSING;
4125		}
4126	}
4127	if (th->th_flags & TH_RST)
4128		src->state = dst->state = TCPS_TIME_WAIT;
4129
4130	/* update expire time */
4131	(*state)->expire = time_uptime;
4132	if (src->state >= TCPS_FIN_WAIT_2 &&
4133	    dst->state >= TCPS_FIN_WAIT_2)
4134		(*state)->timeout = PFTM_TCP_CLOSED;
4135	else if (src->state >= TCPS_CLOSING &&
4136	    dst->state >= TCPS_CLOSING)
4137		(*state)->timeout = PFTM_TCP_FIN_WAIT;
4138	else if (src->state < TCPS_ESTABLISHED ||
4139	    dst->state < TCPS_ESTABLISHED)
4140		(*state)->timeout = PFTM_TCP_OPENING;
4141	else if (src->state >= TCPS_CLOSING ||
4142	    dst->state >= TCPS_CLOSING)
4143		(*state)->timeout = PFTM_TCP_CLOSING;
4144	else
4145		(*state)->timeout = PFTM_TCP_ESTABLISHED;
4146
4147	return (PF_PASS);
4148}
4149
4150static int
4151pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4152    struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4153    u_short *reason)
4154{
4155	struct pf_state_key_cmp	 key;
4156	struct tcphdr		*th = pd->hdr.tcp;
4157	int			 copyback = 0;
4158	struct pf_state_peer	*src, *dst;
4159	struct pf_state_key	*sk;
4160
4161	bzero(&key, sizeof(key));
4162	key.af = pd->af;
4163	key.proto = IPPROTO_TCP;
4164	if (direction == PF_IN)	{	/* wire side, straight */
4165		PF_ACPY(&key.addr[0], pd->src, key.af);
4166		PF_ACPY(&key.addr[1], pd->dst, key.af);
4167		key.port[0] = th->th_sport;
4168		key.port[1] = th->th_dport;
4169	} else {			/* stack side, reverse */
4170		PF_ACPY(&key.addr[1], pd->src, key.af);
4171		PF_ACPY(&key.addr[0], pd->dst, key.af);
4172		key.port[1] = th->th_sport;
4173		key.port[0] = th->th_dport;
4174	}
4175
4176	STATE_LOOKUP(kif, &key, direction, *state, pd);
4177
4178	if (direction == (*state)->direction) {
4179		src = &(*state)->src;
4180		dst = &(*state)->dst;
4181	} else {
4182		src = &(*state)->dst;
4183		dst = &(*state)->src;
4184	}
4185
4186	sk = (*state)->key[pd->didx];
4187
4188	if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4189		if (direction != (*state)->direction) {
4190			REASON_SET(reason, PFRES_SYNPROXY);
4191			return (PF_SYNPROXY_DROP);
4192		}
4193		if (th->th_flags & TH_SYN) {
4194			if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4195				REASON_SET(reason, PFRES_SYNPROXY);
4196				return (PF_DROP);
4197			}
4198			pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4199			    pd->src, th->th_dport, th->th_sport,
4200			    (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4201			    TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4202			REASON_SET(reason, PFRES_SYNPROXY);
4203			return (PF_SYNPROXY_DROP);
4204		} else if (!(th->th_flags & TH_ACK) ||
4205		    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4206		    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4207			REASON_SET(reason, PFRES_SYNPROXY);
4208			return (PF_DROP);
4209		} else if ((*state)->src_node != NULL &&
4210		    pf_src_connlimit(state)) {
4211			REASON_SET(reason, PFRES_SRCLIMIT);
4212			return (PF_DROP);
4213		} else
4214			(*state)->src.state = PF_TCPS_PROXY_DST;
4215	}
4216	if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4217		if (direction == (*state)->direction) {
4218			if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4219			    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4220			    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4221				REASON_SET(reason, PFRES_SYNPROXY);
4222				return (PF_DROP);
4223			}
4224			(*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4225			if ((*state)->dst.seqhi == 1)
4226				(*state)->dst.seqhi = htonl(arc4random());
4227			pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4228			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
4229			    sk->port[pd->sidx], sk->port[pd->didx],
4230			    (*state)->dst.seqhi, 0, TH_SYN, 0,
4231			    (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4232			REASON_SET(reason, PFRES_SYNPROXY);
4233			return (PF_SYNPROXY_DROP);
4234		} else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4235		    (TH_SYN|TH_ACK)) ||
4236		    (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4237			REASON_SET(reason, PFRES_SYNPROXY);
4238			return (PF_DROP);
4239		} else {
4240			(*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4241			(*state)->dst.seqlo = ntohl(th->th_seq);
4242			pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4243			    pd->src, th->th_dport, th->th_sport,
4244			    ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4245			    TH_ACK, (*state)->src.max_win, 0, 0, 0,
4246			    (*state)->tag, NULL);
4247			pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4248			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
4249			    sk->port[pd->sidx], sk->port[pd->didx],
4250			    (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4251			    TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4252			(*state)->src.seqdiff = (*state)->dst.seqhi -
4253			    (*state)->src.seqlo;
4254			(*state)->dst.seqdiff = (*state)->src.seqhi -
4255			    (*state)->dst.seqlo;
4256			(*state)->src.seqhi = (*state)->src.seqlo +
4257			    (*state)->dst.max_win;
4258			(*state)->dst.seqhi = (*state)->dst.seqlo +
4259			    (*state)->src.max_win;
4260			(*state)->src.wscale = (*state)->dst.wscale = 0;
4261			(*state)->src.state = (*state)->dst.state =
4262			    TCPS_ESTABLISHED;
4263			REASON_SET(reason, PFRES_SYNPROXY);
4264			return (PF_SYNPROXY_DROP);
4265		}
4266	}
4267
4268	if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4269	    dst->state >= TCPS_FIN_WAIT_2 &&
4270	    src->state >= TCPS_FIN_WAIT_2) {
4271		if (V_pf_status.debug >= PF_DEBUG_MISC) {
4272			printf("pf: state reuse ");
4273			pf_print_state(*state);
4274			pf_print_flags(th->th_flags);
4275			printf("\n");
4276		}
4277		/* XXX make sure it's the same direction ?? */
4278		(*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4279		pf_unlink_state(*state, PF_ENTER_LOCKED);
4280		*state = NULL;
4281		return (PF_DROP);
4282	}
4283
4284	if ((*state)->state_flags & PFSTATE_SLOPPY) {
4285		if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4286			return (PF_DROP);
4287	} else {
4288		if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4289		    &copyback) == PF_DROP)
4290			return (PF_DROP);
4291	}
4292
4293	/* translate source/destination address, if necessary */
4294	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4295		struct pf_state_key *nk = (*state)->key[pd->didx];
4296
4297		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4298		    nk->port[pd->sidx] != th->th_sport)
4299			pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
4300			    &th->th_sum, &nk->addr[pd->sidx],
4301			    nk->port[pd->sidx], 0, pd->af);
4302
4303		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4304		    nk->port[pd->didx] != th->th_dport)
4305			pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
4306			    &th->th_sum, &nk->addr[pd->didx],
4307			    nk->port[pd->didx], 0, pd->af);
4308		copyback = 1;
4309	}
4310
4311	/* Copyback sequence modulation or stateful scrub changes if needed */
4312	if (copyback)
4313		m_copyback(m, off, sizeof(*th), (caddr_t)th);
4314
4315	return (PF_PASS);
4316}
4317
4318static int
4319pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4320    struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4321{
4322	struct pf_state_peer	*src, *dst;
4323	struct pf_state_key_cmp	 key;
4324	struct udphdr		*uh = pd->hdr.udp;
4325
4326	bzero(&key, sizeof(key));
4327	key.af = pd->af;
4328	key.proto = IPPROTO_UDP;
4329	if (direction == PF_IN)	{	/* wire side, straight */
4330		PF_ACPY(&key.addr[0], pd->src, key.af);
4331		PF_ACPY(&key.addr[1], pd->dst, key.af);
4332		key.port[0] = uh->uh_sport;
4333		key.port[1] = uh->uh_dport;
4334	} else {			/* stack side, reverse */
4335		PF_ACPY(&key.addr[1], pd->src, key.af);
4336		PF_ACPY(&key.addr[0], pd->dst, key.af);
4337		key.port[1] = uh->uh_sport;
4338		key.port[0] = uh->uh_dport;
4339	}
4340
4341	STATE_LOOKUP(kif, &key, direction, *state, pd);
4342
4343	if (direction == (*state)->direction) {
4344		src = &(*state)->src;
4345		dst = &(*state)->dst;
4346	} else {
4347		src = &(*state)->dst;
4348		dst = &(*state)->src;
4349	}
4350
4351	/* update states */
4352	if (src->state < PFUDPS_SINGLE)
4353		src->state = PFUDPS_SINGLE;
4354	if (dst->state == PFUDPS_SINGLE)
4355		dst->state = PFUDPS_MULTIPLE;
4356
4357	/* update expire time */
4358	(*state)->expire = time_uptime;
4359	if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4360		(*state)->timeout = PFTM_UDP_MULTIPLE;
4361	else
4362		(*state)->timeout = PFTM_UDP_SINGLE;
4363
4364	/* translate source/destination address, if necessary */
4365	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4366		struct pf_state_key *nk = (*state)->key[pd->didx];
4367
4368		if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4369		    nk->port[pd->sidx] != uh->uh_sport)
4370			pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
4371			    &uh->uh_sum, &nk->addr[pd->sidx],
4372			    nk->port[pd->sidx], 1, pd->af);
4373
4374		if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4375		    nk->port[pd->didx] != uh->uh_dport)
4376			pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
4377			    &uh->uh_sum, &nk->addr[pd->didx],
4378			    nk->port[pd->didx], 1, pd->af);
4379		m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4380	}
4381
4382	return (PF_PASS);
4383}
4384
4385static int
4386pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4387    struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4388{
4389	struct pf_addr  *saddr = pd->src, *daddr = pd->dst;
4390	u_int16_t	 icmpid = 0, *icmpsum;
4391	u_int8_t	 icmptype;
4392	int		 state_icmp = 0;
4393	struct pf_state_key_cmp key;
4394
4395	bzero(&key, sizeof(key));
4396	switch (pd->proto) {
4397#ifdef INET
4398	case IPPROTO_ICMP:
4399		icmptype = pd->hdr.icmp->icmp_type;
4400		icmpid = pd->hdr.icmp->icmp_id;
4401		icmpsum = &pd->hdr.icmp->icmp_cksum;
4402
4403		if (icmptype == ICMP_UNREACH ||
4404		    icmptype == ICMP_SOURCEQUENCH ||
4405		    icmptype == ICMP_REDIRECT ||
4406		    icmptype == ICMP_TIMXCEED ||
4407		    icmptype == ICMP_PARAMPROB)
4408			state_icmp++;
4409		break;
4410#endif /* INET */
4411#ifdef INET6
4412	case IPPROTO_ICMPV6:
4413		icmptype = pd->hdr.icmp6->icmp6_type;
4414		icmpid = pd->hdr.icmp6->icmp6_id;
4415		icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4416
4417		if (icmptype == ICMP6_DST_UNREACH ||
4418		    icmptype == ICMP6_PACKET_TOO_BIG ||
4419		    icmptype == ICMP6_TIME_EXCEEDED ||
4420		    icmptype == ICMP6_PARAM_PROB)
4421			state_icmp++;
4422		break;
4423#endif /* INET6 */
4424	}
4425
4426	if (!state_icmp) {
4427
4428		/*
4429		 * ICMP query/reply message not related to a TCP/UDP packet.
4430		 * Search for an ICMP state.
4431		 */
4432		key.af = pd->af;
4433		key.proto = pd->proto;
4434		key.port[0] = key.port[1] = icmpid;
4435		if (direction == PF_IN)	{	/* wire side, straight */
4436			PF_ACPY(&key.addr[0], pd->src, key.af);
4437			PF_ACPY(&key.addr[1], pd->dst, key.af);
4438		} else {			/* stack side, reverse */
4439			PF_ACPY(&key.addr[1], pd->src, key.af);
4440			PF_ACPY(&key.addr[0], pd->dst, key.af);
4441		}
4442
4443		STATE_LOOKUP(kif, &key, direction, *state, pd);
4444
4445		(*state)->expire = time_uptime;
4446		(*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4447
4448		/* translate source/destination address, if necessary */
4449		if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4450			struct pf_state_key *nk = (*state)->key[pd->didx];
4451
4452			switch (pd->af) {
4453#ifdef INET
4454			case AF_INET:
4455				if (PF_ANEQ(pd->src,
4456				    &nk->addr[pd->sidx], AF_INET))
4457					pf_change_a(&saddr->v4.s_addr,
4458					    pd->ip_sum,
4459					    nk->addr[pd->sidx].v4.s_addr, 0);
4460
4461				if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4462				    AF_INET))
4463					pf_change_a(&daddr->v4.s_addr,
4464					    pd->ip_sum,
4465					    nk->addr[pd->didx].v4.s_addr, 0);
4466
4467				if (nk->port[0] !=
4468				    pd->hdr.icmp->icmp_id) {
4469					pd->hdr.icmp->icmp_cksum =
4470					    pf_cksum_fixup(
4471					    pd->hdr.icmp->icmp_cksum, icmpid,
4472					    nk->port[pd->sidx], 0);
4473					pd->hdr.icmp->icmp_id =
4474					    nk->port[pd->sidx];
4475				}
4476
4477				m_copyback(m, off, ICMP_MINLEN,
4478				    (caddr_t )pd->hdr.icmp);
4479				break;
4480#endif /* INET */
4481#ifdef INET6
4482			case AF_INET6:
4483				if (PF_ANEQ(pd->src,
4484				    &nk->addr[pd->sidx], AF_INET6))
4485					pf_change_a6(saddr,
4486					    &pd->hdr.icmp6->icmp6_cksum,
4487					    &nk->addr[pd->sidx], 0);
4488
4489				if (PF_ANEQ(pd->dst,
4490				    &nk->addr[pd->didx], AF_INET6))
4491					pf_change_a6(daddr,
4492					    &pd->hdr.icmp6->icmp6_cksum,
4493					    &nk->addr[pd->didx], 0);
4494
4495				m_copyback(m, off, sizeof(struct icmp6_hdr),
4496				    (caddr_t )pd->hdr.icmp6);
4497				break;
4498#endif /* INET6 */
4499			}
4500		}
4501		return (PF_PASS);
4502
4503	} else {
4504		/*
4505		 * ICMP error message in response to a TCP/UDP packet.
4506		 * Extract the inner TCP/UDP header and search for that state.
4507		 */
4508
4509		struct pf_pdesc	pd2;
4510		bzero(&pd2, sizeof pd2);
4511#ifdef INET
4512		struct ip	h2;
4513#endif /* INET */
4514#ifdef INET6
4515		struct ip6_hdr	h2_6;
4516		int		terminal = 0;
4517#endif /* INET6 */
4518		int		ipoff2 = 0;
4519		int		off2 = 0;
4520
4521		pd2.af = pd->af;
4522		/* Payload packet is from the opposite direction. */
4523		pd2.sidx = (direction == PF_IN) ? 1 : 0;
4524		pd2.didx = (direction == PF_IN) ? 0 : 1;
4525		switch (pd->af) {
4526#ifdef INET
4527		case AF_INET:
4528			/* offset of h2 in mbuf chain */
4529			ipoff2 = off + ICMP_MINLEN;
4530
4531			if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4532			    NULL, reason, pd2.af)) {
4533				DPFPRINTF(PF_DEBUG_MISC,
4534				    ("pf: ICMP error message too short "
4535				    "(ip)\n"));
4536				return (PF_DROP);
4537			}
4538			/*
4539			 * ICMP error messages don't refer to non-first
4540			 * fragments
4541			 */
4542			if (h2.ip_off & htons(IP_OFFMASK)) {
4543				REASON_SET(reason, PFRES_FRAG);
4544				return (PF_DROP);
4545			}
4546
4547			/* offset of protocol header that follows h2 */
4548			off2 = ipoff2 + (h2.ip_hl << 2);
4549
4550			pd2.proto = h2.ip_p;
4551			pd2.src = (struct pf_addr *)&h2.ip_src;
4552			pd2.dst = (struct pf_addr *)&h2.ip_dst;
4553			pd2.ip_sum = &h2.ip_sum;
4554			break;
4555#endif /* INET */
4556#ifdef INET6
4557		case AF_INET6:
4558			ipoff2 = off + sizeof(struct icmp6_hdr);
4559
4560			if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4561			    NULL, reason, pd2.af)) {
4562				DPFPRINTF(PF_DEBUG_MISC,
4563				    ("pf: ICMP error message too short "
4564				    "(ip6)\n"));
4565				return (PF_DROP);
4566			}
4567			pd2.proto = h2_6.ip6_nxt;
4568			pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4569			pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4570			pd2.ip_sum = NULL;
4571			off2 = ipoff2 + sizeof(h2_6);
4572			do {
4573				switch (pd2.proto) {
4574				case IPPROTO_FRAGMENT:
4575					/*
4576					 * ICMPv6 error messages for
4577					 * non-first fragments
4578					 */
4579					REASON_SET(reason, PFRES_FRAG);
4580					return (PF_DROP);
4581				case IPPROTO_AH:
4582				case IPPROTO_HOPOPTS:
4583				case IPPROTO_ROUTING:
4584				case IPPROTO_DSTOPTS: {
4585					/* get next header and header length */
4586					struct ip6_ext opt6;
4587
4588					if (!pf_pull_hdr(m, off2, &opt6,
4589					    sizeof(opt6), NULL, reason,
4590					    pd2.af)) {
4591						DPFPRINTF(PF_DEBUG_MISC,
4592						    ("pf: ICMPv6 short opt\n"));
4593						return (PF_DROP);
4594					}
4595					if (pd2.proto == IPPROTO_AH)
4596						off2 += (opt6.ip6e_len + 2) * 4;
4597					else
4598						off2 += (opt6.ip6e_len + 1) * 8;
4599					pd2.proto = opt6.ip6e_nxt;
4600					/* goto the next header */
4601					break;
4602				}
4603				default:
4604					terminal++;
4605					break;
4606				}
4607			} while (!terminal);
4608			break;
4609#endif /* INET6 */
4610		}
4611
4612		switch (pd2.proto) {
4613		case IPPROTO_TCP: {
4614			struct tcphdr		 th;
4615			u_int32_t		 seq;
4616			struct pf_state_peer	*src, *dst;
4617			u_int8_t		 dws;
4618			int			 copyback = 0;
4619
4620			/*
4621			 * Only the first 8 bytes of the TCP header can be
4622			 * expected. Don't access any TCP header fields after
4623			 * th_seq, an ackskew test is not possible.
4624			 */
4625			if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4626			    pd2.af)) {
4627				DPFPRINTF(PF_DEBUG_MISC,
4628				    ("pf: ICMP error message too short "
4629				    "(tcp)\n"));
4630				return (PF_DROP);
4631			}
4632
4633			key.af = pd2.af;
4634			key.proto = IPPROTO_TCP;
4635			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4636			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4637			key.port[pd2.sidx] = th.th_sport;
4638			key.port[pd2.didx] = th.th_dport;
4639
4640			STATE_LOOKUP(kif, &key, direction, *state, pd);
4641
4642			if (direction == (*state)->direction) {
4643				src = &(*state)->dst;
4644				dst = &(*state)->src;
4645			} else {
4646				src = &(*state)->src;
4647				dst = &(*state)->dst;
4648			}
4649
4650			if (src->wscale && dst->wscale)
4651				dws = dst->wscale & PF_WSCALE_MASK;
4652			else
4653				dws = 0;
4654
4655			/* Demodulate sequence number */
4656			seq = ntohl(th.th_seq) - src->seqdiff;
4657			if (src->seqdiff) {
4658				pf_change_a(&th.th_seq, icmpsum,
4659				    htonl(seq), 0);
4660				copyback = 1;
4661			}
4662
4663			if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4664			    (!SEQ_GEQ(src->seqhi, seq) ||
4665			    !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4666				if (V_pf_status.debug >= PF_DEBUG_MISC) {
4667					printf("pf: BAD ICMP %d:%d ",
4668					    icmptype, pd->hdr.icmp->icmp_code);
4669					pf_print_host(pd->src, 0, pd->af);
4670					printf(" -> ");
4671					pf_print_host(pd->dst, 0, pd->af);
4672					printf(" state: ");
4673					pf_print_state(*state);
4674					printf(" seq=%u\n", seq);
4675				}
4676				REASON_SET(reason, PFRES_BADSTATE);
4677				return (PF_DROP);
4678			} else {
4679				if (V_pf_status.debug >= PF_DEBUG_MISC) {
4680					printf("pf: OK ICMP %d:%d ",
4681					    icmptype, pd->hdr.icmp->icmp_code);
4682					pf_print_host(pd->src, 0, pd->af);
4683					printf(" -> ");
4684					pf_print_host(pd->dst, 0, pd->af);
4685					printf(" state: ");
4686					pf_print_state(*state);
4687					printf(" seq=%u\n", seq);
4688				}
4689			}
4690
4691			/* translate source/destination address, if necessary */
4692			if ((*state)->key[PF_SK_WIRE] !=
4693			    (*state)->key[PF_SK_STACK]) {
4694				struct pf_state_key *nk =
4695				    (*state)->key[pd->didx];
4696
4697				if (PF_ANEQ(pd2.src,
4698				    &nk->addr[pd2.sidx], pd2.af) ||
4699				    nk->port[pd2.sidx] != th.th_sport)
4700					pf_change_icmp(pd2.src, &th.th_sport,
4701					    daddr, &nk->addr[pd2.sidx],
4702					    nk->port[pd2.sidx], NULL,
4703					    pd2.ip_sum, icmpsum,
4704					    pd->ip_sum, 0, pd2.af);
4705
4706				if (PF_ANEQ(pd2.dst,
4707				    &nk->addr[pd2.didx], pd2.af) ||
4708				    nk->port[pd2.didx] != th.th_dport)
4709					pf_change_icmp(pd2.dst, &th.th_dport,
4710					    NULL, /* XXX Inbound NAT? */
4711					    &nk->addr[pd2.didx],
4712					    nk->port[pd2.didx], NULL,
4713					    pd2.ip_sum, icmpsum,
4714					    pd->ip_sum, 0, pd2.af);
4715				copyback = 1;
4716			}
4717
4718			if (copyback) {
4719				switch (pd2.af) {
4720#ifdef INET
4721				case AF_INET:
4722					m_copyback(m, off, ICMP_MINLEN,
4723					    (caddr_t )pd->hdr.icmp);
4724					m_copyback(m, ipoff2, sizeof(h2),
4725					    (caddr_t )&h2);
4726					break;
4727#endif /* INET */
4728#ifdef INET6
4729				case AF_INET6:
4730					m_copyback(m, off,
4731					    sizeof(struct icmp6_hdr),
4732					    (caddr_t )pd->hdr.icmp6);
4733					m_copyback(m, ipoff2, sizeof(h2_6),
4734					    (caddr_t )&h2_6);
4735					break;
4736#endif /* INET6 */
4737				}
4738				m_copyback(m, off2, 8, (caddr_t)&th);
4739			}
4740
4741			return (PF_PASS);
4742			break;
4743		}
4744		case IPPROTO_UDP: {
4745			struct udphdr		uh;
4746
4747			if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4748			    NULL, reason, pd2.af)) {
4749				DPFPRINTF(PF_DEBUG_MISC,
4750				    ("pf: ICMP error message too short "
4751				    "(udp)\n"));
4752				return (PF_DROP);
4753			}
4754
4755			key.af = pd2.af;
4756			key.proto = IPPROTO_UDP;
4757			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4758			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4759			key.port[pd2.sidx] = uh.uh_sport;
4760			key.port[pd2.didx] = uh.uh_dport;
4761
4762			STATE_LOOKUP(kif, &key, direction, *state, pd);
4763
4764			/* translate source/destination address, if necessary */
4765			if ((*state)->key[PF_SK_WIRE] !=
4766			    (*state)->key[PF_SK_STACK]) {
4767				struct pf_state_key *nk =
4768				    (*state)->key[pd->didx];
4769
4770				if (PF_ANEQ(pd2.src,
4771				    &nk->addr[pd2.sidx], pd2.af) ||
4772				    nk->port[pd2.sidx] != uh.uh_sport)
4773					pf_change_icmp(pd2.src, &uh.uh_sport,
4774					    daddr, &nk->addr[pd2.sidx],
4775					    nk->port[pd2.sidx], &uh.uh_sum,
4776					    pd2.ip_sum, icmpsum,
4777					    pd->ip_sum, 1, pd2.af);
4778
4779				if (PF_ANEQ(pd2.dst,
4780				    &nk->addr[pd2.didx], pd2.af) ||
4781				    nk->port[pd2.didx] != uh.uh_dport)
4782					pf_change_icmp(pd2.dst, &uh.uh_dport,
4783					    NULL, /* XXX Inbound NAT? */
4784					    &nk->addr[pd2.didx],
4785					    nk->port[pd2.didx], &uh.uh_sum,
4786					    pd2.ip_sum, icmpsum,
4787					    pd->ip_sum, 1, pd2.af);
4788
4789				switch (pd2.af) {
4790#ifdef INET
4791				case AF_INET:
4792					m_copyback(m, off, ICMP_MINLEN,
4793					    (caddr_t )pd->hdr.icmp);
4794					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4795					break;
4796#endif /* INET */
4797#ifdef INET6
4798				case AF_INET6:
4799					m_copyback(m, off,
4800					    sizeof(struct icmp6_hdr),
4801					    (caddr_t )pd->hdr.icmp6);
4802					m_copyback(m, ipoff2, sizeof(h2_6),
4803					    (caddr_t )&h2_6);
4804					break;
4805#endif /* INET6 */
4806				}
4807				m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4808			}
4809			return (PF_PASS);
4810			break;
4811		}
4812#ifdef INET
4813		case IPPROTO_ICMP: {
4814			struct icmp		iih;
4815
4816			if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4817			    NULL, reason, pd2.af)) {
4818				DPFPRINTF(PF_DEBUG_MISC,
4819				    ("pf: ICMP error message too short i"
4820				    "(icmp)\n"));
4821				return (PF_DROP);
4822			}
4823
4824			key.af = pd2.af;
4825			key.proto = IPPROTO_ICMP;
4826			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4827			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4828			key.port[0] = key.port[1] = iih.icmp_id;
4829
4830			STATE_LOOKUP(kif, &key, direction, *state, pd);
4831
4832			/* translate source/destination address, if necessary */
4833			if ((*state)->key[PF_SK_WIRE] !=
4834			    (*state)->key[PF_SK_STACK]) {
4835				struct pf_state_key *nk =
4836				    (*state)->key[pd->didx];
4837
4838				if (PF_ANEQ(pd2.src,
4839				    &nk->addr[pd2.sidx], pd2.af) ||
4840				    nk->port[pd2.sidx] != iih.icmp_id)
4841					pf_change_icmp(pd2.src, &iih.icmp_id,
4842					    daddr, &nk->addr[pd2.sidx],
4843					    nk->port[pd2.sidx], NULL,
4844					    pd2.ip_sum, icmpsum,
4845					    pd->ip_sum, 0, AF_INET);
4846
4847				if (PF_ANEQ(pd2.dst,
4848				    &nk->addr[pd2.didx], pd2.af) ||
4849				    nk->port[pd2.didx] != iih.icmp_id)
4850					pf_change_icmp(pd2.dst, &iih.icmp_id,
4851					    NULL, /* XXX Inbound NAT? */
4852					    &nk->addr[pd2.didx],
4853					    nk->port[pd2.didx], NULL,
4854					    pd2.ip_sum, icmpsum,
4855					    pd->ip_sum, 0, AF_INET);
4856
4857				m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
4858				m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4859				m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
4860			}
4861			return (PF_PASS);
4862			break;
4863		}
4864#endif /* INET */
4865#ifdef INET6
4866		case IPPROTO_ICMPV6: {
4867			struct icmp6_hdr	iih;
4868
4869			if (!pf_pull_hdr(m, off2, &iih,
4870			    sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
4871				DPFPRINTF(PF_DEBUG_MISC,
4872				    ("pf: ICMP error message too short "
4873				    "(icmp6)\n"));
4874				return (PF_DROP);
4875			}
4876
4877			key.af = pd2.af;
4878			key.proto = IPPROTO_ICMPV6;
4879			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4880			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4881			key.port[0] = key.port[1] = iih.icmp6_id;
4882
4883			STATE_LOOKUP(kif, &key, direction, *state, pd);
4884
4885			/* translate source/destination address, if necessary */
4886			if ((*state)->key[PF_SK_WIRE] !=
4887			    (*state)->key[PF_SK_STACK]) {
4888				struct pf_state_key *nk =
4889				    (*state)->key[pd->didx];
4890
4891				if (PF_ANEQ(pd2.src,
4892				    &nk->addr[pd2.sidx], pd2.af) ||
4893				    nk->port[pd2.sidx] != iih.icmp6_id)
4894					pf_change_icmp(pd2.src, &iih.icmp6_id,
4895					    daddr, &nk->addr[pd2.sidx],
4896					    nk->port[pd2.sidx], NULL,
4897					    pd2.ip_sum, icmpsum,
4898					    pd->ip_sum, 0, AF_INET6);
4899
4900				if (PF_ANEQ(pd2.dst,
4901				    &nk->addr[pd2.didx], pd2.af) ||
4902				    nk->port[pd2.didx] != iih.icmp6_id)
4903					pf_change_icmp(pd2.dst, &iih.icmp6_id,
4904					    NULL, /* XXX Inbound NAT? */
4905					    &nk->addr[pd2.didx],
4906					    nk->port[pd2.didx], NULL,
4907					    pd2.ip_sum, icmpsum,
4908					    pd->ip_sum, 0, AF_INET6);
4909
4910				m_copyback(m, off, sizeof(struct icmp6_hdr),
4911				    (caddr_t)pd->hdr.icmp6);
4912				m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
4913				m_copyback(m, off2, sizeof(struct icmp6_hdr),
4914				    (caddr_t)&iih);
4915			}
4916			return (PF_PASS);
4917			break;
4918		}
4919#endif /* INET6 */
4920		default: {
4921			key.af = pd2.af;
4922			key.proto = pd2.proto;
4923			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4924			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4925			key.port[0] = key.port[1] = 0;
4926
4927			STATE_LOOKUP(kif, &key, direction, *state, pd);
4928
4929			/* translate source/destination address, if necessary */
4930			if ((*state)->key[PF_SK_WIRE] !=
4931			    (*state)->key[PF_SK_STACK]) {
4932				struct pf_state_key *nk =
4933				    (*state)->key[pd->didx];
4934
4935				if (PF_ANEQ(pd2.src,
4936				    &nk->addr[pd2.sidx], pd2.af))
4937					pf_change_icmp(pd2.src, NULL, daddr,
4938					    &nk->addr[pd2.sidx], 0, NULL,
4939					    pd2.ip_sum, icmpsum,
4940					    pd->ip_sum, 0, pd2.af);
4941
4942				if (PF_ANEQ(pd2.dst,
4943				    &nk->addr[pd2.didx], pd2.af))
4944					pf_change_icmp(pd2.src, NULL,
4945					    NULL, /* XXX Inbound NAT? */
4946					    &nk->addr[pd2.didx], 0, NULL,
4947					    pd2.ip_sum, icmpsum,
4948					    pd->ip_sum, 0, pd2.af);
4949
4950				switch (pd2.af) {
4951#ifdef INET
4952				case AF_INET:
4953					m_copyback(m, off, ICMP_MINLEN,
4954					    (caddr_t)pd->hdr.icmp);
4955					m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4956					break;
4957#endif /* INET */
4958#ifdef INET6
4959				case AF_INET6:
4960					m_copyback(m, off,
4961					    sizeof(struct icmp6_hdr),
4962					    (caddr_t )pd->hdr.icmp6);
4963					m_copyback(m, ipoff2, sizeof(h2_6),
4964					    (caddr_t )&h2_6);
4965					break;
4966#endif /* INET6 */
4967				}
4968			}
4969			return (PF_PASS);
4970			break;
4971		}
4972		}
4973	}
4974}
4975
4976static int
4977pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
4978    struct mbuf *m, struct pf_pdesc *pd)
4979{
4980	struct pf_state_peer	*src, *dst;
4981	struct pf_state_key_cmp	 key;
4982
4983	bzero(&key, sizeof(key));
4984	key.af = pd->af;
4985	key.proto = pd->proto;
4986	if (direction == PF_IN)	{
4987		PF_ACPY(&key.addr[0], pd->src, key.af);
4988		PF_ACPY(&key.addr[1], pd->dst, key.af);
4989		key.port[0] = key.port[1] = 0;
4990	} else {
4991		PF_ACPY(&key.addr[1], pd->src, key.af);
4992		PF_ACPY(&key.addr[0], pd->dst, key.af);
4993		key.port[1] = key.port[0] = 0;
4994	}
4995
4996	STATE_LOOKUP(kif, &key, direction, *state, pd);
4997
4998	if (direction == (*state)->direction) {
4999		src = &(*state)->src;
5000		dst = &(*state)->dst;
5001	} else {
5002		src = &(*state)->dst;
5003		dst = &(*state)->src;
5004	}
5005
5006	/* update states */
5007	if (src->state < PFOTHERS_SINGLE)
5008		src->state = PFOTHERS_SINGLE;
5009	if (dst->state == PFOTHERS_SINGLE)
5010		dst->state = PFOTHERS_MULTIPLE;
5011
5012	/* update expire time */
5013	(*state)->expire = time_uptime;
5014	if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5015		(*state)->timeout = PFTM_OTHER_MULTIPLE;
5016	else
5017		(*state)->timeout = PFTM_OTHER_SINGLE;
5018
5019	/* translate source/destination address, if necessary */
5020	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5021		struct pf_state_key *nk = (*state)->key[pd->didx];
5022
5023		KASSERT(nk, ("%s: nk is null", __func__));
5024		KASSERT(pd, ("%s: pd is null", __func__));
5025		KASSERT(pd->src, ("%s: pd->src is null", __func__));
5026		KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5027		switch (pd->af) {
5028#ifdef INET
5029		case AF_INET:
5030			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5031				pf_change_a(&pd->src->v4.s_addr,
5032				    pd->ip_sum,
5033				    nk->addr[pd->sidx].v4.s_addr,
5034				    0);
5035
5036
5037			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5038				pf_change_a(&pd->dst->v4.s_addr,
5039				    pd->ip_sum,
5040				    nk->addr[pd->didx].v4.s_addr,
5041				    0);
5042
5043				break;
5044#endif /* INET */
5045#ifdef INET6
5046		case AF_INET6:
5047			if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5048				PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5049
5050			if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5051				PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5052#endif /* INET6 */
5053		}
5054	}
5055	return (PF_PASS);
5056}
5057
5058/*
5059 * ipoff and off are measured from the start of the mbuf chain.
5060 * h must be at "ipoff" on the mbuf chain.
5061 */
5062void *
5063pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5064    u_short *actionp, u_short *reasonp, sa_family_t af)
5065{
5066	switch (af) {
5067#ifdef INET
5068	case AF_INET: {
5069		struct ip	*h = mtod(m, struct ip *);
5070		u_int16_t	 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5071
5072		if (fragoff) {
5073			if (fragoff >= len)
5074				ACTION_SET(actionp, PF_PASS);
5075			else {
5076				ACTION_SET(actionp, PF_DROP);
5077				REASON_SET(reasonp, PFRES_FRAG);
5078			}
5079			return (NULL);
5080		}
5081		if (m->m_pkthdr.len < off + len ||
5082		    ntohs(h->ip_len) < off + len) {
5083			ACTION_SET(actionp, PF_DROP);
5084			REASON_SET(reasonp, PFRES_SHORT);
5085			return (NULL);
5086		}
5087		break;
5088	}
5089#endif /* INET */
5090#ifdef INET6
5091	case AF_INET6: {
5092		struct ip6_hdr	*h = mtod(m, struct ip6_hdr *);
5093
5094		if (m->m_pkthdr.len < off + len ||
5095		    (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5096		    (unsigned)(off + len)) {
5097			ACTION_SET(actionp, PF_DROP);
5098			REASON_SET(reasonp, PFRES_SHORT);
5099			return (NULL);
5100		}
5101		break;
5102	}
5103#endif /* INET6 */
5104	}
5105	m_copydata(m, off, len, p);
5106	return (p);
5107}
5108
5109int
5110pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5111    int rtableid)
5112{
5113#ifdef RADIX_MPATH
5114	struct radix_node_head	*rnh;
5115#endif
5116	struct sockaddr_in	*dst;
5117	int			 ret = 1;
5118	int			 check_mpath;
5119#ifdef INET6
5120	struct sockaddr_in6	*dst6;
5121	struct route_in6	 ro;
5122#else
5123	struct route		 ro;
5124#endif
5125	struct radix_node	*rn;
5126	struct rtentry		*rt;
5127	struct ifnet		*ifp;
5128
5129	check_mpath = 0;
5130#ifdef RADIX_MPATH
5131	/* XXX: stick to table 0 for now */
5132	rnh = rt_tables_get_rnh(0, af);
5133	if (rnh != NULL && rn_mpath_capable(rnh))
5134		check_mpath = 1;
5135#endif
5136	bzero(&ro, sizeof(ro));
5137	switch (af) {
5138	case AF_INET:
5139		dst = satosin(&ro.ro_dst);
5140		dst->sin_family = AF_INET;
5141		dst->sin_len = sizeof(*dst);
5142		dst->sin_addr = addr->v4;
5143		break;
5144#ifdef INET6
5145	case AF_INET6:
5146		/*
5147		 * Skip check for addresses with embedded interface scope,
5148		 * as they would always match anyway.
5149		 */
5150		if (IN6_IS_SCOPE_EMBED(&addr->v6))
5151			goto out;
5152		dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5153		dst6->sin6_family = AF_INET6;
5154		dst6->sin6_len = sizeof(*dst6);
5155		dst6->sin6_addr = addr->v6;
5156		break;
5157#endif /* INET6 */
5158	default:
5159		return (0);
5160	}
5161
5162	/* Skip checks for ipsec interfaces */
5163	if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5164		goto out;
5165
5166	switch (af) {
5167#ifdef INET6
5168	case AF_INET6:
5169		in6_rtalloc_ign(&ro, 0, rtableid);
5170		break;
5171#endif
5172#ifdef INET
5173	case AF_INET:
5174		in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5175		break;
5176#endif
5177	default:
5178		rtalloc_ign((struct route *)&ro, 0);	/* No/default FIB. */
5179		break;
5180	}
5181
5182	if (ro.ro_rt != NULL) {
5183		/* No interface given, this is a no-route check */
5184		if (kif == NULL)
5185			goto out;
5186
5187		if (kif->pfik_ifp == NULL) {
5188			ret = 0;
5189			goto out;
5190		}
5191
5192		/* Perform uRPF check if passed input interface */
5193		ret = 0;
5194		rn = (struct radix_node *)ro.ro_rt;
5195		do {
5196			rt = (struct rtentry *)rn;
5197			ifp = rt->rt_ifp;
5198
5199			if (kif->pfik_ifp == ifp)
5200				ret = 1;
5201#ifdef RADIX_MPATH
5202			rn = rn_mpath_next(rn);
5203#endif
5204		} while (check_mpath == 1 && rn != NULL && ret == 0);
5205	} else
5206		ret = 0;
5207out:
5208	if (ro.ro_rt != NULL)
5209		RTFREE(ro.ro_rt);
5210	return (ret);
5211}
5212
5213#ifdef INET
5214static void
5215pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5216    struct pf_state *s, struct pf_pdesc *pd)
5217{
5218	struct mbuf		*m0, *m1;
5219	struct sockaddr_in	dst;
5220	struct ip		*ip;
5221	struct ifnet		*ifp = NULL;
5222	struct pf_addr		 naddr;
5223	struct pf_src_node	*sn = NULL;
5224	int			 error = 0;
5225	uint16_t		 ip_len, ip_off;
5226
5227	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5228	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5229	    __func__));
5230
5231	if ((pd->pf_mtag == NULL &&
5232	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5233	    pd->pf_mtag->routed++ > 3) {
5234		m0 = *m;
5235		*m = NULL;
5236		goto bad_locked;
5237	}
5238
5239	if (r->rt == PF_DUPTO) {
5240		if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5241			if (s)
5242				PF_STATE_UNLOCK(s);
5243			return;
5244		}
5245	} else {
5246		if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5247			if (s)
5248				PF_STATE_UNLOCK(s);
5249			return;
5250		}
5251		m0 = *m;
5252	}
5253
5254	ip = mtod(m0, struct ip *);
5255
5256	bzero(&dst, sizeof(dst));
5257	dst.sin_family = AF_INET;
5258	dst.sin_len = sizeof(dst);
5259	dst.sin_addr = ip->ip_dst;
5260
5261	if (r->rt == PF_FASTROUTE) {
5262		struct rtentry *rt;
5263
5264		if (s)
5265			PF_STATE_UNLOCK(s);
5266		rt = rtalloc1_fib(sintosa(&dst), 0, 0, M_GETFIB(m0));
5267		if (rt == NULL) {
5268			KMOD_IPSTAT_INC(ips_noroute);
5269			error = EHOSTUNREACH;
5270			goto bad;
5271		}
5272
5273		ifp = rt->rt_ifp;
5274		counter_u64_add(rt->rt_pksent, 1);
5275
5276		if (rt->rt_flags & RTF_GATEWAY)
5277			bcopy(satosin(rt->rt_gateway), &dst, sizeof(dst));
5278		RTFREE_LOCKED(rt);
5279	} else {
5280		if (TAILQ_EMPTY(&r->rpool.list)) {
5281			DPFPRINTF(PF_DEBUG_URGENT,
5282			    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5283			goto bad_locked;
5284		}
5285		if (s == NULL) {
5286			pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5287			    &naddr, NULL, &sn);
5288			if (!PF_AZERO(&naddr, AF_INET))
5289				dst.sin_addr.s_addr = naddr.v4.s_addr;
5290			ifp = r->rpool.cur->kif ?
5291			    r->rpool.cur->kif->pfik_ifp : NULL;
5292		} else {
5293			if (!PF_AZERO(&s->rt_addr, AF_INET))
5294				dst.sin_addr.s_addr =
5295				    s->rt_addr.v4.s_addr;
5296			ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5297			PF_STATE_UNLOCK(s);
5298		}
5299	}
5300	if (ifp == NULL)
5301		goto bad;
5302
5303	if (oifp != ifp) {
5304		if (pf_test(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5305			goto bad;
5306		else if (m0 == NULL)
5307			goto done;
5308		if (m0->m_len < sizeof(struct ip)) {
5309			DPFPRINTF(PF_DEBUG_URGENT,
5310			    ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5311			goto bad;
5312		}
5313		ip = mtod(m0, struct ip *);
5314	}
5315
5316	if (ifp->if_flags & IFF_LOOPBACK)
5317		m0->m_flags |= M_SKIP_FIREWALL;
5318
5319	ip_len = ntohs(ip->ip_len);
5320	ip_off = ntohs(ip->ip_off);
5321
5322	/* Copied from FreeBSD 10.0-CURRENT ip_output. */
5323	m0->m_pkthdr.csum_flags |= CSUM_IP;
5324	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5325		in_delayed_cksum(m0);
5326		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5327	}
5328#ifdef SCTP
5329	if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5330		sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5331		m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5332	}
5333#endif
5334
5335	/*
5336	 * If small enough for interface, or the interface will take
5337	 * care of the fragmentation for us, we can just send directly.
5338	 */
5339	if (ip_len <= ifp->if_mtu ||
5340	    (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0 ||
5341	    ((ip_off & IP_DF) == 0 && (ifp->if_hwassist & CSUM_FRAGMENT))) {
5342		ip->ip_sum = 0;
5343		if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5344			ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5345			m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5346		}
5347		m_clrprotoflags(m0);	/* Avoid confusing lower layers. */
5348		error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5349		goto done;
5350	}
5351
5352	/* Balk when DF bit is set or the interface didn't support TSO. */
5353	if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5354		error = EMSGSIZE;
5355		KMOD_IPSTAT_INC(ips_cantfrag);
5356		if (r->rt != PF_DUPTO) {
5357			icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5358			    ifp->if_mtu);
5359			goto done;
5360		} else
5361			goto bad;
5362	}
5363
5364	error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5365	if (error)
5366		goto bad;
5367
5368	for (; m0; m0 = m1) {
5369		m1 = m0->m_nextpkt;
5370		m0->m_nextpkt = NULL;
5371		if (error == 0) {
5372			m_clrprotoflags(m0);
5373			error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5374		} else
5375			m_freem(m0);
5376	}
5377
5378	if (error == 0)
5379		KMOD_IPSTAT_INC(ips_fragmented);
5380
5381done:
5382	if (r->rt != PF_DUPTO)
5383		*m = NULL;
5384	return;
5385
5386bad_locked:
5387	if (s)
5388		PF_STATE_UNLOCK(s);
5389bad:
5390	m_freem(m0);
5391	goto done;
5392}
5393#endif /* INET */
5394
5395#ifdef INET6
5396static void
5397pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5398    struct pf_state *s, struct pf_pdesc *pd)
5399{
5400	struct mbuf		*m0;
5401	struct sockaddr_in6	dst;
5402	struct ip6_hdr		*ip6;
5403	struct ifnet		*ifp = NULL;
5404	struct pf_addr		 naddr;
5405	struct pf_src_node	*sn = NULL;
5406
5407	KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5408	KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5409	    __func__));
5410
5411	if ((pd->pf_mtag == NULL &&
5412	    ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5413	    pd->pf_mtag->routed++ > 3) {
5414		m0 = *m;
5415		*m = NULL;
5416		goto bad_locked;
5417	}
5418
5419	if (r->rt == PF_DUPTO) {
5420		if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5421			if (s)
5422				PF_STATE_UNLOCK(s);
5423			return;
5424		}
5425	} else {
5426		if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5427			if (s)
5428				PF_STATE_UNLOCK(s);
5429			return;
5430		}
5431		m0 = *m;
5432	}
5433
5434	ip6 = mtod(m0, struct ip6_hdr *);
5435
5436	bzero(&dst, sizeof(dst));
5437	dst.sin6_family = AF_INET6;
5438	dst.sin6_len = sizeof(dst);
5439	dst.sin6_addr = ip6->ip6_dst;
5440
5441	/* Cheat. XXX why only in the v6 case??? */
5442	if (r->rt == PF_FASTROUTE) {
5443		if (s)
5444			PF_STATE_UNLOCK(s);
5445		m0->m_flags |= M_SKIP_FIREWALL;
5446		ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5447		return;
5448	}
5449
5450	if (TAILQ_EMPTY(&r->rpool.list)) {
5451		DPFPRINTF(PF_DEBUG_URGENT,
5452		    ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5453		goto bad_locked;
5454	}
5455	if (s == NULL) {
5456		pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5457		    &naddr, NULL, &sn);
5458		if (!PF_AZERO(&naddr, AF_INET6))
5459			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5460			    &naddr, AF_INET6);
5461		ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5462	} else {
5463		if (!PF_AZERO(&s->rt_addr, AF_INET6))
5464			PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5465			    &s->rt_addr, AF_INET6);
5466		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5467	}
5468
5469	if (s)
5470		PF_STATE_UNLOCK(s);
5471
5472	if (ifp == NULL)
5473		goto bad;
5474
5475	if (oifp != ifp) {
5476		if (pf_test6(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5477			goto bad;
5478		else if (m0 == NULL)
5479			goto done;
5480		if (m0->m_len < sizeof(struct ip6_hdr)) {
5481			DPFPRINTF(PF_DEBUG_URGENT,
5482			    ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5483			    __func__));
5484			goto bad;
5485		}
5486		ip6 = mtod(m0, struct ip6_hdr *);
5487	}
5488
5489	if (ifp->if_flags & IFF_LOOPBACK)
5490		m0->m_flags |= M_SKIP_FIREWALL;
5491
5492	/*
5493	 * If the packet is too large for the outgoing interface,
5494	 * send back an icmp6 error.
5495	 */
5496	if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5497		dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5498	if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5499		nd6_output(ifp, ifp, m0, &dst, NULL);
5500	else {
5501		in6_ifstat_inc(ifp, ifs6_in_toobig);
5502		if (r->rt != PF_DUPTO)
5503			icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5504		else
5505			goto bad;
5506	}
5507
5508done:
5509	if (r->rt != PF_DUPTO)
5510		*m = NULL;
5511	return;
5512
5513bad_locked:
5514	if (s)
5515		PF_STATE_UNLOCK(s);
5516bad:
5517	m_freem(m0);
5518	goto done;
5519}
5520#endif /* INET6 */
5521
5522/*
5523 * FreeBSD supports cksum offloads for the following drivers.
5524 *  em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5525 *   ti(4), txp(4), xl(4)
5526 *
5527 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5528 *  network driver performed cksum including pseudo header, need to verify
5529 *   csum_data
5530 * CSUM_DATA_VALID :
5531 *  network driver performed cksum, needs to additional pseudo header
5532 *  cksum computation with partial csum_data(i.e. lack of H/W support for
5533 *  pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5534 *
5535 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5536 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5537 * TCP/UDP layer.
5538 * Also, set csum_data to 0xffff to force cksum validation.
5539 */
5540static int
5541pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5542{
5543	u_int16_t sum = 0;
5544	int hw_assist = 0;
5545	struct ip *ip;
5546
5547	if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5548		return (1);
5549	if (m->m_pkthdr.len < off + len)
5550		return (1);
5551
5552	switch (p) {
5553	case IPPROTO_TCP:
5554		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5555			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5556				sum = m->m_pkthdr.csum_data;
5557			} else {
5558				ip = mtod(m, struct ip *);
5559				sum = in_pseudo(ip->ip_src.s_addr,
5560				ip->ip_dst.s_addr, htonl((u_short)len +
5561				m->m_pkthdr.csum_data + IPPROTO_TCP));
5562			}
5563			sum ^= 0xffff;
5564			++hw_assist;
5565		}
5566		break;
5567	case IPPROTO_UDP:
5568		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5569			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5570				sum = m->m_pkthdr.csum_data;
5571			} else {
5572				ip = mtod(m, struct ip *);
5573				sum = in_pseudo(ip->ip_src.s_addr,
5574				ip->ip_dst.s_addr, htonl((u_short)len +
5575				m->m_pkthdr.csum_data + IPPROTO_UDP));
5576			}
5577			sum ^= 0xffff;
5578			++hw_assist;
5579		}
5580		break;
5581	case IPPROTO_ICMP:
5582#ifdef INET6
5583	case IPPROTO_ICMPV6:
5584#endif /* INET6 */
5585		break;
5586	default:
5587		return (1);
5588	}
5589
5590	if (!hw_assist) {
5591		switch (af) {
5592		case AF_INET:
5593			if (p == IPPROTO_ICMP) {
5594				if (m->m_len < off)
5595					return (1);
5596				m->m_data += off;
5597				m->m_len -= off;
5598				sum = in_cksum(m, len);
5599				m->m_data -= off;
5600				m->m_len += off;
5601			} else {
5602				if (m->m_len < sizeof(struct ip))
5603					return (1);
5604				sum = in4_cksum(m, p, off, len);
5605			}
5606			break;
5607#ifdef INET6
5608		case AF_INET6:
5609			if (m->m_len < sizeof(struct ip6_hdr))
5610				return (1);
5611			sum = in6_cksum(m, p, off, len);
5612			break;
5613#endif /* INET6 */
5614		default:
5615			return (1);
5616		}
5617	}
5618	if (sum) {
5619		switch (p) {
5620		case IPPROTO_TCP:
5621		    {
5622			KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5623			break;
5624		    }
5625		case IPPROTO_UDP:
5626		    {
5627			KMOD_UDPSTAT_INC(udps_badsum);
5628			break;
5629		    }
5630#ifdef INET
5631		case IPPROTO_ICMP:
5632		    {
5633			KMOD_ICMPSTAT_INC(icps_checksum);
5634			break;
5635		    }
5636#endif
5637#ifdef INET6
5638		case IPPROTO_ICMPV6:
5639		    {
5640			KMOD_ICMP6STAT_INC(icp6s_checksum);
5641			break;
5642		    }
5643#endif /* INET6 */
5644		}
5645		return (1);
5646	} else {
5647		if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5648			m->m_pkthdr.csum_flags |=
5649			    (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5650			m->m_pkthdr.csum_data = 0xffff;
5651		}
5652	}
5653	return (0);
5654}
5655
5656
5657#ifdef INET
5658int
5659pf_test(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5660{
5661	struct pfi_kif		*kif;
5662	u_short			 action, reason = 0, log = 0;
5663	struct mbuf		*m = *m0;
5664	struct ip		*h = NULL;
5665	struct m_tag		*ipfwtag;
5666	struct pf_rule		*a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5667	struct pf_state		*s = NULL;
5668	struct pf_ruleset	*ruleset = NULL;
5669	struct pf_pdesc		 pd;
5670	int			 off, dirndx, pqid = 0;
5671
5672	M_ASSERTPKTHDR(m);
5673
5674	if (!V_pf_status.running)
5675		return (PF_PASS);
5676
5677	memset(&pd, 0, sizeof(pd));
5678
5679	kif = (struct pfi_kif *)ifp->if_pf_kif;
5680
5681	if (kif == NULL) {
5682		DPFPRINTF(PF_DEBUG_URGENT,
5683		    ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5684		return (PF_DROP);
5685	}
5686	if (kif->pfik_flags & PFI_IFLAG_SKIP)
5687		return (PF_PASS);
5688
5689	if (m->m_flags & M_SKIP_FIREWALL)
5690		return (PF_PASS);
5691
5692	pd.pf_mtag = pf_find_mtag(m);
5693
5694	PF_RULES_RLOCK();
5695
5696	if (ip_divert_ptr != NULL &&
5697	    ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5698		struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5699		if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5700			if (pd.pf_mtag == NULL &&
5701			    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5702				action = PF_DROP;
5703				goto done;
5704			}
5705			pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5706			m_tag_delete(m, ipfwtag);
5707		}
5708		if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5709			m->m_flags |= M_FASTFWD_OURS;
5710			pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5711		}
5712	} else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5713		/* We do IP header normalization and packet reassembly here */
5714		action = PF_DROP;
5715		goto done;
5716	}
5717	m = *m0;	/* pf_normalize messes with m0 */
5718	h = mtod(m, struct ip *);
5719
5720	off = h->ip_hl << 2;
5721	if (off < (int)sizeof(struct ip)) {
5722		action = PF_DROP;
5723		REASON_SET(&reason, PFRES_SHORT);
5724		log = 1;
5725		goto done;
5726	}
5727
5728	pd.src = (struct pf_addr *)&h->ip_src;
5729	pd.dst = (struct pf_addr *)&h->ip_dst;
5730	pd.sport = pd.dport = NULL;
5731	pd.ip_sum = &h->ip_sum;
5732	pd.proto_sum = NULL;
5733	pd.proto = h->ip_p;
5734	pd.dir = dir;
5735	pd.sidx = (dir == PF_IN) ? 0 : 1;
5736	pd.didx = (dir == PF_IN) ? 1 : 0;
5737	pd.af = AF_INET;
5738	pd.tos = h->ip_tos;
5739	pd.tot_len = ntohs(h->ip_len);
5740
5741	/* handle fragments that didn't get reassembled by normalization */
5742	if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5743		action = pf_test_fragment(&r, dir, kif, m, h,
5744		    &pd, &a, &ruleset);
5745		goto done;
5746	}
5747
5748	switch (h->ip_p) {
5749
5750	case IPPROTO_TCP: {
5751		struct tcphdr	th;
5752
5753		pd.hdr.tcp = &th;
5754		if (!pf_pull_hdr(m, off, &th, sizeof(th),
5755		    &action, &reason, AF_INET)) {
5756			log = action != PF_PASS;
5757			goto done;
5758		}
5759		pd.p_len = pd.tot_len - off - (th.th_off << 2);
5760		if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5761			pqid = 1;
5762		action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5763		if (action == PF_DROP)
5764			goto done;
5765		action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5766		    &reason);
5767		if (action == PF_PASS) {
5768			if (pfsync_update_state_ptr != NULL)
5769				pfsync_update_state_ptr(s);
5770			r = s->rule.ptr;
5771			a = s->anchor.ptr;
5772			log = s->log;
5773		} else if (s == NULL)
5774			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5775			    &a, &ruleset, inp);
5776		break;
5777	}
5778
5779	case IPPROTO_UDP: {
5780		struct udphdr	uh;
5781
5782		pd.hdr.udp = &uh;
5783		if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5784		    &action, &reason, AF_INET)) {
5785			log = action != PF_PASS;
5786			goto done;
5787		}
5788		if (uh.uh_dport == 0 ||
5789		    ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5790		    ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5791			action = PF_DROP;
5792			REASON_SET(&reason, PFRES_SHORT);
5793			goto done;
5794		}
5795		action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5796		if (action == PF_PASS) {
5797			if (pfsync_update_state_ptr != NULL)
5798				pfsync_update_state_ptr(s);
5799			r = s->rule.ptr;
5800			a = s->anchor.ptr;
5801			log = s->log;
5802		} else if (s == NULL)
5803			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5804			    &a, &ruleset, inp);
5805		break;
5806	}
5807
5808	case IPPROTO_ICMP: {
5809		struct icmp	ih;
5810
5811		pd.hdr.icmp = &ih;
5812		if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5813		    &action, &reason, AF_INET)) {
5814			log = action != PF_PASS;
5815			goto done;
5816		}
5817		action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5818		    &reason);
5819		if (action == PF_PASS) {
5820			if (pfsync_update_state_ptr != NULL)
5821				pfsync_update_state_ptr(s);
5822			r = s->rule.ptr;
5823			a = s->anchor.ptr;
5824			log = s->log;
5825		} else if (s == NULL)
5826			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5827			    &a, &ruleset, inp);
5828		break;
5829	}
5830
5831#ifdef INET6
5832	case IPPROTO_ICMPV6: {
5833		action = PF_DROP;
5834		DPFPRINTF(PF_DEBUG_MISC,
5835		    ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
5836		goto done;
5837	}
5838#endif
5839
5840	default:
5841		action = pf_test_state_other(&s, dir, kif, m, &pd);
5842		if (action == PF_PASS) {
5843			if (pfsync_update_state_ptr != NULL)
5844				pfsync_update_state_ptr(s);
5845			r = s->rule.ptr;
5846			a = s->anchor.ptr;
5847			log = s->log;
5848		} else if (s == NULL)
5849			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5850			    &a, &ruleset, inp);
5851		break;
5852	}
5853
5854done:
5855	PF_RULES_RUNLOCK();
5856	if (action == PF_PASS && h->ip_hl > 5 &&
5857	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
5858		action = PF_DROP;
5859		REASON_SET(&reason, PFRES_IPOPTIONS);
5860		log = 1;
5861		DPFPRINTF(PF_DEBUG_MISC,
5862		    ("pf: dropping packet with ip options\n"));
5863	}
5864
5865	if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
5866		action = PF_DROP;
5867		REASON_SET(&reason, PFRES_MEMORY);
5868	}
5869	if (r->rtableid >= 0)
5870		M_SETFIB(m, r->rtableid);
5871
5872#ifdef ALTQ
5873	if (action == PF_PASS && r->qid) {
5874		if (pd.pf_mtag == NULL &&
5875		    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5876			action = PF_DROP;
5877			REASON_SET(&reason, PFRES_MEMORY);
5878		}
5879		if (pqid || (pd.tos & IPTOS_LOWDELAY))
5880			pd.pf_mtag->qid = r->pqid;
5881		else
5882			pd.pf_mtag->qid = r->qid;
5883		/* add hints for ecn */
5884		pd.pf_mtag->hdr = h;
5885
5886	}
5887#endif /* ALTQ */
5888
5889	/*
5890	 * connections redirected to loopback should not match sockets
5891	 * bound specifically to loopback due to security implications,
5892	 * see tcp_input() and in_pcblookup_listen().
5893	 */
5894	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
5895	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
5896	    (s->nat_rule.ptr->action == PF_RDR ||
5897	    s->nat_rule.ptr->action == PF_BINAT) &&
5898	    (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
5899		m->m_flags |= M_SKIP_FIREWALL;
5900
5901	if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
5902	    !PACKET_LOOPED(&pd)) {
5903
5904		ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
5905		    sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
5906		if (ipfwtag != NULL) {
5907			((struct ipfw_rule_ref *)(ipfwtag+1))->info =
5908			    ntohs(r->divert.port);
5909			((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
5910
5911			if (s)
5912				PF_STATE_UNLOCK(s);
5913
5914			m_tag_prepend(m, ipfwtag);
5915			if (m->m_flags & M_FASTFWD_OURS) {
5916				if (pd.pf_mtag == NULL &&
5917				    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5918					action = PF_DROP;
5919					REASON_SET(&reason, PFRES_MEMORY);
5920					log = 1;
5921					DPFPRINTF(PF_DEBUG_MISC,
5922					    ("pf: failed to allocate tag\n"));
5923				}
5924				pd.pf_mtag->flags |= PF_FASTFWD_OURS_PRESENT;
5925				m->m_flags &= ~M_FASTFWD_OURS;
5926			}
5927			ip_divert_ptr(*m0, dir ==  PF_IN ? DIR_IN : DIR_OUT);
5928			*m0 = NULL;
5929
5930			return (action);
5931		} else {
5932			/* XXX: ipfw has the same behaviour! */
5933			action = PF_DROP;
5934			REASON_SET(&reason, PFRES_MEMORY);
5935			log = 1;
5936			DPFPRINTF(PF_DEBUG_MISC,
5937			    ("pf: failed to allocate divert tag\n"));
5938		}
5939	}
5940
5941	if (log) {
5942		struct pf_rule *lr;
5943
5944		if (s != NULL && s->nat_rule.ptr != NULL &&
5945		    s->nat_rule.ptr->log & PF_LOG_ALL)
5946			lr = s->nat_rule.ptr;
5947		else
5948			lr = r;
5949		PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
5950		    (s == NULL));
5951	}
5952
5953	kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
5954	kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
5955
5956	if (action == PF_PASS || r->action == PF_DROP) {
5957		dirndx = (dir == PF_OUT);
5958		r->packets[dirndx]++;
5959		r->bytes[dirndx] += pd.tot_len;
5960		if (a != NULL) {
5961			a->packets[dirndx]++;
5962			a->bytes[dirndx] += pd.tot_len;
5963		}
5964		if (s != NULL) {
5965			if (s->nat_rule.ptr != NULL) {
5966				s->nat_rule.ptr->packets[dirndx]++;
5967				s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
5968			}
5969			if (s->src_node != NULL) {
5970				s->src_node->packets[dirndx]++;
5971				s->src_node->bytes[dirndx] += pd.tot_len;
5972			}
5973			if (s->nat_src_node != NULL) {
5974				s->nat_src_node->packets[dirndx]++;
5975				s->nat_src_node->bytes[dirndx] += pd.tot_len;
5976			}
5977			dirndx = (dir == s->direction) ? 0 : 1;
5978			s->packets[dirndx]++;
5979			s->bytes[dirndx] += pd.tot_len;
5980		}
5981		tr = r;
5982		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
5983		if (nr != NULL && r == &V_pf_default_rule)
5984			tr = nr;
5985		if (tr->src.addr.type == PF_ADDR_TABLE)
5986			pfr_update_stats(tr->src.addr.p.tbl,
5987			    (s == NULL) ? pd.src :
5988			    &s->key[(s->direction == PF_IN)]->
5989				addr[(s->direction == PF_OUT)],
5990			    pd.af, pd.tot_len, dir == PF_OUT,
5991			    r->action == PF_PASS, tr->src.neg);
5992		if (tr->dst.addr.type == PF_ADDR_TABLE)
5993			pfr_update_stats(tr->dst.addr.p.tbl,
5994			    (s == NULL) ? pd.dst :
5995			    &s->key[(s->direction == PF_IN)]->
5996				addr[(s->direction == PF_IN)],
5997			    pd.af, pd.tot_len, dir == PF_OUT,
5998			    r->action == PF_PASS, tr->dst.neg);
5999	}
6000
6001	switch (action) {
6002	case PF_SYNPROXY_DROP:
6003		m_freem(*m0);
6004	case PF_DEFER:
6005		*m0 = NULL;
6006		action = PF_PASS;
6007		break;
6008	default:
6009		/* pf_route() returns unlocked. */
6010		if (r->rt) {
6011			pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6012			return (action);
6013		}
6014		break;
6015	}
6016	if (s)
6017		PF_STATE_UNLOCK(s);
6018
6019	return (action);
6020}
6021#endif /* INET */
6022
6023#ifdef INET6
6024int
6025pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6026{
6027	struct pfi_kif		*kif;
6028	u_short			 action, reason = 0, log = 0;
6029	struct mbuf		*m = *m0, *n = NULL;
6030	struct ip6_hdr		*h = NULL;
6031	struct pf_rule		*a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6032	struct pf_state		*s = NULL;
6033	struct pf_ruleset	*ruleset = NULL;
6034	struct pf_pdesc		 pd;
6035	int			 off, terminal = 0, dirndx, rh_cnt = 0;
6036
6037	M_ASSERTPKTHDR(m);
6038
6039	if (!V_pf_status.running)
6040		return (PF_PASS);
6041
6042	memset(&pd, 0, sizeof(pd));
6043	pd.pf_mtag = pf_find_mtag(m);
6044
6045	if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6046		return (PF_PASS);
6047
6048	kif = (struct pfi_kif *)ifp->if_pf_kif;
6049	if (kif == NULL) {
6050		DPFPRINTF(PF_DEBUG_URGENT,
6051		    ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6052		return (PF_DROP);
6053	}
6054	if (kif->pfik_flags & PFI_IFLAG_SKIP)
6055		return (PF_PASS);
6056
6057	if (m->m_flags & M_SKIP_FIREWALL)
6058		return (PF_PASS);
6059
6060	PF_RULES_RLOCK();
6061
6062	/* We do IP header normalization and packet reassembly here */
6063	if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6064		action = PF_DROP;
6065		goto done;
6066	}
6067	m = *m0;	/* pf_normalize messes with m0 */
6068	h = mtod(m, struct ip6_hdr *);
6069
6070#if 1
6071	/*
6072	 * we do not support jumbogram yet.  if we keep going, zero ip6_plen
6073	 * will do something bad, so drop the packet for now.
6074	 */
6075	if (htons(h->ip6_plen) == 0) {
6076		action = PF_DROP;
6077		REASON_SET(&reason, PFRES_NORM);	/*XXX*/
6078		goto done;
6079	}
6080#endif
6081
6082	pd.src = (struct pf_addr *)&h->ip6_src;
6083	pd.dst = (struct pf_addr *)&h->ip6_dst;
6084	pd.sport = pd.dport = NULL;
6085	pd.ip_sum = NULL;
6086	pd.proto_sum = NULL;
6087	pd.dir = dir;
6088	pd.sidx = (dir == PF_IN) ? 0 : 1;
6089	pd.didx = (dir == PF_IN) ? 1 : 0;
6090	pd.af = AF_INET6;
6091	pd.tos = 0;
6092	pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6093
6094	off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6095	pd.proto = h->ip6_nxt;
6096	do {
6097		switch (pd.proto) {
6098		case IPPROTO_FRAGMENT:
6099			action = pf_test_fragment(&r, dir, kif, m, h,
6100			    &pd, &a, &ruleset);
6101			if (action == PF_DROP)
6102				REASON_SET(&reason, PFRES_FRAG);
6103			goto done;
6104		case IPPROTO_ROUTING: {
6105			struct ip6_rthdr rthdr;
6106
6107			if (rh_cnt++) {
6108				DPFPRINTF(PF_DEBUG_MISC,
6109				    ("pf: IPv6 more than one rthdr\n"));
6110				action = PF_DROP;
6111				REASON_SET(&reason, PFRES_IPOPTIONS);
6112				log = 1;
6113				goto done;
6114			}
6115			if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6116			    &reason, pd.af)) {
6117				DPFPRINTF(PF_DEBUG_MISC,
6118				    ("pf: IPv6 short rthdr\n"));
6119				action = PF_DROP;
6120				REASON_SET(&reason, PFRES_SHORT);
6121				log = 1;
6122				goto done;
6123			}
6124			if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6125				DPFPRINTF(PF_DEBUG_MISC,
6126				    ("pf: IPv6 rthdr0\n"));
6127				action = PF_DROP;
6128				REASON_SET(&reason, PFRES_IPOPTIONS);
6129				log = 1;
6130				goto done;
6131			}
6132			/* FALLTHROUGH */
6133		}
6134		case IPPROTO_AH:
6135		case IPPROTO_HOPOPTS:
6136		case IPPROTO_DSTOPTS: {
6137			/* get next header and header length */
6138			struct ip6_ext	opt6;
6139
6140			if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6141			    NULL, &reason, pd.af)) {
6142				DPFPRINTF(PF_DEBUG_MISC,
6143				    ("pf: IPv6 short opt\n"));
6144				action = PF_DROP;
6145				log = 1;
6146				goto done;
6147			}
6148			if (pd.proto == IPPROTO_AH)
6149				off += (opt6.ip6e_len + 2) * 4;
6150			else
6151				off += (opt6.ip6e_len + 1) * 8;
6152			pd.proto = opt6.ip6e_nxt;
6153			/* goto the next header */
6154			break;
6155		}
6156		default:
6157			terminal++;
6158			break;
6159		}
6160	} while (!terminal);
6161
6162	/* if there's no routing header, use unmodified mbuf for checksumming */
6163	if (!n)
6164		n = m;
6165
6166	switch (pd.proto) {
6167
6168	case IPPROTO_TCP: {
6169		struct tcphdr	th;
6170
6171		pd.hdr.tcp = &th;
6172		if (!pf_pull_hdr(m, off, &th, sizeof(th),
6173		    &action, &reason, AF_INET6)) {
6174			log = action != PF_PASS;
6175			goto done;
6176		}
6177		pd.p_len = pd.tot_len - off - (th.th_off << 2);
6178		action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6179		if (action == PF_DROP)
6180			goto done;
6181		action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6182		    &reason);
6183		if (action == PF_PASS) {
6184			if (pfsync_update_state_ptr != NULL)
6185				pfsync_update_state_ptr(s);
6186			r = s->rule.ptr;
6187			a = s->anchor.ptr;
6188			log = s->log;
6189		} else if (s == NULL)
6190			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6191			    &a, &ruleset, inp);
6192		break;
6193	}
6194
6195	case IPPROTO_UDP: {
6196		struct udphdr	uh;
6197
6198		pd.hdr.udp = &uh;
6199		if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6200		    &action, &reason, AF_INET6)) {
6201			log = action != PF_PASS;
6202			goto done;
6203		}
6204		if (uh.uh_dport == 0 ||
6205		    ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6206		    ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6207			action = PF_DROP;
6208			REASON_SET(&reason, PFRES_SHORT);
6209			goto done;
6210		}
6211		action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6212		if (action == PF_PASS) {
6213			if (pfsync_update_state_ptr != NULL)
6214				pfsync_update_state_ptr(s);
6215			r = s->rule.ptr;
6216			a = s->anchor.ptr;
6217			log = s->log;
6218		} else if (s == NULL)
6219			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6220			    &a, &ruleset, inp);
6221		break;
6222	}
6223
6224	case IPPROTO_ICMP: {
6225		action = PF_DROP;
6226		DPFPRINTF(PF_DEBUG_MISC,
6227		    ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6228		goto done;
6229	}
6230
6231	case IPPROTO_ICMPV6: {
6232		struct icmp6_hdr	ih;
6233
6234		pd.hdr.icmp6 = &ih;
6235		if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6236		    &action, &reason, AF_INET6)) {
6237			log = action != PF_PASS;
6238			goto done;
6239		}
6240		action = pf_test_state_icmp(&s, dir, kif,
6241		    m, off, h, &pd, &reason);
6242		if (action == PF_PASS) {
6243			if (pfsync_update_state_ptr != NULL)
6244				pfsync_update_state_ptr(s);
6245			r = s->rule.ptr;
6246			a = s->anchor.ptr;
6247			log = s->log;
6248		} else if (s == NULL)
6249			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6250			    &a, &ruleset, inp);
6251		break;
6252	}
6253
6254	default:
6255		action = pf_test_state_other(&s, dir, kif, m, &pd);
6256		if (action == PF_PASS) {
6257			if (pfsync_update_state_ptr != NULL)
6258				pfsync_update_state_ptr(s);
6259			r = s->rule.ptr;
6260			a = s->anchor.ptr;
6261			log = s->log;
6262		} else if (s == NULL)
6263			action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6264			    &a, &ruleset, inp);
6265		break;
6266	}
6267
6268done:
6269	PF_RULES_RUNLOCK();
6270	if (n != m) {
6271		m_freem(n);
6272		n = NULL;
6273	}
6274
6275	/* handle dangerous IPv6 extension headers. */
6276	if (action == PF_PASS && rh_cnt &&
6277	    !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6278		action = PF_DROP;
6279		REASON_SET(&reason, PFRES_IPOPTIONS);
6280		log = 1;
6281		DPFPRINTF(PF_DEBUG_MISC,
6282		    ("pf: dropping packet with dangerous v6 headers\n"));
6283	}
6284
6285	if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6286		action = PF_DROP;
6287		REASON_SET(&reason, PFRES_MEMORY);
6288	}
6289	if (r->rtableid >= 0)
6290		M_SETFIB(m, r->rtableid);
6291
6292#ifdef ALTQ
6293	if (action == PF_PASS && r->qid) {
6294		if (pd.pf_mtag == NULL &&
6295		    ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6296			action = PF_DROP;
6297			REASON_SET(&reason, PFRES_MEMORY);
6298		}
6299		if (pd.tos & IPTOS_LOWDELAY)
6300			pd.pf_mtag->qid = r->pqid;
6301		else
6302			pd.pf_mtag->qid = r->qid;
6303		/* add hints for ecn */
6304		pd.pf_mtag->hdr = h;
6305	}
6306#endif /* ALTQ */
6307
6308	if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6309	    pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6310	    (s->nat_rule.ptr->action == PF_RDR ||
6311	    s->nat_rule.ptr->action == PF_BINAT) &&
6312	    IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6313		m->m_flags |= M_SKIP_FIREWALL;
6314
6315	/* XXX: Anybody working on it?! */
6316	if (r->divert.port)
6317		printf("pf: divert(9) is not supported for IPv6\n");
6318
6319	if (log) {
6320		struct pf_rule *lr;
6321
6322		if (s != NULL && s->nat_rule.ptr != NULL &&
6323		    s->nat_rule.ptr->log & PF_LOG_ALL)
6324			lr = s->nat_rule.ptr;
6325		else
6326			lr = r;
6327		PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6328		    &pd, (s == NULL));
6329	}
6330
6331	kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6332	kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6333
6334	if (action == PF_PASS || r->action == PF_DROP) {
6335		dirndx = (dir == PF_OUT);
6336		r->packets[dirndx]++;
6337		r->bytes[dirndx] += pd.tot_len;
6338		if (a != NULL) {
6339			a->packets[dirndx]++;
6340			a->bytes[dirndx] += pd.tot_len;
6341		}
6342		if (s != NULL) {
6343			if (s->nat_rule.ptr != NULL) {
6344				s->nat_rule.ptr->packets[dirndx]++;
6345				s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6346			}
6347			if (s->src_node != NULL) {
6348				s->src_node->packets[dirndx]++;
6349				s->src_node->bytes[dirndx] += pd.tot_len;
6350			}
6351			if (s->nat_src_node != NULL) {
6352				s->nat_src_node->packets[dirndx]++;
6353				s->nat_src_node->bytes[dirndx] += pd.tot_len;
6354			}
6355			dirndx = (dir == s->direction) ? 0 : 1;
6356			s->packets[dirndx]++;
6357			s->bytes[dirndx] += pd.tot_len;
6358		}
6359		tr = r;
6360		nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6361		if (nr != NULL && r == &V_pf_default_rule)
6362			tr = nr;
6363		if (tr->src.addr.type == PF_ADDR_TABLE)
6364			pfr_update_stats(tr->src.addr.p.tbl,
6365			    (s == NULL) ? pd.src :
6366			    &s->key[(s->direction == PF_IN)]->addr[0],
6367			    pd.af, pd.tot_len, dir == PF_OUT,
6368			    r->action == PF_PASS, tr->src.neg);
6369		if (tr->dst.addr.type == PF_ADDR_TABLE)
6370			pfr_update_stats(tr->dst.addr.p.tbl,
6371			    (s == NULL) ? pd.dst :
6372			    &s->key[(s->direction == PF_IN)]->addr[1],
6373			    pd.af, pd.tot_len, dir == PF_OUT,
6374			    r->action == PF_PASS, tr->dst.neg);
6375	}
6376
6377	switch (action) {
6378	case PF_SYNPROXY_DROP:
6379		m_freem(*m0);
6380	case PF_DEFER:
6381		*m0 = NULL;
6382		action = PF_PASS;
6383		break;
6384	default:
6385		/* pf_route6() returns unlocked. */
6386		if (r->rt) {
6387			pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
6388			return (action);
6389		}
6390		break;
6391	}
6392
6393	if (s)
6394		PF_STATE_UNLOCK(s);
6395
6396	return (action);
6397}
6398#endif /* INET6 */
6399