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