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