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